Question:
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

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


Question:
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

Answer:
```
```
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.


Question:
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.

Answer:
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


Question: 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.

Answer:
```
```
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()).


Question:
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!

Answer:
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.


Question:
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?

Answer:
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
.


Question:
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?

Answer:
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.


Question:
What is the @ symbol mean in oracle?

For example:

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

Answer:
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
```


Question:
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)

Answer:
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.


Question:
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

Answer:
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));
    }
}
```
```


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

Answer:
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%
```
```


Question:
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?

Answer:
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());
```
```


Question:
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!

Answer:
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.


Question:
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.

Answer:
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.


Question: 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?

Answer:
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.


Question:
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.

Answer:
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...


Question: 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?

Answer:
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;}'
```
```


Question:
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.)

Answer:
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.


Question: 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.

Answer:
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.


Question:
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?

Answer:
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.


Question:
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?

Answer:
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()
```
```


Question:
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?

Answer:
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
    }
}
```
```


Question:
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

Answer: 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?


Question:
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.

Answer:
```
```
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
```
```


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

Answer:
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 :)


Question: 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?

Answer:
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).


Question:
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

Answer:
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
.


Question:
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?

Answer:
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"
```
```


Question:
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?

Answer:
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...


Question:
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.

Answer:
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
```
.


Question:
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.

Answer:
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.


Question:
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.

Answer:
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.


Question:
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.

Answer:
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.


Question:
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?

Answer:
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


Question:
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.

Answer:
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.


Question:
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?

Answer:
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


Question:
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.

Answer:
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.


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

Answer:
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'"


Question:
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!

Answer:
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.


Question:
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?

Answer:
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.


Question:
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
  }
}

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


Question:
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.

Answer:
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. :)


Question:
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.

Answer:
```
```
String.Format("{0} Weeks, {1} days", days / 7, days % 7);
```
```


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

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


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

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

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

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


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

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

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

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


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

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

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

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

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


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

file systems

web services (none that I've used)

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

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

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

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


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

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


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

Example: 5:42:12 PM

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


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

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

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


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

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

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

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

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


Question:
What could the following line possibly mean?

my $x = shift;

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


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

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

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

TIA.

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


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

What's the difference between

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

and

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

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

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


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

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

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

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

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


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

Thanks

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

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

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


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

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

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


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

What experience do you have with either of these frameworks?

Have you run into any pitfalls with either framework?

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

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


Question:
In another Stack Overflow question Leon Timmermans asserted:

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

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

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

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

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

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


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

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

My question is a two parter:

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

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

Thanks!

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


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

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

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


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

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

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

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

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


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

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


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

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

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

Thanks

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


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

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


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

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

Could someone provide a solution for this small problem?

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


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

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


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

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


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

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

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

var ret = ParseJSON(response.value);;

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


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

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

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

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

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


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

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

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

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

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

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

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


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

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

Client-side registry hacking is not an option.

Does anyone know a way to get around this error?

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

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


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

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

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

    return View();
}

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

    string selectedItem = form["FruitDropDown"];

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

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

    return View();

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

<%= ViewData["Message"] %>

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


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

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

Thanks.

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


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

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


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

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

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

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


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

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

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

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


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

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

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

Thoughts?

from django.forms import ModelForm

from testprogram.online_bookings.models import Passenger

class PassengerInfoForm(ModelForm):

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

    class Meta:
        model = Passenger
        exclude = []

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

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

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

    return MyPassengerForm()

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


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

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

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


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

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


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

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

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


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

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

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


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

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


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

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

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


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

var factory = new ChannelFactory<IMyService>();

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

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

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

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

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

Why?

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


Question:
If I have...

class Bunny < ActiveRecord::Base
  has_many :carrots
end

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

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

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

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


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

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

Answer:
You can use
hbm2ddl
from Hibernate. The docs are
here
.


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

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


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

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


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

using System;

public struct Vector2
{
    public event EventHandler trigger;

    public float X;
    public float Y;

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

hi!

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

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


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

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

Cheers,
Zac

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

Some Text

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


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

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

Does anyone have any insight?

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

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

Some Text

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


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

Answer:
Look up the DAYOFWEEK() function
here
in the MySQL Online Docs


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

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

How would you go about this?

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

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

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

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

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

    }

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


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

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

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

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


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

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


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

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

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


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

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

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

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

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


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

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


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

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

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

#define WINAPI      __stdcall

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

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


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

SEL callback = @selector(mymethod:parameter2);

And I have a method like

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

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

I have tried:

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

but it won't compile.

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