q:
I've got a stored procedure in my database, that looks like this

ALTER PROCEDURE [dbo].[GetCountingAnalysisResults]
    @RespondentFilters varchar
AS
BEGIN

@RespondentFilters = '''8ec94bed-fed6-4627-8d45-21619331d82a, 114c61f2-8935-4755-b4e9-4a598a51cc7f'''

DECLARE @SQL nvarchar(600)

SET @SQL =
   'SELECT *
    FROM Answer
    WHERE Answer.RespondentId IN ('+@RespondentFilters+'''))
    GROUP BY ChosenOptionId'

exec sp_executesql @SQL

END

It compiles and executes, but somehow it doesn't give me good results, just like the IN statement wasn't working. Please, if anybody know the solution to this problem, help me.

[A]
It looks like you don't have closing quotes around your @RespondentFilters
```
'8ec94bed-fed6-4627-8d45-21619331d82a, 114c61f2-8935-4755-b4e9-4a598a51cc7f'
```
Since GUIDs do a string compare, that's not going to work.
Your best bet is to use some code to split the list out into multiple values.
Something like this:
```
```
-- This would be the input parameter of the stored procedure, if you want to do it that way, or a UDF
declare @string varchar(500)
set @string = 'ABC,DEF,GHIJK,LMNOPQRS,T,UV,WXY,Z'

declare @pos int
declare @piece varchar(500)

-- Need to tack a delimiter onto the end of the input string if one doesn't exist
if right(rtrim(@string),1)  ','
 set @string = @string  + ','

set @pos =  patindex('%,%' , @string)
while @pos  0
begin
 set @piece = left(@string, @pos - 1)

 -- You have a piece of data, so insert it, print it, do whatever you want to with it.
 print cast(@piece as varchar(500))

 set @string = stuff(@string, 1, @pos, '')
 set @pos =  patindex('%,%' , @string)
end
```
```
Code stolen from
Raymond Lewallen


q: I'd sort of like to use SQLite from within C#.Net, but I can't seem to find an appropriate library. Is there one? An official one? Are there other ways to use SQLite than with a wrapper?

[A]
From
https://system.data.sqlite.org
:
System.Data.SQLite is an ADO.NET adapter for SQLite.
System.Data.SQLite was started by Robert Simpson. Robert still has commit privileges on this repository but is no longer an active contributor. Development and maintenance work is now mostly performed by the SQLite Development Team. The SQLite team is committed to supporting System.Data.SQLite long-term.
"System.Data.SQLite is the original SQLite database engine and a complete ADO.NET 2.0 provider all rolled into a single mixed mode assembly.  It is a complete drop-in replacement for the original sqlite3.dll (you can even rename it to sqlite3.dll).  Unlike normal mixed assemblies, it has no linker dependency on the .NET runtime so it can be distributed independently of .NET."
It even supports Mono.

s: huggingface

c: devops

d: intermediate


q:
I have an XML file that's the output from a database.  I'm using the Java SAX parser to parse the XML and output it in a different format.  The XML contains some invalid characters and the parser is throwing errors like 'Invalid Unicode character (0x5)'

Is there a good way to strip all these characters out besides pre-processing the file line-by-line and replacing them?  So far I've run into 3 different invalid characters (0x5, 0x6 and 0x7).  It's a ~4gb database dump and we're going to be processing it a bunch of times, so having to wait an extra 30 minutes each time we get a new dump to run a pre-processor on it is going to be a pain, and this isn't the first time I've run into this issue.

[A]
I haven't used this personally but Atlassian made a command line XML cleaner that may suit your needs (it was made mainly for JIRA but XML is XML):
Download
atlassian-xml-cleaner-0.1.jar
Open a DOS console or shell, and locate the XML or ZIP backup file on your computer, here assumed to be called data.xml
Run:
   java -jar atlassian-xml-cleaner-0.1.jar data.xml > data-clean.xml
This will write a copy of data.xml to data-clean.xml, with invalid characters removed.


q: Is there a 7-Zip command-line switch that prevents the filenames from echoing to the screen as they are added to the archive?

[A]
If it doesn't have one, you can still redirect the output using
```
>
```
into a file, then deleting the file afterwards. If you are on *nix, you can redirect into
```
/dev/null
```
.
Edit
In MS-DOS and
```
cmd.exe
```
you can redirect into NUL, instead of a file. Thanks to
agnul
for this hint.


q:
My users would like to be able to hit Ctrl+S to save a form.  Is there a good cross-browser way of capturing the Ctrl+S key combination and submit my form?

App is built on Drupal, so jQuery is available.

[A]
```
```
$(window).keypress(function(event) {
    if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
    alert("Ctrl-S pressed");
    event.preventDefault();
    return false;
});
```
```
Key codes can differ between browsers, so you may need to check for more than just 115.


q: How can I hide the title bar from a Windows Form but still have a Resizing Frame?

[A]
Setting FormBorderStyle = None will remove the title bar (at both design and
run time) - and also remove your ability to resize the form.
If you need a border you can set:
```
```
ControlBox = false
Text = ""
```
```


q:
How do I represent an aggregation relation between two classes in UML, such that each class has a link to the other class's interface, not the implementing class?

E.g. I have a class Foo that implements iFoo, and Bar that implements iBar. Foo should have a member variable of type iBar, and Bar should have a member variable of type iFoo.

If I create an aggregation between the two implementing classes, then the member will be of the type of the implementing class, not the superclass. And aggregations between interfaces are invalid in UML (and don't make much sense).


q:
I am using the mootools based Rokbox plugin, on one of my sites, and I can't figure out how to close it with javascript.

I triggered the click event on the close button, but that did not work.

I found the code in the rokbox source that is used to add the click listener

this.closeButton.addEvent('click',function(e){new Event(e).stop();self.swtch=false;self.close(e)});

but since it is minified i cannot find what "this" refers to

[A]
The
```
this
```
likely refers to the rokbox instance; I don't think you need to worry about it, you're interested in the code that runs on the click event. The salient part looks to be the following:
```
```
self.swtch=false;
self.close(e);
```
```
```
self
```
most likely refers to the rokbox instance, again, so assuming you instantiate it with something like
```
```
var rokbox = new RokBox(...);
```
```
you should be able to just call
```
```
rokbox.close();
```
```
and have it close. I haven't looked at rokbox source, so no guarantees, and not quite sure what the
```
swtch=false
```
does, so you probably will need to experiment a bit.


q:
I was looking at DataMapper, which appeared at first glance to use the ActiveRecord ORM pattern.  Other people said that it uses the DataMapper and/or the Domain Object pattern.

What is the difference between those patterns?

[A]
The main difference between the two patterns is this:
In the ActiveRecord you have one domain object that both knows all the business logic and how to save/update itself in the database, user.getLinkToProfile() and User::find(1), User::save(user)
In the DataMapper pattern you have one domain object that holds all the business logic, for exmaple user.getLinkToProfile() (or something similar) but knows
nothing
about the database in question, in addition to this you have a mapper-object that is responsible for saving, updating, selecting, etc. user objects from the database which would have UserMapper::find(1), UserMapper.save(user)
DataMapper is potentially more complex then ActiveRecord but it's a lot easier to develop your domain model and database asynchronous then with ActiveRecord.


q:
Ok,I'm running a setup with a single master and a number of slaves. All writes go through the master and are replicated down to the slaves which are used strictly for reads.

Now I have a stored procedure (not function) which is called by a trigger on an insert. According to the MySQL docs, for replication triggers log the call to the trigger while stored procedures actually log the result of the stored procedure.

So my question is, when my trigger gets fired, will it replicate both the trigger and the results of the procedure that the trigger calls (resulting in the procedure effectively being run twice)? Or will it simply replicate the trigger have the slaves re-run the stored procedure on their own?

Thanks

[A]
In MySQL 5.0 (and MySQL 5.1 with statement based binary logging), only the calling query is logged, so in your case, the INSERT would be logged.
On the slave, the INSERT will be executed and then the trigger will be re-run on the slave.  So the trigger needs to exist on the slave, and assuming it does, then it will be executed in exactly the same way as the master.
In MySQL 5.1, there is row-based binary logging, which will log only the rows being changed, so the trigger would not be re-fired on the slave, but all rows that changed would still be propagated.


q:
If you have binary strings (literally String objects that contain only 1's and 0's), how would you output them as bits into a file?

This is for a text compressor I was working on; it's still bugging me, and it'd be nice to finally get it working. Thanks!

[A]
Easiest is to simply take 8 consecutive characters, turn them into a byte and output that byte. Pad with zeros at the end if you can recognize the end-of-stream, or add a header with length (in bits) at the beginning of the file.
The inner loop would look something like:
```
```
byte[] buffer = new byte[ ( string.length + 7 ) / 8 ];
for ( int i = 0; i < buffer.length; ++i ) {
   byte current = 0;
   for ( int j = 7; j >= 0; --j )
       if ( string[ i * 8 + j ] == '1' )
           current |= 1 << j;
   output( current );
}
```
```
You'll need to make some adjustments, but that's the general idea.


q:
The located assembly's manifest definition does not match the assembly reference

getting this when running nunit through ncover. Any idea?

[A]
This is a mismatch between assemblies: a DLL referenced from an assembly doesn't have a method signature that's expected.
Clean the solution, rebuild everything, and try again.
Also, be careful if this is a reference to something that's in the GAC; it could be that something somewhere is pointing to an incorrect version. Make sure (through the Properties of each reference) that the correct version is chosen or that Specific Version is set false.


q: We are getting an error in a VB6 application that sends data back and forth over TCP sockets.  We get a runtime error "out of string space".  Has anyone seen this or have any thoughts on why this would happen?  It seems like we are hitting some VB6 threshhold so any other thoughts would be helpful as well.

[A]
Text found on MSDN:
http://msdn.microsoft.com/en-us/library/aa264524(VS.60).aspx
Visual Basic for Applications
  Reference Out of string space (Error
  14)
Specifics
Visual Basic permits you to use very
  large strings. However, the
  requirements of other programs and the
  way you manipulate your strings may
  cause this error. This error has the
  following causes and solutions:
Expressions requiring that temporary strings be created for
  evaluation may cause this error. For
  example, the following code causes an
  Out of string space error on some
  operating systems:
```
```
MyString = "Hello"
For Count = 1 To 100
MyString = MyString & MyString
Next Count
```
```
```
```
Assign the string to a variable of another name.
* Your system may have run out of memory, which prevented a string from
```
```
being allocated.
Remove any unnecessary applications from memory to create
  more space.
For additional information, select the
  item in question and press F1.


q:
How do you check if a one-character String is a letter - including any letters with accents?

I had to work this out recently, so I'll answer it myself, after the recent VB6 question reminded me.

[A]
Just checking if a letter is in A-Z because that doesn't include letters with accents or letters in other alphabets.
I found out that you can use the regular expression class for 'Unicode letter', or one of its case-sensitive variations:
```
```
string.matches("\\p{L}"); // Unicode letter
string.matches("\\p{Lu}"); // Unicode upper-case letter
```
```
You can also do this with
Character
class:
```
```
Character.isLetter(character);
```
```
but that is less convenient if you need to check more than one letter.


q: How can I take the string foo[]=1&foo[]=5&foo[]=2 and return a collection with the values 1,5,2 in that order. I am looking for an answer using regex in C#. Thanks

[A]
I don't know C#, but...
In java:
```
```
String[] nums = String.split(yourString, "&?foo[]");
```
```
The second argument in the
```
String.split()
```
method is a regex telling the method where to split the String.


q: In .NET, what's the best way to prevent multiple instances of an app from running at the same time? And if there's no "best" technique, what are some of the caveats to consider with each solution?


q:
Here is my problem: I've got a dialog with some parameters that the user can change (via a spinner for example). Each time one of these parameters is changed, I launch a thread to update a 3D view according to the new parameter value.
If the user changes another value (or the same value again by clicking many times on the spinner arrow) while the first thread is working, I would like to abort the first thread (and the update of the 3D view) and launch a new one with the latest parameter value.

How can I do something like that?

PS: There is no loop in the run() method of my thread, so checking for a flag is not an option: the thread updating the 3D view basically only calls a single method that is very long to execute. I can't add any flag in this method asking to abort either as I do not have access to its code.

[A]
The thread that is updating the 3D view should periodically check some flag (use a
```
volatile boolean
```
) to see if it should terminate.  When you want to abort the thread, just set the flag.  When the thread next checks the flag, it should simply break out of whatever loop it is using to update the view and return from its
```
run
```
method.
If you truly cannot access the code the Thread is running to have it check a flag, then there is no safe way to stop the Thread.  Does this Thread ever terminate normally before your application completes?  If so, what causes it to stop?
If it runs for some long period of time, and you simply must end it, you can consider using the deprecated
```
Thread.stop()
```
method.  However, it was deprecated for a good reason.  If that Thread is stopped while in the middle of some operation that leaves something in an inconsistent state or some resource not cleaned up properly, then you could be in trouble.  Here's a note from the
documentation
:
This method is inherently unsafe.
  Stopping a thread with Thread.stop
  causes it to unlock all of the
  monitors that it has locked (as a
  natural consequence of the unchecked
  ThreadDeath exception propagating up
  the stack). If any of the objects
  previously protected by these monitors
  were in an inconsistent state, the
  damaged objects become visible to
  other threads, potentially resulting
  in arbitrary behavior. Many uses of
  stop should be replaced by code that
  simply modifies some variable to
  indicate that the target thread should
  stop running. The target thread should
  check this variable regularly, and
  return from its run method in an
  orderly fashion if the variable
  indicates that it is to stop running.
  If the target thread waits for long
  periods (on a condition variable, for
  example), the interrupt method should
  be used to interrupt the wait. For
  more information, see
Why are
  Thread.stop, Thread.suspend and
  Thread.resume Deprecated?


q:
How can I convert a character to its ASCII code using JavaScript?

For example:

get 10 from "\n".


q: I'd like to use regular expressions in selecting elements using the match function.  I'd prefer not to use an external library (such as saxon) to do this.

[A]
Yes, 3.5 XPathNavigator supports XSLT 2.0.
http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx
"The XPathNavigator class in the System.Xml.XPath namespace is an abstract class which defines a cursor model for navigating and editing XML information items as instances of the XQuery 1.0 and XPath 2.0 Data Model."


q:
For ASP.Net application deployment what type of information (if any) are you storing in the machine.config?

If you're not using it, how are you managing environment specific configuration settings that may change for each environment?

I'm looking for some "best practices" and the benefits/pitfalls of each. We're about to deploy a brand new application to production in two months and I've got some latitude in these types of decisions. I want to make sure that I'm approaching things in the best way possible and attempting to avoid shooting myself in the foot at a later date.

FYI We're using it (machine.config) currently for just the DB connection information and storing all other variables that might change in a config table in the database.

[A]
I use machine.config for not just ASP.NET, but for overall config as well.  I implemented a hash algorithm (Tiger) in C# and wanted it to be available via machine request.  So, registered my assembly in the GAC and added the following to machine.config:
```
```
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <mscorlib>
        <cryptographySettings>
            <cryptoNameMapping>
                <cryptoClasses>
                    <cryptoClass Tiger192="Jcs.Tiger.Tiger192, Jcs.Tiger, Culture=neutral, PublicKeyToken=66c61a8173417e64, Version=1.0.0.4"/>
                    <cryptoClass Tiger160="Jcs.Tiger.Tiger160, Jcs.Tiger, Culture=neutral, PublicKeyToken=66c61a8173417e64, Version=1.0.0.4"/>
                    <cryptoClass Tiger128="Jcs.Tiger.Tiger128, Jcs.Tiger, Culture=neutral, PublicKeyToken=66c61a8173417e64, Version=1.0.0.4"/>
                </cryptoClasses>
                <nameEntry name="Tiger" class="Tiger192"/>
                <nameEntry name="TigerFull" class="Tiger192"/>
                <nameEntry name="Tiger192" class="Tiger192"/>
                <nameEntry name="Tiger160" class="Tiger160"/>
                <nameEntry name="Tiger128" class="Tiger128"/>
                <nameEntry name="System.Security.Cryptography.HashAlgorithm" class="Tiger192"/>
            </cryptoNameMapping>
            <oidMap>
                <oidEntry OID="1.3.6.1.4.1.11591.12.2" name="Jcs.Tiger.Tiger192"/>
            </oidMap>
        </cryptographySettings>
    </mscorlib>
</configuration>
```
```
This allows my code to look like so:
```
```
using (var h1 = HashAlgorithm.Create("Tiger192"))
{
   ...
}
```
```
and there's no dependency on the Jcs.Tiger.dll assembly in my code at all, hard or soft.


q:
I am attempting to get the Resharper test runner to recognize my MSTest unit tests via Gallio.

I have the following installed:
VSTS 2005 8.0.50727.762
Resharper 4.1
Gallio 3.0.0.285

I am also running Windows XP x64.

The unit test options only shows NUnit as being available. I am thinking that I must have some versioning wrong. Can someone point me in the right direction? Am I barking up the wrong tree and this is only works in VS2k8?

UPDATE: Well I updated Gallio to GallioBundle-3.0.4.385-Setup and it now shows up in the unit test options for R#. But I get the following error when running tests in either R# or Icarus:

Failures Cannot
  run tests because the
  MSTest executable was not found

Thanks

[A]
I'm not sure if this applies to your question, but the latest news on the Gallio site states :
Gallio and ReSharper 4.0
A few people have asked when Gallio will
  support the final release of ReSharper
  4.0. Unfortunately there were some last-minute breaking changes between
  ReSharper 4.0 Beta and the Final
  release. So the ReSharper plugin in
  Gallio Alpha 3 Update 2 will not work
  anymore. No matter... we plan to
  release another update of Gallio later
  this week.
Update:
just saw this applied to an earlier version than you were using so disregard that.


q:
I'm using wget to connect to a secure site like this:

wget -nc -i inputFile

where inputeFile consists of URLs like this:

https://clientWebsite.com/TheirPageName.asp?orderValue=1.00&merchantID=36&programmeID=92&ref=foo&Ofaz=0

This page returns a small gif file.  For some reason, this is taking around 2.5 minutes.  When I paste the same URL into a browser, I get back a response within seconds.

Does anyone have any idea what could be causing this?

The version of wget, by the way, is "GNU Wget 1.9+cvs-stable (Red Hat modified)"

[A]
Try forging your UserAgent
```
```
-U "Mozilla/5.0 (X11; U; Linux i686 (x86_64); en-GB; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1"
```
```
Disable Ceritificate Checking ( slow )
```
```
--no-check-certificate
```
```
Debug whats happening by enabling verbostity
```
```
-v
```
```
Eliminate need for DNS lookups:
Hardcode thier IP address in your HOSTS file
```
```
/etc/hosts
123.122.121.120  foo.bar.com
```
```


q:
Is there an easy way to find the number of classes contained within a visual studio solution?   Other than writing a funky find script, I couldn't find a way to do it within the code metrics piece of VS.

I am running Visual Studio 2008 and this is a VB.Net project through and through.

thanks!

[A]
I haven't used these tools before, but they probably have some facility that can help you.  Basically any code metrics package can help.  VS 2008 was supposed to have a built in code metrics tool, but I think it was nixed for one reason or another.
CodeMetrics Plugin for Reflector
NDepend
- commercial I think, though has a trial download
--Edit--
JRoppert is correct.  I actually remember reading that the metrics tool was only available in the Team edition, not in Pro or Express


q:
Does anyone know how SQL Server determines the order triggers (of same type, i.e. before triggers) are executed.  And is there any way of changing this so that I can specify the order I want.  If not, why not.

Thanks.

[A]
The order is set by sql server, the only thing you can do is use a system sp (sp_settriggerorder) to set which trigger will fire first and which will fire last.
Beyond setting the first and last triggers to fire, you can't modify or tell which order sql server will use.  Therefore you will want to build your triggers so they do not rely on which order they are fired.  Even if you determine the order they fire in today, it may change tomorrow.
This information is based on Sql Server 2000, however I do not believe 2005/2008 act differently in this regard.


q:
My code takes an interface as input but only excercises a couple of the interface's methods (often, just getters).

When testing the code, I'd love to define an anonymous inner class that returns the test data.  But what do I do about all the other methods that the interface requires?

I could use my IDE to auto-generate a stub for the interface but that seems fairly code-heavy.

What is the easiest way to stub the two methods I care about and none of the methods I don't?

[A]
If you are using JUnit to test, use Mocks instead of stubs.
Read Martin Fowler's seminal article "
Mocks Aren't Stubs
"
I recommend the
EasyMock
framework, it works like a charm automatically Mocking your interface using reflection.  It is a bit more advanced than the code samples in Fowler's article, especially when you use the
unitils
library to wrap EasyMock, so the syntax will be much simpler than that in the article.  Also, if you don't have an interface, but you want to mock a concrete class, EasyMock has a class extension.


q:
I am attempting to use the 'tempfile' module for manipulating and creating text files. Once the file is ready I want to save it to disk. I thought it would be as simple as using 'shutil.copy'. However, I get a 'permission denied' IOError:

>>> import tempfile, shutil
>>> f = tempfile.TemporaryFile(mode ='w+t')
>>> f.write('foo')
>>> shutil.copy(f.name, 'bar.txt')

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    shutil.copy(f.name, 'bar.txt')
  File "C:\Python25\lib\shutil.py", line 80, in copy
    copyfile(src, dst)
  File "C:\Python25\lib\shutil.py", line 46, in copyfile
    fsrc = open(src, 'rb')
IOError: [Errno 13] Permission denied: 'c:\\docume~1\\me\\locals~1\\temp\\tmpvqq3go'
>>>

Is this not intended when using the 'tempfile' library? Is there a better way to do this? (Maybe I am overlooking something very trivial)

[A]
You could always use
shutil.copyfileobj
, in your example:
```
```
new_file = open('bar.txt', 'rw')
shutil.copyfileobj(f, new_file)
```
```


q:
In C#.Net WPF During UserControl.Load ->

What is the best way of showing a whirling circle / 'Loading' Indicator on the UserControl until it has finished gathering data and rendering it's contents?

[A]
I generally would create a layout like this:
```
```
<Grid>
    <Grid x:Name="MainContent" IsEnabled="False">
    ...
    </Grid>

    <Grid x:Name="LoadingIndicatorPanel">
    ...
    </Grid>
</Grid>
```
```
Then I load the data on a worker thread, and when it's finished I update the UI under the "MainContent" grid and enable the grid, then set the LoadingIndicatorPanel's Visibility to Collapsed.
I'm not sure if this is what you were asking or if you wanted to know how to show an animation in the loading label.  If it's the animation you're after, please update your question to be more specific.


q:
I have the following XAML:

<TextBlock Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Margin="0,0,5,0"/>
<TextBlock Text="items selected">
    <TextBlock.Style>
        <Style TargetType="{x:Type TextBlock}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Value="1">
                    <Setter Property="TextBlock.Text" Value="item selected"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

The first text block happily changes with SelectedItems.Count, showing 0,1,2, etc.  The datatrigger on the second block never seems to fire to change the text.

Any thoughts?

[A]
The DataTrigger is firing but the Text field for your second TextBlock is hard-coded as "items selected" so it won't be able to change. To see it firing, you can remove Text="items selected".
Your problem is a good candidate for using a
ValueConverter
instead of
DataTrigger
. Here's how to create and use the ValueConverter to get it to set the Text to what you want.
Create this ValueConverter:
```
```
public class CountToSelectedTextConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((int)value == 1)
            return "item selected";
        else
            return "items selected";
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}
```
```
Add the namespace reference to your the assembly the converter is located:
```
```
xmlns:local="clr-namespace:ValueConverterExample"
```
```
Add the converter to your resources:
```
```
<Window.Resources>
    <local:CountToSelectedTextConverter x:Key="CountToSelectedTextConverter"/>
</Window.Resources>
```
```
Change your second textblock to:
```
```
<TextBlock Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count, Converter={StaticResource CountToSelectedTextConverter}}"/>
```
```


q:
I have a working copy of my project, checked out using Subversion 1.5.1. When I attempt to run StatSVN against it, I get the following error:

Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger info
  INFO: StatSVN - SVN statistics generation

Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger info
  INFO: svn: '.' is not a working copy
  Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger error
  SEVERE: Repository root not available - verify that the project was checked out with svn version 1.3.0 or above.

Has anyone experienced this? I've seen suggestions it might be related to using a locale other than en_US, but I am using en_US.

[A] Just guessing here, but are you sure that statSVN is compatible with working copies created with version 1.5 of the client? The format changed with svn 1.5...


q:
I have 4 versions of file A.txt in my subversion repository, say: A.txt.r1, A.txt.r2, A.txt.r3 and A.txt.r4. My working copy of the file is r4 and I want to switch back to r2. I don't want to use "svn update -r 2 A.txt" because this will delete all the revisions after r2, namely r3 and r4.

So is there any way that I update my working copy to r2 and still having the option to switch to r3 and r4 later? Put it another way, I want to still be able to see all 4 revisions by using "svn log A.txt" after doing the update.

[A]
updating to an older rev will not delete your newer revs.
so you could do
```
svn up -r2 file
```
, then
```
svn up -r4 file
```
.
also, you wouldn't be able to commit the r2 file this way, because you'd have to update before committing, and you'd end up with r4 again.


q: I'm looking to have a couple of plugins in a Flex project I'm working on. I know I can load a SWF using the SWFLoader, but I thought in Flex3 you can now have Runtime Shared Libraries or something. Does anyone have any good documentation on loading a plugin at runtime? Ideally I'd like to be able to load a plugin from a URL, then execute some code from within the plugin (e.g. add a control to the page).

[A]
You can use either Modules or RSL.
RSLs have the advantage of getting cached by flash rather than the browser so they stick around longer.
Modules are easier to create and use. I have used modules and had issues with modules failing to load (code needs to handle that case). I haven't tried RSLs yet.
Here is some documentation on creating RSLs
http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:Flex_3_RSLs


q: I want to change the Text of the browse button in the FileUpload Control (System.Web.UI.WebControls), instead of the [Browse...] text I want to use [...]

[A]
This isn't technically possible for security purposes, so the user cannot be misled.
However, there are a couple of workarounds, although these require working with the raw HTML rather than the .NET server control - take a look at
http://www.quirksmode.org/dom/inputfile.html
for one example.


q:
I am building a quiz and i need to calculate the total time taken to do the quiz.
and i need to display the time taken  in  HH::MM::SS..any pointers?

[A]
new Date().time returns the time in milliseconds.
```
```
var nStart:Number = new Date().time;

// Some time passes

var nMillisElapsed:Number = new Date().time - nStart;

var strTime:String = Math.floor(nMillisElapsed / (1000 * 60 * 60)) + "::" +
   (Math.floor(nMillisElapsed / (1000 * 60)) % 60) + "::" +
   (Math.floor(nMillisElapsed / (1000)) % 60);
```
```


q: Is there a method for controlling the Balance of the Wave output that will work on both XP and Vista?

[A]
Vista has a new api for everything related to mixers and audio, per process legacy api's should still work, but to change global volume, you would have to look at the new COM interfaces added to Vista
This
should get you started


q:
I'm generating a self-signed SSL certificate to protect my server's admin section, and I keep getting this message from OpenSSL:

unable to write 'random state'

What does this mean?

This is on an Ubuntu server. I have upgraded libssl to fix the recent security vulnerability.

[A]
In practice, the most common reason for this happening seems to be that the .rnd file in your home directory is owned by root rather than your account.  The quick fix:
```
```
sudo rm ~/.rnd
```
```
For more information, here's the entry from the
OpenSSL FAQ
:
Sometimes the openssl command line utility does not abort with a "PRNG not seeded" error message, but complains that it is "unable to write 'random state'". This message refers to the default seeding file (see previous answer). A possible reason is that no default filename is known because neither RANDFILE nor HOME is set. (Versions up to 0.9.6 used file ".rnd" in the current directory in this case, but this has changed with 0.9.6a.)
So I would check RANDFILE, HOME, and permissions to write to those places in the filesystem.
If everything seems to be in order, you could try running with
strace
and see what exactly is going on.


q:
I'd like to install Gentoo. I need it to develop GUI C++ applications using wxWidgets, so I need:

build tools: make, automake, autoconf, etc.

C++ compiler (GCC)

X Window System for testing (Fluxbox or something minimal would be enough)

Now, I have two options:

download the small network installer (57MB) do a network install

download the 600MB CD

I'd like to download as less as possible and still have all the tools above.

I also don't understand whether the network installer will first prompt me for the packages I want, or it will fetch 600 MB of data anyway?

I might want to install it on other computers later, so I'd go with 'full' install from CD if the network install does not save me anything.

[A]
Gentoo is ultraminimalist by default.
The install CD gets you a basic working system, a basic compile environment ( Some version of the GCC suite ), and package management.
Its up to you then to install what you want to use.
Its not like many other distributions where theres a big set of "default" packages to have installed.
You have to know what you want, and install what you want.
The "Live" Cd will make things a bit quicker  by having a few precompiled binaries available, but besides that, you still have to choose what you want to install.
I also don't understand whether the
  network installer will first prompt me
  for the packages I want, or it will
  fetch 600 MB of data anyway?
it will only install what you want to. If you use NetInstall and install nothing except GCC, it will only download enough to have GCC.
Welcome to gentoo.
It can be a little daunting for first timers, but once you've gotten past the steep learning curve you'll love it :)


q:
I need to read selected files, matching on the file name, from a remote zip archive using Python. I don't want to save the full zip to a temporary file (it's not that large, so I can handle everything in memory).

I've already written the code and it works, and I'm answering this myself so I can search for it later. But since evidence suggests that I'm one of the dumber participants on Stackoverflow, I'm sure there's room for improvement.

[A]
Here's how I did it (grabbing all files ending in ".ranks"):
```
```
import urllib2, cStringIO, zipfile

try:
    remotezip = urllib2.urlopen(url)
    zipinmemory = cStringIO.StringIO(remotezip.read())
    zip = zipfile.ZipFile(zipinmemory)
    for fn in zip.namelist():
        if fn.endswith(".ranks"):
            ranks_data = zip.read(fn)
            for line in ranks_data.split("\n"):
                # do something with each line
except urllib2.HTTPError:
    # handle exception
```
```


q:
I have a handful of projects that all use one project for the data model.  Each of these projects has its own applicationContext.xml file with a bunch of repetitive data stuff within it.

I'd like to have a modelContext.xml file and another for my ui.xml, etc.

Can I do this?

[A]
Yes, you can do this via the import element.
```
```
<import resource="services.xml"/>
```
```
Each element's resource attribute is a valid path (e.g. classpath:foo.xml)


q: I can never remember the number. I need a memory rule.

[A]
Well, it has 32 bits and hence can store 2^32 different values. Half of those are negative.
The solution is 2,147,483,647
And the lowest is −2,147,483,648.
(Notice that there is one more negative value.)


q:
I'm implementing a simple service using datagrams over unix local sockets (AF_UNIX address family, i.e. not UDP).  The server is bound to a public address, and it receives requests just fine.  Unfortunately, when it comes to answering back, sendto fails unless the client is bound too.  (the common error is Transport endpoint is not connected).

Binding to some random name (filesystem-based or abstract) works.  But I'd like to avoid that: who am I to guarantee the names I picked won't collide?

The unix sockets' stream mode documentation tell us that an abstract name will be assigned to them at connect time if they don't have one already.  Is such a feature available for datagram oriented sockets?

[A]
I'm not so sure I understand your question completely, but here is a datagram implementation of an echo server I just wrote. You can see the server is responding to the client on the same IP/PORT it was sent from.
Here's the code
First, the server (listener)
```
```
from socket import *
import time
class Listener:
    def __init__(self, port):
        self.port = port
        self.buffer = 102400

    def listen(self):

        sock = socket(AF_INET, SOCK_DGRAM)
        sock.bind(('', self.port))

        while 1:
            data, addr = sock.recvfrom(self.buffer)
            print "Received: " + data
            print "sending to %s" % addr[0]
            print "sending data %s" % data
            time.sleep(0.25)
            #print addr # will tell you what IP address the request came from and port
            sock.sendto(data, (addr[0], addr[1]))
            print "sent"
        sock.close()

if __name__ == "__main__":
    l = Listener(1975)
    l.listen()
```
```
And now, the Client (sender) which receives the response from the Listener
```
```
from socket import *
from time import sleep
class Sender:
    def __init__(self, server):
       self.port = 1975
       self.server = server
       self.buffer = 102400

    def sendPacket(self, packet):
        sock = socket(AF_INET, SOCK_DGRAM)
        sock.settimeout(10.75)

        sock.sendto(packet, (self.server, int(self.port)))

        while 1:
            print "waiting for response"
            data, addr = sock.recvfrom(self.buffer)
            sock.close()
            return data

if __name__ == "__main__":
        s = Sender("127.0.0.1")
        response = s.sendPacket("Hello, world!")
        print response
```
```


q:
How can I bind an array parameter in the HQL editor of the HibernateTools plugin?
The query parameter type list does not include arrays or collections.

For example:

     Select * from Foo f where f.a in (:listOfValues).

How can I bind an array to that listOfValues?

[A]
You probably cannot. Hibernate replaces the objects it gets out of the database with it's own objects (kind of proxies). I would strongly assume Hibernate cannot do that with an array. So if you want to bind the array-data put it into a List on access by Hibernate.
As an example one could do:
```
```
select * from Foo f where f.a in f.list
```
```


q:
We are trying to integrate tests in our daily builds using TestComplete, so far we have a machine dedicated for testing and our build script copies to this machine everything TestComplete needs for its tests (Application, Database, Test script project and source files, etc).

Basically we can open the TestComplete project manually and run the tests.

Now we want to automate that process, so how do you do it? Or how do you think would be the simplest and best way to make this automation?

Keeping it short, we want to automate the process of opening TestComplete after each build, run all the tests and send an email with the test results.

Anyone can share some experience about this?

Thanks.

[A]
Well, although I have not used TestComplete I have used a competing package called QA Wizard Pro. Since you are asking this question I am assuming that it isn't something that is natively supported by TestComplete. QA Wizard is the same way and they expect it to be run manually instead of automatically, though there are test run files that can be run. For QA Wizard I created a batch file that was run nightly from the task scheduler. The account to run the software must be able to interact with the desktop and a user must be logged in
with
a display. I used a free piece of software called
AutoHotKey
to automate the running of the tests and then some
Cygwin
tools to parse the results and trigger an email through
Blat
with the results. It isn't a perfect solution but it does work.


q:
I am new to asp and have a deadline in the next few days.
i receive the following xml from within a webservice response.

print("<?xml version="1.0" encoding="UTF-8"?>
<user_data>
<execution_status>0</execution_status>
<row_count>1</row_count>
<txn_id>stuetd678</txn_id>
<person_info>
    <attribute name="firstname">john</attribute>
    <attribute name="lastname">doe</attribute>
    <attribute name="emailaddress">john.doe@johnmail.com</attribute>
</person_info>
</user_data>");

How can i parse this xml into asp attributes?

Any help is greatly appreciated

Thanks
Damien

On more analysis, some soap stuff is also returned as the aboce response is from a web service call. can i still use lukes code below?

[A]
You need to read about MSXML parser. Here is a link to a good all-in-one example
http://oreilly.com/pub/h/466
Some reading on XPath will help as well. You could get all the information you need in MSDN.
Stealing the code from
Luke
excellent reply for aggregation purposes:
```
```
Dim oXML, oNode, sKey, sValue

Set oXML = Server.CreateObject("MSXML2.DomDocument.6.0") 'creating the parser object
oXML.LoadXML(sXML) 'loading the XML from the string

For Each oNode In oXML.SelectNodes("/user_data/person_info/attribute")
  sKey = oNode.GetAttribute("name")
  sValue = oNode.Text
  Select Case sKey
    Case "execution_status"
    ... 'do something with the tag value
    Case else
    ... 'unknown tag
  End Select
Next

Set oXML = Nothing
```
```


q: I know it happens sometime before Load, but during what event exactly?

[A]
It's loaded into memory between init and load. See t
his article
for a full break down of the page lifecycle.


q:
I have a web application where there are number of Ajax components which refresh themselves every so often inside a page (it's a dashboard of sorts).

Now, I want to add functionality to the page so that when there is no Internet connectivity, the current content of the page doesn't change and a message appears on the page saying that the page is offline (currently, as these various gadgets on the page try to refresh themselves and find that there is no connectivity, their old data vanishes).

So, what is the best way to go about this?

[A]
```
```
navigator.onLine
```
```
That should do what you're asking.
You probably want to check that in whatever code you have that updates the page. Eg:
```
```
if (navigator.onLine) {
    updatePage();
} else {
    displayOfflineWarning();
}
```
```


q: I've recently come across a problem which requires at least a basic degree of image processing, can I do this in Python, and if so, with what?

[A]
There is actually a wonderful
Python Imaging Library (PIL)
.  It gives you the ability to alter existing images, including anti-aliasing capabilities, and create new images with text and such.  You can also find a
decent introductory tutorial
in the PIL handbook provided on the aforementioned site.


q:
I'm running a SQL query on SQL Server 2005, and in addition to 2 columns being queried from the database, I'd also like to return 1 column of random numbers along with them. I tried this:

select column1, column2, floor(rand() * 10000) as column3
from table1

Which kinda works, but the problem is that this query returns the same random number on every row. It's a different number each time you run the query, but it doesn't vary from row to row. How can I do this and get a new random number for each row?

[A]
You need to use a UDF
first:
```
```
CREATE VIEW vRandNumber
AS
SELECT RAND() as RandNumber
```
```
second:
```
```
CREATE FUNCTION RandNumber()
RETURNS float
AS
  BEGIN
  RETURN (SELECT RandNumber FROM vRandNumber)
  END
```
```
test:
```
```
SELECT dbo.RandNumber(), *
FROM <table>
```
```
Above borrowed from
Jeff's SQL Server Blog


q:
I have a table with game scores, allowing multiple rows per account id: scores (id, score, accountid). I want a list of the top 10 scorer ids and their scores.

Can you provide an sql statement to select the top 10 scores, but only one score per account id?

Thanks!

[A]
Try this:
```
```
select top 10 username,
              max(score)
from usertable
group by username
order by max(score) desc
```
```


q:
Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about

for i in range(0, 20):
for i in xrange(0, 20):

[A]
See this
post
to find difference between range and xrange:
To quote:
```
range
```
returns exactly what you think: a list of consecutive
  integers, of a defined length beginning with 0.
```
xrange
```
, however,
  returns an
"xrange object"
, which acts a great deal like an iterator


q:
I have a couple of triggers on a table that I want to keep separate and would like to priortize them.

I could have just one trigger and do the logic there, but I was wondering if there was an easier/logical way of accomplishing this of having it in a pre-defined order ?

[A]
Use sp_settriggerorder.  You can specify the first and last trigger to fire depending on the operation.
sp_settriggerorder on MSDN
From the above link:
A. Setting the firing order for a DML trigger
The following example specifies that trigger uSalesOrderHeader be the first trigger to fire after an UPDATE operation occurs on the Sales.SalesOrderHeader table.
```
USE AdventureWorks;
GO
sp_settriggerorder
    @triggername= 'Sales.uSalesOrderHeader',
    @order='First',
    @stmttype = 'UPDATE';
```
B. Setting the firing order for a DDL trigger
The following example specifies that trigger ddlDatabaseTriggerLog be the first trigger to fire after an ALTER_TABLE event occurs in the AdventureWorks database.
```
USE AdventureWorks;
GO
sp_settriggerorder
    @triggername= 'ddlDatabaseTriggerLog',
    @order='First',
    @stmttype = 'ALTER_TABLE',
    @namespace = 'DATABASE';
```


q: Suppose you have a program which reads from a socket. How do you keep the download rate below a certain given threshold?

[A]
Assuming a network transport, a TCP/IP based one, Packets are sent in response to ACK/NACK packets going the other way.
By limiting the rate of packets acknowledging receipt of the incoming packets, you will in turn reduce the rate at which new packets are sent.
It can be a bit imprecise, so its possibly optimal to monitor the downstream rate and adjust the response rate adaptively untill it falls inside a comfortable threshold. ( This will happen really quick however, you send dosens of acks a second )


q:
I've started figuring out drupal, and so far most of the results are just ugly.
May be I need to learn it in something similar to a real-life project.
I thought — to reproduce this site's functionality might be a good learning project. But I need help. :)

Without assuming this site is based on drupal (it most likely is not — too quick, I think) is there a way to build something similar in functionality (yes, slower, OK if not as fancy as this one, but close) with existing drupal modules and schemes (or with minimal tweaking)?

Or drupal is not good enough for that?
Or — is it too complicated project for a student?

Which existing modules and schemes might help to build something similar?

(No competition is intended with stackoverflow.)

[A]
Firstly, Drupal is by no means a slow system, actually it works quite well.
Secondly, this has been already asked and answered
here
.
By the way Drupal has a medium learning curve but, once you learn how to use you'll find it simple and you'll find it will satisfy almost everything you want to do with it. Its plugin system is just great and it's very SEO friendly (I don't get paid from Drupal I swear, I just happen to like it a lot)
My
website
is made in drupal if you wanna take a look (is in spanish though).


q:
It is a real pain to deploy my InfoPath 2007 Forms from the designer into our development environment's SharePoint server.  All of our forms require "full trust" since they include business logic written in C#.  Here are the manual steps:

1) Run the "Publish Form" wizard in InfoPath, specifying the target site to publish to and location to save the xsn file.

2) De-activate the existing version of the form from the site collection features (if an older version exists).

3) Log into Central Admin on the development server.  Navigate to Application Management -> Manage Form Templates and upload the xsn file.

4) Activate the form as a site collection feature.

Does anyone have an idea how this can be automated?  Maybe via stsadm?

[A]
You can package InfoPath forms in SharePoint solutions (WSP files). These can be deployed by making use of STSADM. For more information:
http://blogs.importchaos.com/alonsorobles/2008/06/04/creating-a-sharepoint-solution-for-an-infopath-form-template-deployment/#comments
http://www.crsw.com/mark/Lists/Posts/Post.aspx?ID=37
http://blah.winsmarts.com/2008-8-Deploying_InfoPath_2007_Forms_to_Forms_Server_-and-ndash_Properly.aspx


q: How can I tell Activerecord to not load blob columns unless explicitly asked for? There are some pretty large blobs in my legacy DB that must be excluded for 'normal' Objects.

[A]
I believe you can ask AR to load specific columns in your invocation to find:
```
```
MyModel.find(id, :select => 'every, attribute, except, the, blobs')
```
```
However, this would need to be updated as you add columns, so it's not ideal.  I don't think there is any way to specifically exclude one column in rails (nor in a single SQL select).
I guess you could write it like this:
```
```
MyModel.find(id, :select => (MyModel.column_names - ['column_to_exclude']).join(', '))
```
```
Test these out before you take my word for it though. :)


q:
Using the method Application.Restart() in C# should restart the current application: but it seems that this is not always working.

Is there a reason for this Issue, can somebody tell me, why it doesn't work all the time?

[A]
Try locking before dumping. Here's how I initiate a full app-dump. Might work for you, might not.
```
```
Context.Application.Lock();
Context.Session.Abandon();
Context.Application.RemoveAll();
Context.Application.Restart();
Context.Application.UnLock();
```
```


q: Convert.ToString() only allows base values of 2, 8, 10, and 16 for some odd reason; is there some obscure way of providing any base between 2 and 16?

[A]
```
```
string foo = Convert.ToString(myint,base);
```
```
http://msdn.microsoft.com/en-us/library/14kwkz77.aspx
EDIT
: My bad, this will throw an argument exception unless you pass in the specified bases (2, 8, 10, and 16)
Your probably SOL if you want to use a different base (but why???).


q:
Is there a Vim shortcut for jumping to the argument list of the current function?  I often find myself needing to mess with the argument list of a function, and it's kind of annoying to have to do ?def or ?function or 10k or what-have-you until I finally get to it, then /( or t( or 5e to get to the right position in the argument list, and so on.  It would be great if I could just hit ,a for example and instantly get put into insert mode at the end/beginning of the argument list.

Possible approaches:

Folding

Tag support (ctags)

Also, I'm using Python, so solutions based on curly braces unfortunately won't work.

If no such shortcut exists, I'll just write one and post it here as an answer.  :-)

[A]
map ,a ma[{F(a
Hit ,a to go to the argument list, then `a to return to where you were when you invoked ,a. Caveat: [{ jumps back to the last unmatched { character, so if you're inside a loop or other control structure, it will take you to the beginning of that, instead.
I don't know of a way to get to the beginning of the function in a fool-proof way. If you're consistent about your tabbing, you may be able to do something like this:
map ,a ma?function :nohlf(a
where, if you don't use a single tab before you define your functions, you'd change  to appropriate value.


q:
I'm using the following code to query a database from my jsp, but I'd like to know more about what's happening behind the scenes.

These are my two primary questions.

Does the tag access the ResultSet directly, or is the query result being stored in a datastructure in memory?

When is the connection closed?

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

<sql:query var="query" dataSource="${ds}" sql="${listQuery}"></sql:query>
<c:forEach var="row" items="${query.rows}" begin="0">
    ${row.data }
    ${row.more_data }
</c:forEach>

Note: I've always been against running queries in the jsp, but my result set is too large to store in memory between my action and my jsp. Using this tag library looks like the easiest solution.

[A]
The key thing here is this: javax.servlet.jsp.jstl.sql.Result
That's what JSTL uses as the result of a SQL Query. If you look at the interface, it has this method:
public java.util.SortedMap[] getRows()
c:forEach "knows" about javax.servlet.jsp.jstl.sql.Result, since Result isn't anything else that forEach knows about (Collections, arrays, iterators, etc).
So, all of that implies that the SQL query will suck the entire result set in to RAM.
If you moved your query in to the JSP because you didn't want to load the entire result set in to a collection, then it doesn't look like the SQL tag will solve that problem for you.
In truth you should look up Value List Pattern.
But a "simple" solution to your problem would be to create a custom Iterator that "knows" about your ResultSet. This one wraps a result set and closes everything if it encounters an exception or if the result runs its course (like it would in a forEach). Kind of a special purpose thing.
```
public class ResultSetIterator implements Iterator {
```
```
```
Connection con;
Statement s;
ResultSet rs;
Object curObject;
boolean closed;

public ResultSetIterator(Connection con, Statement s, ResultSet rs) {
    this.con = con;
    this.s = s;
    this.rs = rs;
    closed = false;
}

public boolean hasNext() {
    advance();
    return curObject != null;
}

public Object next() {
    advance();
    if (curObject == null) {
        throw new NoSuchElementException();
    } else {
        Object result = curObject;
        curObject = null;
        return result;
    }
}

public void remove() {
    throw new UnsupportedOperationException("Not supported yet.");
}

private void advance() {
    if (closed) {
        curObject = null;
        return;
    }
    if (curObject == null) {
        try {
            if (rs.next()) {
                curObject = bindObject(rs);
            }
        } catch (SQLException ex) {
            shutDown();
            throw new RuntimeException(ex);
        }
    }
    if (curObject == null) {
        // Still no object, must be at the end of the result set
        shutDown();
    }
}

protected Object bindObject(ResultSet rs) throws SQLException {
    // Bind result set row to an object, replace or override this method
    String name = rs.getString(1);
    return name;
}

public void shutDown() {
    closed = true;
    try {
        rs.close();
    } catch (SQLException ex) {
        // Ignored
    }
    try {
        s.close();
    } catch (SQLException ex) {
        // Ignored
    }
    try {
        con.close();
    } catch (SQLException ex) {
        // Ignored
    }
}
```
```
}
This is, naturally, untested. But since JSTLs forEach can work with an Iterator, it's the simplest object you could really pass to it. This will prevent you from loading the entire result set in to memory. (As an interesting aside, it's notable how almost, but not quite, completely unlike Iterator a ResultSets behavior is.)


q: I'm new to .Net and I'm trying to understand the basics first. What is the difference between MSIL and Java bytecode?

[A]
There are not that much differences. Both are intermediate formats of the code you wrote. When executed, the Virtual machines will execute the intermediate language managed that means that the Virtual Machine controls the variables and calls. There is even a language which I don't remeber right now that can run at .Net and Java the same way.
Basicly, it's just another format for the same thing
Edit: Found the language (besides Scala): It's FAN (
http://www.fandev.org/
), looks very interesting, but no time yet to evaluate


q:
I have:

class MyClass extends MyClass2 implements Serializable {
  //...
}

In MyClass2 is a property that is not serializable. How can I serialize (and de-serialize) this object?

Correction: MyClass2 is, of course, not an interface but a class.

[A]
MyClass2 is just an interface so techinicaly it has no properties, only methods.  That being said if you have instance variables that are themselves not serializeable the only way I know of to get around it is to declare those fields transient.
ex:
```
```
private transient Foo foo;
```
```
When you declare a field transient it will be ignored during the serialization and deserialization process.  Keep in mind that when you deserialize an object with a transient field that field's value will always be it's default (usually null.)
Note you can also override the readResolve() method of your class in order to initialize transient fields based on other system state.


q:
Our CruiseControl system checks out from starteam. I've noticed that it is sometimes not checking out new versions of files, only added files.

Does anyone know why this is?

[A]
I cannot say
why
this happens, but for what it's worth, we avoid the problem entirely by having StarTeam delete all of the local files before checking-out. We get
all
of the files that way. We use the following StarTeam arguments in our NAnt script:
```
```
delete-local -q -p "${starteam_project_root}" -is -filter "N" -cfgd "${exec_time}"
```
```
Which translates to something like:
```
```
delete-local -q -p "user:passwd@SERVER:49201/ProjectName/" -is -filter "N"-cfgd "09/18/2008 14:33:22"
```
```


q:
I want to generate a Makefile from an existing Xcode project on the Mac. Specifically, an existing iPhone, Objective-C program on the Mac.

I found PBToMake, but it looks like it is for Xcode 2.1 and when I tried using it, it did not work for an Xcode 3.1 project.

[A]
Xcode does not support generating a Makefile from a project. If you just want to build your project outside of the IDE, check out the
```
xcodebuild
```
command-line tool.


q:
I found this link http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/, but there isn't a lot of description around it, aside that it's "simple".

Ideally, I'd like an extension to CcMode that can do it, or at least a mode that can handle auto-styling and has similar shortcuts to CcMode.

If there isn't one, any good elisp references to help me get started writing it myself would be greatly appreciated.

EDIT: David's response prompted me to take a closer look at glsl-mode.el, and it is in fact based on cc-mode, so it's exactly what I was looking for in the first place.

[A]
Add the following code to your ~/.emacs file.
```
```
(autoload 'glsl-mode "glsl-mode" nil t)
(add-to-list 'auto-mode-alist '("\\.vert\\'" . glsl-mode))
(add-to-list 'auto-mode-alist '("\\.frag\\'" . glsl-mode))
```
```
Put the file
http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/glsl-mode.el
somewhere on your emacs path.  You can eval (print load-path) in your
scratch
buffer to get the list of possible locations.  If you don't have write access to any of those, you can append another location to load-paths by adding
```
```
(setq load-path (cons "~/.emacs.d" load-path))
```
```
to your ~/.emacs file.


q: I'd like to be able to create a parameterized query in MS Access 2003 and feed the values of certain form elements to that query and then get the corresponding resultset back and do some basic calculations with them. I'm coming up short in figuring out how to get the parameters of the query to be populated by the form elements. If I have to use VBA, that's fine.

[A]
Here is a snippet of code. It updates a table using the parameter txtHospital:
```
```
Set db = CurrentDb

Set qdf = db.QueryDefs("AddHospital")
qdf.Parameters!txtHospital = Trim(Me.HospName)
qdf.ReturnsRecords = False

qdf.Execute dbFailOnError

intResult = qdf.RecordsAffected
```
```
Here is a sample of the SQL:
```
```
PARAMETERS txtHospital Text(255);

INSERT INTO tblHospitals (
[Hospital] )

VALUES (
[txtHospital] )
```
```


q:
I have the following configuration, but I have not able to find any documentation on how to set a maximum backup files on date rolling style.  I know that you can do this with size rolling style by using the maxSizeRollBackups.

<appender name="AppLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="mylog.log" />
    <appendToFile value="true" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <rollingStyle value="Date" />
    <datePattern value=".yyMMdd.'log'" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%d %-5p %c - %m%n"  />
    </layout>
</appender>

[A]
Not sure exactly what you need.  Below is an extract from one of my lo4net.config files:
```
```
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="App_Data\log"/>
    <param name="DatePattern" value=".yyyy-MM-dd-tt".log""/>
    <param name="AppendToFile" value="true"/>
    <param name="RollingStyle" value="Date"/>
    <param name="StaticLogFileName" value="false"/>
    <param name="maxSizeRollBackups" value="60" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%r %d [%t] %-5p %c - %m%n"/>
    </layout>
  </appender>
```
```


q:
Some programming languages such as Java and C# include encryption packages in their standard libraries.  Others such as Python and Ruby make you download third-party modules to do strong encryption.  I assume that this is for legal reasons; perhaps Sun Microsystems has enough lawyers that they aren't afraid of getting sued, while Guido van Rossum feels more vulnerable.

But what does the law actually say about this?  At this point, would open source authors have anything to fear if they included strong encryption in their programming languages' standard libraries?  If so, then why don't they?  If not, then how do Sun and Microsoft get away with it.

[A]
IANAL, But...
Java and C# are closed-source, and thus have terms in the EULA that say more-or-less "It's not our fault if you use this somewhere you're not supposed to". They also have teams of lawyers to protect themselves and enforce that clause.
Most open-source licenses do not have similar langauge, and even the ones that do, they don't have teams of lawyers on their side, as the OP said.
Also, Python and PERL are older than Java and C#, from the days when it was illegal to export cryptographic software from the US. Not adding cryptography since the law was changed is perhaps simply a "consistency-is-good" decision.


q:
I am trying to fix memory leaks in IE 7. Using Drip for investigations but it is not helping much when most dynamically generated DOM elements do not have unique ids.

Tips?

[A]
Just remember that memory leaks are really about you not cleaning up after yourself. All you need is a little organization.
In the past, I have created my own proxy object for attaching events to DOM elements. It uses my javascript library's api to actually set and remove events. The proxy itself just keeps track of all of the references so that I can call a method on it to have it clean up all of my potential memory leaks.
For my purposes, I was able to just call a single deconstructor on the page that would clean up the leaks for the entire page when the user was leaving the page.
You may have to be more granular but the technique is the same.


q:
I have a LINQ to SQL generated class with a readonly property:

<Column(Name:="totalLogins", Storage:="_TotalLogins", DbType:="Int", UpdateCheck:=UpdateCheck.Never)>  _
Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer)
    Get
        Return Me._TotalLogins
    End Get
End Property

This prevents it from being changed externally, but I would like to update the property from within my class like below:

Partial Public Class User

...

    Public Shared Sub Login(Username, Password)
        ValidateCredentials(UserName, Password)

        Dim dc As New MyDataContext()
        Dim user As User = (from u in dc.Users select u where u.UserName = Username)).FirstOrDefault()
        user._TotalLogins += 1
        dc.SubmitChanges()
    End Sub

...

End Class

But the call to user._TotalLogins += 1 is not being written to the database? Any thoughts on how to get LINQ to see my changes?

[A]
```
```
Make a second property that is protected or internal(?)

<Column(Name:="totalLogins", Storage:="_TotalLogins", DbType:="Int", UpdateCheck:=UpdateCheck.Never)>  _
protected Property TotalLogins2() As System.Nullable(Of Integer)
    Get
        Return Me._TotalLogins
    End Get
    Set(byval value as System.Nullable(Of Integer))
        Return Me._TotalLogins
    End Get
End Property
```
```
and then update that . I think it won't save readonly properties by default. And why should it anyway. I now it's a hack but hey that's life.


q:
What is a tool or technique that can be used to perform spell checks upon a whole source code base and its associated resource files?

The spell check should be source code aware meaning that it would stick to checking string literals in the code and not the code itself.  Bonus points if the spell checker understands common resource file formats, for example text files containing name-value pairs (only check the values).  Super-bonus points if you can tell it which parts of an XML DTD or Schema should be checked and which should be ignored.

Many IDEs can do this for the file you are currently working with.  The difference in what I am looking for is something that can operate upon a whole source code base at once.

Something like a Findbugs or PMD type tool for mis-spellings would be ideal.


q:
I want to override the JSON MIME type ("application/json") in Rails to ("text/x-json").  I tried to register the MIME type again in mime_types.rb but that didn't work.  Any suggestions?

Thanks.

[A]
Try:
```
```
render :json => var_containing_my_json, :content_type => 'text/x-json'
```
```


q:
There's a diagram depicting the difference between traditional MVC and Cocoa MVC here:

Cocoa Design Patterns: The Model-View-Controller Design Pattern

Are there any benefits of doing it the "Cocoa" way in .NET using Visual Studio?

[A]
There's no reason
not
to do it that way, if it makes more sense to you. Be aware that a lot of things in the Cocoa framework are the way they are due to higher-level design decisions, for example favoring composition and delegation over subclassing.
If you want, you can design C# software that looks like Objective-C software, but people with no Cocoa experience will have to have it explained to them, because the loosely-coupled design will just seem "weird" to them.
Oh, right - the advantages of that design include greater re-usability of the UI view and model classes (since they won't have any knowledge of each other), slightly simpler code in the view classes, and more of the "application logic" in a single place (the controller classes).


q: In XNA, how do I load in a texture or mesh from a file without using the content pipeline?

[A]
I believe Texture2D.FromFile(); is what you are looking for.
It does not look like you can do this with a Model though.
http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.texture2d.fromfile.aspx


q: Basically, we have a rule setup to run a script when a code word is detected in the body of an incoming message. The script will append the current subject header with a word in front. For example, Before: "Test Message", After: "Dept - Test Message". Any ideas?

[A]
Not tested:
```
```
mailItem.Subject = "Dept - " & mailItem.Subject
mailItem.Save
```
```


q:
Suppose I want to open a file in an existing Emacs session using su or sudo, without dropping down to a shell and doing sudoedit or sudo emacs. One way to do this is

C-x C-f /sudo::/path/to/file

but this requires an expensive round-trip through SSH. Is there a more direct way?

[EDIT] @JBB is right. I want to be able to invoke su/sudo to save as well as open. It would be OK (but not ideal) to re-authorize when saving. What I'm looking for is variations of find-file and save-buffer that can be "piped" through su/sudo.

[A]
Ugh. Perhaps you could open a shell in Emacs and exec sudo emacs.
The problem is that you presumably don't just want to open the file. You want to be able to save it later. Thus you need your root privs to persist, not just exist for opening the file.
Sounds like you want Emacs to become your window manager. It's bloated enough without that. :)


q: What does a JIT compiler specifically do as opposed to a non-JIT compiler? Can someone give a succinct and easy to understand description?

[A]
A JIT compiler runs
after
the program has started and compiles the code (usually bytecode or some kind of VM instructions) on the fly (or just-in-time, as it's called) into a form that's usually faster, typically the host CPU's native instruction set. A JIT has access to dynamic runtime information whereas a standard compiler doesn't and can make better optimizations like inlining functions that are used frequently.
This is in contrast to a traditional compiler that compiles
all
the code to machine language
before
the program is first run.
To paraphrase, conventional compilers build the whole program as an EXE file BEFORE the first time you run it. For newer style programs, an assembly is generated with pseudocode (p-code). Only AFTER you execute the program on the OS (e.g., by double-clicking on its icon) will the (JIT) compiler kick in and generate machine code (m-code) that the Intel-based processor or whatever will understand.


q:
I once was asked to increase thread priority to fix a problem.  I refused, saying that changing it was dangerous and was not the root cause of the problem.

My question is, under what circumstannces should I conider changing priority of threads?

[A]
Not many.  The only time I've ever had to change thread priorities in a
positive
direction was with a user interface thread.  UIs must be extremely snappy in order for the app to feel right, so a lot of times it is best to prioritize painting threads higher than others.  For example, the Swing Event Dispatch Thread runs at priority 6 by default (1 higher than the default).
I do push threads down in priority quite a bit.  Again, this is usually to keep the UI responsive while some long-running background process does its thing.  However, this also will sometimes apply to polling daemons and the like which I
know
that I don't want to be interfering with anything, regardless of how minimal the interference.


q:
I have a .NET 3.5 (target framework) web application.  I have some code that looks like this:

public string LogPath { get; private set; }
public string ErrorMsg { get; private set; }

It's giving me this compilation error for these lines:

"must declare a body because it is not marked abstract or extern."

Any ideas?  My understanding was that this style of property was valid as of .NET 3.0.

Thanks!

The problem turned out to be in my .sln file itself.  Although I was changing the target version in my build options, in the .sln file, I found this:

TargetFramework = "3.0"

Changing that to "3.5" solved it.  Thanks, guys!

[A]
It is, as long as you put
abstract
in front, or implement the methods.
```
```
public abstract string LogPath { get; private set; }
public abstract string ErrorMsg { get; private set; }
```
```
See
http://forums.asp.net/t/1031651.aspx


q:
I am looking to build a multi-threaded text import  facility (generally CSV into SQL Server 2005) and would like to do this in VB.NET but I am not against C#.  I have VS 2008 trial and just dont know where to begin.  Can anyone point me in the direction of where I can look at and play with the source of a VERY simple multi-threaded application for VS 2008?

Thanks!

[A]
This is a great article:
http://www.devx.com/DevX/10MinuteSolution/20365
In particular:
```
```
Dim t As Thread
t = New Thread(AddressOf Me.BackgroundProcess)
t.Start()

Private Sub BackgroundProcess()
   Dim i As Integer = 1
   Do While True
        ListBox1.Items.Add("Iterations: " + i)
        i += 1
        Thread.CurrentThread.Sleep(2000)
   Loop
End Sub
```
```


q:
I am a .Net developer that has been tasked with upgrading a classic asp website to asp.net. The website is currently running on luck and bubble gum but there is not enough time or money to stop progress and do a full rewrite. Of course I will still need to be able to deliver new features while I am upgrading.

What strategies should I use to make a smooth gradual change to asp.net? Should I convert to a single tier .net solution and then refactor to a proper multi-tier solution or should I design my business and data layers now? Should I go straight to 3.5 or is it easier to just get to 1.1 and upgrade to 2.0 or 3.5 after?

A full conversion would probably take 3-5 months. There is also some existing 1.1 code, which is why I am considering using that as a jumping off point.

[A]
How long would a complete conversion/rewrite take? It's also going to depend on how you've structured your original project.
I
can
answer that you should just target v2.0 (3.5 if you want/need it's features) from the beginning. There's no need to subject yourself to 1.1 of the framework.


q:
Let's say we have 0.33, we need to output 1/3.

If we have 0.4, we need to output 2/5.

The idea is to make it human-readable to make the user understand "x parts out of y" as a better way of understanding data.

I know that percentages is a good substitute but I was wondering if there was a simple way to do this?

[A]
You might want to read
What Every Computer Scientist Should Know about Floating Point Arithmetic
.
You'll have to specify some precision by multiplying by a large number:
```
```
3.141592 * 1000000 = 3141592
```
```
then you can make a fraction:
```
```
3 + (141592 / 1000000)
```
```
and reduce via GCD...
```
```
3 + (17699 / 125000)
```
```
but there is no way to get the
intended
fraction out. You might want to
always
use fractions throughout your code instead --just remember to reduce fractions when you can to avoid overflow!


q:
In order to distribute a function I've written that depends on other functions I've written that have their own dependencies and so on without distributing every m-file I have ever written, I need to figure out what the full list of dependencies is for a given m-file. Is there a built-in/freely downloadable way to do this?

Specifically I am interested in solutions for MATLAB 7.4.0 (R2007a), but if there is a different way to do it in older versions, by all means please add them here.

[A]
For newer releases of Matlab (eg 2007 or 2008) you could use the built in functions:
mlint
dependency report and
coverage report
Another option is to use Matlab's profiler. The command is profile, it can also be used to track dependencies.  To use profile, you could do
```
```
>> profile on   % turn profiling on
>> foo;         % entry point to your matlab function or script
>> profile off  % turn profiling off
>> profview     % view the report
```
```
If profiler is not available, then perhaps the following two functions are (for pre-MATLAB 2015a):
depfun
depdir
For example,
```
```
>> deps = depfun('foo');
```
```
gives a structure, deps, that contains all the dependencies of foo.m.
From answers
2
, and
3
, newer versions of MATLAB (post 2015a) use
```
matlab.codetools.requiredFilesAndProducts
```
instead.
See answers
EDIT:
Caveats thanks to @Mike Katz comments
Remember that the Profiler will only
  show you files that were actually used
  in those runs, so if you don't go
  through every branch, you may have
  additional dependencies. The
  dependency report is a good tool, but
  only resolves static dependencies on
  the path and just for the files in a
  single directory.
Depfun is more reliable but gives you
  every possible thing it can think of,
  and still misses LOAD's and EVAL's.


q: We'd like a trace in our application logs of these exceptions - by default Java just outputs them to the console.

[A]
There are two ways:
/* Install a Thread.UncaughtExceptionHandler on the EDT */
Set a system property:
System.setProperty("sun.awt.exception.handler",MyExceptionHandler.class.getName());
I don't know if the latter works on non-SUN jvms.
--
Indeed, the first is not correct, it's only a mechanism for detecting a crashed thread.


q: I'm using Eclipse PHP Development Tools.  What would be the easiest way to access a file or maybe create a remote project trough FTP and maybe SSH and SFTP?.

[A]
have you checked
RSE
(
R
emote
S
ystem
E
xplorer) ? I think it's pretty close to what you want to achieve.
a blog post about it, with screenshots


q:
Let's say I have an array, and I know I'm going to be doing a lot of "Does the array contain X?" checks. The efficient way to do this is to turn that array into a hash, where the keys are the array's elements, and then you can just say
if($hash{X}) { ... }

Is there an easy way to do this array-to-hash conversion? Ideally, it should be versatile enough to take an anonymous array and return an anonymous hash.

[A]
```
```
%hash = map { $_ => 1 } @array;
```
```
It's not as short as the "@hash{@array} = ..." solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash.
What this does is take each element in the array and pair it up with a "1". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.


q:
I have been playing with Haml recently and really like the way the resulting code looks to me...the developer. I'm also not too worried about a designer being able to consume or change it...we're a small team.

That said, beginning work on a project we believe will generate quite a bit of traffic (who doesn't?). I'm concerned that there are things I just don't know about haml. Is there anything erb can do that haml can't? Does haml have a negative effect as a project grows? Are there other things that should be considered?

And finally...how does Haml compare speedwise to erubis? I see that it supposedly beats erb and eruby now...

Thanks!

[A]
I would personally recommend us erubis in precompiled templates.
Especially if there's no need for dynamic templating. Then your biggest slowdown will be limited by the speed at which ruby can parse ruby.
I'd probably set up a small cron job that just monitors for changed source templates and autocompiles them on-change that you can turn off when not in use.
Compile once, use many.
Oh, and if you're really concerned about speed, Tenjin may be worth a look too ( same creators as erubis )
http://www.kuwata-lab.com/tenjin/rbtenjin-examples.html


q:
I have a Windows Workflow application that uses classes I've written for COM automation. I'm opening Word and Excel from my classes using COM.

I'm currently implementing IDisposable in my COM helper and using Marshal.ReleaseComObject(). However, if my Workflow fails, the Dispose() method isn't being called and the Word or Excel handles stay open and my application hangs.

The solution to this problem is pretty straightforward, but rather than just solve it, I'd like to learn something and gain insight into the right way to work with COM. I'm looking for the "best" or most efficient and safest way to handle the lifecycle of the classes that own the COM handles. Patterns, best practices, or sample code would be helpful.

[A]
I can not see what failure you have that does not calls the Dispose() method. I made a test with a sequential workflow that contains only a code activity which just throws an exception and the Dispose() method of my workflow is called twice (this is because of the standard WorkflowTerminated event handler). Check the following code:
Program.cs
```
```
class Program
    {
        static void Main(string[] args)
        {
            using(WorkflowRuntime workflowRuntime = new WorkflowRuntime())
            {
                AutoResetEvent waitHandle = new AutoResetEvent(false);
                workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
                {
                    waitHandle.Set();
                };
                workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)
                {
                    Console.WriteLine(e.Exception.Message);
                    waitHandle.Set();
                };

                WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(WorkflowConsoleApplication1.Workflow1));
                instance.Start();

                waitHandle.WaitOne();
            }
            Console.ReadKey();
        }
    }
```
```
Workflow1.cs
```
```
public sealed partial class Workflow1: SequentialWorkflowActivity
    {
        public Workflow1()
        {
            InitializeComponent();
            this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode);
        }

        [DebuggerStepThrough()]
        private void codeActivity1_ExecuteCode(object sender, EventArgs e)
        {
            Console.WriteLine("Throw ApplicationException.");
            throw new ApplicationException();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Here you must free your resources
                // by calling your COM helper Dispose() method
                Console.WriteLine("Object disposed.");
            }
        }
    }
```
```
Am I missing something? Concerning the lifecycle-related methods of an Activity (and consequently of a Workflow) object, please check this post:
Activity "Lifetime" Methods
. If you just want a generic article about disposing, check
this
.


q: I'm looking for the total commit charge.

[A]
Here's an example using WMI:
```
```
strComputer = "."

Set objSWbemServices = GetObject("winmgmts:\\" & strComputer)
Set colSWbemObjectSet = _
 objSWbemServices.InstancesOf("Win32_LogicalMemoryConfiguration")

For Each objSWbemObject In colSWbemObjectSet
 Wscript.Echo "Total Physical Memory (kb): " & _
 objSWbemObject.TotalPhysicalMemory
 WScript.Echo "Total Virtual Memory (kb): " & _
 objSWbemObject.TotalVirtualMemory
 WScript.Echo "Total Page File Space (kb): " & _
 objSWbemObject.TotalPageFileSpace
Next
```
```
If you run this script under CScript, you should see the number of kilobytes of physical memory installed on the target computer displayed in the command window. The following is typical output from the script:
Total Physical Memory (kb): 261676
Edit:
Included total page file size property also
taken from:
http://www.microsoft.com/technet/scriptcenter/guide/sas_wmi_dieu.mspx?mfr=true


q:
I have a web application that is dynamically loading PDF files for viewing in the browser.
Currently, it uses "innerHTML" to replace a div with the PDF Object.  This works.

But, is there a better way to get the ID of the element and set the "src" or "data"  parameter for the Object / Embed and have it instantly load up a new document?
I'm hoping the instance of Adobe Acrobat Reader will stay on the screen, but the new document will load into it.

Here is a JavaScript example of the object:

document.getElementById(`divPDF`).innerHTML = `<OBJECT id='objPDF' DATA="'+strFilename+'" TYPE="application/pdf" TITLE="IMAGING" WIDTH="100%" HEIGHT="100%"></object>`;

Any insight is appreciated.

[A]
I am not sure if this will work, as I have not tried this out in my projects.
(Looking at your JS, I believe you are using jQuery. If not, please correct me)
Once you have populated the divPDF with the object you might try the code below:
```
```
$("objPDF").attr({
    data: "dir/to/newPDF"
});
```
```
Again, I am not sure if this will work for your particular needs but if you attach this code to an event handler you can switch out the data of the object.
You could also wrap it in a function to be used over and over again:
```
```
function pdfLoad(dirToPDF) {
    $("objPDF").attr({
        data: dirToPDF
    });
}
```
```


q:
I have a simple table  comments (id INT, revision INT, comment VARCHAR(140)) with some content like this:

1|1|hallo1|
1|2|hallo2|
1|3|hallo3|
2|1|hallo1|
2|2|hallo2|

I'm searching for an SQL statement which will return each comment with the highest revision:

1|3|hallo3|
2|2|hallo2|

I've come up with this solution:

select id, revision, comment
  from comments
  where revision = (
      select max(revision)
        from comments as f
        where f.id = comments.id
  );

but it is very slow on large data sets. Are there any better queries to accomplish this?

[A]
Make sure you have your indexes set up appropriately.  Indexing on id, revision would be good.
Here's a different take on your query. Haven't checked its execution plan, but if you set up the index well it should help:
```
```
SELECT c.*
  FROM comments c
  INNER JOIN (
        SELECT id,max(revision) AS maxrev
          FROM comments
          GROUP BY id
  ) b
    ON c.id=b.id AND c.revision=b.maxrev
```
```
Editted to add:
If you're on SQL Server, you might want to check out Indexed Views as well:
http://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx
Editted again to add info:
```
```
Subquery:
25157 records
2 seconds
Execution plan includes an Index Seek (82%) base and a Segment (17%)

Left Outer Join:
25160 records
3 seconds
Execution plan includes two Index Scans @ 22% each with a Right Outer Merge at 45% and a Filter at 11%
```
```
I'd still go with the sub query.


q:
How do I see if a certain object has been loaded, and if not, how can it be loaded, like the following?

if (!isObjectLoaded(someVar)) {
    someVar= loadObject();
}

[A]
```
typeof(obj)
```
would return "object" for an object of a class among other possible values.


q:
When someone talks about a variables storage class specifier, what are they talking about?

They also often talk about variable linkage in the same context, what is that?

[A]
The storage class specifier controls the
storage
and the
linkage
of your variables. These are two concepts that are different.
C specifies the following specifiers for variables: auto, extern, register, static.
Storage
The storage duration determines how long your variable will live in ram.
There are three types of storage duration: static, automatic and dynamic.
static
If your variable is declared at file scope, or with an extern or static specifier, it will have static storage. The variable will exist for as long as the program is executing. No execution time is spent to create these variables.
automatic
If the variable is declared in a function, but
without
the extern or static specifier, it has automatic storage. The variable will exist only while you are executing the function.  Once you return, the variable no longer exist.  Automatic storage is typically done on the stack.  It is a very fast operation to create these variables (simply increment the stack pointer by the size).
dynamic
If you use malloc (or new in C++) you are using dynamic storage.  This storage will exist until you call free (or delete). This is the most expensive way to create storage, as the system must manage allocation and deallocation dynamically.
Linkage
Linkage specifies who can see and reference the variable. There are three types of linkage: internal linkage, external linkage and no linkage.
no linkage
This variable is only visible where it was declared. Typically applies to variables declared in a function.
internal linkage
This variable will be visible to all the functions within the file (called a
translation unit
), but other files will not know it exists.
external linkage
The variable will be visible to other translation units.  These are often thought of as "global variables".
Here is a table describing the storage and linkage characteristics based on the specifiers
```
Storage Class   Function            File
  Specifier        Scope              Scope
-----------------------------------------------------
  none           automatic         static
                 no linkage        external linkage

 extern          static            static
                 external linkage  external linkage

 static          static            static
                 no linkage        internal linkage

  auto           automatic         invalid
                 no linkage

register         automatic         invalid
                 no linkage
```


q: I have two DateTime objects: StartDate and EndDate. I want to make sure StartDate is before EndDate. How is this done in C#?

[A]
```
```
if(StartDate < EndDate)
{}
```
```
DateTime supports normal comparision operators.


q: My Vista application needs to know whether the user has launched it "as administrator" (elevated) or as a standard user (non-elevated). How can I detect that at run time?

[A]
The following C++ function can do that:
```
```
HRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet );

/*
Parameters:

ptet
    [out] Pointer to a variable that receives the elevation type of the current process.

    The possible values are:

    TokenElevationTypeDefault - This value indicates that either UAC is disabled,
        or the process is started by a standard user (not a member of the Administrators group).

    The following two values can be returned only if both the UAC is enabled
    and the user is a member of the Administrator's group:

    TokenElevationTypeFull - the process is running elevated.

    TokenElevationTypeLimited - the process is not running elevated.

Return Values:

    If the function succeeds, the return value is S_OK.
    If the function fails, the return value is E_FAIL. To get extended error information, call GetLastError().

Implementation:
*/

HRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet )
{
    if ( !IsVista() )
        return E_FAIL;

    HRESULT hResult = E_FAIL; // assume an error occurred
    HANDLE hToken   = NULL;

    if ( !::OpenProcessToken(
                ::GetCurrentProcess(),
                TOKEN_QUERY,
                &hToken ) )
    {
        return hResult;
    }

    DWORD dwReturnLength = 0;

    if ( ::GetTokenInformation(
                hToken,
                TokenElevationType,
                ptet,
                sizeof( *ptet ),
                &dwReturnLength ) )
    {
            ASSERT( dwReturnLength == sizeof( *ptet ) );
            hResult = S_OK;
    }

    ::CloseHandle( hToken );

    return hResult;
}
```
```


q:
On my desktop I have written a small Pylons app that connects to Oracle.   I'm now trying to deploy it to my server which is running Win2k3 x64. (My desktop is 32-bit XP) The Oracle installation on the server is also 64-bit.

I was getting errors about loading the OCI dll, so I installed the 32 bit client into C:\oracle32.

If I add this to the PATH environment variable, it works great.   But I also want to run the Pylons app as a service (using this recipe) and don't want to put this 32-bit library on the path for all other applications.

I tried using sys.path.append("C:\\oracle32\\bin") but that doesn't seem to work.

[A]
sys.path is python's internal representation of the PYTHONPATH, it sounds to me like you want to modify the PATH.
I'm not sure that this will work, but you can try:
```
```
import os
os.environ['PATH'] += os.pathsep + "C:\\oracle32\\bin"
```
```


q:
Suppose we have:

interface Foo
{
 bool Func(int x);
}

class Bar: Foo
{
  bool Func(int x)
  {
   return (x>0);
  }
}

class Baz: Foo
{
  bool Func(int x)
  {
   return (x<0);
  }
}

Now we can toss around Bar and Baz as a Foos and call their Func methods.

Delegates simplify this a little bit:

delegate bool Foo(int x);

bool Bar(int x)
{
 return (x<0);
}

bool Baz(int x)
{
 return (x>0);
}

Now we can toss around Bar and Baz as Foo delegates.

What is the real benefit of delegates, except for getting shorter code?

[A]
No, delegates are for method pointers. Then you can make sure that the signature of the method associated w/ the delegate is correct.
Also, then you don't need to know the structure of the class. This way, you can use a method that you have written to pass into a method in another class, and define the functionality you want to have happen.
Take a look at the
List<> class with the Find method
. Now you get to define what determines if something is a match or not, without requiring items contained in the class to implement IListFindable or something similar.


q: Simple question, how do you list the primary key of a table with T-SQL? I know how to get indexes on a table, but can't remember how to get the PK.

[A]
The system stored procedure
```
sp_help
```
will give you the information. Execute the following statement:
```
```
execute sp_help table_name
```
```


q:
Let's say I have two models, Classes and People. A Class might have one or two People as instructors, and twenty people as students. So, I need to have multiple relationships between the models -- one where it's 1->M for instructors, and one where it's 1->M for students.

Edit: Instructors and Students must be the same; instructors could be students in other classes, and vice versa.

I'm sure this is quite easy, but Google isn't pulling up anything relevant and I'm just not finding it in my books.

[A]
There are many options here, but assuming instructors are always instructors and students are always students, you can use inheritance:
```
```
class Person < ActiveRecord::Base; end  # btw, model names are singular in rails
class Student < Person; end
class Instructor < Person; end
```
```
then
```
```
class Course < ActiveRecord::Base  # renamed here because class Class already exists in ruby
  has_many :students
  has_many :instructors
end
```
```
Just remember that for single table inheritance to work, you need a
```
type
```
column in the
```
people
```
table.
using an association model might solve your issue
```
```
class Course < ActiveRecord::Base
  has_many :studentships
  has_many :instructorships
  has_many :students,    :through => :studentships
  has_many :instructors, :through => :instructorships
end

class Studentship < ActiveRecord::Base
  belongs_to :course
  belongs_to :student, :class_name => "Person", :foreign_key => "student_id"
end

class Instructorship < ActiveRecord::Base
  belongs_to :course
  belongs_to :instructor, :class_name => "Person", :foreign_key => "instructor_id"
end
```
```


q:
For example, given a type param method i'm looking for something like the part in bold

void MyMethod< T >() {

  if ( typeof(T).Implements( IMyInterface ) )
  {

  //Do something

else

  //Do something else

}

Anwers using C# 3.0 are also welcome, but first drop the .NET 2.0 ones please ;)

[A]
Type.IsAssignableFrom
```
```
if(typeof(IMyInterface).IsAssignableFrom(typeof(T)))
{
  // something
}
else
{
  // something else
}
```
```


q:
I have the feeling that is easy to find samples, tutorials and simple examples on Flex.

It seems harder to find tips and good practices based on real-life projects.

Any tips on how to :

How to write maintainable actionscript code

How to ensure a clean separation of concern. Has anybody used an MVC framework such as cairngorm, puremvc or easymvc on a real Flex project ?

How to fetch data from a server with blazeds/amfphp ?

How to reduce latency for the end-user ?

...

[A]
I work often with Flex in my job, and I will be happy to help.. but your questions deserve an article for each one :) I'll try some short answer.
Maintenable code: I think that the same rules of any other OO languages apply. Some flex-specific rules I'm use to follow: use strong typed variables, always consider dispatching events as the way for your UI components talk each other (a little more initial work, very flexible and decoupled later).
Frameworks: looked at it, read the documentation.. very nice, but I still feel that their complications are not balanced by the benefits they provide. Anyway I'd like to change my mind on this point..
Talking with server: Right now I'm using BlazeDS, it works very well.. there are many tutorials on the subject out there, if you find any trouble setting up it I would be happy to help.
Latency: Do you mean in client/server comunications? If so, you should explore the various type of channels BlazeDS implements.. pull-only, two-way http polling, near real-time on http (comet).. if you need more, LiveCycle Data Services ES, the commrcial implementation from which BlazeDS is born, among other things offer another protocol called RTMP, it isn't http-tunnelled so there can be problem with firewalls and proxies, but it offers better performance (there is a free closed-source version of LCDS). I use the standard http channels in intranet environments, and found no real performance problems even with large datasets.
Well.. quite a lot of stuff, can't be more specific now on each of this points, ask you if need :)


q:
Suppose I want to store many small configuration objects in XML, and I don't care too much about the format. The XMLDecoder class built into the JDK would work, and from what I hear, XStream works in a similar way.

What are the advantages to each library?

[A]
If you are planning on storing all those configuration objects in a single file, and that file will be quite large, both the options you've outlined above could be quite memory intensive, as they both require the entire file to be read into memory to be deserialized.
If memory usage is a concern (the file containing the XML will be very large), I recommend
SAX
.
If memory usage is not a concern (the file containing the XML will not be very large), I'd use whatever is included with the default JRE (in this case XMLDecoder) just to remove 3rd party dependencies.