q:
Is there a way to specify the font size for a class to be, say, 70% of the inherited font size?

I have a general "button" class that sets up my buttons with the appropriate borders, background, etc. I use it in multiple places, including one where the font size is fairly small and another where the font size is quite large.

<div style="font-size: 26px;">
Push this: <input class="button" type="submit" value="Go">
</div>
<div style="font-size: 10px;">
Push this too: <input class="button" type="submit" value="Go">
</div>

In both instances I'd like the button font-size to be about 70% of the font size of the span or div the button is in.

Can I do this with pure CSS?

[A]
Try:
```
```
font-size: 0.7em;
```
```
Here's some more information:
How to Size Text in CSS
at A List Apart


q: The ListChanged event for an IBindingList fires a type ListChangedType.ItemDeleted when items are deleted, perhaps by a user deleting a row in a datagrid control bound to the list. The problem is that the NewIndex into the list is invalid in this event, it's been deleted, and the item that was deleted is not available. There should be an ItemDeleting event, but I doubt they will ever fix this.

[A]
It's not really intended for that purpose.
```
NewIndex
```
is the index where the item was when it was deleted, and it's useful for bound controls to be able to locate their associated display item in their own lists and remove that.
What is the use case you want to enable with an
```
ItemDeleting
```
?

s: huggingface

c: devops

d: intermediate


q: I have a movie which is made up of a series of SWF files that read XML. Is there any way to burn it to a CD/DVD or at least convert it to a 'burnable' format such as AVI, MPEG, or ISO? Currently in order to burn it I have to so some funky screen capture stuff and recorded it to a DVD that way.

[A]
Flash CS3 has a nifty way to export any swf (including those that use scripts) to video, but for some reason this is only available when exporting to .mov
Open up your animation in Flash, if you don't have a .fla available making a simple wrapper that loads your swf should work too. Then go File -> Export -> Export movie, and choose Quicktime. Set the various fiddly bits to your liking, and then Flash will step through your animation as fast as it can, saving you both the risk of dropped frames and having to wait for a 1 fps capture.


q: In C#, what makes a field different from a property, and when should a field be used instead of a property?

[A]
Properties expose fields.  Fields should (almost always) be kept private to a class and accessed via get and set properties.  Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.
```
```
public class MyClass
{
    // this is a field.  It is private to your class and stores the actual data.
    private string _myField;

    // this is a property. When accessed it uses the underlying field,
    // but only exposes the contract, which will not be affected by the underlying field
    public string MyProperty
    {
        get
        {
            return _myField;
        }
        set
        {
            _myField = value;
        }
    }

    // This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
    // used to generate a private field for you
    public int AnotherProperty { get; set; }
}
```
```
@Kent points out that Properties are not required to encapsulate fields, they could do a calculation on other fields, or serve other purposes.
@GSS points out that you can also do other logic, such as validation, when a property is accessed, another useful feature.


q:
I have a method in an interface that I want to deprecate with portable C++.
When I Googled for this all I got was a Microsoft specific solution; #pragma deprecated and __declspec(deprecated).

A second prize solution would be to ifdef a MSVC and a GCC solution.

[A]
In GCC you can declare your function with the attribute deprecated like this:
```
```
void myfunc() __attribute__ ((deprecated));
```
```
This will trigger a compile-time warning when that function is used in a .c file.
You can find more info under "Diagnostic pragmas" at
http://gcc.gnu.org/onlinedocs/gcc/Pragmas.html


q:
I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.

I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like "_-.() ". What's the most elegant solution?

The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.

[A]
This whitelist approach (ie, allowing only the chars present in valid_chars) will work if there aren't limits on the formatting of the files or combination of valid chars that are illegal (like ".."), for example, what you say would allow a filename named " . txt" which I think is not valid on Windows. As this is the most simple approach I'd try to remove whitespace from the valid_chars and prepend a known valid string in case of error, any other approach will have to know about what is allowed where to cope with
Windows file naming limitations
and thus be a lot more complex.
```
```
>>> import string
>>> valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
>>> valid_chars
'-_.() abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
>>> filename = "This Is a (valid) - filename%$&$ .txt"
>>> ''.join(c for c in filename if c in valid_chars)
'This Is a (valid) - filename .txt'
```
```


q:
I have 3 projects in my solution that I want to deploy. Is there a nice and quick way of using Visual Studio's setup projects to deploy all three apps using one MSI and letting the user decide which apps he wants to install during the install process?

I have setup projects for the 3 individual apps, I also have an overarching setup project that has the output of those other three projects. Am I on the right track or is there a better way?

[A]
I think you probably want merge modules. Accrding to MSDN:
A merge module is a standard feature of Microsoft Windows Installer that packages components together with any related files, resources, registry entries, and setup logic. You can use merge modules to install components that multiple applications share. You cannot install merge modules directly. You must merge them into deployment projects.
http://support.microsoft.com/kb/827025
In your case, each application would be a merge module and you would need to provide some UI to select which applications you would like to install. You could modify one of the default page templates to do that.


q:
If you try to launch a .NET 3.5 application on a Windows computer which does not have this version of the .NET framework installed, you get a FileNotFoundException for some system assemblies (for example System.Core 3.5.0.0).

Is it possible to catch this exception and tell the user to upgrade their .NET framework or is it thrown too early to handle it?

[A]
The simplest thing would just be to try it. (I don't have any non-3.5 machines to test it on, but I assume you do.)
Make your entry point a very simple one which just tries to load
```
System.Core.dll
```
and handles the exception appropriately. If it passes, move on to another class which can then use it. If it fails, give the appropriate error message and exit.
I
suspect
you don't need to have quite this level of isolation - so long as you don't have any fields which are of unavailable types, I wouldn't expect the assembly to be resolved until you first call a method which needs it. I'd have to consult CLR via C# to check. However, keeping it quite isolated would probably be safer - it avoids you accidentally introducing dependencies later. Heck, you could even have your "boot and check" type in a separate assembly which did nothing but launch another one if everything's okay.


q:
A program written in Visual C/C++ 2005/2008 might not compile with another compiler such as GNU C/C++ or vice-versa. For example when trying to reuse code, which uses windows.h, written for a particular compiler with another, what are the differences to be aware of?

Is there any information about how to produce code which is compatible with either one compiler or another e.g. with either GC/C++ or MSVC/C++? What problems will attempting to do this cause?

What about other compilers, such as LCC and Digital Mars?

[A]
Well this is a quite difficult question. Fact is that MSVC does not support the newest
C standard, about it's c++ compliance I can tell you anyything. Howerver "windows" C is understand by both MSVC and gcc you just can not hope for the other way. E.g if you use ANSI C99 features then you might have a hard time "porting" from gcc to MSVC.
But as  long as you try the way MSVC-> gcc you chances will be better. The only point you have to be aware of is the libraries. Most of the libraries on Windows are supposed to work with MSVC and so you need some extra tools to make them accessible to gcc also.
LCC is a quite older system,which AFAIKT does not support much from ANSI C99, it also needs tools from MSVC to work properly. LCC is "just " a compiler.
lcc-win32 is a C Development system striving to be ANSI C99 compliant. It comes along with linker,  IDE etc.
I can not tell about the state of Digital Mars implementation
Then there is also Pelles-C which is a fully fledged IDE also.
And we have hanging around OpenWatcom. Which once was quite a decent system but I can't tell how conformant it is.
All in all the "best" you can hope  for the easier way from MSVC -> other system but it will probably be much worse the other way round.
Regards
Friedrich


q:
The problem is simple:

Using bash, I want to add a directory to my PYTHONPATH for ease of script execution. Unfortunately, the directory I want to use has a : in it. So I try each of the following

export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com:3344/
export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com\:3344/
export PYTHONPATH=${PYTHONPATH}:"/home/shane/mywebsite.com:3344/"

None of these work. Every time, the path is created as two separate directories on the path in python.
My question is, is it possible to do this for bash?
If so, what's the syntax required?

[A]
There is only one you didn't try:
```
```
export PYTHONPATH=${PYTHONPATH}:"/home/shane/mywebsite.com\:3344/"
```
```
The problem is without the quotes, the escaping is interpreted directly, and converted into a literal ":" in the string.  But the ":" needs to be evaluated later.
```
```
$ echo "foo:"
foo:
$ echo \:foo
:foo
$ echo ":foo"
:foo
$ echo "\:foo"
\:foo
```
```
I can't guarantee this will fix your python-path problem, but it will get the \ literal into the string.


q:
I have tried, 'PreviousPage', 'PreviousPage.IsCrossPagePostBack' 'Page.previousPage', page.title

It causes the client to stop rendering the page after this line.

simple example

protected void Page_Load(object sender, EventArgs e)
{
response.write("I can see this");
string test = PreviousPage.IsCrossPagePostBack.toString(); //Any page call Causes client rendering to freeze
response.write("But i cant see this");
System.Windows.Forms.MessageBox.Show("However i can see this,proving that the server is still running the code");
}

Anybody Please, any ideas?

[A]
Have you checked PreviousPage for null?
From
msdn
:
The PreviousPage property is a null
  reference (Nothing in Visual Basic)
  when the user requests that page
  directly from the server.
Also -
```
MessageBox
```
in a web form,
not
a great idea... perhaps use the inbuilt
trace.axd


q:
I'm talking about this:

If we have the letter 'A' which is 77 in decimal and 4D in Hex.
I am looking for the fastest way to get D.

I thought about two ways:

Given x is a byte.

x << 4; x >> 4

x %= 16

Any other ways? Which one is faster?

[A]
Single AND operation can do it.
```
```
x = (x & 0x0F);
```
```


q:
Are SQL Server timeouts (SELECT queries, in particular) logged in the ERRORLOG file?

Background is a customer with a web site having occasional "Request timeout" messages, looking to me assuming that the timeout is caused by a database timeout.  There are no timeout errors in the ERRORLOG in question.

[A]
No. You will need to use SQL Profiler. A standard trace with the
Lock Timeout
event and
Deadlock Graph
events should do it.
Lock:Timeout Event Class
Deadlock Graph Event Class
Hardware aside (such as enough RAM and fast drives, and appropriate placement of Data and Log files on the appropriate RAID configurations) most timeouts are caused by not having a sufficently 'good' set of indexes for your workload.
Do you have index maintenance plans scheduled regularly?


q:
Is this the best way to handle file moving in a windows service? we have many files that get matched and moved, but an end user may have the file opened at the time of moving.

This is what the code currently says:

Do While IO.File.Exists(OriginalFilePath)

    Try
        IO.File.Move(OriginalFilePath, BestMatchPath)
    Catch ex As IO.IOException
        Log(TraceLevel.Warning, "The file '{0}' was unable to be moved (probably opened by someone)", OriginalFilePath)
        Threading.Thread.Sleep(1000)
    End Try

Loop

Is there a better way to manage this? I have thought of threading it to allow the process to continue, but currently i am unsure if this is viable, as the rest of the process might need the files path to be accurate.


q:
When I launch an ant script from Eclipse 3.4.x it prints the output to console until certain stage. After that it often hangs (wait forever). Last lines that I see at the screen (console) - partial output from my obfuscator.

Under Eclipse 3.3.2 everything works fine (the same project, workspace, settings, JVM etc.).

Does anybody have the same issue? Any thoughts how to fix it?

[A]
One possible cause is that you are
running out of memory
Also try to run ant with the
```
-diagnostics
```
option.
You can check your
memory usage
and your
eclipse.ini
.
Another classic culprit is a
blocking access to a locked resource
(like an access to a file already being used by another process): try to close a many applications you can and relaunch ant.


q:
I have this java code:

<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.2.6");

$("a#more").click(function() {

$("#info_box").show("blind", { direction: "vertical" }, 800);

});
</script>

And this link:

<a href="#" id="more">More Info...</a>

info_box is just a div with the properties:

width: 30%;
position: absolute;
left: 35%;
top: 250px;
background-color: #FFFFFF;
border: 2px solid #000000;
visibility: hidden;

How can this not be working, been trying to figure it out for 20 minutes.

[A]
Are you sure you're calling the right function? According to the docs at
http://docs.jquery.com/Effects/show
the show function takes a speed as the first parameter, and a callback function as the second. Your
```
"blind"
```
and
```
{ direction: "vertical" }
```
are misplaced I think.
Also worth checking there's no conflict with another script e.g. mootools.


q: Is there any way to find out if the user pressed the delete key or dot? It has the same keycode in FireFox.

[A]
According to
Detecting keystrokes
, it is possible, provided that:
you search for the keyCode (
8
for delete) onkeydown/up, and
ignore both onkeypress and charCode (Especially if you consider the fact that IE does not fire keypressed event, only key up/down).


q:
If you put up an NSAlert while your app is in the background your dock icon starts bouncing and keeps on bouncing until you switch back.

I find this annoying.

Does anyone know how disable that for a single app?

[A]
Not that I'd recommend it, but there is a Haxie that may help:
Dock Detox
.
They allow you to intercept the bouncing and do other stuff, I think.
A quick google showed up:
```
```
- (void)cancelUserAttentionRequest:(int)request
```
```
But I really don't know if this will work for your purposes.


q:
i'm currently experimenting using PixelShaders introduced with .net 3.5 sp1 to improve image processing performance. everything is much faster , but til yet i just had effects applied to some elements in my wpf forms, that i actually want to avoid.

we have a bunch of image processing functionality and i'd like to replace some othe the stuff piece by piece with pixel shaders to gain some performance.
is there a way to apply such a pixel shader to an ImageSource without having to display it?

[A]
What is generally done in C++ / DirectX to achive this is:
Preparation (done once)
Create render target using CreateRenderTarget
Create off-screen surface using CreateOffscreenPlainSurface
Set render target surface using SetRenderTarget
Create any other input resources needed (Textures, Vertex Buffers ...)
Rendering (done multiple times)
Update input resources (textures, buffers) as needed
Render
Copy the contents of the render target into the off-screen surface via GetRenderTarget
Lock the off-screen surface and read its content on the CPU


q:
I want to save a set of email addresses collected from a text field (separated by commas) into a single field in a table. I am trying to use serialize but I'm getting SerializationTypeMismatch error. How can I do this?

This is my model:

class Crew < ActiveRecord::Base

class Recipients < HashWithIndifferentAccess ; end

serialize :recipients, Recipients

end

[A]
I would really reccomend that you parse (e.g. split on comma) the email list and put each in a row in a separate table (I assume you're talkin about a database table?). If you want to use the email addresses for something it's better to store them individually, and since you're talking about serialization I guess you've allready parsed the emails, and try to store an array or similar into a single field in a database. The "correct" normalized database way of doing this is to in your model wich you're currently trying to save the object, add a
```
has_many :emails
```
(or similar) and creat a new email table for each email.
One should allways have a very
good reason
for storing list type data in a blob, instead of using a proper associated table.


q:
Many times I use 'mqsc' for create MQ queue manager from script files but I don't know how to generate script files.

Thanks

[A]
There is a SupportPac that installs a program called "saveqmgr.exe".
Here's a link to the download of the Pac:
http://shrinkster.com/17kc
IBM seems to frequently reorganize its website, so the above link might not work if you check back here after a long while, but the SupportPac can be found easily by doing a search for "saveqmgr" on the Websphere MQ page.  Hope this helps!
IBM has this to say about the SupportPac:
Abstract
This SupportPac (saveqmgr) saves all the objects, such
  as queues, channels, etc, defined in a
  either local or remote queue manager
  to a file.
Download Description
This SupportPac interrogates the attributes
  of all the objects defined to a queue
  manager (either local or remote) and
  saves them to a file.
Possible Uses
The format of this file is suitable for use with runmqsc.
  It is therefore possible to use this
  SupportPac to save the definitions of
  objects known to a queue manager and
  subsequently recreate that queue
  manager.


q:
I have a .net winforms app which has a few animation effects, fade ins and scroll animations etc.  These work fine however if I'm in a Remote Desktop Protocol session the animations start to grate.

Can someone suggest a way of determining whether or not an app is running across an RDP session so I can turn the effects off in this case?

[A]
Use the
GetSystemMetrics()
function in the user32.dll.  Use
PInvoke
to call it.  The following is sample code provided by the first link.  The second link tells you how to invoke it in .NET.
```
```
BOOL IsRemoteSession(void){
      return GetSystemMetrics( SM_REMOTESESSION );
   }
```
```
Complete code:
```
```
[DllImport("User32.dll")]
static extern Boolean IsRemoteSession()
{
 return GetSystemMetrics ( SM_REMOTESESSION);
}
```
```
There's also the
```
SystemInformation.TerminalServerSession
```
Property, which determines whether or not the client is connected to a Terminal Server session.  The
code provided
by MSDN is extensive, so I won't duplicate it here.


q:
I'm trying to find an editor (or some simple JavaScript - preferably jQuery) that will allow me to edit the contents of a textarea.

I don't want it to be rich text or WYSIWYG; I just want to be able to select a bit of text, click a button/link and have some simple HTML tags that I define put either side of the highlighted text. I also want to be able to insert empty tags at the cursor if no text is selected in the textarea. Essentially, what I'm looking for is similar to the Stack Overflow text editor, but for custom HTML, not Markdown.

What options are there that I could use?

Thanks in advance.

[A]
Would something like
this
fit the bill? I think it just uses
```
document.selection
```
to identify where to insert the markup.


q:
I've got a message contained in an byte[], encrypted with "RSA/ECB/PKCS1Padding". To decrypt it I create a Cipher c and initiate it with

c = Cipher.getInstance("RSA/ECB/PKCS1Padding");

Untill now I have only decrypted small messages, using the doFinal() method, returning an byte[] with the decrypted bytes.

c.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptetBytes = c.doFinal(encryptedBytes);

But in this case the data is bigger (approx 500 Bytes), and the doFinal()-method throws an exception (javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes). I guess I need to use the update()- method, but I can't figure out how to get it to work properly. How is this done?

[A]
With RSA you can only encrypt/decrypt block with size up to your key length minus padding length. If you have data longer than your key maybe it is just merged in one array so you should split it into chunks with size of your key (128 bytes suggests 1024 key with no padding, I'm not sure if it's possible). Using update() is not the case here.
Simply, you have to know how this array was created.
Generally speaking, RSA shouldn't be used to encrypt large amount of data as it's quite time consuming. Should be used to encrypt key to symmetric cipher, like AES.
Take a look here:
https://www.owasp.org/index.php/Digital_Signature_Implementation_in_Java


q:
I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.

What is the best way to control what urllib.urlopen returns?

[A]
Probably the best way to handle this is to split up the code, so that logic that processes the page contents is split from the code that fetches the page.
Then pass an instance of the fetcher code into the processing logic, then you can easily replace it with a mock fetcher for the unit test.
e.g.
```
```
class Processor(oject):
    def __init__(self, fetcher):
        self.m_fetcher = fetcher

    def doProcessing(self):
        ## use self.m_fetcher to get page contents

class RealFetcher(object):
    def fetchPage(self, url):
        ## get real contents

class FakeFetcher(object):
    def fetchPage(self, url):
        ## Return whatever fake contents are required for this test
```
```


q:
A number of business areas I work with use a folder structure to organise their Sharepoint housed documents (not ideal I know, but we're stuck with it).

I would like to use a web part page to present a number of views of their document libraries based on the subfolders that the documents appear in, but this is proving more difficult than I had thought.  Has anyone overcome this problem in the past?

[A]
What kind of document library information do you want in the view?
How do you want the user to filter the view?
In general the most powerful way of creating views in sharepoint is with the data view web part.
http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx
You will need Microsoft Office SharePoint Designer.
You can present different views of you folders using the data view filter and sorting controls.
You can use web part connections to filter a dataview.
You can use any datasource linked to say a drop down to filter a dataview.
How to tie a dropdown list to a gridview in Sharepoint 2007?


q:
In Oracle we can print output by dbms_output.put_line() but I don't know to do the same thing in DB2.

I currently use signal for printing some messages when I debug.


q:
How do I execute the following shell command using the Python subprocess module?

echo "input data" | awk -f script.awk | sort > outfile.txt

The input data will come from a string, so I don't actually need echo.  I've got this far, can anyone explain how I get it to pipe through sort too?

p_awk = subprocess.Popen(["awk","-f","script.awk"],
                          stdin=subprocess.PIPE,
                          stdout=file("outfile.txt", "w"))
p_awk.communicate( "input data" )

UPDATE:  Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place!

[A]
http://www.python.org/doc/2.5.2/lib/node535.html
covered this pretty well. Is there some part of this you didn't understand?
Your program would be pretty similar, but the second
```
Popen
```
would have stdout= to a file, and you wouldn't need the output of its
```
.communicate()
```
.


q:
When connecting to a network share for which the current user (in my case, a network enabled service user) has no rights, name and password have to be provided.

I know how to do this with Win32 functions (the WNet* family from mpr.dll), but would like to do it with .Net (2.0) functionality.

What options are available?

Maybe some more information helps:

The use case is a windows service, not an Asp.Net application.

The service is running under an account which has no rights on the share.

The user account needed for the share is not known on the client side.

Client and server are not members of the same domain.

[A]
You should be looking at adding a line like this:
```
```
<identity impersonate="true" userName="domain\user" password="****" />
```
```
Into your web.config.
More Information.


q:
What's the best way to do it in .NET?
I always forget what I need to Dispose() (or wrap with using).

EDIT: after a long time using WebRequest, I found out about customizing WebClient. Much better.

[A]
Here's what I use, it seems to work, but I don't know if it's the best way:
```
```
public string GetRequest(Uri uri, int timeoutMilliseconds)
{
    var request = System.Net.WebRequest.Create(uri);
    request.Timeout = timeoutMilliseconds;
    using (var response = request.GetResponse())
    using (var stream = response.GetResponseStream())
    using (var reader = new System.IO.StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}
```
```


q:
I need to disable windows-update service from my installation. I already use vbscript to do some stuff so I would like to do it in vbscript.

My knowledge of vbscript (or any other script language) is very limited so...can anybody help me out with that? I'll really appreciate it!

Thanks.

[A]
If you want to use VBScript, use WMI:
```
```
strComputer = "."  'could be any computer, not just the local one '
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colServiceList = objWMIService.ExecQuery _
("Select * from Win32_Service where Name = 'wuauserv'")

For Each objService in colServiceList
  objService.ChangeStartMode("Disabled")
Next
```
```
Look into
the documentation of the WMI Win32_Service Class
to find out what else might be doable.
Easier would be the use of
```
sc.exe
```
:
```
sc config wuauserv start=auto
```
Here is an excerpt of what
```
sc.exe
```
can do:
```
```
C:\>sc config
Modifies a service entry in the registry and Service Database.
SYNTAX:
sc <server> config [service name] <option1> <option2>...
CONFIG OPTIONS:
NOTE: The option name includes the equal sign.
 type= <own|share|interact|kernel|filesys|rec|adapt>
 start= <boot|system|auto|demand|disabled>
 error= <normal|severe|critical|ignore>
 binPath= <BinaryPathName>
 group= <LoadOrderGroup>
 tag= <yes|no>
 depend= <Dependencies(separated by / (forward slash))>
 obj= <AccountName|ObjectName>
 DisplayName= <display name>
 password= <password>
```
```


q:
I have a List containing several keywords.
I foreach through them building my linq query with them like so (boiled down to remove the code noise):

List<string> keys = FillKeys()
foreach (string key in keys){
    q = q.Where(c => c.Company.Name.Contains(key));
}

When I now make my keys contain 2 keys that return results seperatly, but can never occure together (every item in q is either "xyz" or "123", never "123" AND "xyz"), I still get results. The resultset is then the same as the last string it got to.

I had a look at the linq query and it appears it creates the correct sql, but it replaces @p1 AND @p2 both by the same (last itterated) value.

What am I doing wrong?

[A]
You're reusing the same variable (
```
key
```
) in your lambda expression.
See my article on
anonymous methods
for more details, and there are a number of related SO questions too:
LINQ to SQL bug (or very strange feature)...
Local variables with delegates
C# captured variable in a loop
C# gotcha answer
Building a LINQ query programmatically without local variables tricking me
The simple fix is to copy the variable first:
```
```
List<string> keys = FillKeys()
foreach (string key in keys){
    string copy = key;
    q = q.Where(c => c.Company.Name.Contains(copy));
}
```
```


q:
I'm writing an applicationt hat was prototyped on MySQL and is now connecting to an Oracle database.

All I had to do to connect to the oracle database (having built up the table structure) was change the connection string.

What is the format to connect to a SQL Server DB on another machine?

I've read some tutorials which tell you to use the SQL Server JDBC adaptor but I'd rather configure the application so that it's database agnostic, and just have the connection string specify the protocol etc.

Any references I've seen which tell you how to use the bridge with SQL Server require the ODBC Data Source to be installed, this is less than ideal as my app may run on Linux or windows.

I'm not doing anything complicated just inserts.

[A]
You should not use the JDBC-ODBC bridge in a production environment. It is much slower than other JDBC drivers and only necessary when a JDBC driver is not available.
SQL Server has a
JDBC driver
available from Microsoft. If you use it then you will get the required result.
With the ODBC bridge you have no choice but to install the ODBC driver.
This
article
describes the connection string you will need to use to connect to the SQL Server.


q:
Any ideas on how I can acheive 'Hierarchical' gridview?
Basically I want when the user clicks on the '+', i "expand" and insert new rows without a full page post back.

Does this sound like a lot of AJAX stuff? Or should I read on ASP.NET MVC

Please point me in right direction

[A]
You have two options I suppose:
You can render out those rows you want to insert, and the [+] shows them and hides them
You don't render them out, and they are sent to the browser via AJAX, and then inserted into the table.
I've done it both ways, and the more gridviewy way to do it is the first, in my opinion.  You can create a new templatefield for the [+]; define a child relationship name, and then  call
GetChildRows
(or an equivalent) on each row as you render, having those rows render hidden.


q:
Given the following Delphil DLL declaration

function csd_HandleData(aBuf: PChar; aLen: integer): integer; stdcall;

what would be the VB6 declaration to use it?

I've tried a variety of declarations, e.g.

Declare Function csd_HandleData Lib "chsdet.dll" (ByVal aBuf As String, ByVal aLen As Integer)
Declare Function csd_HandleData Lib "chsdet.dll" (aBuf As Long, ByVal aLen As Integer)
Declare Function csd_HandleData Lib "chsdet.dll" (aBuf As Byte, ByVal aLen As Integer)

with the relevant code to suit the parameters, but nothing seems to work, i.e. the Delphi debugger says I have a too-largish value in aLen and a null string in aBuf.

I am working toward using a TypeLib to drive the connection, but was prototyping with Declares.

[A]
try
```
```
Declare Function csd_HandleData Lib "chsdet.dll" (ByVal aBuf As String,
ByVal aLen As Integer) As Integer
```
```
Seems you forgot the return value.


q:
I'm writing an application which has to be configurable to connect to Oracle, SQL Server and MySQL depending on client whim.

Up till now I'd been planning on using the JDBC-ODBC bridge and just connecting to the databases using different connection strings.

I'm told this is not very efficient.

Is there a pattern or best practice for connecting to multiple database systems? Or for selecting which driver to use?

Should I have it configurable? but include all three drivers or build three separate clients?

I'm not doing anything complex just pumping (inserting) data into the database from an event stream.

[A]
If you need anything complex, Hibernate is a good choice.
otherwise, what I would do is store your connection details in a properties file (or some other form of configuration) - namely: driver classname, JDBC url, username and password.
Then, all you need to do is load up the connection details from your properties file and include the correct JAR file on your classpath and you're done.
You could use a library such as Commons-DBCP if you wanted it to be a little easier to configure but other than that it's all you need to do (provided your SQL statements work on every database, of course).


q:
I am trying to have one one layer, and center images within. I.E., if I have 3 images and want 3 links beneath them, is there a way to do this without using a separate div tag for each link and image? To automatically make the links be centered under the images, and the images to be spaced evenly within a layer?

I was also wondering how I would make the div show behind standard html if that is possible. I.E. if I have some text and a div over the text, the div will default show over the text, when I would like it to be behind. Is this only possible by using another layer?

[A]
Yes, you'll have to put a container element, such as a div, around each image and its caption to keep them together.
```
```

        caption caption

        more caption

--------
.pictureBox div {
    text-align: center;
    /* whatever width/height/positioning you want */
}
```
```
for the second part of the question, regarding putting it behind the other text, take a look at
CSS z-index
, though I think that only applies to absolutely positioned elements.


q:
What is and how can it be used in C#.

Can you use the same concept in Python/Perl?

[A]
A
partial type
(it doesn't have to be a class; structs and interfaces can be partial too) is basically a single type which has its code spread across multiple files.
The main use for this is to allow a code generator (e.g. a Visual Studio designer) to "own" one file, while hand-written code is put in another.
I've no idea whether Python/Perl have the same capabilities, I'm afraid.


q:
I would like to get the path to the execution directory of a Windows Forms application. (That is, the directory in which the executable is located.)

Does anyone know of a built-in method in .NET to do this?

[A]
In VB.NET
```
```
Dim directory as String = My.Application.Info.DirectoryPath
```
```
In C#
```
```
string directory = AppDomain.CurrentDomain.BaseDirectory;
```
```


q:
A game that I play stores all of its data in a .DAT file. There has been some work done by people in examining the file. There are also some existing tools, but I'm not sure about their current state. I think it would be fun to poke around in the data myself, but I've never tried to examine a file, much less anything like this before.

Is there anything I should know about examining a file format for data extraction purposes before I dive headfirst into this?

EDIT: I would like very general tips, as examining file formats seems interesting. I would like to be able to take File X and learn how to approach the problem of learning about it.

[A]
You'll definitely want a hex editor before you get too far.  It will let you see the raw data as numbers instead of as large empty blocks in whatever font notepad is using (or whatever text editor).
Try opening it in any archive extractors you have (i.e. zip, 7z, rar, gz, tar etc.) to see if it's just a renamed file format (.PK3 is something like that).
Look for headers of known file formats somewhere within the file, which will help you discover where certain parts of the data are stored (i.e. do a search for "IPNG" to find any (uncompressed) png files somewhere within).
If you do find where a certain piece of data is stored, take a note of its location and length, and see if you can find numbers equal to either of those values near the beginning of the file, which usually act as pointers to the actual data.
Some times you just have to guess, or intuit what a certain value means, and if you're wrong, well, keep moving.  There's not much you can do about it.
I have found that
http://www.wotsit.org
is particularly useful for known file type formats, for help finding headers within the .dat file.


q:
Currently I have two MediaWikis, one a slightly older version than the other.  I want to merge the contents of both together, without eliminating duplicate pages.  So far the best option I can think of is to use a bot (like pywikipedia) to go through all the pages of one wiki, and try inserting them into the other, renaming duplicate pages.

This solution seems like it would take a while to accomplish though.  Is there a more pleasant way to do this that I'm just unaware of? I haven't worked with the MediaWiki database directly very much, so I'm not very comfortable messing with it without knowing what I'm doing.

[A]
MediaWiki has
import
and
export
features, that you can use for moving the contents. It does merge histories of existing pages (see import link).
However, it does not handle conlicts of two different pages with the same name, so you'll have to handle moving the pages by yourself. As far as I can see in description of MediaWiki
page table
, you might be able to find and rename duplicate pages directly in SQL, but pywikipedia should work too (but you'll need to delete redirects that will result from "correct" page moves, otherwise they'll mess up with imported pages from the other wiki).


q:
I have a website built in C#.NET that tends to produce a fairly steady stream of SQL timeouts from various user controls and I want to easily pop some code in to catch all unhandled exceptions and send them to something that can log them and display a friendly message to the user.

How do I, through minimal effort, catch all unhandled exceptions?

this question seems to say it's impossible, but that doesn't make sense to me (and it's about .NET 1.1 in windows apps):

[A]
Do you mean handling it in all threads, including ones created by third-party code? Within "known" threads just catch
```
Exception
```
at the top of the stack.


q: I am trying to write an installer (by creating a .vdproj) that will work on both Windows Vista and XP.  The only thing I am finding is that when I try to run it on Vista, the files that I include in the installer are installed with Read-only permissions for the Users groups.  This is a problem because the application needs to read/write from these files.  The only way I have been able to get it to work is to either "Run as Administrator" or actually change the permissions.  Does anyone know how to make these files be open to anyone to write?  Thanks.

[A]
The Program Files folder and it's contents are read only for standard users.  This is by design, and you'll find that
this is the case on Windows XP as well.
It's just that on windows xp, so many people run with administrator rights all the time that you might get away with it.  If you ever want to distribute your app into a business environment, you'll soon find that   it won't work on XP there, either.
The solution is to NOT place files in the program's executable folder if standard users will need write access.  Put them in the Application Data folder instead.  For most xp machines, that will be here:
C:\Documents And Settings\All Users\Application Data\Your App
However, that won't always be the case and it's a little different on Vista anyway, so make sure you get that path via the mechanism provided by your programming environment.  In .Net, you can use the
```
Environment.GetFolderPath()
```
function.


q:
The XML file I want to parse starts with  :

<!DOCTYPE plist PUBLIC "-//...//DTD PLIST 1.0//EN" "http://www.....dtd">

So when I start the SAX praser, it tries to access this DTD online, and I get a java.net.UnknownHostException.

I cannot modify the XML file before feeding it to the SAX parser

I have to run even with no internet connection

How can I change the SAX Parser behaviour so that it does not try to load the DTD ?
Thanks.

javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
factory.setValidating(false);

javax.xml.parsers.SAXParser parser = factory.newSAXParser();
parser.parse(xmlFile, handler);

[A]
You can implement a custom
```
EntityResolver
```
which is what is used to lookup external entities during XML parsing.
```
```
org.xml.sax.EntityResolver customEntityResolver = new DummyEntityResolver();
javax.xml.parsers.SAXParser parser = factory.newSAXParser();
parser.getXMLReader().setEntityResolver(customEntityResolver);
parser.parse(xmlFile, handler);
```
```
And in your custom EntityResolver, just always return null. I think that should fix this problem.


q:
I get the message that the namespace can't be found when I use the code below. Where does the AccessDeniedException live?

try { ... }
catch (SomeKindOfException ex)
{
MessageBox.Show(ex.Message);
}
catch (AccessDeniedException ex)
{
//Do something else
}

Thanks

[A]
I don't think that's the exception you're looking for.  The only one with this name (that I can find) is in a Sharepoint namespace.  Try attaching the debugger and seeing exactly what the type of the thrown exception is.
The type of the exception is going to vary depending on your context.  So for example, if it's an "access denied" when trying to open a file, it could be a FileLoadException, or something similar.  If it's encountered because of Code Access Security,  it will be SecurityException.  And so on.


q: We have very strange problem, one of our applications is continually querying server by using .net remoting, and every 100 seconds the application stops querying for a short duration and then resumes the operation. The problem is on a client and not on the server because applications actually queries several servers in the same time and stops receiving data from all of them in the same time.

[A]
100 Seconds is a give away number as it's the default timeout for a webrequest in .Net.
I've seen in the past that the PSI (Project Server Interface within Microsoft Project) didn't override the timeout and so the default of 100 seconds was applied and would terminate anything talking to it for longer than that time.
Do you have access to all of the code and are you sure you have set timeouts where applicable so that any defaults are not being applied unbeknownst to you?


q:
I'm sure there is a quick and easy way to calculate the sum of a column of values on Unix systems (using something like awk or xargs perhaps), but writing a shell script to parse the rows line by line is the only thing that comes to mind at the moment.

For example, what's the simplest way to modify the command below to compute and display the total for the SEGSZ column (70300)?

ipcs -mb | head -6
IPC status from /dev/kmem as of Mon Nov 17 08:58:17 2008
T         ID     KEY        MODE        OWNER     GROUP      SEGSZ
Shared Memory:
m          0 0x411c322e --rw-rw-rw-      root      root        348
m          1 0x4e0c0002 --rw-rw-rw-      root      root      61760
m          2 0x412013f5 --rw-rw-rw-      root      root       8192

[A]
You could start by running the data through
```
cut
```
- which would at least trim the columns down.
You should then be able to pipe that into
```
grep
```
, stripping-out non-numerics.
Then ... well, then I'm not sure. It might be possible to pipe that to
```
bc
```
. If not, it could certainly be handed to a shell script to add each item.
If you used
```
tr
```
to change the newlines (
```
\n
```
) to spaces (
```
```
), and piped that through xargs into your script that loops until there are no more inputs, adding each one, you may have an answer.
So, something akin to the following:
```
```
cat <whatever> | cut -d'\t` -f7 | grep -v <appropriate-character-class> | tr '\n' ' ' | xargs script-that-adds-arguments
```
```
I may have the
```
cut
```
flags slightly wrong - but
```
man
```
is your friend :)


q:
I have a .jar file that i've placed in my D:\Coldfusion8\wwwroot\web-inf\lib\ directory.  The file is abcdef.jar

This is my first time doing this, not sure what the path should be in my createObject().

<cfset abcObj = createObject("java","com.abcdef") />
<cfset result = acbObj.doStuff("123456") />

But when I run it, I get

Object Instantiation Exception.
Class not found: com.vp4jo_b

What am I missing in the path?

[A]
Have you restarted the Coldfusion Service?
Even when in the class path, jars are only loaded at server start.
Info moved up from the comments:
Make sure the file is in the System class path, or in the one of the configured class paths of ColdFusion.
As for the class name parameter of
```
CreateObject()
```
: The class name starts within the jar. Open it like a .zip file and look at its structure. The dotted path mimics the folder structure, so if the Server still complains, you must be missing something in the dotted path.


q:
Consider the following code in VB9:

Dim text = "Line1<br/>Line2"
Dim markup = <span><%= text %></span>.ToString

While I was hoping markup would end up being <span>Line1<br/>Line2</span>, it actually evaluates to <span>Line1&lt;br/&gt;Line2</span>.

Is there any way to get the value of the variable not to be HTML encoded?

P.S.: This is an oversimplified example of what I'm trying to do. I know this could be rewritten a number of ways to make it work, but the way my code is constructed, un-encoding the variable would be optimal. If that's not possible, then I'll go down a different road.

More detail: The "text" is coming from a database, where a user can enter free-form text, with carriage returns. The output is HTML, so somehow I need to get the value from the database and convert the carriage returns to line breaks.

[A]
This behavior is "By Design."  When embedding a string expression inside an XML literal the value will be escaped to be a legal string value.
To get the behavior you are looking for you'll need to be embedding an XElement/XNode within an XML literal.  Take the following example.  It will correctly keep the
```
<br/>
```
tag as an XElement.
```
```
Dim text2 = Line
Line
Dim markup2 = <%= text2 %>.ToString
```
```
One way to achieve this is to fake an XElement.  To make the text a valid string, simply wrap it on both ends with a normal tag,
```
<a>
```
for example.  This is now a parsable XML fragment.  Once you have an XElement, it's easy to get the embedded behavior you are looking for
```
```
Dim text = "Line1
Line2"
Dim text2 = XElement.Parse("" + text + "")
Dim markup = <%= text2.Nodes %>.ToString
```
```


q:
Could someone explain why this works in C#.NET 2.0:

    Nullable<DateTime> foo;
    if (true)
        foo = null;
    else
        foo = new DateTime(0);

...but this doesn't:

    Nullable<DateTime> foo;
    foo = true ? null : new DateTime(0);

The latter form gives me an compile error "Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime'."

Not that I can't use the former, but the second style is more consistent with the rest of my code.

[A]
The compiler is telling you that it doesn't know how convert
```
null
```
into a
```
DateTime
```
.
The solution is simple:
```
```
DateTime? foo;
foo = true ? (DateTime?)null : new DateTime(0);
```
```
Note that
```
Nullable<DateTime>
```
can be written
```
DateTime?
```
which will save you a bunch of typing.


q:
When using CDT I would like to have std::string show up in the 'variable' debug window with the string it contains. For instance if it is currently holding the word "history" I would like to see history in the debugger window labeled "variables".

I think that there is a general way to have it drill down into objects but I can't put my finger on it. Does anyone out there know how to do this?

This would also be useful for me to use when outputting just a single field from a complex object.

Thanks,
Bill

[A]
Note that you
don't
want a general way of drilling down into objects; you want to pretty-print STL containers.
I think CDT delegates this to the debugger backend; i.e. it is up to your debugger (gdb, perhaps?) to inform CDT about the value of a variable and how it can be expanded.
Edit: I don't think that the GDB backend shipped with CDT has any support for "intelligent" display of STL containers. If you're really interested in this, I'd suggest that you contact the CDT development team at cdt-dev@eclipse.org.
Update/Edit: Please see other responses below for instructions on how to enable pretty printers in CDT.


q:
In Perl

print "a" x 3;  # aaa

In C#

Console.WriteLine( ??? )

[A]
It depends what you need... there is
```
new string('a',3)
```
for example.
For working with strings; you could just loop... not very interesting, but it'll work.
With 3.5, you could use
```
Enumerable.Repeat("a",3)
```
, but this gives you a sequence of strings, not a compound string.
If you are going to use this a lot, you could use a bespoke C# 3.0 extension method:
```
```
static void Main()
    {
        string foo = "foo";
        string bar = foo.Repeat(3);
    }
    // stuff this bit away in some class library somewhere...
    static string Repeat(this string value, int count)
    {
        if (count < 0) throw new ArgumentOutOfRangeException("count");
        if (string.IsNullOrEmpty(value)) return value; // GIGO
        if (count == 0) return "";
        StringBuilder sb = new StringBuilder(value.Length * count);
        for (int i = 0; i < count; i++)
        {
            sb.Append(value);
        }
        return sb.ToString();
    }
```
```


q:
Being a Windows developer I'm currently working on my own project using LAMP. I understand what I need to know of PHP and MySQL, but Linux looks huge and it's not clear where to start and what is enough given my goals.
And my goals are to grasp general concepts, being able to deploy the project to a hosting provider and to be able to monitor the site's performance in order to spot problems, load issues, etc.

I know, the best solution is to get a Linux administrator to do that, but before I can do that I need to do it myself.

[A]
You might consider, based on your introduction, a
WAMP
option (Windows Apache MySQL Python, Perl, and PHP).
Learning Linux isn't
hard
, but it's certainly not a short task, either. There're a lot of system administration tasks that carry over platform-to-platform, but the real answer to your question is to become at least a hobbyist Linux administrator, and then go from there.


q:
We have 50+ Java batch processes that run at different times of the day.  They run on a Solaris box, and are started via cron.  Currently, the only way we only know if they succeed or fail is by an email generated at the end of each batch process.  We have a support team that monitors these emails.  Recently, we've had issues with emails not being received, even though the batches are running.  There must be a better way.

Without having to reinvent the wheel, are there any open source batch monitoring applications?

And a more general question, what is the best way to monitor batch processes?

[A]
Is there currently some batch management system in-place?  Or are the jobs run through the OS scheduler? (ie, Windows
```
Schedule Tasks
```
or *nix
```
cron
```
)
Quartz
is an Open Source (Apache License) java-based job scheduler that has infrastructure in place for
listeners
that can be used for notification purposes, but there would be some code development involved.


q:
I can't seem to figure out what I am doing wrong here. I publish my website to my server and when I try to run it I get the following exception:

Could not load the assembly 'App_Web_kh7-x3ka'. Make sure that it is compiled before accessing the page.

Has anyone else ever encountered this?

[A]
A quick google for "Make sure that it is compiled before accessing the page."
led me to the following
http://www.velocityreviews.com/forums/t301533-could-not-load-assembly-make-sure-that-it-is-compiled-before-accessing-the-page.html
And the problem might be as described that the application pool / website is not set to the correct version of .NET
The following question has another solution as the last reply
http://forums.asp.net/t/1131537.aspx
From the looks up it it would seem your webserver is not properly configured, or that you are refering to a nonexistant/old dll


q:
How could I setup a nice indice on cap:deploy?

I want the remote server to nice the cp commands like so:

nice -n 19 cp ...

[A]
Using E4X syntax in ActionScript 3 I guess that would be something like:
```
```
report.prop5[0] = false;
```
```


q: Is there a way to print out the diffs like they show when you open them with "gvim -d", with all the common code folded away and only the diffs showing in context?  I tried the print menu option, but it printed the entire file that I was currently "in", rather than printing the folded diffs.

[A]
I dont think theres a way to get a side by side printout of the two files being diffed. But, you could use Vim's "Convert to HTML" tool on each of the two files being diffed and print those out separately. You could then stack them side by side to get the same effect.
Convert to HTML is kind of "pretty printing" - it saves all of the visual colour/syntax/fold  information.
```
```
:he convert-to-HTML
```
```


q: Does any one know the best way to deploy a resource file to the App_GlobalResource folder of the web application when a feature is activated?

[A]
Application resource files cannot be deployed via a feature unless you execute some code and start a SharePoint timer job that copies the files to the App_GlobalResources folder on each Web front-end server.
You should instead let the SharePoint solutions framework deploy the .RESX files to the App_GlobalResources folder on each server. You can specify application resource files as follows in the manifest.xml file of your WSP solution package:
```
```
<?xml version="1.0" encoding="utf-8"?>
<Solution SolutionId="{185E973C-3A10-4e2a-9E0F-DC14414551F9}"
          xmlns="http://schemas.microsoft.com/sharepoint/"
          DeploymentServerType="WebFrontEnd">

  <ApplicationResourceFiles>
    <ApplicationResourceFile Location="yourappname.resx"/>
    <ApplicationResourceFile Location="yourappname.en-US.resx"/>
  </ApplicationResourceFiles>

 ...
</Solution>
```
```
When you deploy the WSP solution package using STSADM or Central Administration, the SharePoint solutions framework will start a timer job that deploys these files to the App_GlobalResources folder of all the Web applications you decided to deploy the solution to.


q:
How can I create a table that has its first row and first column both locked, as in Excel, when you activate 'freeze panes'?  I need the table to both scroll horizontally and vertically (a lot of solutions for this exist, but only allow vertical scrolling).

So, when you scroll down in the table, the first row will stay put, since it will have the column headings.  This may end up being in a thead, or it may not, whatever makes the solution easier.

When you scroll right, the first column stays put, since it holds the labels for the rows.

I'm pretty certain this is impossible with CSS alone, but can anyone point me toward a JavaScript solution?  It needs to work in all major browsers.

[A]
How about a solution where you put the actual "data" of the table inside its own div, with
```
overflow: scroll;
```
? Then the browser will automatically create scrollbars for the portion of the "table" you do not want to lock, and you can put the "table header"/first row just above that
```
<div>
```
.
Not sure how that would work with scrolling horizontally though.


q:
I am preparing a project proposal for a client who wants to publish video in his website. I need to define which video formats will be allowed, which video sizes, as well as the necessary tools for conversion and preparation.

I have no experience with embedding video in websites so which markup do I need to play video online?

[A]
You could embed them using a flash player, like Youtube for example.
A quick way to do this is using some already made player, like the excellent
JW FLV Player
, free for non-commercial projects and very cheap for commercial ones.
It supports FLV and MP4 video files, you can convert your videos in this formats in a lot of ways, for example using
ffmpegx
.


q: Let's say I want to create the alias %xed for %edit -x. How would I do it?

[A]
Update:
The first response( below) does not accept parameters. So put this snippet at the end of the ipy_user_conf.py file ( it is in your home directory ).
```
```
def ed_xed(self,arg):
    ip = self.api
    return ip.magic.im_class.magic_edit(ip.IP," -x %s "%arg)

ip.expose_magic('xed',ed_xed)
```
```
Before update:
Does it has to be %magic?
You can use the macro and store magic to reproduce this behavior without the magic %.
```
```
In [5]: %edit -x
In [6]: macro xed 5
In [7]: store xed
In [8]: xed
```
```
for magic alias from the documentation ( %magic? ):
You can also define your own aliased
  names for magic functions. In your
  ipythonrc file, placing a line like:
execute
IPYTHON
.magic_pf =
IPYTHON
.magic_profile
will define %pf as a new name for
  %profile.
But I don't know how too add the parameter.


q:
I'm writing code in Java, using the NetBeans IDE. I keep getting a couple of "Incompatible Type" errors. I declare a variable as String and then assign to it the value from a method that returns a String too. The error says that there was expected a type of "String" but instead found "..." where "..." the name of the method I call.

For example, this is a line that gives me the error:

incompatible types
found:     encode_monoalphabetic_engine
required:  java.lang.String

encoded = encode_monoalphabetic_engine(string);

[A]
Perhaps you could post a more complete code snippet?
It looks like your method argument
```
string
```
isn't a
```
java.lang.String
```
?


q:
we're dealing with a very slow update statement in an Oracle project.

Here's a little script to replciate the issue:

drop table j_test;

CREATE TABLE J_TEST
(
  ID  NUMBER(10) PRIMARY KEY,
  C1   VARCHAR2(50 BYTE),
  C2   VARCHAR2(250 BYTE),
  C3   NUMBER(5),
  C4   NUMBER(10)
);

-- just insert a bunch of rows
insert into j_test (id)
select rownum
from <dummy_table>
where rownum < 100000;

-- this is the statement that runs forever (longer than my patience allows)
update j_test
set C3 = 1,
    C1 = 'NEU';

There are some environments where the Update-Statement takes just about 20 seconds, some where the statement runs for a few minutes. When using more rows, the problem gets even worse.

We have no idea what is causing this behavior, and would like to have an understanding of what is going on before proposing a solution.

Any ideas and suggestions?
Thanks
Thorsten

[A]
Try this:
```
```
insert into j_test (id, C3, C4)
select rownum, 1, 'NEU'
from <dummy_table>
where rownum < 100000;
```
```


q:
I am sure making a silly mistake but I can't figure what:

In SQL Server 2005 I am trying select all customers except those who have made a reservation before 2 AM.

When I run this query:

SELECT idCustomer FROM reservations
WHERE idCustomer NOT IN
  (SELECT distinct idCustomer FROM reservations
   WHERE DATEPART ( hour, insertDate) < 2)

I get 0 results.

But

SELECT idCustomer FROM reservations

returns 152.000 results and the "NOT IN" part:

SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2

returns only 284 rows

[A]
```
```
SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2
  and idCustomer is not null
```
```
Make sure your list parameter does not contain null values.
Here's an explanation:
```
```
WHERE field1 NOT IN (1, 2, 3, null)
```
```
is the same as:
```
```
WHERE NOT (field1 = 1 OR field1 = 2 OR field1 = 3 OR field1 = null)
```
```
That last comparision evaluates to null.
That null is OR'd with the rest of the boolean expression, yielding null. (*)
null is negated, yielding null.
null is not true - the where clause only keeps true rows, so all rows are filtered.
(*) Edit:  this explanation is pretty good, but I wish to address one thing to stave off future nit-picking.  (TRUE OR NULL) would evaluate to TRUE.  This is relevant if field1 = 3, for example.  That TRUE value would be negated to FALSE and the row would be filtered.


q:
I have the following div layout:

Everything is fine when I put normal txt elements in both the blue and the orange div. However, when I place an image in the orange div (which is 31px), the elements in the blue div get pushed down by about half the height of the blue div.

(additional info, when hovering over the html for the orange div in firebug, it seems like only half of the image is contained within it, even though to the naked eye it appears fine).

Would appreciate any help, I'm still a bit rusty on the box model. Thanks.

[A]
I'm not so good with CSS boxes, but could adding: display:inline; to the image style fix the porblem? And/Or adding margin:0px;
Oh and is the brwoser rendering in Quirks mode, since not making it render in Quirks mode could fix some problems too.
Edit
By quirks mode I mean, does your page has a DOCTYPE declaration similar to the one below (although you should off course use the corrext DOCTYPE)
```
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
```
```
more about DOCTYPES here:
http://htmlhelp.com/tools/validator/doctype.html


q: I'd like to copy the files that have a specific file extension to a new folder. I have an idea how to use os.walk but specifically how would I go about using that? I'm searching for the files with a specific file extension in only one folder (this folder has 2 subdirectories but the files I'm looking for will never be found in these 2 subdirectories so I don't need to search in these subdirectories). Thanks in advance.

[A]
```
```
import glob, os, shutil

files = glob.iglob(os.path.join(source_dir, "*.ext"))
for file in files:
    if os.path.isfile(file):
        shutil.copy2(file, dest_dir)
```
```
Read the
documentation
of the shutil module to choose the function that fits your needs (shutil.copy(), shutil.copy2() or shutil.copyfile()).


q:
In javascript, I've got a block of HTML like this:

<h2>{title}</h2>
<p><a href="{url}">{content}</a></p>

And I'm trying use regex "match" to spit out an array of all the {item}'s. So my output should look like:

['title', 'url', 'content']

I've gotten as far as:

var pattern = new RegExp("\{[a-zA-Z]+\}+");
var match = pattern.exec("{Sample} bob {text}");

But it's only returning the first tag.

This is just beyond my regex skills. Can anyone help?

Cheers!

[A]
I think you want:
```
```
var pattern = new RegExp("\{[a-zA-Z]+\}+", "g");
```
```
The second option is a flag telling it to search the entire string and return all matches.
See:
http://www.evolt.org/article/Regular_Expressions_in_JavaScript/17/36435/
for more details.


q:
I am looking for a Windows based library which can be used for parsing a bunch of C files to list global and local variables. The global and local variables may be declared using typedef. The output (i.e. list of global and local variables) can then be used for post processing (e.g. replacing the variable names with a new name).

Is such a library available?

[A]
Some of the methods available:
Elsa: The Elkhound-based C/C++ Parser
CIL - Infrastructure for C Program Analysis and Transformation
Sparse - a Semantic Parser for C
clang: a C language family frontend for LLVM
pycparser: C parser and AST generator written in Python
Alternately you could write your own using
lex and yacc
(or their kin- flex and bison) using a public
lex specification
and a
yacc grammar
.


q:
When I try using a Name="id" and\or x:name="id" I get a compiler error:

The Type 'MyName' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.

When I don't have this specified my control runs just fine. Any suggestions?

[A]
I've run into this before and believe it's a compiler bug. I ended up just sticking a named
```
ContentControl
```
in my XAML and sticking the user control in it from the code behind. Hopefully someone can share an actual fix for this.


q:
What is the @ symbol mean in oracle?

For example:

select * from question_answer@abcd where id = '45'

[A]
It refers to a non-local table, the bit behind the @ is the db descriptor.
```
```
select * from question_answer@abcd where id = '45'
```
```
Means select not from the local
```
question_answer
```
table, but from the table on the db designated as
```
abcd
```
. The keyword to google for is
```
dblink
```


q:
I apologize in advance if this question seems remedial.

Which would be considered more efficient in Python:

Standard import

import logging

try:
  ...some code...
exception Exception, e:
  logging.error(e)

...or...

Contextual import

try:
  ...some code...
exception Exception, e:
  import logging
  logging.error(e)

[A]
They're essentially the same. The Python interpreter will only load a used module
once
, no matter how many times you import it. Changing the location of the import statement only has an effect on where the name is bound -- for example, if your
```
import
```
statement is inside a function, the name can only be used in that function.
Generally, though, imports are usually done as close to the "top" of a file as possible.


q:
I would like to create dynamic urls that route to controller actions with an Id value. I've created the following route using a catch-all parameter

routes.MapRoute(
            "RouteName",
            "{id}/{*Url}",
            new { controller = "Controller", action = "Action", id = "" }
        );

This works as expected and allows me to use the following Urls:

"http://website.com/1/fake/url/path" (1 being the id that gets passed to the action method)

Does anyone know a way to achieve it this way instead without creating my own http module?:

"http://website.com/fake/url/path/1"

Thanks - Mark

[A]
That's a really difficult one, for me anyway.
Given the following route:
```
```
routes.MapRoute("Default", "{*token}",
    new { controller = "Home", action = "Index", token = 0 });
```
```
Your controller and supporting classes would be something like this:
```
```
[HandleError]
public class HomeController : Controller
{
    public ActionResult Index([ModelBinder(typeof(IndexReqquestBinder))] IndexRequest request)
    {
        ViewData["Title"] = "Home Page";
        ViewData["Message"] = String.Format("We're looking at ID: {0}", request.ID);

        return View();
    }
}

public class IndexRequest
{
    public Int32 ID { get; set; }
    public IndexRequest(Int32 id)
    {
        this.ID = id;
    }
}

public class IndexReqquestBinder : IModelBinder
{
    public ModelBinderResult BindModel(ModelBindingContext bindingContext)
    {
        if ( null != bindingContext.RouteData.Values["token"] ) {
            foreach ( String v in bindingContext.RouteData.Values["token"].ToString().Split('/') ) {
                Int32 id = 0;
                if ( Int32.TryParse(v, out id) ) {
                    return new ModelBinderResult(new IndexRequest(id));
                }
            }

        }
        return new ModelBinderResult(new IndexRequest(0));
    }
}
```
```


q: How do I install a specific package, like derbytools, with Maven without specifying it as a dependency of project?

[A]
Here is a sample using the
```
mvn install
```
goal.  I used windows style env vars in place of parameters you will need to provide.
```
```
mvn install:install-file -DgroupId=%DERBYTOOLS_GROUP_ID% \
    -DartifactId=%DERBYTOOLS_ARTIFACT_ID% \
    -Dversion=%DERBYTOOLS_VERSION% \
    -Dpackaging=jar \
    -Dfile=%DERBYTOOLS_FILE_PATH%
```
```


q:
I'm using Spring's dependency injection but I'm running into difficulty loading a resource in my Spring config file.

The resource is an XML file and is in a JAR file on my classpath. I try to access it as follows:

<import resource="classpath:com/config/resources.xml" />

however I keep getting encountering the following error:

Failed to import bean definitions from URL location [classpath:com/config/resources.xml]

The JAR file is on the classpath of a Java project, which is in turn used by my web app. Should I really be doing my Spring configuration in the web project as opposed the Java project, or does that matter?

[A]
If it needs to be in the classpath of your webapp, then you should stick the JAR containing the config file into your WEB-INF/lib directory.
If you're using a webapp, then the common convention is use a ContextLoaderListener to ensure a WebApplicationContext is inserted into a standard place in the ServletContext:
```
```
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/com/config/resources.xml</param-value>
</context-param>
```
```
Then use
WebApplicationContextUtils
to fish the application context out of the servlet context using:
```
```
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
```
```


q:
I'm teaching Java EE at the university, and this was a question a student asked. I said "no", but I wasn't really sure, so I thought I might ask you mighty developers. :)

Basically, what I'd like to do is to use entities if they were in my context: cat getters, setters, etc, so like normal POJOs. if I use an EJB using its remote inferface, the entities gets decoupled from the core infrastructure, so that's a no-go.

I thought about writing a layer such as this in my MSc thesis. If it's a dead idea, feel free to tell me. If it's not, tell me if you'd like one.

Or if there is such a tool out there, let me know!

[A]
One alternative is
the Spring Framework
.  Spring provides its own support for binding entity objects to the view and handles the getting/setting for you once it is wired up.  There are many Spring modules to pick and choose from.  Spring MVC and Spring Webflow are both worth checking out.  Spring MVC (IMO) is simpler to get started with, but Sring Webflow allows for more complex navigation and more scope options (ex: flow scope).  If you're looking for a book
Spring In Action
is descent.  There are some concepts you will need to tackle (such as dependency injection) in order to use Spring but it is well worth the time.


q:
I have a directory full of files and I need to pull the headers and footers off of them. They are all variable length so using head or tail isn't going to work. Each file does have a line I can search for, but I don't want to include the line in the results.

It's usually

*** Start (more text here)

And ends with

*** Finish (more text here)

I want the file names to stay the same, so I need to overwrite the originals, or write to a different directory and I'll overwrite them myself.

Oh yeah, it's on a linux server of course, so I have Perl, sed, awk, grep, etc.

[A]
Maybe? Start to Finish with not-delete.
```
```
$ sed -i '/^\*\*\* Start/,/^\*\*\* Finish/d!' *
```
```
or...less sure of it...but, if it works, should remove the Start and Finish lines as well:
```
```
$ sed -i -e '/./,/^\*\*\* Start/d' -e '/^\*\*\* Finish/,/./d' *
```
```
```
d!
```
may depend on the build of
```
sed
```
you have -- not sure.
And, I wrote that entirely on (probably poor) memory.


q: I am writing an algorithm to find the dominating set of a tournament graph. Is the minimum spanning tree of a directed graph equivalent to the dominating set of the graph? In other words, if I find the smallest MST for the tournament graph (by iterating through all of the vertices), can I then say this is equivalent to the dominating set of the graph?

[A]
No, because the MST will include all vertices of the graph, and the dominating set might not.
See for example the graph here:
http://en.wikipedia.org/wiki/Tournament
```
_
```
(graph
```
_
```
theory)
Vertices 2 and 4 create a dominating set, and not a spanning tree.


q:
I have a datagridview where the users can select which subset of columns to view.
The problem I am having is that when I change the columns being displayed, the column widths are only being determined by the width of the Header Cells, not the data in it.
I do have each column set to AutoSizeMode = AllCells.

If a new row is added, the columns become the correct width. But when the set of columns is changed, the widths are wrong.

[A]
Hmm... can't say I've seen that myself, but (as a workaround) you could try toggling the resize mode after you change the columns:
```
```
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
```
```
Worth a try...


q: Is there a quick-and-dirty way to tell programmatically, in shell script or in Perl, whether a path is located on a remote filesystem (nfs or the like) or a local one? Or is the only way to do this to parse /etc/fstab and check the filesystem type?

[A]
You can use "df -T" to get the filesystem type for the directory, or use the -t option to limit reporting to specific types (like nfs) and if it comes back with "no file systems processed", then it's not one of the ones you're looking for.
```
```
df -T $dir | tail -1 | awk '{print $2;}'
```
```


q:
In the .xsd file for a typed DataSet in .NET, there's a <Connections> section that contains a list of any data connections I've used to set up the DataTables and TableAdapters.

There are times when I'd prefer not to have those there.  For instance, sometimes I prefer to pass in a connection string to a custom constructor and use that rather than look for one in settings, .config, etc.

But it seems like if I remove the connection strings from that section (leaving it empty), or remove the section entirely, the DataSet code-generation tool freaks out.  Whereas if I don't remove them, the DataSet gripes when I put it in a different project because it can't find the settings for those connection strings.

Is there any way I can tell a typed DataSet not to worry about any connections?  (Obviously I'll have to give it a connection if I change any TableAdapter SQL or stored procs, but that should be my problem.)

[A]
This has bugged me for a long time as well and I did some testing recently.  Here is what I came up with.  For the record, I'm using VS 2008 SP1.
Datasets
will
store connection string information whether you want them to or not.
You
can
make sure datasets won't store passwords in their connection strings.
You can either have the connection string stored in the 'connections' section the .xsd file or you can have it stored in the app.config file and referenced from the 'connections' section of the .xsd file.  Either way, the 'connections' section appears to be a requirement.
If you find a way to make it work, please post here.  Currently, I store the connection string in the xsd file and make sure I'm not storing the password.  Then, when I use it it code, I always create my own connection and never use one stored in the dataset.


q: I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should use) properly. These two files will always be discarded at the conclusion of my script (which packages a series of files together in a zip format). Thanks in advance.

[A]
Just call
```
os.remove("path/to/file")
```
. For example, to remove the file
```
.emacs
```
, call
```
```
os.remove(".emacs")
```
```
The path should be a
```
str
```
that's the pathname of the file. It may be relative or absolute.


q:
This is a subjective question, but I need opinions.

I have a WinForms C# application whose window hides itself after a specific keystroke (Enter or Escape), with possible modifiers (e.g. Ctrl-Enter). When hiding on KeyDown or KeyPress, the other application that becomes active after my window hides itself receives the KeyUp event for that keystroke. Normally, it shouldn't affect that other application, but some of them out there react on KeyUp. For example, TweetDeck sends the message currently being edited on "Enter" KeyUp, even if it did not receive KeyDown/KeyPress.

So I thought, fine, I'll be a good citizen, I'll hide on KeyUp. But this doesn't feel right. If I only look for keys up, I'm doing what I blame others of doing! If I try to create an history of matching KeyDown/KeyUp, I'm over-complicating my code (modifiers generate their own key up).

What should I do? What should a well-implemented application do?

[A]
This is a hack, but you can set the state of your program to "pending hide" when receive the key down.  And then when you get the key up for that sequence, reset the "pending state" and then hide.
Alternatively, can you just "eat" the key up off the message queue after you receive the key down?
I would not worry too much about applications handling key up rather than key down - like you point out - the only reason this is an issue is because your app changes active windows in the middle of a key down key up sequence.  It is your responsibility (IMO) to also "eat" the key up messages.  You can probably just handle the key up instead of key down with no adverse side effects.
EDIT
Thinking about this further - when doing alt-tab to go to a new window - the action does not happen until the key up.  In the meantime it shows a window of possible apps to change to.  You can do similar action and the behavior has a precedent.
So:
On key down: Display window that indicates app will hide.
on key up: hide window
This is "stateful" - you can only go into hiding if you received the key down and the key up - at least that is what I would do.  99.9999% (guess) not handling key down would be ok.


q:
Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents.

Is this possible?

And how could I go about doing it?

[A]
Here is a recursive version
```
```
def zipfolder(path, relname, archive):
    paths = os.listdir(path)
    for p in paths:
        p1 = os.path.join(path, p)
        p2 = os.path.join(relname, p)
        if os.path.isdir(p1):
            zipfolder(p1, p2, archive)
        else:
            archive.write(p1, p2)

def create_zip(path, relname, archname):
    archive = zipfile.ZipFile(archname, "w", zipfile.ZIP_DEFLATED)
    if os.path.isdir(path):
        zipfolder(path, relname, archive)
    else:
        archive.write(path, relname)
    archive.close()
```
```


q:
I have a user control where the XAML of the control can bind to the appropriate properties from the parent's data context like normal (the data context propagates in xaml).

For example, I have a window whose DataContext I am setting to ObjectA for example. My user control within the window is then try to access the properties within the dataContext

So my window's xaml and code behind can both see a non-null DataContext.

My control that DataContext propagates to can see a non-null DataContext in the Xaml but not in the code behind.

What is the proper way of handling this?

[A]
I think you are checking the 'DataContext' in the constructor of the UserControl. It will be null at the Constructor since the user control hasnt yet created while execution is in the constructor code. But check the property at Loaded event you will see the object properly.
```
```
public partial class UserControl1
{
    public UserControl1()
    {
        this.InitializeComponent();

        //DataContext will be null here
        this.Loaded += new RoutedEventHandler(UserControl1_Loaded);
    }

    void UserControl1_Loaded(object sender, RoutedEventArgs e)
    {
        //Check DataContext Property here - Value is not null
    }
}
```
```


q:
I have a Win32 console application which is doing some computations, compiled in Compaq Visual Fortran (which probably doesn't matter).

I need to run a lot of them simultaneously.

In XP, they take around 90-100% CPU together, work very fast.
In Vista, no matter how many of them I run, they take no more than 10% of CPU (together), and work very slow respectively.

There is quite a bit of console output going on, but now VERY much.
I can minimize all the windows, it does not help. CPU is basically doing nothing...

Any ideas?

Update:

No, these are different machines, but they run relatively the same hardware. 2. Threads are not used, this is a VERY OLD (20 yrs) plain app for DOS, compiled in win32. It is supposed to compute iterations until they meet, consume all it has. My impression - VISTA just does NOT GIVE IT MORE CPU

[A] Is it the same machine hardware on your Vista and XP? It might use just 10% of the Vista because it doesn't require more. Are you using Thread? I think it requires more information about your project to have a better idea. Have you try to use a profiler to see what's going on?


q:
Example

There is an application that measures temperature in each town of the world. Each measurement is taken every 5 minutes and written in to the Measurement table.

CREATE TABLE [dbo].[Measurement](
    [MeasurementID] [int] IDENTITY(1,1) NOT NULL,
    [Town] [varchar](50) NOT NULL,
    [Date] [datetime] NOT NULL,
    [Temp] [int] NOT NULL,
CONSTRAINT [PK_Measurement] PRIMARY KEY CLUSTERED
(
    [MeasurementID] ASC
)) ON [PRIMARY]

Question

What is the most efficient query to get a list of the towns and their current temperature?

Assume there are 100k towns and 10 million records

NOTE: I have added a couple of possible answers, but there are probably other options.

[A]
```
```
select s.*
from Measurement s
where exists (
   select 1
   from Measurement s1
   where s.Town = s1.Town
   group by s1.Town
   having max( s1.Date )= s.Date)
   order by s.Town
```
```


q: What's the different between SCSF and Acropolis ?

[A]
http://en.wikipedia.org/wiki/Microsoft_codename_Acropolis
http://msdn.microsoft.com/en-us/library/aa480482.aspx
Acropolis has not been released yet. SCSF is available now? Not sure what else you could find out since one of them technically is not in existence :)


q: I understand how Lucene.net can work for text indexing. Will I be able to efficiently search for documents based on a given date range? Or will Lucene.net just use text matching to match the dates?

[A]
Lucene.Net will just use text matching, so you'd need to format the dates correctly before adding to the index:
```
```
public static string Serialize(DateTime dateTime)
    {
        return dateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
    }

    public static DateTime Deserialize(string str)
    {
        return DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
    }
```
```
You can then, for example, perform a range based query to filter by date (e.g. 2006* to 2007* to include all dates in 2006 and 2007).


q:
I am looking for a way to mount\unmount a USB flash drive using VBScript.  This is the closest I was able to get.

Sub EjectDrive(strDrive)
On Error Resume Next
CONST SSF_DRIVES = 17
Set objShell = CreateObject("Shell.Application")
Set objDrive = objShell.Namespace(SSF_DRIVES).ParseName(strDrive)
objDrive.InvokeVerb "E&ject"
End Sub

[A]
This will work on Windows Server 2003, but not NT/2000/XP/Vista unfortunately.
```
```
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery _
    ("Select * From Win32_Volume Where Name = 'E:\\'")

For Each objItem in colItems
    objItem.Dismount(True, True)
Next
```
```
From
Dismount a Volume
.


q:
Greetings!

I'm scratching my head, wondering why when I do the following:

Response.Redirect(@"http://www.example.com/file.exe?id=12345");

Both IE6 and IE7 will download the file as "file" (with no extension), but Firefox, Opera, Google Chrome and Safari have no problems at all downloading the file as "file.exe".

Any idea what IE6/7's problem is and how can I fix this?

[A]
Have You tried to set correct content-type in Your response headers? For example:
```
```
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="file.exe"
```
```


q:
FreeMarker templates support an if-statement with the following syntax

<#if hot>
  It's hot.
</#if>

I've looked in the documentation and can't find any support for an if-else statement. Of course, I could achieve the same result with:

<#if hot>
  It's hot.
</#if>
<#if !hot>
  It's not hot.
</#if>

Is there support for if-else in FreeMarker?

[A]
Yes, you can write:
```
```
<#if hot>
it's hot
<#else>
it's not
</#if>
```
```
And if you're doing lots of freemarker, I really can recommend IntelliJ IDEA 8, its freemarker support really helps...


q:
I have a function, a(), that I want to override, but also have the original a() be performed in an order depending on the context. For example, sometimes when I'm generating a page I'll want to override like this:

function a() {
    new_code();
    original_a();
}

and sometimes like this:

function a() {
    original_a();
    other_new_code();
}

How do I get that original_a() from within the over-riding a()? Is it even possible?

Please don't suggest alternatives to over-riding in this way, I know of many. I'm asking about this way specifically.

[A]
You could do something like this:
```
```
var a = (function() {
    var original_a = a;

    if (condition) {
        return function() {
            new_code();
            original_a();
        }
    } else {
        return function() {
            original_a();
            other_new_code();
        }
    }
})();
```
```
Declaring
```
original_a
```
inside an anonymous function keeps it from cluttering the global namespace, but it's available in the inner functions.
Like Nerdmaster mentioned in the comments, be sure to include the
```
()
```
at the end. You want to call the outer function and store the
result
(one of the two inner functions) in
```
a
```
, not store the outer function itself in
```
a
```
.


q:
I am trying to autoreload my page after every 20 seconds. I am using JavaScript for this instead of the <meta>.

I have <body onload="SetTimer()">
and here is my JavaScript function

    function SetTimer(){
        setTimeout('window.location.replace(window.location.pathname)', 20000)
    }

Now my problem is I also pass a parameter within the querystring when this page is loaded first. But when the page relaods again (window.location.pathname does not include the parameter) hence I am not able to assign values to the labels on the page which is based on the parameters passed.

[A]
window.location will include the GET parameters that were that was passed.
```
```
function SetTimer(){
    setTimeout('window.location.replace(window.location)', 20000)
}
```
```
If you are submitting parameters through POST, the best method will probably be to create a form with hidden inputs for each parameter.  Submit the form every twenty seconds.


q:
I'm creating a (Java) class to represent an object in a musical score that has a specific onset time, and possibly a duration as well.  I need a good name for this class.  Is something like "Timed" or "TimedObject" appropriate?  I've tried to come up with something that ends in "-able" (like Runnable) but I can't think of anything good; "OnsetTimeable" sounds silly, because "OnsetTime" isn't a verb.  I don't really like "MusicalObject" either since that doesn't imply the object has an onset time (a "musical object" could be anything related to the score).

Update:  Musically, this class represents an abstraction of something that happens at a point in time in the score. This is supposed to be the superclass of classes like Note, KeyChange, MeterChange, DynamicMarking, TempoMark, etc.

[A]
What is the main service (or services) your object is supposed to propose to the rest of your system ?
I believe its name should represents the
abstraction
you want to make by designing it in the first place.
So far, we know what your object is made of (an onset times, ...), but we do not know what is
does
, and more importantly as
baash05
points out, what it
is
: in a word, what it represents.
As mentioned in the question
What’s the best approach to naming classes?
,
the single responsibility principle
can also be a good approach.
If it must represent some common structure of any characteristics of a score (note, ...), a name like
ScoreAttribute
could be appropriate.


q:
I need to unzip a compressed file on the fly in my program.  It works when I try it on my own linux computer, but for some reason the school computers fail whenever I tell them to do it.  To unzip I'm using the following command:

 zcat /file/address/file.tar.gz

and get the error:

 /file/address/file.tar.gz.Z: No such file or directory

I tried looking through the documentation but couldn't find a flag to turn off this odd behavior.

[A]
Your school's system still has the old "compress" style utilities rather than the newer GNU "gzip" based ones.
You need to use
```
gzcat
```
rather than
```
zcat
```
, assuming that it's available.


q:
What's a good rule of thumb for naming methods that return properties/attributes/members of an object?  If an object has some immutable quality "blarg", should a method that returns that quality be called "blarg()" or "getBlarg()"?  The Java API, for example, is inconsistent: most properties are accessed through "get" methods (even those that don't have corresponding "set" methods), but yet we also have things like Object.hashCode() instead of Object.getHashCode().

Update: Should whether or not it's the property is a field (in the implementation) be the determiner here?  What about a class to represent immutable points in 2-d space?  Regardless of whether the point is stored as (x,y) or (r,theta), I would still want accessors for all four properties.  Should they be getX(), getY(), etc, or just x(), y(), etc?  From the point of view of the user, shouldn't all four have the same naming convention since we don't want our user to know/care about our implementation?

[A]
I believe the most often used conventions are:
```
```
GetBlarg() or getBlarg()
```
```
It could be argued that the name
```
GetHashCode()
```
is incorrect, since the object doesn't have a field called
```
hashcode
```
and that it's calculated.
These are of course all conventions, not rules, and most of them have evolved over a long time and as such are not 100% consistent.
Regards
K


q:
When is it appropriate to use <cflock scope="application"> or it's ilk as opposed to <cflock name="foo">?

Specifically, I'm interested in using CFLock to protect shared objects in the application, session, or server scopes, but I'm also interested in finding out about different uses of locking in ColdFusion.

[A]
Typically you should always use cflock for session, application and server vars any time you're reading or changing those vars outside of an Application.cfc so as to prevent race-conditions.  Here's an article that may be helpful:
http://www.horwith.com/index.cfm/2008/4/28/cflock-explained
Edit:
To further answer your question about scope, I always use
```
<cflock scope="application">
```
(for example) whenever interacting with shared resources.


q:
I am creating a new table inside mysql and I am trying to add a foreign key constraint to one of the fields.

CREATE TABLE `onlineorder` (
  `receiptid` varchar(10) NOT NULL default '',
  `delivereddate` date default NULL,
  `cid` int(10) NOT NULL,
  `card#` int(10) default NULL,
  `expire` date default NULL,
  PRIMARY KEY  (`receiptid`),
  FOREIGN KEY (receiptid) REFERENCES purchase
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

However, after it creates it, I go into phpMyAdmin and export the table.  and it seems like the foreign key constraint has disappeared.

CREATE TABLE `onlineorder` (
  `receiptid` varchar(10) NOT NULL default '',
  `delivereddate` date default NULL,
  `cid` int(10) NOT NULL,
  `card#` int(10) default NULL,
  `expire` date default NULL,
  PRIMARY KEY  (`receiptid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Does phpMyAdmin get rid of foreign keys or am I doing something wrong here?

[A]
You need to use the InnoDB engine to have foreign keys.
Ref:
http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html


q:
I'd love to know if there is a module to parse "human formatted" dates in Perl. I mean things like "tomorrow", "Tuesday", "next week", "1 hour ago".

My research with CPAN suggest that there is no such module, so how would you go about creating one? NLP is way over the top for this.

[A]
Date::Manip
does exactly this.
Here is an example program:
```
```
#!/usr/bin/perl

use strict;
use Date::Manip;

while (<DATA>)
{
  chomp;
  print UnixDate($_, "%Y-%m-%d %H:%M:%S"),  " ($_)\n";
}

__DATA__
today
yesterday
tomorrow
last Tuesday
next Tuesday
1 hour ago
next week
```
```
Which results in the following output:
```
```
2008-11-17 15:21:04 (today)
2008-11-16 15:21:04 (yesterday)
2008-11-18 15:21:04 (tomorrow)
2008-11-11 00:00:00 (last Tuesday)
2008-11-18 00:00:00 (next Tuesday)
2008-11-17 14:21:04 (1 hour ago)
2008-11-24 00:00:00 (next week)
```
```
UnixDate is one of the functions provided by
```
Date::Manip
```
, the first argument is a date/time in any format that the module supports, the second argument describes how to format the date/time.  There are other functions that just parse these "human" dates, without formatting them, to be used in delta calculations, etc.


q: Why does Resharper want you to change most variables to var type instead of the actual type in the code?

[A]
It's just an option. You can disable it:
ReSharper -> Options -> Code Inspection -> Inspection Severity -> Code Redundencies -> Use 'var' keyword where possible: change this to "Do not show"
There's also the context (lightbulb) option which will take you in each direction - this is under ReSharper -> Options -> Languages -> C# -> Context Actions -> "Replaces explicit type declaration with 'var'"


q:
In SQL Server Mgt Studio 2005, when I open the Object Explorer to script an object to a new Query Editor window, the tab for that new script window is titled something like 'MyServerName.MyDatabaseName - sqlquery37.sql'

Not very descriptive. So when I get a bunch of windows open at the same time, I have no idea which one is which.

The 'Active Files' dropdown is useless because of this.

Is there a way to configure Mgt. Studio so that the Query Editor Window tab title more accurately reflects the object that I'm working on?

Thanks!

[A]
Not [easily] without actually saving the script window to a file - then you get
```
```
MyServerName.MyDatabaseName - MyFileName.sql
```
```
as the title.
You might be able to change this with a plugin/add-on, but not without writing code.


q:
When I open a file for reading in Haskell, I've found that I can't use the contents of the file after closing it. For example, this program will print the contents of a file:

main = do inFile <- openFile "foo" ReadMode
          contents <- hGetContents inFile
          putStr contents
          hClose inFile

I expected that interchanging the putStr line with the hClose line would have no effect, but this program prints nothing:

main = do inFile <- openFile "foo" ReadMode
          contents <- hGetContents inFile
          hClose inFile
          putStr contents

Why does this happen? I'm guessing it has something to do with lazy evaluation, but I thought these expressions would get sequenced so there wouldn't be a problem. How would you implement a function like readFile?

[A]
The explanation is rather long to be included here. Forgive me for dispensing a short tip only: you need to read about "semi-closed file handles" and "unsafePerformIO".
In short - this behaviour is a design compromise between a semantic clearness and lazy evaluation. You should either postpone hClose until you are absolutely sure you woudnt be doing anything with the file content (like, call it in error handler, or somesuch), or use something else besides hGetContents to get file contents non-lazily.


q:
How can I get the name of a file in in PHP?   What I want to do is have a function take a string of a filename and then do some stuff if it's actually on the page.

function onThisPageFunction(fileNameFromFunction)
{
  if(onThisPage == fileNameFromFunction)
  {
    do stuff
  }
}

[A]
If I understand correctly you want
```
__FILE__
```
.
Ref:
http://php.net/manual/en/language.constants.predefined.php


q:
I have a 5GB database and a 20GB transaction log (SQL Server 2005). Not sure why it is so large or what happened to make it that large, it used to be around 1/2 the size of the DB. DB grows about 1GB/month.

Are there any guidelines to how how big your transaction log should be relative to your database file size?

EDIT: I'm not saying my transaction log is huge (I know some DBAs would laugh at my weenie-sized DB), just in relation to the DB file I think it is huge.

[A]
If you have a lot of transactional behavior, it's not uncommon at all. However, you probably should investigate means of making it smaller. There are quite a few options for this, but without knowing your recovery model, I could never presume to make a recommendation. Start with this
MSDN link
, this
knowledge base article
, then move from there. Carefully. :)


q:
Given an amount of days, say 25, convert it into a duration text such as "3 Weeks, 4 Days"

C# and F# solutions would both be great if the F# variation offers any improvement over C#.

Edit: The solution should expand past weeks to include months and years. Bonus points for including centuries and so on. Extra bonus if it is somewhat configurable, meaning you can tell the method to exclude the normalization of weeks.