q:
I'd like to capture the output of var_dump to a string.

The PHP documentation says;

As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example).

What would be an example of how that might work?

print_r() isn't a valid possibility, because it's not going to give me the information that I need.

[A]
Use output buffering:
```
```
<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>
```
```


q:
I made a class from Linq to SQL Clasees with VS 2008 SP1 Framework 3.5 SP1, in this case I extended the partial

partial void UpdateMyTable(MyTable instance){
   // Business logic
   // Validation rules, etc.
}

My problem is when I execute db.SubmitChanges(), it executes UpdateMyTable and makes the validations but it doesn't update, I get this error:

[Exception: Deliver]
   System.Data.Linq.ChangeProcessor.SendOnValidate(MetaType type, TrackedObject item, ChangeAction changeAction) +197
   System.Data.Linq.ChangeProcessor.ValidateAll(IEnumerable`1 list) +255
   System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) +76
   System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) +331
   System.Data.Linq.DataContext.SubmitChanges() +19

[A]
if you provide this method, you must perform the update in the method.
http://msdn.microsoft.com/en-us/library/bb882671.aspx
If you implement the Insert, Update and Delete methods in your partial class, the LINQ to SQL runtime will call them
instead
of its own default methods when SubmitChanges is called.
Try
MiTabla.OnValidate

s: huggingface

c: devops

d: intermediate


q:
I've just solved another *I-though-I-was-using-this-version-of-a-library-but-apparently-my-app-server-has-already-loaded-an-older-version-of-this-library-*issue (sigh).

Does anybody know a good way to verify (or monitor) whether your application has access to all the appropriate jar-files, or loaded class-versions?

Thanks in advance!

[P.S. A very good reason to start using the OSGi module architecture in my view!]

Update: This article helped as well! It gave me insight which classes JBoss' classloader loaded by writing it to a log file.

[A]
I don't think there is a good way to check that. And I'm not sure you want to do that. What you need to do  is get familiar with your app-server's class loading architecture, and understand how that works.
A simplified explanation of how it works is: an EJB or a web-app will first look for a class or a resource in  libraries declared in its own module (ejb-jar or war). if the class is not found there, the class loader forwards the request to the its parent class loader which is either a declared dependency (usualy an ejb) or the the application class loader which is responsible to load libraries and resources declared in the ear package. If the class or the resource is still not found the request is forwarded to the app server which will look in its own classpath.
This being said, you should remember that a Java EE module (web-app, ejb) will always load classes from a jar that is in the nearest scope. For example if you package log4j v1 in the war file, log4j v2 at ear level and you put log4j v3 in your app-server's class path, the module will use the jar in its own module. take that away and it'll use the one at ear level. take that out and it will use the one in the app-server's classpath. Things get more tricky when you have complex dependencies between modules.
Best is to put application global libraries at ear level.


q:
I've never developed a web application that uses distributed memory.

Is it common practice to run a tool such as Microsoft Velocity on my local machine as I develop, should I run Velocity on another server as I develop, or should I just develop as normal (default session & cache) and use Velocity only after I've deployed to our development server?

We are running into a lot of memory issues in our production web application so we are researching into splitting our servers into a farm.

[A]
I'm looking at using Velocity on a project as well. What I've done thus far is to write a common caching interface and a simple implementation that utilizes the standard ASP.NET caching system. This way I can program against that interface and later plug in the Velocity caching via a concrete implementation of the interface. You can accomplish this more easily using a dependency injection framework such as Unity or Structure Map.
As for where to use Velocity, I'd be sure to try it out in a development environment before going live. If you have a limited number of physical machines, use Virtual PC to set up some virtual servers and install the caching framework onto them.


q: I've got a generic dictionary Dictionary<string, T> that I would like to essentially make a Clone() of ..any suggestions.

[A]
(Note: although the cloning version is potentially useful, for a simple shallow copy the constructor I mention in the other post is a better option.)
How deep do you want the copy to be, and what version of .NET are you using? I suspect that a LINQ call to ToDictionary, specifying both the key and element selector, will be the easiest way to go if you're using .NET 3.5.
For instance, if you don't mind the value being a shallow clone:
```
```
var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
                                               entry => entry.Value);
```
```
If you've already constrained T to implement ICloneable:
```
```
var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
                                               entry => (T) entry.Value.Clone());
```
```
(Those are untested, but should work.)


q:
I have the following code:

info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args));
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd()); //need the StandardOutput contents

I know that the output from the process I am starting is around 7MB long. Running it in the Windows console works fine. Unfortunately programmatically this hangs indefinitely at WaitForExit. Note also this code does NOT hang for smaller outputs (like 3KB).

Is it possible that the internal StandardOutput in ProcessStartInfo can't buffer 7MB? If so, what should I do instead? If not, what am I doing wrong?

[A]
The
documentation
for
```
Process.StandardOutput
```
says to read before you wait otherwise you can deadlock, snippet copied below:
```
```
// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();
```
```


q:
I've seen both done in some code I'm maintaining, but don't know the difference. Is there one?

let me add that myCustomer is an instance of Customer

[A]
The result of both are exactly the same in your case. It will be your custom type that derives from
```
System.Type
```
. The only real difference here is that when you want to obtain the type from an instance of your class, you use
```
GetType
```
. If you don't have an instance, but you know the type name (and just need the actual
```
System.Type
```
to inspect or compare to), you would use
```
typeof
```
.
Important difference
EDIT: Let me add that the call to
```
GetType
```
gets resolved at runtime, while
```
typeof
```
is resolved at compile time.


q:
How do I cause the page to make the user jump to a new web page after X seconds. If possible I'd like to use HTML but a niggly feeling tells me it'll have to be Javascript.

So far I have the following but it has no time delay

<body onload="document.location='newPage.html'">

[A]
A meta refresh is ugly but will work.  The following will go to the new url after 5 seconds:
```
```
<meta http-equiv="refresh" content="5;url=http://example.com/"/>
```
```
http://en.wikipedia.org/wiki/Meta_refresh


q:
What's the difference between TRUNCATE and DELETE in SQL?

If your answer is platform specific, please indicate that.

[A]
Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below.
General Overview
If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE.
Various system-specific issues have to be considered, as detailed below.
Statement type
Delete is DML, Truncate is DDL (
What is DDL and DML?
)
Commit and Rollback
Variable by vendor
SQL*Server
Truncate can be rolled back.
PostgreSQL
Truncate can be rolled back.
Oracle
Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway.
However, see Flashback below.
Space reclamation
Delete does not recover space, Truncate recovers space
Oracle
If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset.
Row scope
Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows.
Oracle
When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible.
Object types
Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific)
Data Object Identity
Oracle
Delete does not affect the data object id, but truncate assigns a new data object id
unless
there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation.
Flashback (Oracle)
Flashback works across deletes, but a truncate prevents flashback to states prior to the operation.
However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition
Use of FLASHBACK in Oracle
http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638
Privileges
Variable
Oracle
Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant.
Redo/Undo
Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each.
Indexes
Oracle
A truncate operation renders unusable indexes usable again. Delete does not.
Foreign Keys
A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys.
Table Locking
Oracle
Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table.
Triggers
DML triggers do not fire on a truncate.
Oracle
DDL triggers are available.
Remote Execution
Oracle
Truncate cannot be issued over a database link.
Identity Columns
SQL*Server
Truncate resets the sequence for IDENTITY column types, delete does not.
Result set
In most implementations, a
```
DELETE
```
statement can return to the client the rows that were deleted.
e.g. in an Oracle PL/SQL subprogram you could:
```
```
DELETE FROM employees_temp
WHERE       employee_id = 299
RETURNING   first_name,
            last_name
INTO        emp_first_name,
            emp_last_name;
```
```


q:
I'd like to structure a Form with a TabControl but I'd like to avoid having every control on each TabPage end up being a member of the Form I'm adding the TabControl to. So far I've identified these options, please comment or suggest alternatives:

1) Write a UserControl for each TabPage

2) Leave only the Control on the main Form but turn the control variable public and cut-and-past all actual code into separate classes

3) Forgo the Form designer and do everything at runtime

4) Derive from Tabpage (not sure if this works and what the design-time implications are)

Thanks all,

Andrew

[A]
In any complex WinForms application, you will probably run into the problem of too many controls on a form. Not that you'll run into a hard limit, but rather you'll run into a pain point -- such as you're describing.
In most scenarios, for me, your option #1 -- a user control for each tab page -- is the least painful approach. It allows you to encapsulate logical breakdowns of the controls in their own way, scoping them appropriately.
The downside to this is that you will likely end up exposing either a
ton
of properties on your user control. The way out of that problem is fairly simple, though: Use a custom class to represent the data which is "bound" to said control, and then expose a single property for the bound instance of the class.
You'll have better architecture overall, you'll be more maintainable, and as an added bonus, you won't go nuts trying to get the form to work. :)
EDIT:
I should note that you may also end up needing to expose some custom events from the user controls which represent your tab pages. Essentially, if there's a control on the tab whose event is needed by the parent form, you'll have to create an event and raise it so that the parent form knows about it. This isn't terribly difficult, but can add significant LOCs to the user controls.


q:
if I call php's parse_ini_file("foo.ini"), in what paths does it look for foo.ini ?
the include path? the function's documentation doesn't mention it.

[A]
I would imagine it only looks in the current working directory - See
http://uk3.php.net/manual/en/function.getcwd.php
if you want to know what that is.
You can always find a path relative to your application by basing it on $_SERVER['DOCUMENT_ROOT']


q:
I've been doing a massive code review and one pattern I notice all over the place is this:

public bool MethodName()
{
    bool returnValue = false;
    if (expression)
    {
        // do something
        returnValue = MethodCall();
    }
    else
    {
        // do something else
        returnValue = Expression;
    }

    return returnValue;
}

This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct?

I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned.

[A]
I would have used ternary, to reduce control structures...
```
```
return expression ? MethodCall() : Expression;
```
```


q:
Is there any way to list all the files that have changed between two tags in CVS?

Every time we do a release we apply a tag to all the files in that release. I want to find all the files that changed between releases.

It would also work if I could find all files that had changed between two dates.

[A]
I suppose this command would help:
```
```
cvs diff -N -c -r RELEASE_1_0 -r RELEASE_1_1 > diffs
```
```
where
```
RELEASE_1_0
```
and
```
RELEASE_1_1
```
are the names of your tags.
You can find a little more information on cvs diff command
here
plus it should be fairly simple to create a script to make report more suitbable for your needs, ex: number of files changed, created deleted etc. As far as I know the most common cvs GUI tools (wincvs and tortoise) do not provide something like this out of the box.
Hope it helps
```
;)
```


q: I have a Console application hosting a WCF service.  I would like to be able to fire an event from a method in the WCF service and handle the event in the hosting process of the WCF service.  Is this possible?  How would I do this?  Could I derive a custom class from ServiceHost?

[A]
You don't need to inherit from
```
ServiceHost
```
. There are other approaches to your problem.
You can pass an instance of the service class, instead of a type to
```
ServiceHost
```
. Thus, you can create the instance before you start the
```
ServiceHost
```
, and add your own event handlers to any events it exposes.
Here's some sample code:
```
```
MyService svc = new MyService();
svc.SomeEvent += new MyEventDelegate(this.OnSomeEvent);
ServiceHost host = new ServiceHost(svc);
host.Open();
```
```
There are some caveats when using this approach, as described in
http://msdn.microsoft.com/en-us/library/ms585487.aspx
Or you could have a well-known singleton class, that your service instances know about and explicitly call its methods when events happen.


q:
The following test fails:

#!/usr/bin/env python
def f(*args):
    """
    >>> t = 1, -1
    >>> f(*map(lambda i: lambda: i, t))
    [1, -1]
    >>> f(*(lambda: i for i in t)) # -> [-1, -1]
    [1, -1]
    >>> f(*[lambda: i for i in t]) # -> [-1, -1]
    [1, -1]
    """
    alist = [a() for a in args]
    print(alist)

if __name__ == '__main__':
    import doctest; doctest.testmod()

In other words:

>>> t = 1, -1
>>> args = []
>>> for i in t:
...   args.append(lambda: i)
...
>>> map(lambda a: a(), args)
[-1, -1]
>>> args = []
>>> for i in t:
...   args.append((lambda i: lambda: i)(i))
...
>>> map(lambda a: a(), args)
[1, -1]
>>> args = []
>>> for i in t:
...   args.append(lambda i=i: i)
...
>>> map(lambda a: a(), args)
[1, -1]

[A]
The lambda captures variables, not values, hence the code
```
```
lambda : i
```
```
will always return the value i is
currently
bound to in the closure.  By the time it gets called, this value has been set to -1.
To get what you want, you'll need to capture the actual binding at the time the lambda is created, by:
```
```
>>> f(*(lambda i=i: i for i in t)) # -> [-1, -1]
[1, -1]
>>> f(*[lambda i=i: i for i in t]) # -> [-1, -1]
[1, -1]
```
```


q: What is the bare minimum I need to put in web.config to get WCF working with REST? I have annotated my methods with [WebGet], but they are not getting the message.

[A]
Ensure that you use a webHttpBinding on your endpoint (and not an httpBinding or wsHttpBinding). Here's my endpoint config...
```
```
<endpoint address="" binding="webHttpBinding" bindingConfiguration=""
      contract="WcfCore.ICustomer">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
```
```


q:
I am using StringReplace to replace &gt and &lt by the char itself in a generated XML like this:

StringReplace(xml.Text,'&gt;','>',[rfReplaceAll]) ;
StringReplace(xml.Text,'&lt;','<',[rfReplaceAll]) ;

The thing is it takes way tooo long to replace every occurence of &gt.

Do you purpose any better idea to make it faster?

[A]
The problem is that you are iterating the entire string size twice (one for replacing > by > and another one to replace < by <).
You should iterate with a for and simply check ahead whenever you find a & for a gt; or lt; and do the immediate replace and then skipping 3 characters ((g|l)t;). This way it can do that in proportional time to the size of the string
xml.Text
.
A simple C# example as I do not know Delphi but should do for you to get the general idea.
```
```
String s = "<xml>test</xml>";
char[] input = s.ToCharArray();
char[] res = new char[s.Length];
int j = 0;
for (int i = 0, count = input.Length; i < count; ++i)
{
    if (input[i] == '&')
    {
        if (i < count - 3)
        {
            if (input[i + 1] == 'l' || input[i + 1] == 'g')
            {
                if (input[i + 2] == 't' && input[i + 3] == ';')
                {
                    res[j++] = input[i + 1] == 'l' ? '<' : '>';
                    i += 3;
                    continue;
                }
            }
        }
    }

    res[j++] = input[i];
}
Console.WriteLine(new string(res, 0, j));
```
```
This outputs:
```
```
<xml>test</xml>
```
```


q:
I have a C# WinForms borderless window, for which I override WndProc and handle the WM_NCHITTEST message. For an area of that form, my hit test function returns HTSYSMENU. Double-clicking that area successfully closes the form, but right-clicking it does not show the window's system menu, nor does it show up when right-clicking the window's name in the taskbar.

This form uses these styles:

this.SetStyle( ControlStyles.AllPaintingInWmPaint, true );
this.SetStyle( ControlStyles.UserPaint, true );
this.SetStyle( ControlStyles.OptimizedDoubleBuffer, true );
this.SetStyle( ControlStyles.ResizeRedraw, true );

And has these non-default property values:

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;

I've tried handling WM_NCRBUTTONDOWN and WM_NCRBUTTONUP, and send the WM_GETSYSMENU message, but it didn't work.

[A]
I have the same properties in my application and Right click doesn't work either, so this is not
your problem
, it appears to be the way windows forms respond when they have no border.
If you set your border to the normal value, you will be able to have right click in the taskbar and such.
For right click on other controls, you'll need to set the ContextMenuStrip and provide your "menu". But I'm not sure if this works when you have it without border. I have been unable to make it work.


q:
Is it a good idea to use while loop instead of a cursor?

What are the advantages/disadvantages of cursors?

[A]
Some of these depends on the DBMS, but generally:
Pros:
Outperform loops when it comes to row-by-row processing
Works reasonably well with large datasets
Cons:
Don't scale as well
Use more server resources
Increases load on tempdb
Can cause leaks if used incorrectly (eg. Open without corresponding Close)


q:
The MEF team keep saying it is about plug-in model. So, are we talking about UI plugins? How can we use this stuff in non-UI code?
I downloaded the code and the examples are all about GUI. Am I guessing it wrong?

[A]
Ayende sums up MEF rather nicely here:
http://ayende.com/Blog/archive/2008/09/25/the-managed-extensibility-framework.aspx
Also the herding code lads had a great interview with Glenn Block, one of the MS MEF guys:
http://herdingcode.com/?p=28
http://herdingcode.com/?p=31


q: Does anyone know of a freely available java 1.5 package that provides a list of ISO 3166-1 country codes as a enum or EnumMap?  Specifically I need the "ISO 3166-1-alpha-2 code elements", i.e. the 2 character country code like "us", "uk", "de", etc.  Creating one is simple enough (although tedious), but if there's a standard one already out there in apache land or the like it would save a little time.

[A]
This code gets 242 countries in Sun Java 6:
```
```
String[] countryCodes = Locale.getISOCountries();
```
```
Though
the ISO website
claims there are 249
ISO 3166-1-alpha-2 code elements
, though the
javadoc
links to the same information.


q:
Google results on this one are a bit thin, but suggest that it is not easily possible.

My specific problem is that I need to renumber the IDs in two tables that are related to each other such that table B has an "table_a_id" column in it. I can't renumber table A first because then its children in B point to the old IDs. I can't renumber table B first because then they would point to the new IDs before they were created. Now repeat for three or four tables.

I don't really want to have to fiddle around with individual relationships when I could just "start transaction; disable ref integrity; sort IDs out; re-enable ref integrity; commit transaction". Mysql and MSSQL both provide this functionality IIRC so I would be surprised if Postgres didn't.

Thanks!

[A]
It does not seem possible. Other suggestions almost always refer to dropping the constraints and recreating them after work is done.
However, it seems you can make constraints
```
DEFERRABLE
```
, such that they are not checked until the end of a transaction. See
PostgreSQL documentation for
```
CREATE TABLE
```
(search for 'deferrable', it's in the middle of the page).


q: I have a problem with setting the TTL on my Datagram packets.  I am calling the setTTL(...) method on the packet before sending the packet to the multicastSocket but if I capture the packet with ethereal the TTL field is always set to 0

[A]
Basically you have to set an special system property telling the JVM to use an IPv4 stack:
```
```
-Djava.net.preferIPv4Stack=true
```
```


q:
I'm using the document.form.submit() function for a rather large input form (hundreds of fields, it's an inventory application).  I'm calling this after the user has been idle for a certain amount of time and I would like to save any data they've typed.  When I try this the page reloads (the action is #) but any new text typed in the fields is not passed in the REQUEST, so I don't get to put it in the DB.  Is there some fundamental reason why this happens or is my code just not playing nice together (I'm using the EXTJS grid view to show the form and a library for tracking idle time)?
Thanks,
Robert

[A]
Might the server be voiding out the input values. Say if your page on the server looks like this:
```
```
<form action="/page.cgi">
  ...
  <input name="Fieldx" value=""/>
</form>
```
```
I think it'll void out the field. Or this the server action might be setting it indirectly. In JSF, something like this.
```
```
<input name="Fieldx" value="#{bean.nullProperty}"/>
```
```
What do you have on the server and what's your browser?


q:
I've started with ASP.NET MVC recently, reading blogs, tutorials, trying some routes, etc. Now, i've stumbled on a issue where i need some help.

Basically, i have an URL like /products.aspx?categoryid=foo&productid=bar

Most tutorials/examples propose to map this to something like: /products/category/foo/bar where "products" is the controller, "category" is the action, etc.

But i need to map it to /products/foo/bar. (without "category")

Is it possible? Am i missing something? Help will be highly appreciated. Thank you advance :)

P.S. Sorry for my bad English.

[A]
(your English is just fine, no need to apologize!)
You can define a route like this:
```
```
routes.MapRoute("productsByCategory", "products/{category}/{productid}",
  new { controller="products", action="findByCategory" })
```
```
This will match
```
products/foo/bar
```
and call an action looking like this:
```
```
public class ProductsController : Controller
{
   ...

   public ActionResult FindByCategory(string category, string productid)
   {
          ....
   }
}
```
```
does this help?


q: I have two functions, f and g, which call each other recursively. Unfortunately, when f calls g, it has not yet been declared, so I get an "unbound variable" error.  How can I prototype (or whatever the equivalent vocabulary is) this function in SML/NJ?

[A]
Mutual Recursion. Use
```
and
```
instead of
```
fun
```
between the two functions.


q:
How do I loop into all the resources in the resourcemanager?

Ie:
foreach (string resource in ResourceManager)
  //Do something with the recource.

Thanks

[A]
Use ResourceManager.
GetResourceSet
() for a list of all resources for a given culture. The returned ResourceSet implements IEnumerable (you can use foreach).
To answer Nico's question: you can count the elements of an
```
IEnumerable
```
by casting it to the generic
```
IEnumerable<object>
```
and use the
```
Enumerable.Count<T>()
```
extension method, which is new in C# 3.5:
```
```
using System.Linq;

...

var resourceSet = resourceManager.GetResourceSet(..);
var count = resSet.Cast<object>().Count();
```
```


q:
I need to create a user control in either vb.net or c# to search a RightNow CRM database. I have the documentation on their XML API, but I'm not sure how to post to their parser and then catch the return data and display it on the page.

Any sample code would be greatly appreciated!

Link to API: http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf

[A]
I don't know RightNow CRM, but according to the documentation you can send the XML requests using HTTP post. The simplest way to do this in .NET is using the WebClient class. Alternatively you might want to take a look at the HttpWebRequest/HttpWebResponse classes. Here is some sample code using WebClient:
```
```
using System.Net;
using System.Text;
using System;

namespace RightNowSample
{
    class Program
    {
        static void Main(string[] args)
        {
            string serviceUrl = "http://<your_domain>/cgi-bin/<your_interface>.cfg/php/xml_api/parse.php";
            WebClient webClient = new WebClient();
            string requestXml =
@"<connector>
<function name=""ans_get"">
<parameter name=""args"" type=""pair"">
<pair name=""id"" type=""integer"">33</pair>
<pair name=""sub_tbl"" type='pair'>
<pair name=""tbl_id"" type=""integer"">164</pair>
</pair>
</parameter>
</function>
</connector>";

            string secString = "";
            string postData = string.Format("xml_doc={0}, sec_string={1}", requestXml, secString);
            byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);

            byte[] responseDataBytes = webClient.UploadData(serviceUrl, "POST", postDataBytes);
            string responseData = Encoding.UTF8.GetString(responseDataBytes);

            Console.WriteLine(responseData);
        }
    }
}
```
```
I have no access to RightNow CRM, so I could not test this, but it can serve as s tarting point for you.


q: When creating a class library in C++, you can choose between dynamic (.dll, .so) and static (.lib, .a) libraries. What is the difference between them and when is it appropriate to use which?

[A]
If your library is going to be shared among several executables, it often makes sense to make it dynamic to reduce the size of the executables.  Otherwise, definitely make it static.
There are several disadvantages of using a dll.  There is additional overhead for loading and unloading it.  There is also an additional dependency.  If you change the dll to make it incompatible with your executalbes, they will stop working.  On the other hand, if you change a static library, your compiled executables using the old version will not be affected.


q:
Should it be on the development servers or a Subversion server?

I suppose this could be expanded to any client-server version control system.

[A]
The physical repository should be on a stable system that gets regular backups.
Generally, a development server does not fit this description... it may be acceptable to put the apache server on the dev server and host the files remotely on a stable, backed-up file server (though there are a number of pitfalls with this approach) if you are unable to get additional server resources. Hosting it on the dev server may be fine if you have an aggressive backup system to protect your code...
Just keep in mind that dev servers are prone to configuration changes, being blown-away, or otherwise mucked with that could take down your repo at a critical moment.


q: If something goes wrong in a WCF REST call, such as the requested resource is not found, how can I play with the HTTP response code (setting it to something like HTTP 404, for example) in my OperationContract method?

[A]
There is a
```
WebOperationContext
```
that you can access and it has a
```
OutgoingResponse
```
property of type
```
OutgoingWebResponseContext
```
which has a
```
StatusCode
```
property that can be set.
```
```
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
```
```


q:
I want to consume a web service over https from a java client.
What steps will i need to take in order to do this?

[A] Really, there shouldn't much different from consuming a web service over HTTP. The big thing is that the process calling the web service will have to trust the server's SSL certificate. If the certificate was purchased from a well-known certificate-issuing authority, this usually isn't a problem. Otherwise, the client will want to either trust the root certificate, or the certificate associated with the server's fully qualified host name.


q:
So I have a small C# app that needs to periodically check the contents of directories on multiple machines on the network.  I thought I could just read \hostname\C$ as a directory path, but with the normal Directory class there doesn't seem to be a way to authenticate against the other servers so you can access the hidden share.
I'm sure there's an easy way to do this that I've overlooked, but at the moment I'm a bit stumpted.

[A]
From
http://bytes.com/forum/thread689145.html
:
All processes run in the context of a
logged-in user account. If you want to
open a file on another computer, your
application must be running in the
context of a user that has permissions
to open files on that machine. You can
do this with Impersonation.
The easiest way seems to be to give the current user appropriate rights on the other machines.


q:
I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array.

I couldn't have phrased it better than the person that posted the same question here.

But to keep it original, I'll phrase it my own way: suppose I have a string "00A0BF" that I would like interpreted as the

byte[] {0x00,0xA0,0xBf}

what should I do?

I am a Java novice and ended up using BigInteger and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple.

[A]
The Hex class in commons-codec should do that for you.
http://commons.apache.org/codec/
```
```
import org.apache.commons.codec.binary.Hex;
...
byte[] decoded = Hex.decodeHex("00A0BF");
// 0x00 0xA0 0xBF
```
```


q:
I'm working on a client site who is using Umbraco as a CMS. I need to create a custom 404 error page. I've tried doing it in the IIS config but umbraco overrides that.

Does anyone know how to create a custom 404 error page in Umbraco?
Is there a way to create a custom error page for runtime errors?

[A]
In
```
/config/umbracoSettings.config
```
modify
```
<error404>1</error404>
```
"
1
" with the id of the page you want to show.
```
```
<errors>
   <error404>1</error404>
</errors>
```
```
Other ways to do it can be found at
Not found handlers


q:
How can I find out which column and value is violating the constraint? The exception message isn't helpful at all:

Failed to enable constraints. One or
  more rows contain values violating
  non-null, unique, or foreign-key
  constraints.

[A]
There is a property called RowError you can check.
See
http://dotnetdebug.net/2006/07/16/constraintexception-a-helpful-tip/
Edited to add this link showing iteration of rows to see which had errors.
http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.adonet/topic58812.aspx


q:
In a servlet I do the following:

  Context context = new InitialContext();
  value = (String) context.lookup("java:comp/env/propertyName");

On an Apache Geronimo instance (WAS CE 2.1) how do i associate a value with the key propertyName?

In Websphere AS 6 i can configure these properties for JNDI lookup under the "Name Space Bindings" page in the management console, but for the life of me I can find no way to do this in community edition on the web.

[A]
One possibility is to add the properties to your web.xml file (in the WEB-INF directory), using one or more
```
<env-entry>
```
tags. For example, something like the following:
```
```
<env-entry>
   <description>My string property</descriptor>
   <env-entry-name>propertyName</env-entry-name>
   <env-entry-type>java.lang.String</env-entry-type>
   <env-entry-value>Your string goes here</env-entry-value>
</env-entry>
```
```
Each env-entry tag declares a new environment variable that you can then access from the
```
java:comp/env
```
context.
Once you add the necessary
```
env-entry
```
's you can use code similar to what you already posted to access these values. Mind you, I don't have Geronimo installed, so I don't know if there is any additional configuration that needs to be done in order to make this work.


q: As a developer, how do you use gdb to track down bugs within your code?  What techniques tricks do you use to make your life easier?

[A]
In general you find something that isn't how it should be, and work backwards until you understand why.
The most obvious is the most useful:  Setting a breakpoint on a function or line number and walking through the code line by line.
Another handy tip is to have show functions for all your structures/objects even if they are never used in your program, because you can run these functions from within gdb:
```
```
gdb> p show_my_struct(struct)

My custom display of Foo:
   ...
```
```
Watchpoints can be really handy too, but may slow down your program a lot. These break the flow when the value of a variable or address changes.:
```
```
gdb> watch foo
Watchpoint4: foo
gdb>
```
```


q:
I've got several modules containing functions, classes and templates that I keep in a directory called (hah!) 'reuse'. I know the content reasonably well, so to find a particular class or bit of code doesn't take too long, but it is slowly growing in size and I need some sensible method to store them for easy search & retrieval.

How should I do this?

A related question can be found here: full text search for source code

[A]
Group
the sources by
area of use
(network, security, text processing, etc); best in
directories
for easier browsing.
Tag
functions by adding
keywords
into the source documentation. Use an appropriate comment markup system (like javadoc) and create some kind of indexable docs.
Search
by using some kind of full text search (grep -r, google desktop) on your sources.


q:
I'm developing an application that is targeting the .NET 3.5 Framework. The application's setup installs the .NET 2.0 runtime on the target machine. So far I haven't had any issues with doing this, but I'm wondering what problems I'm going to have down the line. Do I need to be installing the 3.5 runtime?

I must package the .NET runtime installer into our installation (no network install). The size of the runtime installer is the issue. The .NET 2.0 runtime installer is 23MBs (manageable), the .NET 3.0 runtime installer is 50MBs (getting big) and the .NET 3.5 runtime installer is 200MBs (yikes!). What the heck is in those extra 170MBs?

[A] This is a tough question to answer, because ultimately it depends on what .NET 3.5 features you are using.  If you are using some of the new libraries, such as LINQ, then yes, you'll need to install the 3.5 runtimes.  However, if you are just using some of the new syntatic sugars introduced in 3.5, you may not.  The reason for this is that .NET 3.5 is 100% compatible with the 2.0 CLR.


q: I am trying to write a web service to spec and it requires a different response body depending on whether the method completes successfully or not. I have tried creating two different DataContract classes, but how can I return them and have them serialized correctly?

[A] If you are using a xml based binding, then I believe there is no way to do that. A simple solution in that case would to just have part of the message flag if there was a failure, and store the failure information somewhere if needed. For a JSON binding you may be able to use a method that returns an object, then return two different types of objects. If I remember correctly (which is rare), that is possible because the JavaScriptSerializer class uses reflection if the object is clean of serialization attributes.


q:
I know there is a function somewhere that will accept a client rect and it will convert it into a window rect for you. I just can't find / remember it!

Does anyone know what it is?

It will do something similar to:

const CRect client(0, 0, 200, 200);
const CRect window = ClientRectToWindowRect(client);
SetWindowPos(...)

[A]
You're probably thinking of
```
AdjustWindowRectEx()
```
. Keep in mind, this is intended for use when
creating
a window - there's no guarantee that it will produce an accurate set of window dimensions for an existing window; for that, use
```
GetWindowRect()
```
.


q:
We have a typical web application that is essentially a data entry application with lots of screens some of which have some degree of complexity.  We need to provide that standard capability on making sure if the user forgets to click the "Save" button before navigating away or closing their browser they get a warning and can cancel (but only when there is unsaved or dirty data).

I know the basics of what I've got to do-- in fact I'm sure I've done it all before over the years (tie in to onbeforeunload, track the "dirty" state of the page, etc...) but before I embark on coding this YET AGAIN, does anyone have some suggestions for libraries already out there (free or otherwise) that will help out?

[A]
One piece of the puzzle:
```
```
/**
 * Determines if a form is dirty by comparing the current value of each element
 * with its default value.
 *
 * @param {Form} form the form to be checked.
 * @return {Boolean} true if the form is dirty, false
 *                   otherwise.
 */
function formIsDirty(form)
{
    for (var i = 0; i < form.elements.length; i++)
    {
        var element = form.elements[i];
        var type = element.type;
        if (type == "checkbox" || type == "radio")
        {
            if (element.checked != element.defaultChecked)
            {
                return true;
            }
        }
        else if (type == "hidden" || type == "password" || type == "text" ||
                 type == "textarea")
        {
            if (element.value != element.defaultValue)
            {
                return true;
            }
        }
        else if (type == "select-one" || type == "select-multiple")
        {
            for (var j = 0; j < element.options.length; j++)
            {
                if (element.options[j].selected !=
                    element.options[j].defaultSelected)
                {
                    return true;
                }
            }
        }
    }
    return false;
}
```
```
And another
:
```
```
window.onbeforeunload = function(e)
{
    e = e || window.event;
    if (formIsDirty(document.forms["someFormOfInterest"]))
    {
        // For IE and Firefox
        if (e)
        {
            e.returnValue = "You have unsaved changes.";
        }
        // For Safari
        return "You have unsaved changes.";
    }
};
```
```
Wrap it all up, and what do you get?
```
```
var confirmExitIfModified = (function()
{
    function formIsDirty(form)
    {
        // ...as above
    }

    return function(form, message)
    {
        window.onbeforeunload = function(e)
        {
            e = e || window.event;
            if (formIsDirty(document.forms[form]))
            {
                // For IE and Firefox
                if (e)
                {
                    e.returnValue = message;
                }
                // For Safari
                return message;
            }
        };
    };
})();

confirmExitIfModified("someForm", "You have unsaved changes.");
```
```
You'll probably also want to change the registration of the
```
beforeunload
```
event handler to use
```
LIBRARY_OF_CHOICE
```
's event registration.


q:
What is the longest string that can be created in .NET? The docs for the String class are silent on this question as far as I can see, so an authoritative answer might require some knowledge of internals. Would the maximum change on a 64-bit system?

[This is asked more for curiosity than for practical use - I don't intend to create any code that uses gigantic strings!]

[A]
Since the
```
Length
```
property of
```
System.String
```
is an
```
Int32
```
, I would guess that that the maximum length would be 2,147,483,647 chars (max
```
Int32
```
size). If it allowed longer you couldn't check the Length since that would fail.


q:
Which gets called first - the base constructor or "other stuff here"?

public class MyExceptionClass : Exception
{
    public MyExceptionClass(string message, string extrainfo) : base(message)
    {
        //other stuff here
    }
}

[A]
I'd say base
EDIT see:
http://www.c-sharpcorner.com/UploadFile/rajeshvs/ConsNDestructorsInCS11122005010300AM/ConsNDestructorsInCS.aspx
there it says:
```
```
using System;
class Base
{

public Base()
{
    Console.WriteLine("BASE 1");
}
public Base(int x)
{
    Console.WriteLine("BASE 2");
}
}

class Derived : Base
{
public Derived():base(10)
{
    Console.WriteLine("DERIVED CLASS");
}
}

class MyClient
{
public static void Main()
{
    Derived d1 = new Derived();
}
}
```
```
This program outputs
BASE2
DERIVED CLASS


q:
Yup, long title.  I've been programming in PHP for the last 6 years or so for work and personal projects, but I've got an idea for a desktop app (which incidentally, uses a web REST api).

I'm debating on how to approach this - I've got some experience in Java, C++, Perl and Python, but have never had the chance or opportunity to write and distribute an app to others of any significance.

The app will need to communicate with a REST API (with OAuth), as well as access the file system, and possibly do some image manipulation (encoding/resizing, but this is a nice to have). I've been thinking something on .NET, but AIR is a possibility too (though I really dont want a huge runtime hanging around, this will be a system-tray type app).

I'm not looking for someone to write it, but I could use a nudge in the right direction.

[A]
Being a Delphi programmer for years, you can do everything you want with it.
I'm starting to use C# at work. It's a great language too, but for a distributed application. the .NET framework still stops me from using it for my personnal apps.
In my point of view, Delphi is a good option. You can look at Lazarus/Free Pascal if you want a free IDE.
With this option, you build your EXE and that's it. Ship the EXE to the customer and it's working. No need for DLL/framework thing to have on the computer.
Of course, if you're using database stuff or third party DLL, you must ship the necessary stuff with it. But it's simplier than with VB with all the vbrunxx.dll, or with all .NET language.
It's my 2c... I think I'll be flamed for this! ;-)
HTH


q:
How do I detect if my program runs in an Active Directory environment?

I'm using C# and .Net 2.0

[A]
One way might be to query the LOGONSERVER environmental variable.  That'll give the server name of your AD controller... Which, as far as I know, will be blank (or match current workstation? Not sure) if it isn't currently logged into a domain.
Example Usage:
```
```
string ADServer = Environment.GetEnvironmentVariable("LOGONSERVER");
```
```


q: When I try to execute a view that includes tables from different schemas an ORA-001031 Insufficient privileges is thrown.  These tables have execute permission for the schema where the view was created.  If I execute the view's SQL Statement it works.  What am I missing?

[A]
As the table owner you need to grant SELECT access on the underlying tables to the user you are running the SELECT statement as.
```
```
grant SELECT on TABLE_NAME to READ_USERNAME;
```
```


q:
The Erlang documentation contains the documentation of modules.

Where can I find the documentation of the Erlang shell? (Which is not a module, I suppose.)

[A]
This page in the documentation
seems to be a starting point. Especially the link in it. Check also the
first link
in it, with the shell's manpage.


q: I'm wondering which languages support (or don't support) native multithreading, and perhaps get some details about the implementation.  Hopefully we can produce a complete overview of this specific functionality.

[A]
Older versions of C and C++ (namely, C89, C99, C++98, and C++03) have no support at all in the core language, although libraries such as POSIX threads are available for pretty much every platform in common user today.
The newest versions of C and C++, C11 and C++11, do have built-in threading support in the language, but it's an optional feature of C11, so implementations such as single-core embedded systems can choose not to support it while supporting the rest of C11 if they desire.


q:
It often happens that characters such as é gets transformed to Ã©, even though the collation for the MySQL DB, table and field is set to utf8_general_ci. The encoding in the Content-Type for the page is also set to UTF8.

I know about utf8_encode/decode, but I'm not quite sure about where and how to use it.

I have read the "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" article, but I need some MySQL / PHP specific pointers.

How do I ensure that user entered data containing international characters doesn't get corrupted?

[A]
On the first look at
http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet
I think that one important thing is missing (perhaps I overlooked this one).
Depending on your MySQL installation and/or configuration you have to set the connection encoding so that MySQL knows what encoding you're expecting on the client side (meaning the client side of the MySQL connection, which should be you PHP script). You can do this by manually issuing a
```
```
SET NAMES utf8
```
```
query prior to any other query you send to the MySQL server.
If your're using PDO on the PHP side you can set-up the connection to automatically issue this query on every (re)connect by using
```
```
$db=new PDO($dsn, $user, $pass);
$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8");
```
```
when initializing your db connection.


q:
In Java you can do File.listFiles() and receive all of the files in a directory.  You can then easily recurse through directory trees.

Is there an analogous way to do this in Python?

[A]
Straight from Python's Refererence Library
```
```
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
```
```


q:
I am writing a web server in Java and I want it to support HTTP 1.1 Keep-Alive connections. But how can I tell when the client is done sending requests for a given connection? (like a double end-of-line or something).

Lets see how stackoverflow handles this very obscure question -- answers for which, on Google, are mired in technical specifications and obscure language. I want a plain-english answer for a non-C programmer :)

I see. that confirms my suspicion of having to rely on the SocketTimeoutException. But i wasn't sure if there was something i could rely on from the client that indicates it is done with the connection--which would allow me to close the connections sooner in most cases--instead of waiting for the timeout. Thanks

[A] You close it whenever you'd like.  The header indicates that the client would prefer you to leave the connection open, but that doesn't require the server to comply.  Most servers leave it open for about 5-10 seconds, some don't pay attention to it at all.


q:
Can you define a macro that accesses a normal variable, but in a read-only fashion (other than defining it as a call to a function)? For example, can the VALUE macro in the following code be defined in such a way that the dostuff() function causes a compile error?

struct myobj {
  int value;
}

/* This macro does not satisfy the read-only requirement */
#define VALUE(o) (o)->value

/* This macro uses a function, unfortunately */
int getvalue(struct myobj *o) { return o->value; }
#define VALUE(o) getvalue(o)

void dostuff(struct myobj *foo) {
   printf("The value of foo is %d.\n", VALUE(foo)); /* OK */
   VALUE(foo) = 1; /* We want a compile error here */
   foo->value = 1; /* This is ok. */
}

[A]
If the variable is always numeric, this works:
```
```
#define VALUE(x) (x+0)
```
```
or in the context of your example,
```
```
#define VALUE(x) (x->value+0)
```
```


q:
What do you think about this build tool? I'm thinking of migrating from maven2 to raven (my poms are getting bigger and bigger), but I'd like to hear some opinions first.

Thanks!

@andre:

Thank's for writing but I was actually looking for real experiences using raven. Anyway, the fact that nobody wrote is an indicator by itself (it seems few people are using it)

[A] pom growth is a problem that everybody faces w/ maven I guess, but maven is at least maintained (2.1. just around the corner) and the raven project looks pretty dead to me. No updates this year and the mailinglist archives are also very small. It looks to me as it's too risky to switch your build process to a tool w/o a living community. Not quite the answer you wanted I guess, but my 2 cents.


q: Is it possible to make a site with ASP.NET MVC Framework using .NET 2.0?  I am limited to using .NET 2.0 (we use VS 2008, but we have to use the 2.0 Framework) and I really want to try out the MVC Framework.

[A]
Scott Hanselman described a way to make it work, with some caveats, in his blog:
Deploying ASP.NET MVC on ASP.NET 2.0


q:
I have a data stream that may contain \r, \n, \r\n, \n\r or any combination of them.  Is there a simple way to normalize the data to make all of them simply become \r\n pairs to make display more consistent?

So something that would yield this kind of translation table:

\r     --> \r\n
\n     --> \r\n
\n\n   --> \r\n\r\n
\n\r   --> \r\n
\r\n   --> \r\n
\r\n\n --> \r\n\r\n

[A]
A Regex would help.. could do something roughly like this..
(\r\n|\n\n|\n\r|\r|\n) replace with \r\n
This regex produced these results from the table posted (just testing left side) so a replace should normalize.
```
```
\r   => \r
\n   => \n
\n\n => \n\n
\n\r => \n\r
\r\n => \r\n
\r\n => \r\n
\n   => \n
```
```


q: Has anyone used C# with a Sales Logix database?

[A]
Yes.  I have.
(Not the most interesting answer on SOB today, but that's what the question asked...)


q:
In WPF, I want to create a hyperlink that navigates to the details of an object, and I want the text of the hyperlink to be the name of the object. Right now, I have this:

<TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">Object Name</Hyperlink></TextBlock>

But I want "Object Name" to be bound to the actual name of the object. I would like to do something like this:

<TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}" Text="{Binding Path=Name}"/></TextBlock>

However, the Hyperlink class does not have a text or content property that is suitable for data binding (that is, a dependency property).

Any ideas?

[A]
It looks strange, but it works. We do it in about 20 different places in our app.
```
Hyperlink
```
implicitly constructs a
```
<Run/>
```
if you put text in its "content", but in .NET 3.5
```
<Run/>
```
won't let you bind to it, so you've got to explicitly use a
```
TextBlock
```
.
```
```
<TextBlock>
    <Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">
        <TextBlock Text="{Binding Path=Name}"/>
    </Hyperlink>
</TextBlock>
```
```
Update
: Note that as of .NET 4.0 the
Run.Text property
can now be bound:
```
```
<Run Text="{Binding Path=Name}" />
```
```


q: I've seen a few different ways to iterate over a dictionary in C#.  Is there a standard way?

[A]
```
```
foreach(KeyValuePair<string, string> entry in myDictionary)
{
    // do something with entry.Value or entry.Key
}
```
```


q:
"Dirty reads", meaning reading an object's value even though it is write-locked by another thread, are described on Terracotta's website, yet I've heard that they shouldn't be used, even if you don't care about the possibility that you might get old data when you dirty-read the locked object.

Does anyone have any experience of using dirty reads in Terracotta, and are they safe to use if you don't care about the possibility of reading an old value?

[A]
A dirty read is a dirty read. Terracotta, being distributed/clustered, only adds the possibility to read even older values of the shared mutable state that you are accessing without proper synchronization.
You should note that, under the memory model in Java 5, you are not guaranteed to
ever
read an updated value if you don't use proper synchronization. Terracotta may decide to take advantage of this possibility. In fact, any JVM may, at their leisure, take advantage of it. Even if it might work on your machine, it may break on other machines. It may break on minor updates of the JVM, and it may break for the same version of the same JVM on a different CPU.
With that in mind, you can say that dirty reads isn't safe in any JVM... Unless you don't mind the possibility that you won't ever be able to read the updates that other threads make - an unlikely situation but it could happen.
Also, when you actually follow your link to Terracottas wiki, it says that the article has been removed and that the pattern is discouraged.


q:
In an asp.net application, I would like to combine the use of the Webclient Software Factory (WCSF), and its associated Model View Presenter pattern (MVP), with Page Method, that is static methods on the .aspx Views marked with the [WebMethod] attribute.

However, static methods on the aspx page would seem to break the Model View Presenter pattern since an instance method is required on the page to have the context of the Presenter and Controller necessary for the View to talk to.

How would one extended asp .net's MVP pattern in WCSF to support [WebMethods] on the page, aka the View?

[A]
I think you could come close to what you are looking for by using an ASP.Net AJAX Web Service instead of static page methods.  The web service has the advantage of not being static, and depending on how your views are implemented, (I'm not familiar with the specifics of the WCSF MVP pattern) you could potentially make the web service your "View" layer..or at least something fairly close.
I've done something similar in a project I'm working on.  I ended up needing to create a thin data-only class which got serialized to JSON by the web service to carry the data from the model to the "view", but the web service had essentially the same methods that would be exposed as events on the view.
One of the things I liked about this approach is that all the bits, including the web service, are testable.


q:
Is it possible to find the foreach index?

in a for loop as follows:

for ($i = 0; $i < 10; ++$i) {
   echo $i . ' ';
}

$i will give you the index.

Do I have to use the for loop or is there some way to get the index in the foreach loop?

[A]
```
```
foreach($array as $key=>$value) {
    // do stuff
}
```
```
```
$key
```
is the index of each
```
$array
```
element


q:
I have a .net 2.0 ascx control with a start time and end time textboxes. The data is as follows:

txtStart.Text = 09/19/2008 07:00:00

txtEnd.Text = 09/19/2008 05:00:00

I would like to calculate the total time (hours and minutes) in JavaScript then display it in a textbox on the page.

[A]
Once your textbox date formats are known in advance, you can use
Matt Kruse's Date functions
in Javascript to convert the two to a timestamp, subtract and then write to the resulting text box.
Equally the
JQuery Date Input
code for
```
stringToDate
```
could be adapted for your purposes - the below takes a string in the format "YYYY-MM-DD" and converts it to a date object. The timestamp (
```
getTime()
```
) of these objects could be used for your calculations.
```
```
stringToDate: function(string) {
    var matches;
    if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
       return new Date(matches[1], matches[2] - 1, matches[3]);
    } else {
       return null;
    };
}
```
```


q:
I want to know if my server is running Subversion 1.5.

How can I find that out?

Also would be nice to know my SVN client version number. svn help hasn't been helpful.

Note: I don't want my project's revision number, etc. This question is about the Subversion software itself.

[A]
For an HTTP-based server there is a Python script to find the server version at:
http://svn.apache.org/repos/asf/subversion/trunk/tools/client-side/server-version.py
You can get the client version with
```
```
`svn --version`
```
```


q: I'm trying to determine what instances of sql server/sql express I have installed (either manually or programmatically) but all of the examples are telling me to run a SQL query to determine this which assumes I'm already connected to a particular instance.

[A]
You could query this registry value to get the SQL version directly:
```
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\90\Tools\ClientSetup\CurrentVersion
```
```
Alternatively  you can query your instance name and then use sqlcmd with your instance name that you would like:
To see your instance name:
```
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names
```
```
Then execute this:
```
```
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')
```
```
If you are using C++ you can use this code to get the registry information.


q:
I need to see if a given process id is running, and it must work in either Java or JRuby (preferably a Ruby solution).  It can be system dependent for Linux (specifically Debian and/or Ubuntu).

I already have the PID I am looking for, just need to see if it is currently running.

UPDATE:

Thanks for all the responses everyone!  I appreciate it, however it's not QUITE what I'm looking for... I am hoping for something in a standard Ruby library (or Java, but preferably Ruby)... if no such library call exists, I will probably stick with the procfs solution I already have.

[A]
From
my answer to this question
, I was thinking of just using procfs again, by checking if the given directory exists via File.exist? "/proc/#{pid}".  This worked in jirb:
```
irb(main):001:0> File.exist? "/proc/5555"
=> false
irb(main):002:0> File.exist? "/proc/7677"
=> true
```
However, I would still prefer to use a method that specifically exists to detect if a process is running... like Process.exist?(pid)... which unfortunately doesn't exist that I've seen.


q:
Is there a way to detect if the user is holding down the shift key (or other modifier keys) when executing a javascript bookmarklet?

In my tests of Safari 3.1 and Firefox 3, window.event is always undefined.

[A]
If you're looking for a way to detect the mouse position while the bookmarklet is being physically clicked, no, there is no way. Since the bookmarklet is positioned outside of any page (this area is generally called the browser "chrome" - which is confusing since there's now a browser with that name) it's not possible to detect JavaScript-related events there.
That being said, if you created this as a Firefox extension then you would have access to event information, JavaScript, and keyboard modifiers. But that doesn't appear to be what you're looking for.


q:
I'd like the canonical way to do this.  My Google searches have come up short.  I have one ActiveRecord model that should map to a different database than the rest of the application.  I would like to store the new configurations in the database.yml file as well.

I understand that establish_connection should be called, but it's not clear where.  Here's what I got so far, and it doesn't work:

class Foo < ActiveRecord::Base
    establish_connection(('foo_' + ENV['RAILS_ENV']).intern)
end

[A]
Heh.  I was right!  More cleanly:
```
```
class Foo < ActiveRecord::Base
    establish_connection "foo_#{ENV['RAILS_ENV']}"
end
```
```
Great post
at pragedave.pragprog.com
.


q:
I've seen reference in some C# posted questions to a "using" clause.
Does java have the equivalent?

[A]
Yes. Java 1.7 introduced the
try-with-resources
construct allowing you to write:
```
```
try(InputStream is1 = new FileInputStream("/tmp/foo");
    InputStream is2 =  new FileInputStream("/tmp/bar")) {
         /* do stuff with is1 and is2 */
}
```
```
... just like a
```
using
```
statement.
Unfortunately, before Java 1.7, Java programmers were forced to use try{ ... } finally { ... }. In Java 1.6:
```
```
InputStream is1 = new FileInputStream("/tmp/foo");
try{

    InputStream is2 =  new FileInputStream("/tmp/bar");
    try{
         /* do stuff with is1 and is 2 */

    } finally {
        is2.close();
    }
} finally {
    is1.close();
}
```
```


q: How have you tweaked the MATLAB environment to better suit your needs?  One tweak per answer.

[A] I set the number of lines in the command window scroll buffer to the maximum (25,000).  This doesn't seem to noticeably affect performance and allows me to display a large amount of data/results.


q: What is the difference between using the Runnable and Callable interfaces when designing a concurrent thread in Java, why would you choose one over the other?

[A]
See explanation
here
.
The Callable interface is similar to
  Runnable, in that both are designed
  for classes whose instances are
  potentially executed by another
  thread.
A Runnable, however, does not
  return a result and cannot throw a
  checked exception.


q:
Is there a way to check if a file has been opened by ReWrite in Delphi?

Code would go something like this:

AssignFile(textfile, 'somefile.txt');
if not textFile.IsOpen then
   Rewrite(textFile);

[A]
You can get the filemode. (One moment, I'll create an example).
TTextRec(txt).Mode gives you the mode:
```
```
55216 = closed
55217 = open read
55218 = open write

fmClosed = $D7B0;
fmInput  = $D7B1;
fmOutput = $D7B2;
fmInOut  = $D7B3;
```
```
Search TTextRec in the system unit for more information.


q:
Is there a way to check to see if a date/time is valid you would think these would be easy to check:

$date = '0000-00-00';
$time = '00:00:00';
$dateTime = $date . ' ' . $time;

if(strtotime($dateTime)) {
    // why is this valid?
}

what really gets me is this:

echo date('Y-m-d', strtotime($date));

results in: "1999-11-30",

huh? i went from 0000-00-00 to 1999-11-30 ???

I know i could do comparison to see if the date is either of those values is equal to the date i have but it isn't a very robust way to check. Is there a good way to check to see if i have a valid date? Anyone have a good function to check this?

Edit:
People are asking what i'm running:
Running PHP 5.2.5 (cli) (built: Jul 23 2008 11:32:27) on Linux localhost 2.6.18-53.1.14.el5 #1 SMP Wed Mar 5 11:36:49 EST 2008 i686 i686 i386 GNU/Linux

[A]
echo date('Y-m-d', strtotime($date));
results in: "1999-11-30"
The result of
```
strtotime
```
is 943920000 - this is the number of seconds, roughly, between the
Unix epoch
(base from which time is measured) to 1999-11-30.
There is a
documented
mysql bug
on
```
mktime(), localtime(), strtotime()
```
all returning this odd value when you try a pre-epoch time (including "0000-00-00 00:00:00"). There's some debate on the linked thread as to whether this is actually a bug:
Since the time stamp is started from 1970, I don't think it supposed to
  work in anyways.
Below is a function that I use for converting dateTimes such as the above to a timestamp for comparisons, etc, which may be of some use to you, for dates beyond "0000-00-00 00:00:00"
```
```
/**
 * Converts strings of the format "YYYY-MM-DD HH:MM:SS" into php dates
 */
function convert_date_string($date_string)
{
    list($date, $time) = explode(" ", $date_string);
    list($hours, $minutes, $seconds) = explode(":", $time);
    list($year, $month, $day) = explode("-", $date);
    return mktime($hours, $minutes, $seconds, $month, $day, $year);
}
```
```


q:
I'm writing some server code that talks to a client process via STDIN. I'm trying to write a snippet of perl code that asynchronously receives responses from the client's STDOUT. The blocking version of the code might look like this:

sub _read_from_client
{
   my ($file_handle) = @_;
   while (my $line = <$file_handle>) {
      print STDOUT $line;
   }
   return;
}

Importantly, the snippet needs to work in Win32 platform. There are many solutions for *nix platforms that I'm not interested in. I'm using ActivePerl 5.10.

[A]
This thread
on
Perlmonks
suggests you can make a socket nonblocking on Windows in Perl this way:
```
```
ioctl($socket, 0x8004667e, 1);
```
```
More details and resources in that thread


q:
How does one check if a directory is already present in the PATH environment variable? Here's a start. All I've managed to do with the code below, though, is echo the first directory in %PATH%. Since this is a FOR loop you'd think it would enumerate all the directories in %PATH%, but it only gets the first one.

Is there a better way of doing this? Something like FIND or FINDSTR operating on the %PATH% variable? I'd just like to check if a directory exists in the list of directories in %PATH%, to avoid adding something that might already be there.

FOR /F "delims=;" %%P IN ("%PATH%") DO (
    @ECHO %%~P
)

[A]
This may work:
```
```
echo ;%PATH%; | find /C /I ";<string>;"
```
```
It should give you 0 if the string is not found and 1 or more if it is.


q:
My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment.  I've used a Python memory profiler (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.

What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory.  How do I get a core dump of a python process like this?  Once I have one, how do I do something useful with it?

[A]
I don't know how to dump an entire python interpreter state and restore it. It would be useful, I'll keep my eye on this answer in case anyone else has ideas.
If you have an idea where the memory is leaking, you can add checks the refcounts of your objects. For example:
```
```
x = SomeObject()
... later ...
oldRefCount = sys.getrefcount( x )
suspiciousFunction( x )
if (oldRefCount != sys.getrefcount(x)):
    print "Possible memory leak..."
```
```
You could also check for reference counts higher than some number that is reasonable for your app. To take it further, you could modify the python interpreter to do these kinds of check by replacing the
```
Py_INCREF
```
and
```
Py_DECREF
```
macros with your own. This might be a bit dangerous in a production app, though.
Here is an essay with more info on debugging these sorts of things. It's more geared for plugin authors but most of it applies.
Debugging Reference Counts


q:
Our resident Flex expert is out for the day and I thought this would be a good chance to test this site out. I have a dropdown with a dataProvider that is working fine:

<ep:ComboBox id="dead_reason" selectedValue="{_data.dead_reason}"
    dataProvider="{_data.staticData.dead_reason}"
    labelField="@label" width="300"/>

The ComboBox is custom but I'm not sure if that matters for the question. I need to change the combo box to radios (all in one group) but maintain the dynamic options. In other words, what is the best way to generate dynamic RadioButtons?

[A]
Try using an <mx:Repeater>  Something like:
```
```
<mx:Repeater dataProvider="{_data.staticData.dead_reason}">
   <mx:RadioButton groupName="reasons" ...>
</mx:Repeater>
```
```


q:
I'm pretty new to both C++ and Block Cipher encryption, and I am currently in the process of writing a decryption function for AES (16 byte seed / 16 byte blocks). All is going well, but my total data size is not always a multiple of my block size. I'm wondering what the best way to handle leftover data at the end of my data.

I'm using Crypto++ for the AES library.

The ProcessBlock() function takes an Input and Output char array. I'm assuming it is expecting them to be at least big enough as the block size.

What would be the best way to process all 16 byte blocks in a block cipher, and then also process the leftover data?

[A]
What you want is a padding system.
Check out this CodeProject article on Crypto++
:
When a message is not a multiple of
  the cipher's block size, ECB or CBC
  mode messages must be padded. The
  method and values of padding are a
  source of problem with respect to
  interoperability between Cryptographic
  libraries and APIs. As Garth Lancaster
  points out, if you're not aware of the
  particulars of padding, use the
  StreamTransformationFilter. In this
  case, the Crypto++ filter will pad for
  you.


q:
I installed Tomcat 6.0.18 on a windows server 2003 box and it will not start as a service.
I'm running it with jdk 1.6.0_07.

It runs when I start it with tomcat6.exe.

I got a vague error in the System Event Log on Windows.

The Apache Tomcat 6 service terminated with service-specific error 0 (0x0).

[A]
From
gobaco.wordpress.com
Tomcat 6 couldn’t find a file called msvcr71.dll.
I just copied it over from
c:\windows\microsoft.net\framework\v1.1.4322
to
c:\windows\system32
and was able to start tomcat.
I thought this was very strange, so I wanted to post it on SO in case anyone else runs into this problem. If someone wants to post the same answer I'll accept it.


q:
I have created a brand new project in XCode and have the following in my AppDelegate.py file:

from Foundation import *
from AppKit import *

class MyApplicationAppDelegate(NSObject):
    def applicationDidFinishLaunching_(self, sender):
        NSLog("Application did finish launching.")

        statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
        statusItem.setTitle_(u"12%")
        statusItem.setHighlightMode_(TRUE)
        statusItem.setEnabled_(TRUE)

However, when I launch the application no status bar item shows up. All the other code in main.py and main.m is default.

[A]
I had to do this to make it work:
Open MainMenu.xib. Make sure the class of the app delegate is
```
MyApplicationAppDelegate
```
. I'm not sure if you will have to do this, but I did. It was wrong and so the app delegate never got called in the first place.
Add
```
statusItem.retain()
```
because it gets autoreleased right away.


q:
Can anyone explain what advantages there are to using a tool like MSBuild (or NAnt) to build a collection of projects versus running DevEnv.exe from the command-line?

A colleague I had worked with in the past had explained that (at least with older versions of Visual Studio) using DevEnv.exe was much slower than the other techniques, but I haven't read any evidence of that or if that is now a moot point now that starting with 2005, Visual Studio uses MSBuild under the hood.

I know one advantage of using MSBuild allows you to build your projects without requiring Visual Studio to be installed on the build machines, but I wasn't sure if there were others.

[A]
The prime reason for using an external build tool like NAnt or MsBuild is the ability to automate your build process and thus provide continous feedback on the status of your system. Also they can be used for loads of things besides a "pure" build and that's where you really start to get value from them, it's an extremly valuable thing to be able to build and test your application with a single command.
You can also start adding stuff like collection of metrics, packinging of release binaries and all sorts of nifty stuff like that.


q: How do I create a file-like object (same duck type as File) with the contents of a string?

[A]
For Python 2.x, use the
StringIO
module.  For example:
```
```
>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
```
```
I use cStringIO (which is faster), but note that it doesn't
accept Unicode strings that cannot be encoded as plain ASCII strings
.  (You can switch to StringIO by changing  "from cStringIO" to "from StringIO".)
For Python 3.x, use the
```
io
```
module.
```
```
f = io.StringIO('foo')
```
```


q:
I have a select element in a form, and I want to display something only if the dropdown is not visible.  Things I have tried:

Watching for click events, where odd clicks mean the dropdown is visible and even clicks mean the dropdown isn't.  Misses other ways the dropdown could disappear (pressing escape, tabbing to another window), and I think this could be hard to get right cross-browser.

Change events, but these only are triggered when the select box's value changes.

Ideas?

[A]
I don't think there's direct support.  You could also sit on the onblur of the select -- it gets called when the select loses focus.
Depending on how important it is, you could try implementing your own control or starting from one like a drop-down menu control which is similar.  Usually, unless it's critical to your application, it's not worth doing this.  If you decide to go this route, here's a discussion of someone trying to do it using dojo as a basis:
http://dojotoolkit.org/forum/dijit-dijit-0-9/dijit-support/emulating-html-select


q:
I've got a nice little class built that acts as a cache. Each item has an expiration TimeSpan or DateTime. Each time an attempt to access an item in the cache is made, the item's expiration is checked, and if it's expired, the item is removed from the cache and nothing is returned.

That's great for objects that are accessed frequently, but if an item is put in the cache and never accessed again, it's never removed, even though it's expired.

What's a good methodology for expiring such items from the cache?

Should I have a background thread infinitely enumerating every item in the cache to check if it's expired?

[A]
You can implement an LRU (Least Recently Used) strategy, keep your items sorted by access time, when a new item is inserted into the cache
and
the cache is full you evicted the item that is last in that list. See
Cache algorithms
at Wikipedia.
If you want to expire immediately, i would still only do that when things are accessed. I.e. when the cache object is accessed and it's time has expired refetch it.


q:
I want to be able to explore the contents of a DB for this version of the DB. I was thinking of using the Squirrel DB client (which needs a JDBC driver).

Therefore, I'm looking for a JDBC type 4 driver for SQL SERVER 3.5.  Can somone point me to a FREE OR open source or trial ware ?

If no JDBC driver, how do MS developers explore a given .SDF file ?

Thank you,

BR,

~A

[A]
Have you tried
SQL Server Management Studio Express
?
You can access SQL Server Compact 3.5
  databases stored on a smart device or
  on the desktop computer by using SQL
  Server Management Studio in SQL Server
  or SQL Server Management Studio
  Express (SSMSE).
http://technet.microsoft.com/en-us/library/ms172037.aspx
As for the JDBC Driver, you could take a look at
this one
, provided by Microsoft. I don't know if it works with the Compact Edition or if you already tried it, but I thought it was worth mentioning.


q:
I could probably write this myself, but the specific way I'm trying to accomplish it is throwing me off.  I'm trying to write a generic extension method similar to the others introduced in .NET 3.5 that will take a nested IEnumerable of IEnumerables (and so on) and flatten it into one IEnumerable.  Anyone have any ideas?

Specifically, I'm having trouble with the syntax of the extension method itself so that I can work on a flattening algorithm.

[A]
```
```
static class EnumerableExtensions
{
    public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> sequence)
    {
        foreach(var child in sequence)
            foreach(var item in child)
                yield return item;
    }
}
```
```
Maybe like this? Or do you mean that it could potentially be infintly deep?


q:
class Foo(models.Model):
    title = models.CharField(max_length=20)
    slug = models.SlugField()

Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.

[A]
For pre-1.0:
```
```
slug = models.SlugField(prepopulate_from=('title',))
```
```
should work just fine
For 1.0, use
camflan's


q:
I'm not sure if this even exists or not, so I figured I would tap the wisdom of others..

I was wondering if there are any Java libraries out there that can be used to validate a SQL query's syntax. I know that there are many deviations from common SQL spec, so it would probably only work against something like SQL:2006, but that would certainly suffice.

My goal is to use this for unit-testing purposes without needing to attempt the execution against the DB. I know it's of limited use, but it would still be useful.

Thanks!

[A]
I don't think there are such libraries. The SQL syntax has too many derivatives.
A possible solution would be to use parts of an open source pure Java DBMS like
SmallSQL
. In this project you can create an instance of the
SQLParser
. The needed references to the connection can be removed very easily.


q: When do you think we can expect the full release version of ASP.NET MVC?

[A]
EDIT (16/Jul/2009)
Updating to ensure this page contains the most recent details.
ASP.NET MVC is now fully released
http://www.asp.net/mvc/
.
EDIT (28/Jan/2009)
ASP.NET MVC 1.0 RC Now Available.... final next month (
From ScottGu's Blog
)
Today’s RC is the last public release
  of ASP.NET MVC that we’ll ship prior
  to the final “1.0” release.  We expect
  to ship the final ASP.NET MVC 1.0
  release next month.
Last I heard, Q4 2008.
Scott Hanselman posted this
in his blog about 3.5 SP1
What about ASP.NET MVC?
There is likely some confusion around
  MVC as a few people expected ASP.NET
  MVC to ship in SP1. This is probably
  because MVC was included in 3.5
  "Extensions Preview." However, the
  plan was always to ship in Q4CY08.
(That date is marketing speak, I've
  just learned. I tell people what Eilon
  told me - it'll ship in a month ending
  in "-ber." Possible "March-ber" but
  also maybe "next June-ber.")
Anyway, Phil has always said that MVC
  is on its own schedule and will ship
  when its done. Possibly when Duke
  Nukem Forever ships.


q:
I personally use var_dump, but lots of people like print_r.

What does everyone use? Pros and Cons?

Does someone have a special home brew function of their own?

[A]
I use
```
print_r()
```
because I like the pretty array structure... but
```
var_dump
```
does give you a bit more information (like types)
```
```
$obj = (object) array(1, 2, 3);

// output of var_dump:
object(stdClass)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

// output of print_r
stdClass Object
(
  [0] => 1
  [1] => 2
  [2] => 3
)
```
```


q:
I've been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators)...

At a core level, what does bit-shifting (<<, >>, >>>) do, what problems can it help solve, and what gotchas lurk around the bend? In other words, an absolute beginner's guide to bit shifting in all its goodness.

[A]
Let's say we have a single byte:
```
```
0110110
```
```
Applying a single left bitshift gets us:
```
```
1101100
```
```
The leftmost zero was shifted out of the byte, and a new zero was appended to the right end of the byte.
The bits don't rollover; they are discarded. That means if you left shift 1101100 and then right shift it, you won't get the same result back.
Shifting left by N is equivalent to multiplying by 2
N
.
Shifting right by N is (if you are using
ones' complement
) is the equivalent of dividing by 2
N
and rounding to zero.
Bitshifting can be used for insanely fast multiplication and division, provided you are working with a power of 2. Almost all low-level graphics routines use bitshifting.
For example, way back in the olden days, we used mode 13h (320x200 256 colors) for games. In Mode 13h, the video memory was laid out sequentially per pixel. That meant to calculate the location for a pixel, you would use the following math:
```
```
memoryOffset = (row * 320) + column
```
```
Now, back in that day and age, speed was critical, so we would use bitshifts to do this operation.
However, 320 is not a power of two, so to get around this we have to find out what is a power of two that added together makes 320:
```
```
(row * 320) = (row * 256) + (row * 64)
```
```
Now we can convert that into left shifts:
```
```
(row * 320) = (row << 8) + (row << 6)
```
```
For a final result of:
```
```
memoryOffset = ((row << 8) + (row << 6)) + column
```
```
Now we get the same offset as before, except instead of an expensive multiplication operation, we use the two bitshifts...in x86 it would be something like this (note, it's been forever since I've done assembly (editor's note: corrected a couple mistakes and added a 32-bit example)):
```
```
mov ax, 320; 2 cycles
mul word [row]; 22 CPU Cycles
mov di,ax; 2 cycles
add di, [column]; 2 cycles
; di = [row]*320 + [column]

; 16-bit addressing mode limitations:
; [di] is a valid addressing mode, but [ax] isn't, otherwise we could skip the last mov
```
```
Total: 28 cycles on whatever ancient CPU had these timings.
Vrs
```
```
mov ax, [row]; 2 cycles
mov di, ax; 2
shl ax, 6;  2
shl di, 8;  2
add di, ax; 2    (320 = 256+64)
add di, [column]; 2
; di = [row]*(256+64) + [column]
```
```
12 cycles on the same ancient CPU.
Yes, we would work this hard to shave off 16 CPU cycles.
In 32 or 64-bit mode, both versions get a lot shorter and faster.  Modern out-of-order execution CPUs like Intel Skylake (see
http://agner.org/optimize/
) have very fast hardware multiply (low latency and high throughput), so the gain is much smaller.  AMD Bulldozer-family is a bit slower, especially for 64-bit multiply.  On Intel CPUs, and AMD Ryzen, two shifts are slightly lower latency but more instructions than a multiply (which may lead to lower throughput):
```
```
imul edi, [row], 320    ; 3 cycle latency from [row] being ready
add  edi, [column]      ; 1 cycle latency (from [column] and edi being ready).
; edi = [row]*(256+64) + [column],  in 4 cycles from [row] being ready.
```
```
vs.
```
```
mov edi, [row]
shl edi, 6               ; row*64.   1 cycle latency
lea edi, [edi + edi*4]   ; row*(64 + 64*4).  1 cycle latency
add edi, [column]        ; 1 cycle latency from edi and [column] both being ready
; edi = [row]*(256+64) + [column],  in 3 cycles from [row] being ready.
```
```
Compilers will do this for you: See how
GCC, Clang, and Microsoft Visual C++ all use shift+lea when optimizing
```
return 320*row + col;
```
.
The most interesting thing to note here is that
x86 has a shift-and-add instruction (
```
LEA
```
)
that can do small left shifts and add at the same time, with the performance as an
```
add
```
instruction.  ARM is even more powerful: one operand of any instruction can be left or right shifted for free.  So scaling by a compile-time-constant that's known to be a power-of-2 can be even more efficient than a multiply.
OK, back in the modern days... something more useful now would be to use bitshifting to store two 8-bit values in a 16-bit integer. For example, in C#:
```
```
// Byte1: 11110000
// Byte2: 00001111

Int16 value = ((byte)(Byte1 >> 8) | Byte2));

// value = 000011111110000;
```
```
In C++, compilers should do this for you if you used a
```
struct
```
with two 8-bit members, but in practice they don't always.


q:
Let's say I have a class that has a member called data which is a list.

I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.

What's your technique for doing this?

Do you just check the type by looking at __class__?

Is there some trick I might be missing?

I'm used to C++ where overloading by argument type is easy.

[A]
A better way would be to use isinstance and type conversion. If I'm understanding you right, you want this:
```
```
def __init__ (self, filename):
    if isinstance (filename, basestring):
        # filename is a string
    else:
        # try to convert to a list
        self.path = list (filename)
```
```


q:
I am about to start on a journey writing a windows forms application that will open a txt file that is pipe delimited and about 230 mb in size. This app will then insert this data into a sql server 2005 database (obviously this needs to happen swiftly). I am using c# 3.0 and .net 3.5 for this project.

I am not asking for the app, just some communal advise here and potential pitfalls advise. From the site I have gathered that SQL bulk copy is a prerequisite, is there anything I should think about (I think that just opening the txt file with a forms app will be a large endeavor; maybe break it into blob data?).

Thank you, and I will edit the question for clarity if anyone needs it.

[A]
This is going to be a streaming endeavor.
If you can, do not use transactions here. The transactional cost will simply be too great.
So what you're going to do is read the file a line at a time and insert it in a line at a time. You should dump failed inserts into another file that you can diagnose later and see where they failed.
At first I would go ahead and try a bulk insert of a couple of hundred rows just to see that the streaming is working properly and then you can open up all you want.


q:
I can select all the distinct values in a column in the following ways:

SELECT DISTINCT column_name FROM table_name;

SELECT column_name FROM table_name GROUP BY column_name;

But how do I get the row count from that query? Is a subquery required?

[A]
```
```
select Count(distinct columnName) as columnNameCount from tableName
```
```


q:
What I would like is be able to generate a simple report that is the output of svn log for a certain date range.  Specifically, all the changes since 'yesterday'.

Is there an easy way to accomplish this in Subversion besides grep-ing the svn log output for the timestamp?

Example:

svn -v log -d 2008-9-23:2008-9:24 > report.txt

[A]
Very first hit by google for "svn log date range":
http://svn.haxx.se/users/archive-2006-08/0737.shtml
So
```
svn log <url> -r
  {2008-09-19}:{2008-09-26}
```
will get
  all changes for  the past week,
  including today.
And if you want to generate reports for a repo, there's a solution:
Statsvn
.
HTH


q:
I have an Enum like this

package com.example;

public enum CoverageEnum {

    COUNTRY,
    REGIONAL,
    COUNTY
}

I would like to iterate over these constants in JSP without using scriptlet code. I know I can do it with scriptlet code like this:

<c:forEach var="type" items="<%= com.example.CoverageEnum.values() %>">
    ${type}
</c:forEach>

But can I achieve the same thing without scriptlets?

Cheers,
Don

[A]
If you are using Tag Libraries you could encapsulate the code within an EL function. So the opening tag would become:
```
```
<c:forEach var="type" items="${myprefix:getValues()}">
```
```
EDIT: In response to discussion about an implementation that would work for multiple Enum types just sketched out this:
```
```
public static <T extends Enum<T>> Enum<T>[] getValues(Class<T> klass) {
    try {
        Method m = klass.getMethod("values", null);
        Object obj = m.invoke(null, null);
        return (Enum<T>[])obj;
    } catch(Exception ex) {
        //shouldn't happen...
        return null;
    }
}
```
```


q:
I've been working with Perl long enough that many of its idiosyncracies have become second nature to me.  When new programmers join our group, they frequently have little to no experience with Perl, and it's usually my task to train them (to the extent necessary).  I'd like to know what to focus on when training a programmer who is new to Perl but has experience with other languages (this question is meant to be language-agnostic, but most developers I've worked with have come from Java).

A few things occur to me:

The proper use of sigils

Referencing/Dereferencing

Use of list functions like map,
grep, sort

Is there anything in particular that you've found it useful to focus on when helping a programmer to transition to Perl?  Do you stress the similarities or the differences, or both in equal measure?

[A]
I'm a java programmer who recently had to pick up Perl.  The part I found hardest to get used to were all the special built in variables like $_ $~ $' and so on.  Until you get used to them it's hard to keep track of which one does what.
And, of course, the use of regular expressions.
For example, I have to maintain code and when I saw the line below for the first time it was a little confusing.  As a java programmer it looks like gibberish.
```
```
next unless "$_" !~ /^#/;
```
```


q:
Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures.

Some limitations are mentioned in the Closures in Python (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.

Seeing a code example for a concrete limitation would be great.

Related questions:

Can you explain closures (as they relate to Python)?

What is a ‘Closure’?

How does a javascript closure work ?

[A]
The only difficulty I've seen people encounter with Python's in particular is when they try to mix non-functional features like variable reassignment with closures, and are surprised when this doesn't work:
```
```
def outer ():
    x = 1
    def inner ():
        print x
        x = 2
    return inner
outer () ()
```
```
Usually just pointing out that a function has its own local variables is enough to deter such silliness.


q:
I've seen the other post about this, but is there a clean way of doing this in Haskell?

As a 2nd part, can it also be done without making the function monadic?

[A]
If your arguments are going to be natural numbers, you can do simply:
```
```
memo f = let values = map f [0..]
     in \n -> values !! n
```
```
However, that doesn't really help you with the stack overflowing, and it doesn't work with recursive calls. You can see some fancier solutions at
http://www.haskell.org/haskellwiki/Memoization
.


q: How do I tar a list of files and folders (all in the same directory) with the exclusion of a single directory (which contains a huge amount of data)

[A]
```
tar --exclude=PATTERN xvzf nameof.tar.gz ./*
```
PATTERN can be the directory name. GNU tar.


q:
If I do not specify the following in my web.xml file:

<session-config>
    <session-timeout>10</session-timeout>
</session-config>

What will be my default session timeout? (I am running Tomcat 6.0)

[A] I'm sure it depends on your container. Tomcat is 30 minutes.


q:
I have a Python application in a strange state.  I don't want to do live debugging of the process.  Can I dump it to a file and examine its state later?  I know I've restored corefiles of C programs in gdb later, but I don't know how to examine a Python application in a useful way from gdb.

(This is a variation on my question about debugging memleaks in a production system.)

[A]
There is no builtin way other than aborting (with os.abort(), causing the coredump if resource limits allow it) -- although you can certainly build your own 'dump' function that dumps relevant information about the data you care about. There are no ready-made tools for it.
As for handling the corefile of a Python process, the
Python source has a gdbinit file
that contains useful macros. It's still a lot more painful than somehow getting into the process itself (with pdb or the interactive interpreter) but it makes life a little easier.


q:
I know a Haskell module name, but I can't figure out in what package it is defined. This is bad because I can't compile without a package exposing this module.

Specificaly it is Text.Regex that I can't locate, but I would like to know how to solve that problem in general.

[A]
http://www.haskell.org/ghc/docs/latest/html/users_guide/packages.html
ghc-pkg find-module Text.Regex
But that only works for (a) recent GHCs, and (b) packages installed on your system.
You can also grep through the package file (e.g. /usr/lib/ghc-6.8.2/package.conf) to see what's installed.
You can also use either the haskell API search engines
hoogle
or the
hackage
search engine
hayoo
.
Text.Regex is in the package regex-base, and a few others built on top of it.


q:
Motivation

I'd like to find a way to take an arbitrary color and lighten it a few shades, so that I can programatically create a nice gradient from the one color to a lighter version. The gradient will be used as a background in a UI.

Possibility 1

Obviously I can just split out the RGB values and increase them individually by a certain amount. Is this actually what I want?

Possibility 2

My second thought was to convert the RGB to HSV/HSB/HSL (Hue, Saturation, Value/Brightness/Lightness), increase the brightness a bit, decrease the saturation a bit, and then convert it back to RGB. Will this have the desired effect in general?

[A]
I would go for the second option. Generally speaking the RGB space is not really good for doing color manipulation (creating transition from one color to an other, lightening / darkening a color, etc). Below are two sites I've found with a quick search to convert from/to RGB to/from HSL:
from the "Fundamentals of Computer Graphics"
some sourcecode in C#
- should be easy to adapt to other programming languages.


q:
I've looked at the java documentation and scoured the net for information on java's support for international characters with specific fonts (such as Monospace), but haven't been able to get a clear concrete answer.

There has been a change between java 1.4 and java 1.5/1.6. For example, in java 1.4 if you set the font on a JTextArea to Monospace, it won't be able to handle foreign characters (get rectangles instead), but in java 1.5/1.6 it seems to work fine.

Are these differences/improved support clearly documented anywhere?

Thanks

[A]
From
Internationalization Enhancements
:
Multilingual Text Rendering
To render multilingual text, using logical fonts, 2D now takes advantage of installed host OS fonts for all supported writing systems. For example, if you run in a Thai locale environment, but have Korean fonts installed, both Thai and Korean are rendered. The JRE now also automatically detects physical fonts that are installed into its lib/fonts/fallback directory and adds these physical fonts to all logical fonts for 2D rendering.
Use of Unicode APIs on Windows
AWT now uses the Unicode APIs on Windows 2000/XP. As a result, some of its components can handle text without being restricted by Windows locale settings.
For example, AWT text components can accept and display text in the Devanagari writing system regardless of the Windows locale settings.
(emphasis mine)