q: In ActionScript, how can you test if an object is defined, that is, not null?

[A]
Just test it against null.
```
```
var someObj:Object = getSomeObjectOrMaybeNull();
if(someObj == null) {
  trace("someObj is null!");
} else {
  trace("someObj is not null!");
}
```
```


q:
I am powering a web search using Sphinx, and am getting the following error message while building the indexes:

WARNING: sort_hits: merge_block_size=76 kb too low, increasing mem_limit may improve performance

The problem is I can't find any documentation on where this setting is configured. I'm somewhat versed on Sphinx setup, so I just need to know where the setting is configured.

[A]
This is probably happening because you're trying to index too many items at once.  Make sure you're using
ranged queries
.  If you're already using ranged queries, increasing the
```
mem_limit
```
, as it suggests, may help.  The
```
merge_block_size
```
is based on
```
mem_limit
```
and the number of documents.
If you're curious as to how it generates that number, check out the source.  It's freely available.

s: huggingface

c: devops

d: intermediate


q:
My data is such that I want to display values for the Employee and the Supervisor for a particular record. Instead of describing it, I'll show you a rough example:

<table><tr>
<th colspan="3">Employee</th>
<th colspan="3">Supervisor</th>
</tr><tr>
<th>Name</th>
<th>Last Activity</th>
<th>Count</th>
<th>Name</th>
<th>Last Activity</th>
<th>Count</th>
</tr>
</table>

How can I create this for a GridView?  I essentially want 2 rows for the headings, and some of the cells should span more than one column.


q:
Is there a way to use Profiler to determine whether a table is being accessed by queries?

I saw an event named Object:Opened (Indicates when an object has been accessed, such as for SELECT, INSERT, or DELETE statements) and Object:Closed, but these do not seem to work.

In particular, I created a simple trace with both Object:Opened and Object:Closed with no filters (except the standard "Application Name not like 'SQL Profiler'" filter) and ran SELECT TOP 1 * FROM TableName, but no events were reported.

So, is there a way to use Profiler to determine if a table is being SELECTed from?

[A]
I'm not seeing those in SQL Server 2005.
In my experience, I look at
```
SQL:StmtStarting
```
AND
```
SP:StmtStarting
```
- you can filter
```
TextData
```
on
```
%TABLE_NAME%
```
.  This will even catch things inside SPs when you use
```
SP:StmtStarting
```
.
It's not bulletproof, because it has to use the
```
LIKE
```
syntax, but it might get you what you are looking for.


q:
I wouldn't dare do anything complex in a database without transactions. There is nearly always a simple to use in-built command. But when you start working with other persistent data you just don't get this simple to use transaction support. Some example are

file systems

web services (none that I've used)

Even in non-persistent data it is often useful to undo a block of work, following an exception. None of the standard data structures you get with a language, support transactions.

What I would like to know is, why are databases the special case?

Are there any useful links to the topic of transactional behavior out-side of databases?

[A]
Modern file systems do have transactions.  They're just transparent to the end user.
NTFS, XFS, JFS, EXT3, and ReiserFS all do, just to name a few.
And that's just internal to the file system.  Many OSes also support file locking (see flock(2) in the *NIX world, for instance) with exclusive (write) and shared (read) locks.
Edit:
If you think about it, file systems don't have isolation levels like modern DBs because once you finish reading a file, you traditionally close it if you didn't lock it.  Then you reopen it when you want to write to it.


q:
This problem occurred during daylight saving time change. After the change occurred, we've noticed that our server application started writing into the log incorrect time - one hour ahead which means that .NET caches time zone offset. We had to restart our application to resolve this problem.
I wrote a simple application to reproduce this problem. When I change the time zone while application is running, DateTime.Now property keeps producing the time in the old time zone.
Does anybody know if there is a workaround for this problem apart from restarting the application?

[A]
The most common recommendation is to store DateTime.UtcNow and, when you want to show localized time to the user, convert to local time accounting for daylight savings.
.NET provides for calculations involving daylight savings time with the
DaylightTime
and
TimeZone
classes, and the
ToLocalTime
method supposedly can convert UTC to local accounting for daylight savings time.


q:
How do you get the current time (not date AND time)?

Example: 5:42:12 PM

[A]
```
DateTime.Now.TimeOfDay
```
gives it to you as a
```
TimeSpan
```
(from midnight).
```
DateTime.Now.ToString("h:mm:ss tt")
```
gives it to you as a
string
.
DateTime reference:
https://msdn.microsoft.com/en-us/library/system.datetime


q:
Short of rolling your own.  There has to be something out there.  FlexLM/FlexNet is overpriced, and does not work for a company like ours.  The same goes for RLM.  There was one product I had hope in called LUM, but IBM no longer licenses the API.  So what else is available?  Or do you have any known way to get LUM?

Please help, I have been reviewing and searching on and off for over a year, and just can't find the right solution.  Maybe everyone just creates their own, we'd rather not.

[A]
Here's one product -- SoftwarePassport:
http://www.siliconrealms.com/
They purchased Armadillo, which used to be an inexpensive software protection and licensing scheme.  The price is higher than it was back then but I'll bet it's still less than FlexLM.
I do have one suggestion regarding licensing -- as a user and developer of licensed software.  Implement a "soft cutoff", so that your customers are not dead in the water if the licensing mechanism fails (or if the license expires).  Provide some way for them to keep running so that there's enough time to remedy the problem.


q:
How can I prevent the image tag that calls the associated image from displaying if no image is associated with the record?

<%= image_tag @agent.avatar.url %>

...gives me the text "Missing" if there is no image associated with that agent.  I want to test to see there is an image available first, then render the above tag if the test returns true.

Better yet, is there anyway for me to specify a default image if no image is specifically provided?

[A]
Okay, so I got one part of it.
Specifying a default image happens in the model
```
```
has_attached_file :avatar, :default_url => '/images/brokers/agents/anonymous_icon.jpg'
```
```


q:
What could the following line possibly mean?

my $x = shift;

[A]
This is usually an idiom for: $x is a local variable assigned to the first parameter passed to the subroutine, although.
```
```
my ($x) = @_;
```
```
is probably clearer (and it doesn't modify the argument list).


q:
I'm wondering where the callbacks are (or if there are anything) for animations in a CALayer. Specifically, for implied animations like altering the frame, position, etc. In a UIView, you could do something like this:

[UIView beginAnimations:@"SlideOut" context:nil];
[UIView setAnimationDuration:.3];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animateOut:finished:context:)];
CGRect frame = self.frame;
frame.origin.y = 480;
self.frame = frame;
[UIView commitAnimations];

Specifically, the setAnimationDidStopSelector is what I want for an animation in a CALayer. Is there anything like that?

TIA.

[A]
I answered my own question. You have to add an animation using
```
CABasicAnimation
```
like so:
```
```
CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"frame"];
anim.fromValue = [NSValue valueWithCGRect:layer.frame];
anim.toValue = [NSValue valueWithCGRect:frame];
anim.delegate = self;
[layer addAnimation:anim forKey:@"frame"];
```
```
And implement the delegate method
```
animationDidStop:finished:
```
and you should be good to go. Thank goodness this functionality exists! :D


q:
I've got a small piece of code that is parsing an index value to determine a cell input into Excel.  It's got me thinking...

What's the difference between

xlsSheet.Write("C" + rowIndex.ToString(), null, title);

and

xlsSheet.Write(string.Format("C{0}", rowIndex), null, title);

Is one "better" than the other? And why?

[A]
Before C# 6
To be honest, I think the first version is simpler - although I'd simplify it to:
```
```
xlsSheet.Write("C" + rowIndex, null, title);
```
```
I suspect other answers
may
talk about the performance hit, but to be honest it'll be minimal
if present at all
- and this concatenation version doesn't need to parse the format string.
Format strings are great for purposes of localisation etc, but in a case like this concatenation is simpler and works just as well.
With C# 6
String interpolation makes a lot of things simpler to read in C# 6. In this case, your second code becomes:
```
```
xlsSheet.Write($"C{rowIndex}", null, title);
```
```
which is probably the best option, IMO.


q:
Seems like there are two categories of APIs for websites today.

APIs which allow the functionality of the site to be extended like Facebook, Myspace, etc.  These APIs seem to be very diverse.

APIs which allow interaction with the existing site functionality like Twitter, Flickr, etc.  These all claim to be REST based, but are in reality simply "data over HTTP".

If you were creating a website that allowed both functional extension and outside interaction, what existing APIs would you use as a reference model?

[A]
I would check out OpenSocial, a movement to create an API Standard for social network sices.  They use REST for this and have a 'user' centric approach.  But this is a very well documented approach which might help for even a site that is not totally Social based.  If you are looking for some internal code implementations look at Drupals hook system and Wordpress.
http://code.google.com/apis/opensocial/


q:
I have stored a txt file as string in a database column. Now on one of my aspx page I have a link...I want to open a txt file when the user clicks on this link. How can i read a file from database. I know how to do this using streamreader for a file stored on the disk.

Thanks

[A]
This is going to take some clarification.
If the file is stored as a string in the database, all you have to do is read it into a string and display it in a page.
```
```
public void Page_Load(object sender, EventArgs e)
  var text = (from x in dataContext.MyTextTable where x.Id == someId select x.FileText).FirstOrDefault();

  this.textBox.Text = text;
}
```
```
Okay, here's what you need to do. Pseudocode follows:
Load the string from the database
Use the ToCharArray() method on the string to get an array of chars
Use the HttpResponse object to Write() the char array to the response stream
Here's some almost-compilable code:
```
```
public void Page_Load(object sender, EventArgs e)
{
  var text = Repository.GetTextFile(this.FileTextBox.Text).ToCharArray();

  Response.Clear();
  Response.AddHeader("Content-Disposition", "attachment; filename=" & this.FileTextBox.Text);
  Response.AddHeader("Content-Length", text.Length.ToString());
  Response.ContentType = "application/octet-stream";
  Response.Write(text, 0, text.length);
  Response.End();
}
```
```
I believe the mime type should be that rather than text/plain as the browser may attempt to open the file rather than saving it as an attachment.


q: How to get file name and revision number as a list starting from a designated folder?

[A]
```
cvs status
```
will give you that information in the following form per file:
```
```
===================================================================
File: test.pas      Status: Up-to-date

   Working revision:    1.4
   Repository revision: 1.4     /cvsroot/MyModule/test.pas,v
   Expansion option:    kv
   Commit Identifier:   86c473d9b385950
   Sticky Tag:          (none)
   Sticky Date:         (none)
   Sticky Options:      (none)
   Merge From:          (none)
```
```
(output is from CVSNT; Commit ID and Mergepoint will not be shown by vanilla CVS)
You can write a script to extract and reformat that information.


q:
I am in the process of researching/comparing CXF and Spring-WS for web services? I need to function both as a provider and a consumer of WS. In a nutshell, I have been told that Spring-WS is more configurable, but CXF is easier to get up and running. This question is subjective, but will help direct me in my research.

What experience do you have with either of these frameworks?

Have you run into any pitfalls with either framework?

Have you found any useful features provided by either that is possibly not provided by the other?

[A]
I think the biggest difference is Spring-WS is
only
'contract-first' whilst I believe CXF is normally 'contract-last'.
http://static.springsource.org/spring-ws/sites/1.5/reference/html/why-contract-first.html
Contract-last starts with Java code, so it is usually easier to get started with.
However, the WSDL it creates tends to be more fragile.


q:
In another Stack Overflow question Leon Timmermans asserted:

I would advice you not to use prototypes. They have their uses, but not for most cases and definitely not in this one.

Why might this be true (or otherwise)? I almost always supply prototypes for my Perl functions, and I've never before seen anyone else say anything bad about using them.

[A]
The problem is that Perl's function prototypes don't do what people think they do.  Their purpose is to allow you to write functions that will be parsed like Perl's built-in functions.
First of all, method calls completely ignore prototypes.  If you're doing OO programming, it doesn't matter what prototype your methods have.  (So they shouldn't have any prototype.)
Second, prototypes aren't strictly enforced.  If you call a subroutine with
```
&function(...)
```
, the prototype is ignored.  So they don't really provide any type safety.
Third, they're spooky action-at-a-distance.  (Especially the
```
$
```
prototype, which causes the corresponding parameter to be evaluated in scalar context, instead of the default list context.)
In particular, they make it hard to pass parameters from arrays.  For example:
```
```
my @array = qw(a b c);

foo(@array);
foo(@array[0..1]);
foo($array[0], $array[1], $array[2]);

sub foo ($;$$) { print "@_\n" }

foo(@array);
foo(@array[0..1]);
foo($array[0], $array[1], $array[2]);
```
```
prints:
```
```
a b c
a b
a b c
3
b
a b c
```
```
along with 3 warnings about
```
main::foo() called too early to check prototype
```
(if warnings are enabled).  The problem is that an array (or array slice) evaluated in scalar context returns the length of the array.
If you need to write a function that acts like a built-in, use a prototype.  Otherwise, don't use prototypes.
Note:  Perl 6 will have completely revamped and very useful prototypes.  This answer applies only to Perl 5.


q:
I'm working on developing a regular dump of our database. I'm using this script to create the backup and then feeding it through a regular cron job.  In the end we end up with a text file as well as an email archive of everything.

The problem we've encountered is the size of two of our tables.  They each have 60k fields and grow daily. I'm thinking incremental backup are the best solution for backup, but if it ever came to restoring it... It will be a huge project.

My question is a two parter:

a) Is there a more straight forward way to backup huge tables on a daily basis and, if not,

b) Is there an easy way to restore a backup from daily/weekly incremental backups?

Thanks!

[A]
You can use a crob job to execute mysqldump to dump the tables down that you wish to backup.  Then just use a differential backup on that file for the daily backup and do a full backup once a week.  The backup's heavy lifting should be done by your backup engine of choice.
Restoring a DB is never fun, so regardless it will be a big project.
http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html
Let me know if this works for you.


q:
Normally, the method of passing workflow parameters to the workflow happens in the call to RunWorkflow.  However, with the WorkflowServiceHost, there is no such method call involved.  You simply call the Open() method on the instance.  Any ideas?

Of course, the implication is that I add more parameters to the service contract, but these parameters are not relevant for the consumers of the service.  They are more like configuration values.

[A]
You could set up a OneWayToSource binding on the DatePicker.SelectedDate property which pushes the text value into the ObjectDataProvider MethodParameter.
Starts by creating the ObjectDataProvider:
```
```
<ObjectDataProvider ObjectType="{x:Type theObjectType}"
                        MethodName="GetDataForDate"
                        x:Key="odp">
        <ObjectDataProvider.MethodParameters>
            <System:DateTime>2008-01-01</System:DateTime>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
```
```
Then bind the SelectedDate property of the DatePicker to the ObjectDataProvider:
```
```
<dg:DatePicker x:Name="datePicker" >
    <dg:DatePicker.SelectedDate>
        <Binding Source="{StaticResource odp}"
                 Path="MethodParameters[0]"
                     BindsDirectlyToSource="True"
                     Mode="OneWayToSource"/>
    </dg:DatePicker.SelectedDate>
</dg:DatePicker>
```
```
And finally bind the ObjectDataProvider to your ObjectDataProvider:
```
```
<dg:DataGrid x:Name="dtgGrid"
             ItemsSource="{Binding Source={StaticResource odp}}"
             AutoGenerateColumns="False"/>
```
```


q:
I'm looking for Java code that can be used to generate sound at runtime - NOT playback of existing sound files.

For example, what's the best code for generating a sawtooth waveform at 440 Hz for a duration of 2 milliseconds? Source code appreciated!

I remember my Commodore 128 had a simple Sound command that took as parameters voice, frequency, waveform, and duration to define a sound.  That worked great in a lot of simple cases (quick and dirty games, experiments with sound, etc).

I am looking specifically for sound-effect like sounds, not music or MIDI (which the JFugue library covers quite well).

[A]
What you want is probably not a sound API but some kind of synthesizer code, I'm pretty sure you need more low-level sound driver control than Java would allow (it being a interpreted language normally running in a "sandbox").
But the good news is that a quick search for "
java sound synthesizing
" on google revealed a plugin called
JSyn
wich uses native C methods (wich I guessed was one way of doing it) to generate sound. It seems to be free for non-commercial use and available in commercial licenses as well. :)


q: Can anyone point me to an example of how to use ServletUnit to test JSP's?  Do I need I need to call registerServlet()?  If so, what class name do I pass?

[A]
You do not need to registerServlet if you are going use the default Jasper compiler. However, I needed Jasper jars and their dependencies on the CLASSPATH. The Maven dependencies I needed to get a basic JSP to compile and render were:
```
```
<dependency>
  <groupId>tomcat</groupId>
  <artifactId>jasper</artifactId>
  <version>3.3.2</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>tomcat</groupId>
  <artifactId>jasper-compiler</artifactId>
  <version>5.5.23</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>tomcat</groupId>
  <artifactId>tomcat-util</artifactId>
  <version>5.5.23</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>tomcat</groupId>
  <artifactId>core_util</artifactId>
  <version>3.3.2</version>
  <scope>test</scope>
</dependency>
```
```
I am stuck in a JDK1.4 project,so you may be able to use newer versions. I haven't gotten standard taglib working yet...


q:
I want to use the nltk libraries in c++.

Is there a glue language/mechanism I can use to do this?

Reason:
I havent done any serious programming in c++ for a while  and want to revise NLP concepts at the same time.

Thanks

[A]
I haven't tried directly calling Python functions from C++, but here are some alternative ideas...
Generally, it's easier to call C++ code from a high-level language like Python than the other way around.  If you're interested in this approach, then you could create a C++ codebase and access it from Python.  You could either directly use the external API provided by python [it should be described somewhere in the Python docs] or use a tool like SWIG to automate the C++-to-Python wrapping process.
Depending on how you want to use the library, you could alternatively create Python scripts which you call from C++ with the
exec*
functions.


q: Is there a way to tell SQL Server to not cache certain types of plans?  For example, if you have a large number of users queries coming from SQL Server Management Studio, is there a way to tell these to not be cached in the plan cache, thus taking up memory and other resources?  Are there other behavioral tweaks that you can do to prevent adhoc queries from taking up resources on a production server?

[A]
I don't know of any ... but, in general, I think that in most high-performance situations where you'd be worried about this level of detail, you'd probably want a production database that is protected from user-submitted queries in the first place. In production, it's not the little bit of memory for these query plans that will hurt you, it's users submitting queries that issue massive locks and grind your performance to a halt. As a basic architectural issue, you might consider either:
getting a replicated offline server that users can hit with their ad-hoc queries; or
restricting user interactions with the DB to a set of given stored procedures
If you really can't do either of those, and user-submitted query plans are really getting you down, you must be in a pretty unique situation. If you want to edit the question with more details, you might get better suggestions.
(Sorry I didn't answer the question you actually asked; hopefully someone more knowledgeable than me will do so.)


q:
I have a folder "FolderA" which contains three sub-folders: foldera1 foldera2 and foldera3

I need to write a batch file which resides inside "FolderA". It should delete all the folders under "FolderA" as a cleanup activity. I don't know the folder names. rmdir does not support wild cards.

Could someone provide a solution for this small problem?

[A]
something like :
```
```
for /f %%a in ('dir /ad /b') do (rmdir /S /Q "%%a")
for /d %%a in (*) do (rmdir /S /Q "%%a")
```
```
should do the trick. The second form allow some wildcard selection for directories.
To test it outside a script, in a plain DOS session:
```
```
for /f %a in ('dir /ad /b') do (rmdir /S /Q "%a")
for /d %a in (*) do (rmdir /S /Q "%a")
```
```
Note the
double quotes
, in order to be able to delete directories with spaces in them.


q: Is there a way to prompt the user for input during a NAnt build? I want to execute a command that takes a password, but I don't want to put the password into the build script.

[A]
A solution I have used many times is to have a
local
config file containing such things as passwords, connection strings etc. that are specific to each developer. The NAnt build script will include these settings when building.
The local config file does not exist in the version control system so passwords are not exposed. The first time a developer checks out a code base and tries to build he has to create this config file. To make it easy for him, there could be a template file available such as my.config.template containing all the properties that can be customized.


q: We have been using the Client Access ODBC drivers when accessing AS/400 data from our .net applications and SQL DTS/SSIS packages. Are there third party drivers that provide better performance or functionality?

[A]
I know this is on the other side of the hill, but I've been using
JTOpen
as a JDBC (well, Java ...) driver in a previous project. This is an OpenSource version of the
IBM Toolbox for Java
. As such it is usually some versions ahead of the IBM release and had fewer bugs. My experience with this driver was very positive.


q:
I have a simple page that displays a user's email addresses in a table.  I also have a textbox underneath the table and an "add" button.  Currently, I am using a simple form post that is handled by a controller that will add the e-mail address to the database and reload the page.  This works fine, but I'm looking to streamline the process by using jQuery and AJAX so that the page doesn't need to be refreshed.

What's the best way to go about doing this?  I imagine I'll have to set up an event listener for the button's click event, perform an AJAX call to a url like "Email/Add".  Where I get lost is figuring out what type of information to return from that controller action and how that information can get parsed on the client side to update the table of e-mail addresses.  Are there any good samples of this out there?

[A]
You should use XML or JSON. I prefer JSON because it's easy to parse back on the javascript side.
In the click handler for the add button, make an AJAX call to some MVC path specifies what email has been added. Make the code for that path insert the email specified. Then, just return a result:
```
```
{
    result: 'SUCCESS',
    description: 'Email Added.'
}
```
```
Then, in your AJAX callback, parse the result like so:
```
```
//This function abstracts away the strangeness in dealing with the eval method and returning JSON objects
//If there is a better way, let me know
function ParseJSON(jsonText) {
    var ret = null;
    eval('ret = '+jsonText);
    return ret;
}

var ret = ParseJSON(response.value);;

if(ret.result == 'SUCCESS') {
    //Add a new TR to your table here
} else {
    //Display the error message here
    // alert(ret.description);
}
```
```
The result of 'SUCCESS' means that the server already added the email to the database. So, we just add the row into our table dynamically with JavaScript and you don't have to refresh the page.


q:
I'm storing many files of various lengths into a block-oriented medium (fixed-size e.g. 1024 bytes).  When reading back the file, each block will either be missing or correct (no bit errors or the like).  The missing blocks are random, and there's not necessarily any sequence to the missing blocks.  I'd like to be able to reassemble the entire file, as long as the number of  missing blocks is below some threshold, which probably varies with the encoding scheme.

Most of the literature I've seen deals with sequences of bit errors in a stream of data, so that wouldn't seem to apply.

A simple approach is to take N blocks at a time, then store a block containing the XOR of the N blocks.  If one of the N blocks is missing but the check block is not, then the missing block can be reconstructed.

Are there error-correcting schemes which are well suited to this problem?  Links to literature or code are appreciated.

[A]
Look into Reed-Solomon codes:
http://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction


q:
Given a columns' index, how can you get an Excel column name?

The problem is trickier than it sounds because it's not just base-26. The columns don't wrap over like normal digits would. Even the Microsoft Support Example doesn't scale beyond ZZZ.

Disclaimer: This is some code I had done a while back, and it came across my desktop again today. I thought it was worthy of posting here as a pre-answered question.

[A]
The answer I came up with is to get a little recursive.  This code is in VB.Net:
```
```
Function ColumnName(ByVal index As Integer) As String
        Static chars() As Char = {"A"c, "B"c, "C"c, "D"c, "E"c, "F"c, "G"c, "H"c, "I"c, "J"c, "K"c, "L"c, "M"c, "N"c, "O"c, "P"c, "Q"c, "R"c, "S"c, "T"c, "U"c, "V"c, "W"c, "X"c, "Y"c, "Z"c}

        index -= 1 ' adjust so it matches 0-indexed array rather than 1-indexed column

        Dim quotient As Integer = index \ 26 ' normal / operator rounds. \ does integer division, which truncates
        If quotient > 0 Then
               ColumnName = ColumnName(quotient) & chars(index Mod 26)
        Else
               ColumnName = chars(index Mod 26)
        End If
End Function
```
```
And in C#:
```
```
string ColumnName(int index)
{
    index -= 1; //adjust so it matches 0-indexed array rather than 1-indexed column

    int quotient = index / 26;
    if (quotient > 0)
        return ColumnName(quotient) + chars[index % 26].ToString();
    else
        return chars[index % 26].ToString();
}
private char[] chars = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
```
```
The only downside it that it uses 1-indexed columns rather than 0-indexed.


q:
I am developing a site that makes extensive use of JavaScript (jQuery). I regularly get the IE 'Stop running this script?' error dialog when I try to close the browser.

I'm guessing the problem occurs because the site is a single page that uses AJAX, so there are no postbacks to reset IE's count of commands executed.

Client-side registry hacking is not an option.

Does anyone know a way to get around this error?

UPDATE: The page has a number (~10) interval timers that poll continually on 30 or 60 second  intervals.

[A]
Do you by chance use a window.onunload handler? If you do, you might check that you don't have an infinite loop in there.
To check, at the bottom of your javascript do:
```
```
window.onunload = null;
```
```
and test again.


q: How do you repopulate a form in ASP.NET MVC that contains a DropDownList?

[A]
I believe you are asking how to maintain the value for a dropdown list after a form is submitted and re-displayed.  If so, please see below for a
VERY SIMPLE
example:
Create a new MVC app (using MVC beta) and place the following in HomeController:
```
```
private Dictionary<string, string> getListItems()
{
    Dictionary<string, string> d = new Dictionary<string, string>();
    d.Add("Apple", "APPL");
    d.Add("Orange", "ORNG");
    d.Add("Banana", "BNA");
    return d;
}

public ActionResult Index()
{
    Dictionary<string, string> listItems = getListItems();
    SelectList selectList = new SelectList(listItems, "Value", "Key");
    ViewData["FruitDropDown"] = selectList;

    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection form)
{

    string selectedItem = form["FruitDropDown"];

    Dictionary<string, string> listItems = getListItems();
    SelectList selectList = new SelectList(listItems, "Value", "Key", selectedItem);
    ViewData["FruitDropDown"] = selectList;

    ViewData["Message"] = "You selected ID:" + selectedItem;

    return View();

}
```
```
And place this in Home\Index.aspx in between the MainContent tags:
```
```

<%= ViewData["Message"] %>

<% using (Html.BeginForm()) { %>
<%= Html.DropDownList("FruitDropDown","(select a fruit)") %>
<input type="submit" value="Submit" />
<% } %>
```
```


q:
Does anyone know of some good tutorials that explain how to use the JQuery Slider.

I've found a few, but none of them really present what I need in clear terms.  What I really need to figure out how to do is make the slider go from 1.0 - 5.0 (including all tenths) and when it changes set a hidden control based on that value.

Thanks.

[A]
The
documentation on the jQuery site
is pretty good.
```
```
$('#mySlider').slider({
    min : 1,
    max : 5,
    stepping: .1,   // or, steps: 40
    change : function (e, ui) {
        $('#myHiddenInput').val(ui.value);
    }
})
```
```


q: I have a vertical menu in my system which is basically made of HTML ul/li with CSS styling (see image below). However I don't want the li items which are wider than the menu to wrap, I would prefer them to overflow with a horizontal scroll bar at the bottom of the menu. How can I do this in CSS?

[A]
Use
```
white-space:nowrap
```
. Like so:
```
```
li {
  white-space:nowrap;
}
```
```
Here's some
documentation
.


q:
I've got a button that I'm adding as a subview of a table view's tableHeaderView. The button appears fine, and tap-and-holding on it works intermittently - for the most part, though, it's unresponsive. I've tried adding it as a subview of the table itself; the effect is about the same. I thought the problem might be with the scroll view's touch interception, but disabling scrolling on the table has no effect either.

Am I doing something wrong? Has anyone else encountered this?

edit - to clarify, I'm talking about the main table header, not a section header, in a grouped-style table; think basically modeled after the "Contact" screen.

[A] You should consider that this is not the intended sue of the headerView and that an implementation such as that might result in rejection from the AppStore as a result of a HIG violation.  Given that the dimensions of a header are intended to be small, it is probably better to consider a restructuring of your view.  Having said that, there is no easy way to do it short of hand detecting touch events and determining the geometry yourself, then executing a selector based on the geometry - in short, rolling your own button class.


q:
I've got a large amount of data (a couple gigs) I need to write to a zip file in Python.  I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back.

Is there a way to feed a generator or a file-like object to the ZipFile library?  Or is there some reason this capability doesn't seem to be supported?

By zip file, I mean zip file.  As supported in the Python zipfile package.

[A]
gzip.GzipFile writes the data in gzipped chunks , which you can set the size of your chunks according to the numbers of lines read from the files.
an example:
```
```
file = gzip.GzipFile('blah.gz', 'wb')
sourcefile = open('source', 'rb')
chunks = []
for line in sourcefile:
  chunks.append(line)
  if len(chunks) >= X:
      file.write("".join(chunks))
      file.flush()
      chunks = []
```
```


q:
I am hoping to dynamically update a ModelForm's inline Meta class from my view. Although this code seems to update the exclude list in the Meta class, the output from as_p(), as_ul(), etc does not reflect the updated Meta exclude.

I assume then that the html is generated when the ModelForm is created not when the as_*() is called. Is there a way to force the update of the HTML?

Is this even the best way to do it? I just assumed this should work.

Thoughts?

from django.forms import ModelForm

from testprogram.online_bookings.models import Passenger

class PassengerInfoForm(ModelForm):

    def set_form_excludes(self, exclude_list):
        self.Meta.exclude = excludes_list

    class Meta:
        model = Passenger
        exclude = []

[A]
The Meta class is used to dynamically construct the form definition - so by the time you've created the ModelForm instance, the fields not in the exclude have already been added as the new object's attributes.
The normal way to do it would be to just have multiple class definitions for each possible exclude list.  But if you want the form itself to be dynamic, you'll have to create a class definition on the fly.  Something like:
```
```
def get_form(exclude_list):
    class MyForm(ModelForm):
        class Meta:
            model = Passenger
            exclude = exclude_list
    return MyForm

form_class = get_form(('field1', 'field2'))
form = form_class()
```
```
UPDATE
:  I just revisited this post and thought I'd post a little more idiomatic way to handle a dynamic class:
```
```
def PassengerForm(exclude_list, *args, **kwargs):
    class MyPassengerForm(ModelForm):
        class Meta:
            model = Passenger
            exclude = exclude_list

        def __init__(self):
            super(MyPassengerForm, self).__init__(*args, **kwargs)

    return MyPassengerForm()

form = PassengerForm(('field1', 'field2'))
```
```


q:
We have a Silverlight application that needs to load a number of .png files.  We can load the images OK, but Silverlight doesn't support reading the pixel data from the Image class.

Can anyone suggest a simple solution for getting at this data?  Our current best bet would be a third party .png loading library, but we are having trouble finding a suitable one.

[A]
There is no built in classes for doing pixel based imagine manipulation/generation i n Silverlight. You need to implement your own PNG Encoder/Decoder that works on an byte array containing the image information. Joe Stegman has implemented one such encoder you should check out. He got lots of great information about "editable images" in Silverlight over at
http://blogs.msdn.com/jstegman/
. He does things like applying filters to images, generating mandlebrots and more.
This blog discuss a JPEG Silverilght Encoder (FJCore) you can use to resize and recompress photos client size:
http://fluxcapacity.net/2008/07/14/fjcore-to-the-rescue/
Another tool is "Fluxify" which lets you resize and upload photos using Silverilght 2. Can be found over at
http://fluxtools.net/
So yes, client side image processing can definitely be done in Silverilght 2. Happy hacking!


q: I'm preferably looking for a SQL query to accomplish this, but other options might be useful too.

[A]
```
```
SELECT LAST_DDL_TIME, TIMESTAMP
FROM USER_OBJECTS
WHERE OBJECT_TYPE = 'PROCEDURE'
AND OBJECT_NAME = 'MY_PROC';
```
```
```
LAST_DDL_TIME
```
is the last time it was compiled.
```
TIMESTAMP
```
is the last time it was changed.
Procedures may need to be recompiled even if they have not changed when a dependency changes.


q:
How can I validate date strings in Perl?  I'd like to account for leap years and also time zones.  Someone may enter dates in the following formats:

11/17/2008
11/17/2008 3pm
11/17/2008 12:01am
11/17/2008 12:01am EST
11/17/2008 12:01am CST

[A]
CPAN
has many packages for dealing with dates, such as
DateTime
and
Date::Manip
. To parse your date, the Date::Parse module in
TimeDate
might work (yes, there are both DateTime and TimeDate).
In general, whenever you need to do something in Perl, check CPAN. There's probably a module for it. Look at what's available and see what fits your situation.
Good luck, :)


q:
Can someone show me a regex to select #OnlinePopup_AFE53E2CACBF4D8196E6360D4DDB6B70 its okay to assume #OnlinePopup

~DCTM~dctm://aicpcudev/37004e1f8000219e?DMS_OBJECT_SPEC=RELATION_ID#OnlinePopup_AFE53E2CACBF4D8196E6360D4DDB6B70_11472026_1214836152225_6455280574472127786

[A]
NB: The following is .NET Regex syntax, modify for your flavour.
The following:
```
```
#[^_]+_[^_]+
```
```
will match:
Hash
One or more characters until an underscore
Underscore
One or more characters until an underscore
If the first bit is constant, and you want to be more specific you could use:
```
```
#OnlinePopup_[A-F0-9]+
```
```
This will match
OnlinePopup_ (exactly)
One or more hex characters until a non Hex character


q: Does anyone have a list of email addresses that I can use to test my JS address validation script?  I'm looking for as complete of a list as is reasonable to test the most common edge cases, if not all cases.

[A]
Examples valid according to RFC2822
me@example.com
a.nonymous@example.com
name+tag@example.com
name\@tag@example.com – this is a valid email address containing two @ symbols.
spaces\ are\ allowed@example.com
"spaces may be quoted"@example.com
!#$%&'*+-/=.?^_`{|}~@[1.0.0.127]
!#$%&'*+-/=.?^_`{|}~@[IPv6:0123:4567:89AB:CDEF:0123:4567:89AB:CDEF]
me(this is a comment)@example.com – comments are discouraged but not prohibited by RFC2822.
Examples invalid according to RFC2822s
me@
@example.com
me.@example.com
.me@example.com
me@example..com
me.example@com
me\@example.com
From :
http://en.wikibooks.org/wiki/JavaScript/Best_Practices


q:
Where can I set it? I need files to be encoded in UTF-8 by default... there is nothing in Tools -> Options or any other menu as far as I know :(

P.S. I don't need to set default encoding for Project or so, I need it to be default for any files I create. Thanks for your help :)

[A]
IIRC, source files in visual studio are already encoded as UTF-8.
However, if I'm wrong or if you just want to force any specific coding, you can do it by choosing the
```
Save As...
```
option for the file and checking the pull down options under the save button from there.


q:
When I create a new instance of a ChannelFactory:

var factory = new ChannelFactory<IMyService>();

and that I create a new channel, I have an exception saying that the address of the Endpoint is null.

My configuration inside my web.config is as mentioned and everything is as it is supposed to be (especially the address of the endpoint).

If I create a new MyServiceClientBase, it loads all the configuration from my channel factory:

var factoryWithClientBase = new MyServiceClientBase().ChannelFactory;
Console.WriteLine(factoryWithClientBase.Endpoint.Address); //output the configuration inside the web.config

var factoryWithChannelFactory = new ChannelFactory<IMyService>();
Console.WriteLine(factoryWithChannelFactory.Endpoint.Address); //output nothing (null)

Why?

[A]
Will it work if you provide the endpoint with a name like this in Web.Config:
```
```
<endpoint address="http://localhost:2000/MyService/" binding="wsHttpBinding"
    behaviorConfiguration="wsHttpBehaviour" contract="IService"
    name="MyWsHttpEndpoint" />
```
```
And create the channel using ChannelFactory like this:
```
```
var factory = new ChannelFactory<IMyService>("MyWsHttpEndpoint");
```
```


q:
If I have...

class Bunny < ActiveRecord::Base
  has_many :carrots
end

...how can I check in the View if @bunny has any carrots?  I want to do something like this:

<% if @bunny.carrots? %>
  <strong>Yay! Carrots!</strong>
  <% for carrot in @bunny.carrots %>
    You got a <%=h carrot.color %> carrot!<br />
  <% end %>
<% end %>

I know @bunny.carrots? doesn't work -- what would?

[A]
either:
```
```
if @bunny.carrots.length>0
```
```
or
```
```
unless @bunny.carrots.nil? || @bunny.carrots.length>0
```
```
or
```
```
if @bunny.carrots.any?
```
```
by the way, you will find more operations on collections if you use irb or script/console with require 'irb/completion'


q:
I'm using JPA (Hibernate's implementation) to annotate entity classes to persist to a relational database (MySQL or SQL Server). Is there an easy way to auto generate the database schema (table creation scripts) from the annotated classes?

I'm still in the prototyping phase and anticipate frequent schema changes. I would like to be able to specify and change the data model from the annotated code. Grails is similar in that it generates the database from the domain classes.

[A]
You can use
hbm2ddl
from Hibernate. The docs are
here
.


q: Is there any way to force Text-Mate to use a two-space tab instead of a full tab when editing HTML (Rails) documents?

[A]
Yes. There's a pop-up menu near the bottom middle of the window that probably reads
```
Tabs: 4
```
or something like that. Click on it and hange it to
```
2
```
and
```
Soft Tabs
```
.
You should have an
```
rhtml
```
or
```
erb
```
document (or whatever file type you want to change) open for editing when doing this. The changes will stick for all documents of that type.


q: Is it possible to write a PL/SQL query to identify a complete list of a stored procedures dependencies? I'm only interested in identifying other stored procedures and I'd prefer not to limit the depth of nesting that it gets too either. For example, if A calls B, which calls C, which calls D, I'd want B, C and D reported as dependencies for A.

[A]
On
this page
, you will find the following query which uses the
PUBLIC_DEPENDENCY
dictionary table:
```
```
SELECT lvl
     , u.object_id
     , u.object_type
     , LPAD (' ', lvl) || object_name obj
   FROM ( SELECT LEVEL lvl, object_id
            FROM SYS.public_dependency s
         START WITH s.object_id =
                      ( SELECT object_id
                          FROM user_objects
                         WHERE object_name = UPPER ('&OBJECT_NAME')
                           AND object_type = UPPER ('&OBJECT_TYPE'))
         CONNECT BY s.object_id = PRIOR referenced_object_id
         GROUP BY LEVEL, object_id) tree
      , user_objects u
  WHERE tree.object_id = u.object_id
ORDER BY lvl
/
```
```


q:
I get an error when I compile this code:

using System;

public struct Vector2
{
    public event EventHandler trigger;

    public float X;
    public float Y;

    public Vector2 func()
    {
        Vector2 vector;
        vector.X = 1;
        vector.Y = 2;
        return vector;  // error CS0165: Use of unassigned local variable 'vector'
    }
}

hi!

The compiler says: "Use of unassigned local variable 'vector'" and points to the return value. It looks to me that Vector2 become a reference type (without the event member it acts normally). What is happening?

[A]
In C# you still need to 'new' a struct to call a constructor unless you are initializing
all
the fields.  You left EventHandler member 'trigger' unassigned.
Try either assigning to 'trigger' or using:
```
```
Vector2 vector = new Vector2()
```
```
The new object is
not
allocated on the heap, it is still allocated on the functions stack.
To quote
MSDN
:
When you create a struct object using
  the new operator, it gets created and
  the appropriate constructor is called.
  Unlike classes, structs can be
  instantiated without using the new
  operator.
If you do not use new,
the
  fields will remain unassigned and
the
object cannot be used
until all of the
  fields are initialized.


q:
I would like to be able to manipulate the DOM just before my page is sent to be printed. Internet Explorer has an event on the window object called "onbeforeprint" but this is proprietary and isn't supported by other browsers. Is it possible to do this via javascript (jQuery in particular, if possible)?

Before you ask, I can't easily use a print media stylesheet to apply the changes as the elements I need to change have inline styles which can't be overridden with a global stylesheet. I need to override these inline styles for print purposes. It should be possible to modify the existing jQuery if needs be, however that would be a more time-consuming and risky change.

Cheers,
Zac

[A]
Adding
```
!important
```
after a property in your CSS will allow it to override the inline styles. For example:
```
```

Some Text

```
```
css:
```
```
.test {
     color: red !important;
  }
```
```
will be displayed red.


q:
I am wondering if it is possible to use Code Access Security, and a custom permission class (and attribute), without having to register the assembly that the attribute is in, in the GAC.

At the moment, I get a TypeLoadException when the method with my attribute is called, and I can't seem to get around it. Everything i've read seems to imply that you need to use the GAC in order to achieve this.

Does anyone have any insight?

I've tried to acheive the same end-goal with AOP using PostSharp or AspectDNG, but both of those add an addition dependency to my product, which is not ideal.


q: Is there a way in MySQL to select rows which fall on a specific day, as in Mondays, using a date column?

[A]
Look up the DAYOFWEEK() function
here
in the MySQL Online Docs


q:
I do remember seeing someone ask something along these lines a while ago but I did a search and couldn't find anything.

I'm trying to come up with the cleanest way to clear all the controls on a form back to their defaults (e.g., clear textboxes, uncheck checkboxes).

How would you go about this?

[A]
What I have come up with so far is something like this:
```
```
public static class extenstions
{
    private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() {
            {typeof(TextBox), c => ((TextBox)c).Clear()},
            {typeof(CheckBox), c => ((CheckBox)c).Checked = false},
            {typeof(ListBox), c => ((ListBox)c).Items.Clear()},
            {typeof(RadioButton), c => ((RadioButton)c).Checked = false},
            {typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()},
            {typeof(Panel), c => ((Panel)c).Controls.ClearControls()}
    };

    private static void FindAndInvoke(Type type, Control control)
    {
        if (controldefaults.ContainsKey(type)) {
            controldefaults[type].Invoke(control);
        }
    }

    public static void ClearControls(this Control.ControlCollection controls)
    {
        foreach (Control control in controls)
        {
             FindAndInvoke(control.GetType(), control);
        }
    }

    public static void ClearControls<T>(this Control.ControlCollection controls) where T : class
    {
        if (!controldefaults.ContainsKey(typeof(T))) return;

        foreach (Control control in controls)
        {
           if (control.GetType().Equals(typeof(T)))
           {
               FindAndInvoke(typeof(T), control);
           }
        }

    }

}
```
```
Now you can just call the extension method ClearControls like this:
```
```
private void button1_Click(object sender, EventArgs e)
    {
        this.Controls.ClearControls();
    }
```
```
EDIT:  I have just added a generic ClearControls method that will clear all the controls of that type, which can be called like this:
```
```
this.Controls.ClearControls<TextBox>();
```
```
At the moment it will only handle top level controls and won't dig down through groupboxes and panels.


q:
I would like to be able to detect what country a visitor is from on my website, using PHP.

Please note that I'm not trying to use this as a security measure or for anything important, just changing the spelling of some words (Americans seems to believe that the word "enrolment" has 2 Ls.... crazy yanks), and perhaps to give a default option in a "Select your country" list.

As such, using a Geolocation database is a tad over-the-top and I really don't want to muck about with installing new PHP libraries just for this, so what's the easiest/simplest way to find what country a visitor is from?

[A]
You can do some IP comparaison
without
having a whole library to do it.
Solution #1
Use an API, this way nothing is needed from your side. This is a web API that let you know the country:
```
```
Example: http://api.hostip.info/get_html.php?ip=12.215.42.19
 Return : Country: UNITED STATES (US)
```
```
Solution #2
But, Have you think to use the browser agent language? You might be able to know the type of english from it.
Solution #3
This website called
BlockCountry
let you have a list of IP by country. Of course, you do not want to block, but you can use the list of IP and compare them (get all US IP...) this might not be accurate...


q: What internal web service did your company implement first? What did you learn?

[A]
Let me see if I can get this conversation going. My company implemented a wrapper around the most common Active Directory look-up needs. I imagine this might be one of the most common things to do first in Microsoft/.NET shops.
Anybody implement a library of utility services? Write a facade to some SAP module? Wrap up some services for Human Resources? I'm curious to what people are working on.


q:
I know the general consensus for information like shopping cart items is to store them in session.  But what about objects that belong to a user that can be altered by other users?  Say, for instance, an eBay-like site.  If you store a user's "items" in session, which contain the current bid amount, and another user comes in and places a bid on that item, you would have to update both the item in the database as well as the item in session, wouldn't you?

In cases like these, are the only options to store in session and refresh whenever any action another user takes affects a person's session values or store everything in the database and retrieve it every time (could get expensive if, say, you have the bids displayed on the side panel of every page).

[A]
I would store it all in the database and retrieve it everytime. Depending on the volatility of the data caching for a few seconds may be in order. The biggest problem is keeping the two consistent.
I think that it isn't as expensive as you think to retrieve the data every time. Databases are very efficient if you are looking up based on a key. I'd err on the side of simplicity (store in DB and retrieve) until performance problems show up under load (ie in Load Testing).
If there is only going to be a handful of times, you may be able to use the Application Cache (unless you have more than one worker process/server) and make sure the DB and cache stay in sync.


q:
There's some object-oriented engineering principle that states something along the lines of "a class should only know about the contracts of the classes that it takes as arguments, or any internal ones it uses."

The counter-example, in C++, is:

Foo::bar( Baz* baz)
{
  baz()->blargh()->pants()->soil();  // this is bad, Foo knows about blarghs and pants
}

Does this principle have a name?  Also, the actual principle rather than my paraphrase above would be nice to see.

[A]
The
law of demeter
thanks to
Jim Burger
says:
The Law of Demeter (LoD), or Principle of Least Knowledge, is a design guideline for developing software, particularly object-oriented programs. The guideline was invented at Northeastern University towards the end of 1987, and can be succinctly summarized as “Only talk to your immediate friends.” The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents).


q: What is the simplest way to get the NT-ID of a user in a C# application? I would probably need to get it only having a name of the user, or maybe an email address.

[A]
From within SharePoint, you can get a user's Active Directory information (including display name and email) using SPUtility.ResolveWindowsPrincipal:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.utilities.sputility.resolvewindowsprincipal.aspx
For example:
```
```
SPPrincipalInfo pi = SPUtility.ResolveWindowsPrincipal(SPContext.Current.Site.WebApplication, "MYDOMAIN\\myusername", SPPrincipalType.All, false);
```
```
Outside of SharePoint, you want to look at the System.DirectoryServices namespace.


q:
I'm learning about Win32 programming, and the WinMain prototype looks like:

int WINAPI WinMain ( HINSTANCE instance, HINSTANCE prev_instance, PSTR cmd_line, int cmd_show )

I was confused as to what this WINAPI identifier was for and found:

#define WINAPI      __stdcall

What does this do?  I'm confused by this having something at all after a return type.  What is __stdcall for?  What does it mean when there is something between the return type and function name?

[A]
```
__stdcall
```
is the calling convention used for the function.  This tells the compiler the rules that apply for setting up the stack, pushing arguments and getting a return value.
There are a number of other calling conventions,
```
__cdecl
```
,
```
__thiscall
```
,
```
__fastcall
```
and the wonderfully named
```
__declspec(naked)
```
.
```
__stdcall
```
is the standard calling convention for Win32 system calls.
Wikipedia covers the
details
.
It primarily matters when you are calling a function outside of your code (e.g. an OS API) or the OS is calling you (as is the case here with WinMain).  If the compiler doesn't know the correct calling convention then you will likely get very strange crashes as the stack will not be managed correctly.


q:
I have a code sample that gets a SEL from the current object,

SEL callback = @selector(mymethod:parameter2);

And I have a method like

 -(void)mymethod:(id)v1 parameter2;(NSString*)v2 {
}

Now I need to move mymethod to another object, say myDelegate.

I have tried:

SEL callback = @selector(myDelegate, mymethod:parameter2);

but it won't compile.

[A]
You can't pass a parameter in a @selector().
It looks like you're trying to implement a callback.  The best way to do that would be something like this:
```
```
[object setCallbackObject:self withSelector:@selector(myMethod:)];
```
```
Then in your object's setCallbackObject:withSelector: method: you can call your callback method.
```
```
-(void)setCallbackObject:(id)anObject withSelector:(SEL)selector {
    [anObject performSelector:selector];
}
```
```


q:
My compact framework application creates a smooth-scrolling list by rendering all the items to a large bitmap surface, then copying that bitmap to an offset position on the screen so that only the appropriate items show.  Older versions only rendered the items that should appear on screen at the time, but this approach was too slow for a smooth scrolling interface.

It occasionally generates an OutOfMemoryException when initially creating the large bitmap.  If the user performs a soft-reset of the device and runs the application again, it is able to perform the creation without issue.

It doesn't look like this bitmap is being generated in program memory, since the application uses approximately the same amount of program memory as it did before the new smooth-scrolling methods.

Is there some way I can prevent this exception?  Is there any way I can free up the memory I need (wherever it is) before the exception is thrown?

[A]
Your bitmap definitely
is
being created in program memory.  How much memory the bitmap needs depends on how big it is, and whether or not this required size will generate the OutOfMemoryException depends on how much is available to the PDA (which makes this a randomly-occuring error).
Sorry, but this is generally an inadvisable control rendering technique (especially on the Compact Framework) for which there is no fix short of increasing the physical memory on the PDA, which isn't usually possible (and often won't fix the problem anyway, since a CF process is limited to 32MB no matter how much the device has available).
Your best bet is to go back to the old version and improve its rendering speed.  There is also a simple technique available on CF for making a control double-buffered to eliminate flicker.


q:
Every time that I create a new form in my application, it uses the "Microsoft Sans Serif, 8.25pt" font by default. I'm not changing it because I know that in this case my form should pick up whatever the default font is for the system. However, when I run my application, the font that is used is still anything but Segoe UI (my default system font in my Windows Vista OS).

Why does this happen? How do I make sure that my application looks like a normal Windows application?

[A]
Yes, it uses the font returned by
```
GetStockObject(DEFAULT_GUI_FONT)
```
.  Which is MS Sans Serif.  An old font, long gone from most machines.  The font mapper translate it to, no surprise, Microsoft Sans Serif.
There is no documented procedure I know of to change that default font, the SDK docs mention MS Sans Serif explicitly.  If you want Segoe, you'll have to ask for it.  Which isn't that safe to do, there are still a lot of XP machines out there without Office 2007.  The font mapper will translate it on a machine that doesn't have Segoe available.  Not sure what pops out, I don't have such a machine left anymore.


q: I would like to convert an array if IDs, into a string of comma separated values, to use in a MySQL UPDATE query. How would I do this?


q:
Given:

CR = %0d = \r
LF = %0a = \n

What does

%3E,
%3C

Mean?

[A]
They are URL encoded characters.  %3C is <, %3E is >
More info on
URL Encoding
, and
a chart
of some of the lower ASCII values.


q:
I am trying to import an existing PDF as a template with FPDI.  The template is in landscape format.  If I import the template into a new document the template page is inserted in portrait form with the content rotated 90 degrees.  If my new document is in portrait the full content appears, but if the new document is also landscape, the content is cropped.

Is it possible to use a landscape template with FPDI?

[A]
sure, it is no problem. Just add "L" as parameter when calling "addPage()". Here is a sample which works fine for me (the template is in landscape)
```
```
<?php
require_once('fpdf.php');
require_once('fpdi.php');

$pdf =& new FPDI();
$pdf->addPage('L');
$pagecount = $pdf->setSourceFile('template.pdf');
$tplIdx = $pdf->importPage(1);
$pdf->useTemplate($tplIdx);
$pdf->SetFont('Arial');
$pdf->SetTextColor(255,0,0);
$pdf->SetXY(25, 25);
$pdf->Write(0, "This is just a test");
$pdf->Output('newpdf.pdf', 'F');

?>
```
```


q:
I have a question about variable initialization in MASM's assembly.

How can I initialize 2^32 to a variable and to what kind of variable should I initialize? DWORD or REAL4?

I try to do it like:

val DWORD 2.0E+32

When I assign var to a register(e.g. mov eax,val) and try to write the value, I see something that is not 2^32. I also tried it with REAL4 type. Result is still same.

So What I am doing wrong here?

Thanks in advance...


q: In Java, is there a way to have a window that is "Always on top" regardless if the user switches focus to another application?  I've searched the web, and all of the solutions lean to some sort of JNI interface with native bindings.  Truly this can't be the only way to do it?.. or is it?

[A]
Try this method of the
```
Window
```
class:
Window.setAlwaysOnTop(boolean)
It works the same way as the default in the Windows TaskManager: switch to another app but it shows always on top.
This was added in Java 1.5
Sample code:
```
```
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Annoying {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Hello!!");

        // Set's the window to be "always on top"
        frame.setAlwaysOnTop( true );

        frame.setLocationByPlatform( true );
        frame.add( new JLabel("  Isn't this annoying?") );
        frame.pack();
        frame.setVisible( true );
    }
}
```
```
Window remains on top even when is not active


q:
I am developing a .NET CF based Graphics Application, my project involves a lot of drawing images, We have decided to go for porting the application on different handset resolution.(240 X 240 , 480 X 640) etc.

How would i go onto achieve this within single solution/project?

Is there a need to create different projects based on resolutions?
How would i handle common files? and i need the changes in one of the common classes to occur across all devices.

Thank you,
Cronos

[A]
This code has worked for me in determining the resolution of the screen dynamically:
```
```
[DllImport("coredll.dll", EntryPoint = ("GetSystemMetrics"))]
public static extern int GetSystemMetrics(int nIndex);

private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;

private int width = GetSystemMetrics(SM_CXSCREEN);
private int height = GetSystemMetrics(SM_CYSCREEN);
```
```
I don't remember it out of the top of my head, but there is also a way to get the Screen Orientation. These would help merge some code in a single Class.
I would strongly recommend to create a single solution for all resolutions. You could have as many projects as you want under these solution. These projects could be Windows Forms Applications, Dll Library projects or Set Up Projects.
I would aim to create a single Windows Forms Application Project. I would use the above technique and read the static images from the File System. If this doesn't work for you and/or you prefer to read your images as resources, then create an 'engine' dll project, containing all the code that is common to all resolutions. Add then the output of this project as reference to as many Windows Forms Applications projects as you need.


q:
I have some code on my PHP powered site that creates a random hash (using sha1()) and I use it to match records in the database.

What are the chances of a collision? Should I generate the hash, then check first if it's in the database (I'd rather avoid an extra query) or automatically insert it, based on the probability that it probably won't collide with another.

[A]
If you assume that SHA-1 does a good job, you can conclude that there's a 1 in 2^160 chance that two given messages have the same hash (since SHA-1 produces a 160-bit hash).
2^160 is a ridiculously large number. It's roughly 10^48. Even if you have a million entries in your database, that's still a 1 in 10^42 chance that a new entry will share the same hash.
SHA-1 has proved to be fairly good, so I don't think you need to worry about collisions at all.
As a side note, use PHP's
raw_output
feature when you use SHA-1 as this will lead to a shorter string and hence will make your database operations a bit faster.
EDIT: To address the birthday paradox, a database with 10^18 (a million million million) entries has a chance of about 1 in 0.0000000000003 of a collision.
Really
not worth worrying about.


q: What are profound advantages that one get when using COM for developing components over the WCF? Is there anything that can be done with COM and not with WCF?

[A]
No it's not dead yet, but it's on its death-bed, that's for sure. You see there's still to many legacy systems that use/require COM, that assures us it'll be with us for a few more years, but not in the long-run.
As for WCF, there might be some edge cases of stuff COM can do, and WCF can't, but more importantly, and related to legacy stuff, is that there are COM bindings for almost every language you can put on a windows stack, but the WCF bindings are not ready yet for everyone (languages)


q: What are all the problem that you foresee in doing that.

[A]
How big of a code base are you talking about?
Porting a little program (that is mostly non-templated C++ code) should be fairly trivial.
However I once had to convert 100.000 lines of template-using code from VC6 to VC2005, and it was a nightmare week(5 days of work), the main problem was that I had to fix by hand about 30% of the problems (70% were fairly trivial and could fix them with search & replaces). But more of an issue was the fact that the old code had no test cases and no test framework, so even after I got the application to compile and not segfault, and look ok(?), I had no assurance everything it was actually working as it was supposed to be.
So actually my advice is to consider the size of the code, and the availability of tests, and also consider if the code really needs to be ported (in my case that was a Yes, but its not always the case, especially if the software will be faded out soon)


q:
Boost is a great set of libraries and it really boosts productivity. But debugging code that uses it is a total nightmare. Sure, stepping through twenty thousand header files can be a valuable intellectual exercise, but what if you need to do it over and over again?

Is there a developer-friendly way of just skipping the boost portion and having the debugger go straight to my code?

Visual Studio has a DebuggerStepThroughAttribute for .NET framework. Is there anything similar for native C++?

[A]
You can skip the boost namespace entirely by using the techniques described
here
. Just use something like:
```
boost\:\:.*=NoStepInto
```
... in the relevant registry entry.
However if your code gets called from within boost (e.g. through a
```
boost::function
```
or similar) then your code will be skipped as well! I'll be interested if someone can come up with a good solution for
that
problem...


q:
If it does, then how do you justify the overheads incurred (journaling etc.)?
If it does not, then how come the pagefile gets fragmented?
Additionally, would increasing the cluster size improve pagefile performance (cluster slack space is a non-issue)?


q:
I have a custom control that I need to use in another custom control. I have written all code at server side (no HTML). Can anyone tell me how to write below line of code in code behind using htmlTextWriter and how to register this control or how to write custom control within another where html is written from code behind?

<cc2:test id="test1" runat="server" marqueedirection="left" marqueeheight="25"
            marqueewidth="725" ShowImage="False" ShowTitle="False" ShowUrlUnderLine="True"></cc2:test

[A]
First, build a simple custom web control:
```
```
namespace My.Controls
{
    public class InnerControl : Control
    {
        protected override void Render(HtmlTextWriter writer)
        {
            writer.WriteLine("
Inner Control
");
        }
    }
}
```
```
Then build your second web control that contains and renders the first:
```
```
namespace My.Controls
{
    public class OuterControl : Control
    {
        protected override void Render(HtmlTextWriter writer)
        {
            writer.WriteLine("
Outer Control
");
            InnerControl innerControl = new InnerControl();
            innerControl.RenderControl(writer);
        }
    }
}
```
```
Finally, register the control on your page, and display it:
```
```
<%@ Register TagPrefix="c" Namespace="My.Controls" %>
<c:OuterControl runat="server" />
```
```


q:
paredit binds M-<up> and M-<down>, but I want windmove to own those keybindings.  I have paredit-mode set to activate in certain modes only, but windmove is set to run globally.  I want windmove to win, but paredit steals those keybindings when it loads.

How can I easily stop paredit from stomping on windmove's keybindings?  I have been going into paredit.el and commenting out the lines which set the keybinding, but this is far from ideal (I have to remember to do this every time I update paredit).

More generally, can I load an elisp file while "protecting" certain keybindings from being changed?

[A]
You can use
```
eval-after-load
```
to configure paredit's behavior after loading it, as described in its comments:
```
```
;;; Customize paredit using `eval-after-load':
;;;
;;;   (eval-after-load 'paredit
;;;     '(progn ...redefine keys, &c....))
```
```
So, for example:
```
```
(eval-after-load 'paredit
  '(progn
     (define-key paredit-mode-map (kbd "<M-up>") nil)
     (define-key paredit-mode-map (kbd "<M-down>") nil)))
```
```


q:
I want to, from JavaScript, access as a variable the file that is loaded as an image in an img tag.

I don't want to access its name, but the actual data.

The reason for this is that I want to be able to copy it to and from variables so that I can , among other things, change the image without reloading it.

Can this be done? If so, how?

Note: I'm slightly more interested in reading the data than writing it.

[A]
Try this:
```
```
img = new Image();
img.src = "imagefile.jpg";
```
```


q:
I have got a table in MS Access 2007 with 4 fields.

Labour Cost

Labour Hours

Vat

Total

How do I multiply 'Labour Hours' by 'Labour Cost' add the 'VAT' and display the answer in 'Total'

Where would I put any formulas?, in a form or query or table ?

[A]
You don't need the "Total" column in all probability.
Your queries or reports will probably resemble this:
```
```
SELECT [Total] = [Labour Cost] * [Labour Hours] + [VAT]
```
```
You can use the same sort of formula in controls on your forms or reports.


q: I would like to add a method to a built-in type (e.g. Double), so that I can use an infix operator. Is that possible?

[A]
Yes and no.  Yes, you can make it
seem
like you have added a method to
```
double
```
.  For example:
```
```
class MyRichDouble(d: Double) {
  def <>(other: Double) = d != other
}

implicit def doubleToSyntax(d: Double) = new MyRichDouble(d)
```
```
This code adds the previously-unavailable
```
<>
```
operator to any object of type
```
Double
```
.  So long as the
```
doubleToSyntax
```
method is in scope so that it could be invoked without qualification, the following will work:
```
```
3.1415 <> 2.68     // => true
```
```
The "no" part of the answer comes from the fact that you aren't really adding anything to the
```
Double
```
class.  Instead, you are creating a conversion from
```
Double
```
to a new type which does define the method you want.  This can be a much more powerful technique than the open-classes offered by many dynamic languages.  It also happens to be completely type-safe.  :-)
Some limitations you should be aware of:
This technique does not allow you to
remove
or
redefine
existing methods, just add new ones
The implicit conversion method (in this case,
```
doubleToSyntax
```
) absolutely must be in-scope for the desired extension method to be available
Idiomatically, implicit conversions are either placed within singleton objects and imported (e.g.
```
import Predef._
```
) or within traits and inherited (e.g.
```
class MyStuff extends PredefTrait
```
).
Slight aside: "infix operators" in Scala are actually methods.  There is no magic associated with the
```
<>
```
method which allows it to be infix, the parser simply accepts it that way.  You can also use "regular methods" as infix operators if you like.  For example, the
```
Stream
```
class defines a
```
take
```
method which takes a single
```
Int
```
parameter and returns a new
```
Stream
```
.  This can be used in the following way:
```
```
val str: Stream[Int] = ...
val subStream = str take 5
```
```
The
```
str take 5
```
expression is literally identical to
```
str.take(5)
```
.


q:
What is the best way to dynamically add TableRows and TableCells to an ASP.NET table from Javascript?

Thanks,

Jeff

[A]
Your question is too vague to answer completely, I'm afraid.  If you actually want to create TableRow or TableCell objects, you would of course need to post back (no need for JavaScript) or make an AJAX call (JavaScript) to server-side code.  Either way, it's not really JavaScript doing the work.  If you just want to dynamically add a row to an HTML table presented in the browser, you could accomplish this without any need for TableRow/TableCell abstractions from ASP.NET.
For a more complete answer you'll have to be more specific about what you are trying to accomplish.


q:
Instead of writing

((x: Double) => (((y: Double) => y*y))(x+x))(3)

I would like to write something like

((x: Double) => let y=x+x in y*y)(3)

Is there anything like this sort of syntactic sugar in Scala?

[A]
Indeed there is: it's called "
```
val
```
".  :-)
```
```
({ x: Double =>
  val y = x + x
  y * y
})(3)
```
```
The braces are of course optional here, I just prefer them to parentheses when defining functions (after all, this isn't Lisp).  The
```
val
```
keyword defines a new binding within the current lexical scope.  Scala doesn't force locals to define their own scope, unlike languages such as Lisp and ML.
Actually,
```
var
```
also works within any scope, but it's considered bad style to use it.


q:
I'm looking to find a way to access the .net query string contained in the standard ASP.NET request object inside a web service. In other words if I set a SOAP web service to this url:

http://localhost/service.asmx?id=2

Can I access the ID Get variable?

[A]
I just looked for "Request" of the context in asmx file and I saw that. But I'm not sure if it is right.
```
```
this.Context.Request.QueryString["id"];
```
```


q:
I have following string

String str = "replace :) :) with some other string";

And I want to replace first occurance of :) with some other string

And I used str.replaceFirst(":)","hi");

it gives following exception

"Unmatched closing ')'"

I tried using replace function but it replaced all occurance of :).

[A]
The
```
replaceFirst
```
method takes a regular expression as its first parameter. Since
```
)
```
is a special character in regular expressions, you must quote it. Try:
```
```
str.replaceFirst(":\\)", "hi");
```
```
The double backslashes are needed because the double-quoted string also uses backslash as a quote character.


q: Parts of my application are in C++ under windows. I need the process id for the current process. Any thoughts?

[A]
The
```
GetCurrentProcessId
```
function will do this.


q:
When C# 4.0 comes out and we have the dynamic keyword as described in this excellent presentation by Anders Hejlsberg, (C# is evolving faster than I can keep up.. I didn't have much time to acquaint myself with the var keyword)

Would I still need the var keyword ? Is there anything that var can do.. that dynamic can't?

var x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x

dynamic x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x

[A]
No, they're very different.
```
var
```
means "infer the type of the variable at compile-time" - but it's still entirely statically bound.
```
dynamic
```
means "assume I can do anything I want with this variable" - i.e. the compiler doesn't know what operations are available, and the DLR will work out what the calls
really
mean at execution time.
I expect to use
```
dynamic
```
very rarely - only when I truly want dynamic behaviour:
```
var
```
lets you catch typos etc at compile-time
statically bound code is always going to run faster than dynamically bound code (even if the difference becomes reasonably small)
statically bound code gives more compile-time support beyond just errors: you can find call hierarchies, refactoring will work better, Intellisense is available etc


q:
Is it possible to create a list that can be access by either an index or a key?

I am looking for a Collection type that already exists but has this facility, I want to avoid redefining the indexers

[A]
You can add an indexer by adding the following property to your collection:
```
```
public object this[int index]
{
    get { /* return the specified index here */ }
    set { /* set the specified index to value here */ }
}
```
```
This can be quickly added in Visual Studio by typing
indexer
and pressing [tab] [tab].
The return type and indexer type can be changed ofcourse. You can also add multiple indexer types.


q:
I have the following code that I need to add an additonal object to after the results have been retrieved from the databse. Any Ideas on how I might to this ?

   public IEnumerable<ProdPriceDisplay> GetShopProductsPrices()
{

    //ProdPriceDisplay ProdPrice = new ProdPriceDisplay();
    var Products = from shop in db.SHOPs
                   select new ProdPriceDisplay
                   {
                       ProdPrice = shop.S_NAME + " - £" + shop.S_PRICE
                   };

    // *** Want to add something like this:-

    //  Products.Add new ProdPriceDisplay { ProdPrice = "some additional text"; }

    return Products;
}

[A]
That could be a solution;
```
```
var productsAsList = Products.ToList();
productsAsList.Add(new ProdPriceDisplay { ProdPrice = "some additional text"; });

return productsAsList; // As your return type is IEnumarable, that won't be a problem;
```
```


q:
How to do this in Java - passing a collection of subtype to a method requiring a collection of base type?

The example below gives:

The method foo(Map<String,List>) is not applicable for the arguments (Map<String,MyList>)

I can implement by creating a class hierarchy for the typed collections - but is it possible otherwise?

public void testStackOverflow() {

    class MyList extends AbstractList {
        public Object get(int index) {
            return null;
        }
        public int size() {
            return 0;
        }
    };

    Map <String, List>   baseColl = null;
    Map <String, MyList> subColl  = null;

    foo (subColl);
}

private void foo (Map <String, List> in) {
}

EDIT: Turns out from the answers that this requires "bounded wildcard" so adding this text for searchability

[A]
Change
```
foo
```
to:
```
```
private void foo(Map <String, ? extends List> in) {
}
```
```
That will restrict what you can do within
```
foo
```
, but that's reasonable. You know that any value you fetch from the map will be a list, but you don't know what kind of value is valid to put into the map.


q:
Staring JBoss server from within Eclipse Ganymede gives me the following problem:
"Server JBoss v4.0 at localhost was unable to start within 120 seconds. If the server requires more time, try increasing the timeout in the server editor."

The console shows JBoss has started in so and so minutes but soon after, there is a pop up if the above message.
I can also start the JBoss externally.

[A] You may check whether you are running Jboss version 4.0.4 or version 4.2.2.  You might get this error when you have installed Jboss 4.2.2 but configured Jboss 4.0.4 in Eclipse.


q: I have a list of tables i.e. student, teacher, staff, dept. and so on and each of these tables have comments specific to them. Now one record in a table can have one or many comments that shows it's a one to many relation from any table to comments table. I don't know what the best way is to relate comments table to each of these. If I put foreign key from comments table to each of these tables, it will be like 40-50 fields depending on no. of tables. Secondly if I add foreign key from each of these tables to remarks table, it will be like repeating whole row just for the second remarks foreign key? Similarly if I use just one field in each table as comments, I will be actually storing rows in just one text field. Any suggestions on how to achieve efficient solution?

[A]
Lets assume that your tables (student, teacher, staff, dept) all have a int primary key named Id.
For your comments table you could create a table.
```
```
Id int
CommentType enum (student, teacher, staff, dept)
LinkId int
Comment
```
```
A row in Comments might look like this
```
```
1,'Student',347,'text'
```
```


q:
I have a Flash movie embedded in some DIV. The trouble is that when I change any property of the enclosing DIV dynamically, Firefox (not other browsers) restarts/reinitializes Flash movie effectively resetting the whole progress (eg: file selection for upload, etc.).

Is there some sort of a workaround for this?

[A]
Try hiding it with
```
visibility:hidden
```
or if all else fails,
```
position:absolute;left:-9999px
```
.
I presume Firefox doesn't want to waste memory and CPU on Flash animation that's invisible, so it kills it.


q:
In previous releases there were 3 ways to pass data from controller to view AFAIK (shown below).

I want to use method (2) with MVC Beta 1, but I can't find the renderView method. So what's the new syntax (if it's still possible)? Thanks in advance.

Ben.

Syntax #1: Old-school dictionary

ViewData["Name"] = "Moo-moo";
ViewData["Age"] = 6;
ViewData["HasFunnyFace"] = true;
RenderView("ShowCat");

Syntax #2: Explicitly-typed ViewData object

RenderView("ShowCat", new ShowCatViewData {
    Name = "Moo-moo",
    Age = 6,
    HasFunnyFace = true
});

Syntax #3: Anonymously-typed object

RenderView("ShowCat", new {
    Name = "Moo-moo",
    Age = 6,
    HasFunnyFace = true
});

[A]
In beta 1, use the View method:
```
```
return View ("ShowCat", <TYPED_DATA_SET_OR_OTHER_MODEL>);
```
```
The View method has replaced the RenderView method.


q:
I create new ASP.NET web application that use SMTP to send message. The problem is the smtp was not authenticated from who send the message.

How can I make SMTP authenticated in my program? does C# have a class that have attribute for enter username and password?

[A]
```
```
using System.Net;
using System.Net.Mail;

using(SmtpClient smtpClient = new SmtpClient())
{
    var basicCredential = new NetworkCredential("username", "password");
    using(MailMessage message = new MailMessage())
    {
        MailAddress fromAddress = new MailAddress("from@yourdomain.com");

        smtpClient.Host = "mail.mydomain.com";
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = basicCredential;

        message.From = fromAddress;
        message.Subject = "your subject";
        // Set IsBodyHtml to true means you can send HTML email.
        message.IsBodyHtml = true;
        message.Body = "
your message body
";
        message.To.Add("to@anydomain.com");

        try
        {
            smtpClient.Send(message);
        }
        catch(Exception ex)
        {
            //Error, could not send the message
            Response.Write(ex.Message);
        }
    }
}
```
```
You may use the above code.


q: When starting a new ASP.NET application, with the knowledge that at some point in the future it must scale, what are the most important design decisions that will allow future scalability without wholsesale refactoring?

[A]
My Top three decisions are
Disabling or storing session state
in a database.
Storing as little as possible in session state.
Good N-Tier Architecture. Separating business logic and using Webservices instead of directly accessing DLL's ensures that you can scale out both the business layer as well as the presentation layer. Your database will likely be able to handle anything you throw at it although you can probably cluster that too if needed.
You could also look at partitioning data in the database too.
I have to admit though I do this regardless of whether the site has to scale or not.


q:
Is it possible to get a list of all instances with a name in a flash movie using actionscript 2. Like an array containing all named text areas, or all movieClip instances etc. I would like to get this so the designer can add or remove text areas etc. and the actionscript can dynamically find these and get the texts from a separate datasource.

I guess what I want is something like a DOM tree or even better something like how getElementByName() works in JavaScript. And allso get the string value of the instance name so I can find it's text value in an xml.

Let's say the designer add a new text area with the name "copyright" and my code should (without having to change the script) find the data with the id "copyright" in an XML file if it is there, and add the value to the text area.

[A]
It's been a while since I did any AS2 coding but perhaps you could use a combination of MovieClip.getInstanceAtDepth() and this.getNextHighestDepth() to find the highest depth in your movie then trace back through each lower depth until you find a getInstanceAtDepth() that corresponds to the clip you are looking to populate with new data.
I also noticed this example code in the AS2 documentation.
The following code traces the depth of all movie clip instances on the Stage:
```
```
for (var i in this) {
    if (typeof (this[i]) == "movieclip") {
    trace("movie clip '"+this[i]._name+"' is at depth "+this[i].getDepth());
    }
}
```
```
PS: I know you probably don't want to hear this but in AS3 it's a doddle as you can just iterate through this.children!


q:
I have a really simple ASP.NET web application and a web setup project that deploys the project output and content files to a virtual directory in IIS.

What I want is for the MSI to automatically disable Anonymouse Access for that virtual folder in IIS.

I suspect it can probably be done by writing some code in a custom action DLL, that would be acceptable, but is there any way to do it within the the settings of the web setup project?

[A]
Taken from technet
The property for anonymous access is
  unfortunately not available through
  Web setup projects. For this reason,
  you must:
Write a custom installer to enable or disable anonymous access.
Pass the necessary parameters from the setup wizard to the installer at
  run time.


q: I just want to create a C# program which will read a word template and create n number of copies of it with mail merge feature.The data to replace is Name and Address the rest of the things in the template should remains the same. Can any one tell me how to do this ?

[A]
You can use Aspose.Word for handling the Word Object model without having to have office installed (to use interop) where the program is supposed to run, i'm using Aspose.Word to generate word  documents.
Link to Aspose:
http://www.aspose.com/categories/file-format-components/aspose.words-for-.net-and-java/default.aspx
And it works quite decent :)


q:
If I put a DateTime value into an Excel cell using Range.set_value through .Net COM Interop, and then retrieve the value of that same cell using Range.get_value, the Millisecond part of the value is not returned, though everything else is correct.

Is this a bug?

What is the workaround? I'm guessing that using the Value2 property instead might help. Has anybody else tried this?

[A]
If you set a date/time with a millisecond value in Excel manually, does it maintain it? I don't know about the Excel internal object model, but it's conceivable that it just doesn't support milliseconds.
EDIT: Okay, now we know that the set fails (the get may also fail, of course)... you could try setting it as a double after converting it via
DateTime.ToOADate()
. I'm not saying I'm holding out
much
hope, but it's worth a try...


q: in javascript, when I receive a focus event, how can I work out which element has lost focus? I'm trying to avoid having to put an onblur event handler on all elements within my web page.

[A]
@pbrodka: the target/srcElement property would refer to the element with focus for onfocus events
offhand I can't see a way to get this short of onblur, or if the set of objects you care about all have focus methods you could store a reference to that object instead. It's also possible event bubbling could get you out of jail
this all feels like a bit of a code smell though - perhaps you need to describe the problem in more detail


q:
This is the HTML:

<div id="testBlue">
    <span>hello</span>
    <span id="testGreen" class="testGreen">hello2</span>
</div>

If I have set in CSS:

#testBlue span { color:Blue; }
.testGreen, #testGreen { color:Green; }

How can I override the general style in the second SPAN?

I have tried both id and class selectors but it doesnt override it.

[A]
```
```
#testGreen { color: red !important;}
```
```
or
```
```
.testGreen { color: red !important;}
```
```
Either will override the inherited rule, because
```
!important
```
puts more weight to one side of an an otherwise equal decision.


q:
I have many jobs that have a step to send 1 specific email out to a list of people.  That list of reciepients is hardcoded in the step command and I need to remove one person from that list, in all jobs.

How do I loop through ALL the jobs in the Sql Server Agent and modify the command text to find+replace a specific piece of text.

I am using sql server 2005 and have already looked at sp_update_jobStep but doesn't appear to be exactly what i want.

Cheers.

[A]
You could try to update the System tables that hold the information on jobs of the SQL server directly. The relevant ones for you would be:
```
```
msdb.dbo.SysJobs
msdb.dbo.SysJobSteps
```
```
If you have a specific email address to remove, you could update the
Command
field in the
SysJobSteps
table with a single UPDATE statement.
```
```
UPDATE SJS SET
    Command = REPLACE(Command, 'EmailAddress&TestDomain.Com', '')
FROM msdb.dbo.SysJobs SJ
INNER JOIN msdb.dbo.SysJobSteps SJS
    ON SJS.Job_Id = SJ.Job_Id
WHERE SJ.Originating_server = ..... -- Your server here
    AND SJS.Command LIKE '%EmailAddress@TestDomain.Com%'
```
```
It would be advisable to run the above query as a SELECT statement first, to test it returns only the job steps your are expecting to update.


q:
I have some jQuery/JavaScript code that I want to run only when there is a hash (#) anchor link in a URL. How can you check for this character using JavaScript? I need a simple catch-all test that would detect URLs like these:

example.com/page.html#anchor

example.com/page.html#anotheranchor

Basically something along the lines of:

if (thereIsAHashInTheUrl) {
    do this;
} else {
    do this;
}

[A]
Simple use of
location hash
:
```
```
if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}
```
```


q:
Following the JSONRequest proposal, I've found code for the JSONRequest object. However, this object depends on JSONRequestError, and the code for that is nowhere to be found.

Anyone know where I can find the code?

Thanks in advance!

[A]
I used the request
```
JSONRequestError site:devpro.it
```
in Google, it is a useful tip... ^_^
Found
JSONRequestError.js
which explain the API, and ... hmm, no source code!
Just poked around the magical number 153, got lucky:
JSONRequestError.js
:-D


q:
I'm making a C program where I need to get the directory that the program is started from.  This program is written for UNIX computers. I've been looking at opendir() and telldir(), but telldir() returns a off_t (long int), so it really doesn't help me.

How can I get the current path in a string (char array)?

[A]
Look up the man page for
```
getcwd
```
.


q:
On windows mobile when there is no internet connection and I try to
browse the web using internet explorer i get cannot connect
information at the top of the screen. It says cannot connect with
current connection settings. To change your connection settings, tap
settings. And I am able to tap Settings and setup network connections.
How can I display cannot connect information programmatically? When I
cannot connect to a webservice using my application I would like to
show the same information and let the user set up network connections.
I use compact framework 2.0 and csharp.

Thanks in advance.


q:
I'm using Tomcat 5.5 as my servlet container. My web application deploys via .jar and has some resource files (textual files with strings and configuration parameters) located under its WEB-INF directory. Tomcat 5.5 runs on ubuntu linux. The resource file is read with a file reader:

fr = new FileReader("messages.properties");

The problem is that sometimes the servlet can't find the resource file, but if i restart it a couple of times it works, then again after some time it stops working.
Can someone suggest what's the best way of reading resource strings from a servlet? Or a workaround for this problem?
Putting the resource files under WEB-INF/classes doesn't help either.

[A]
I'm guessing the problem is you're trying to use a relative path to access the file.
Using absolute path should help (i.e. "/home/tomcat5/properties/messages.properties").
However, the usual solution to this problem is to use the getResourceAsStream method of the ClassLoader. Deploying the properties file to "WEB-INF/classes" will make it available to the class loader and you'll be able to access the properties stream.
Untested proto-code:
```
```
Properties props = new Properties();

InputStream is =
getClass().getClassLoader().getResourceAsStream("messages.properties");

props.load(is);
```
```


q:
IBM Rational Application Developer is very slow and has many problems.

I tried to use ant scripts to build EAR/WAR files for Websphere Application Server
but it did not work.

[A]
My understanding is that you build the EAR/WAR, then open your browser, login to the admin console, then deploy your application.
If my understanding is correct, just add an instance of the WAS server to your workspace, and then right click on the server, select Add/Remove Projects and add your project. This way, you don't have to build the EAR/WAR file at all... Building your project is enough. If the build is successful, then RAD automatically builds the EAR/WAR and publishes the file to the server.
Atleast that's the way we do it.


q:
I need to write a little tool for a customer to be run on Windows 98. Since this is a very small project I'd hope that I could avoid having to go native C++ and use C#.

The .net Framework 2.0 download claims to support Windows 98. Are there any caveats or hitches to be aware of when installing or coding?

[A] .NET 2.0 supports Windows 98, but you won't have access to some of the base library classes such as EventLog.


q:
I Have a problem with my custom Addin to word because sometimes, MS Word was disabled my addin, and I need to write another AddIn, which Was enabled to turn - on/off my first AddIn. Is it possible?

sorry for my English  :(

[A]
What kind of add-in technology are you using? VSTO?
What version of Office are you using?
In general it is possible to do what you want. However, the reason that Office disables add-ins is that the add-in threw an unhandled exception. In that case Office will set the
```
LoadBehavior
```
value in the Registry to 2.
Maybe it would be better to analyze and handle the underlying problem causing the exception.


q:
I'm trying to make a window that closes when you click outside it, and at the moment I'm looking into doing that by handling the WndProc function.

None of the messages I'm getting so far seem useful, but there are a few I don't understand at all.  What do codes 0x0118, 0xC123, 0xC128 and 0xC12E represent?

[A]
An easy way would be to just capture the mouse.  When you have the mouse captured you get one click event outside your window, then capturing is turned off.
A harder way would be to set a low-level mouse windows hook.  To do a global hook, you'll have to put your hook code in an unmanaged DLL.
A
really
easy way would be to just close your form when it's deactivated.
EDIT
:
Oops.  I just realized I didn't answer your direct question about the message IDs.  Message 0x118 is not defined in winuser.h, so I assume it's an undocumented message ID.  Message IDs in the range 0xC000 to 0xFFFF are application-defined messages.  These IDs are returned by
```
RegisterWindowMessage
```
.


q: Is it possible to generate a XML Schema of a Database programatically with .Net and C#? I want to look into NDbUnit but for big databases it would not really be feasible to make a Schema manually?

[A]
Is it possible to generate a XML
  Schema from a Database?
It sure is,
XMLSpy
can generate XML Schema from a database.
There's
another way
, though I've never tested it:
```
```
create table Person
(
Age int not NULL check( Age > 0) ,
Height numeric(10,2) not NULL check( Height > 5),
Gender varchar(5) not null check( Gender in ('M', 'F', 'O')),
BirthDate datetime null,
)

DECLARE @schema xml
SET @schema = (SELECT * FROM Person FOR XML AUTO, ELEMENTS, XMLSCHEMA('PersonSchema'))
select @schema
```
```


q: How can I find the location of exe that runs as a windows service in run-time?

[A]
If your executable attaches itself to a particular port you could parse the output from
```
```
netstat -ab
```
```
Probably not the most attractive solution though.


q:
The code below always return an empty array from GetModifiedMembers(object)
but dx.GetChangeSet().Updates.Contains( foo ) returns true.

DataContext dx = new DataContext( string.Empty );
MockLinqDataObject foo = new MockLinqDataObject();
dx.GetTable( foo.GetType() ).Attach( foo );

foo.PK = Guid.NewGuid();

// always returns empty array
ModifiedMemberInfo[] arr_Result = dx.GetTable( foo.GetType() ).GetModifiedMembers( foo );
bool isOk = ( arr_Result.Length == 1 );
return isOk;

Does anyone know what there is wrong?

Thanks in advance?

[A]
Why you have difficulty in locating the root? go from parent to parent until parent is not set.
BTW Are you talking about B+ trees? They auto balance using blocks of children that get split when a threshold is exceeded look at this image in wikipedia