Question:
YUI Compressor does not accept wildcard parameters, so I cannot run it like this:

C:>java -jar yuicompressor.jar *.js

But I have over 500 files and would rather not have to create a batch file like this:

C:>java -jar yuicompressor.jar file1.js -o deploy\file1.js
C:>java -jar yuicompressor.jar file2.js -o deploy\file2.js
...
C:>java -jar yuicompressor.jar file500.js -o deploy\file500.js

And of course my file names are not in such uniform way.

Is there way to automate this without writing any code? :)

Answer:
I might go for a makefile (I think it would probably be more maintainable long term), but if you want a quick-n-dirty Windows batch command something like the following should work:
```
```
for %%a in (*.js) do @java -jar yuicompressor.jar "%%a" -o "deploy\%%a"
```
```


Question:
How can I find or generate thousands of company names for testing and demo purposes?  (Address, phone number, and related information would be nice too.)

I've got a system I'm building which includes business contact information.  Pretty common no doubt.

My test/demo database currently has randomly generated individual's names loaded (thanks to a handy IRS spreadsheet I found). This has worked great for internal testing and review purposes, but it looks really odd when shown to prospective customers.

I've tried various online public information sources (e.g. EDGAR, and county based property records searches), but these all require me to manually stitch together the results in blocks of 50 names or so at a time.  I could do this, but was really hoping for a search service or data store out there that had this type of information readily searchable and retrievable in very large batches.

Answer:
I use
Fake Name generator
:
What can I use the Fake Name Generator identities for?
Thousands of individuals, companies, and government organizations have found useful and creative things to do with the Fake Name Generator. Here are a few examples:
Quality test data can be hard to come by, especially with laws (such as HIPAA) preventing use of real data. Read more on
the dangers of testing with real data
.
Many websites, such message boards, are poorly designed, making it difficult for visitors from foreign countries to sign up for accounts. Using fake information, you can easily fill out the sign up forms and log in to the site.
Use fake information when filling out forms to avoid giving out personal information.
Generate a false identity to use as your pseudonym on the internet. This allows you to keep your real life and your internet life separate.
Get ideas for names to use for characters in a book or story.
Generated credit cards can be used to test basic client-/server-side validation techniques without accidentally processing a real card.
Generated national identity numbers can be used to test basic client-/server-side validation techniques without risking disclosure of real information...


Question:
I am building up a view with various text and image elements.

I want to display some text in the view with a blurry copy of the text behind it, but not just a text shadow.

How do I apply Gaussian blurred text onto a UIImage or layer?

Answer:
On the desktop, no question, you'd use CoreImage to do this.
On the phone though, I don't think there exists a way to do this using CoreGraphics. If it is absolutely critical OpenGLES may be able to help.
However, I would suggest rethinking your interface. I would think the blurred text would be distracting.
Edit: mledford points out in the comments that you could use CoreAnimation. I don't know if CA on the phone includes blur radius like on the desktop, but you could try it.


Question:
I have written a standalone app that controls a device through RS-232 port and some customers want to be able to use the device with LabVIEW.  I have seen some threads describing where to start when learning to use LabVIEW, but I was wondering if anyone has experience with writing a plugin/driver (is that the right word?) for LabVIEW and perhaps point me in the right direction.

The existing app is  GUI that allows people to control the device with higher level concepts - rather than have to know the syntax and protocol of the serial port comms stuff.  I want to abstract that away as well so that users can just plug something into LabVIEW and I suppose it exposes some verbs and methods that allow the device to be manipulated and also provide data to clients.

I think there is a serial port interface from LabVIEW, but I am sure the people using this device do not want to have to write the code (parsers and etc) to communicate with the device.

Answer:
There are two options for what you're trying to do.
Create a DLL that users of your device can
call from LabVIEW
.
Rewrite your application in LabVIEW.
To reach the largest possible number of potential customers, option #1 would be the best solution for you.  If your customers are specifically asking for a LabVIEW driver then option #2 would probably be the least hassle for that specific customer.  The reason for this is that LabVIEW is very much a niche language (for automation and data acquisition), and for many LabVIEW developers it's the only language they know (or the only one they know well).


Question:
I want to expose the functionality of an SAP program (transaction) as a BAPI.
I need to call a report and supply range filters such that the GUI is bypassed.

Does anyone have a working example of the SUBMIT ... WITH ... ABAP construct, or other suggestions on how to accomplish what I need to do?

Answer:
Here is a working example:
```
```
SUBMIT SAPF140
    TO SAP-SPOOL                         "optional"
    SPOOL PARAMETERS print_parameters    "optional"
    WITHOUT SPOOL DYNPRO                 "optional (hides the spool pop-up)"
    VIA JOB jobname NUMBER l_number      "optional"
    AND RETURN                           "optional - returns to the calling prog"
    WITH EVENT   =  REVENT
    WITH BUKRS   IN RBUKRS
    WITH BELNR   IN lRBELNR
    WITH GJAHR   IN RGJAHR
    WITH USNAM   =  SY-UNAME
    WITH DATUM   =  SAVE_DATUM
    WITH UZEIT   =  SAVE_UZEIT
    WITH DELDAYS =  RDELDAYS
    WITH KAUTO   =  'X'
    WITH RPDEST  =  SAVE_PDEST
    WITH TITLE   =  TITLE.
```
```
All the "WITH" statements relates to selection fields on the called program where I use = it is a PARAMETER statement (single field), where I use IN it is a SELECT_OPTIONS statement (range)
Here is a simple example of how to fill a range:
```
```
REFRESH lrbelnr.
lrbelnr-sign = 'I'.
lrbelnr-option = 'EQ'.
lrbelnr-low = HBKORM-belnr.
CLEAR lrbelnr-high.
append lrbelnr.
```
```


Question:
I need to round a value up to the nearest multiple of 2.5.

For example:

6 --> 7.5

7.6 --> 10

etc.

This seems like the best way to do this?

   Function RoundToIncrement(ByVal originalNumber As Decimal, ByVal increment As Decimal) As Decimal

        Dim num = Math.Round(originalNumber / increment, MidpointRounding.AwayFromZero) * increment
        If originalNumber Mod increment <> 0 And num < originalNumber Then
            num += increment
        End If
        Return num

    End Function

Answer:
Divide the number by 2.5, round up to the nearest integer, then multiply the result by 2.5.
You're close.
```
```
Function RoundToIncrement(ByVal orignialNumber As Decimal, ByVal increment As Decimal) As Decimal
    Return Math.Ceiling( orignialNumber / increment ) * increment
End Function
```
```
Math.Ceiling will always round non-integers up, so you don't need the post-adjustment.


Question:
Consider the following code:

abstract class SomeClassX<T>
{
  // blah
}

class SomeClassY: SomeClassX<int>
{
  // blah
}

class SomeClassZ: SomeClassX<long>
{
  // blah
}

I want a collection of SomeClassX<T>'s, however, this isn't possible since SomeClassX<int> != SomeClassX<long> and List<SomeClassX<>> isn't allowed.

So my solution is to have SomeClassX<T> implement an interface and define my collection as, where ISomeClassX is the interface:

class CollectionOfSomeClassX: List<ISomeClassX>
{
  // blah
}

Is this the best way to do this, or is there better way?

Answer:
Divide the number by 2.5, round up to the nearest integer, then multiply the result by 2.5.
You're close.
```
```
Function RoundToIncrement(ByVal orignialNumber As Decimal, ByVal increment As Decimal) As Decimal
    Return Math.Ceiling( orignialNumber / increment ) * increment
End Function
```
```
Math.Ceiling will always round non-integers up, so you don't need the post-adjustment.


Question: How do I programmatically return the maximum of two integers without using any comparison operators and without using if, else, etc?

Answer:
return (a > b ? a : b);
or
```
```
int max(int a, int b)
{
        int x = (a - b) >> 31;
        int y = ~x;
        return (y & a) | (x & b);
}
```
```


Question:
I've run across the following line in a VB6 application.

mobjParentWrkBk.ExcelWorkBook.Application.Selection.Insert Shift:=xlToRight

Unfortunately Google and other search engines have not been very useful as they seem to omit the := part.

What would be a C# equivalent?

Answer:
This is Visual Basic syntax for optional named parameters. The
```
Insert
```
function has a parameter named
```
Shift
```
, which is being specified.
C#, as far as I know, doesn't have an equivalent for optional named parameters. Instead, you'd need to call the
```
Insert
```
method, specifying
```
Type.Missing
```
for all parameters other than
```
Shift
```
.
See also the following StackOverflow question:
VB.NET := Operator
UPDATE (2008-10-29):
C# 4.0 is set to introduce optional and named parameters. See this
blog entry on codebetter.com
.


Question:
I am planning a PHP application that needs to store date/times in an MSSQL database. (For the curious, it is a calendar application.) What is the preferred format to store this information?

MSSQL has its own datetime data type, which works well in the database itself and is very readable. However, there aren't any MSSQL functions to translate datetime values to PHP's preferred format--UNIX timestamp. This makes it a bit more painful to use with PHP. UNIX timestamp is attractive because that's what PHP likes, but it's certainly not as readable and there aren't a bunch of nice built-in MSSQL functions for working with the data.

Would you store this information as datetime data type, as UNIX timestamps (as int, bigint, or varchar datatype), as both formats side by side, or as something else entirely?

Answer:
I'd recommend the same as i do for all dates in any db engine, the db native type. (DATETIME)
Just use "YYYY-MM-DD HH:MM:SS" for inserting in php:
```
date('Y-m-d H:i:s', $myTimeStampInSeconds);
```
-edit in response to comments below here -
for selected columns you can use
```
$timestamp =
strtotime
( $yourColumnValue );
```
i recommend storing in the databas native format because you can then use SQL to compare records using SQL date/time functions like DATEADD() etc.


Question:
Here is my function (updated):

Public Shared Function shortenUrl(ByVal URL As String) As String
    Return shortenUrl(URL, 32)
End Function
Public Shared Function shortenUrl(ByVal URL As String, ByVal maxLength As Integer) As String
    If URL.Length > maxLength Then
        String.Format("{0}...{1}", URL.Substring(0, (maxLength / 2)), URL.Substring(URL.Length - ((maxLength / 2) - 3)))
    Else
        Return URL
    End If
End Function

I fixed the problem where it didn't return maxLength chars because it didn't take into account the ellipses.

It seems to me that it is too complicated; any suggestions, comments, concerns are more than welcome.

Answer:
Why not do this?
```
```
Public Shared Function shortenUrl(ByVal URL As String) As String
    Return shortenUrl(URL, 29)
End Function
Public Shared Function shortenUrl(ByVal URL As String, ByVal maxLength As Integer) As String
    If URL.Length > maxLength Then
        Return String.Format("{0}...{1}", URL.Substring(0, maxLength / 2),URL.Substring(URL.Length - (maxLength / 2)))
    Else
        Return URL
    End If
End Function
```
```
That at least gets rid of all of the tempoary declarations


Question:
I'm attempting to determine the row length in bytes of a table by executing the following stored procedure:

CREATE TABLE #tmp
(
  [ID] int,
  Column_name varchar(640),
  Type varchar(640),
  Computed varchar(640),
  Length int,
  Prec int,
  Scale int,
  Nullable varchar(640),
  TrimTrailingBlanks varchar(640),
  FixedLenNullInSource varchar(640),
  Collation varchar(256)
)
INSERT INTO #tmp exec sp_help MyTable
SELECT SUM(Length) FROM #tmp
DROP TABLE #tmp

The problem is that I don't know the table definition (data types, etc..) of the table returned by 'sp_help.'

I get the following error:

Insert Error: Column name or number of supplied values does not match table definition.

Looking at the sp_help stored procedure does not give me any clues.

What is the proper CREATE TABLE statement to insert the results of a sp_help?

Answer:
I can't help you with creating a temp table to store sp_help information, but I can help you with calculating row lengths. Check out this
MSDN article
; it helps you calculate such based on the field lengths, type, etc. Probably wouldn't take too much to convert it into a SQL script you could reuse by querying against sysobjects, etc.
EDIT:
I'm redacting my offer to do a script for it. My way was nowhere near as easy as Vendoran's. :)
As an aside, I take back what I said earlier about not being able to help with the temp table. I can: You can't do it. sp_help outputs seven rowsets, so I don't think you'll be able to do something as initially described in the original question. I think you're stuck using a different method to come up with it.


Question:
I have a Rails application that in the erb code, I use a select box. What I would like to do is reload the page passing the sort parameter. My controller already handles it, but I don't know how to reload the page with the selected value from my select box. Here is my code:

<% @options = {:latest => 'lastest' , :alphabetical => 'alphabetical', :pricelow => 'price-low', :pricehigh =>'pricehigh'} %>
<%= select_tag 'sort[]', options_for_select(@options), :include_blank => true,:onchange => "location.reload('location?sort='+this.value)"%>

Answer:
Have you considered using an ajax call on your list box? If you have a method on your controller that returns just the sorted list, based on sort parameter, then you could do:
```
```
<% @options = {:latest => 'lastest' , :alphabetical => 'alphabetical', :pricelow => 'price-low', :pricehigh =>'pricehigh'} %>
<%= select_tag 'sort[]', options_for_select(@options), :include_blank => true,:onchange => remote_function(:url => {:controller => 'your_controller', :action => 'list_sort_method'}, :with => "'sort='+this.value", :update => "div_containing_list") %>
```
```


Question:
When I use this code to output some XML I parsed (and modified) with XmlParser

XmlParser parser = new XmlParser()
def root = parser.parseText(feedUrl.toURL().text)
def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(root)
println writer.toString()

the namespace declarations on the root node are not printed, even though they are there in the toString() of root...  any ideas?

Answer:
It looks like it's denormalizing the output and including the namespace context along with the nodes that actually need the namespace context.
For example, the webpage for this question comes in with creativeCommons namespace embedded:
```
```
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:thr="http://purl.org/syndication/thread/1.0">
  <!-- snip -->
  <creativeCommons:license>http://www.creativecommons.org/licenses/by-nc/2.5/rdf</creativeCommons:license>
  <!-- snip -->
</feed>
```
```
When you output the xml using this script:
```
```
def root = new XmlParser().parseText("http://stackoverflow.com/feeds/question/227447".toURL().text)
println new XmlNodePrinter().print(root)
```
```
It ends up moving the namespace to the license node that needs that namespace.  Not a huge deal in this case as there is only a single node in that namespace.  If most of the XML were namespaced, it'd probably bloat things quite a bit more.
```
```
<feed xmlns="http://www.w3.org/2005/Atom">
  <!-- snip -->
    <creativeCommons:license xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule">
http://www.creativecommons.org/licenses/by-nc/2.5/rdf
  </creativeCommons:license>
  <!-- snip -->
</feed>
```
```
If you actually wanted the nodes normalized, you'd have to make some tweaks to the XmlNodePrinter to do 2 passes through the XML, first to gather all of the used namespaces and 2nd to output them at the top rather than within each namespaced node.  The groovy source code is actually pretty readable and wouldn't be that hard to modify if you actually needed this.


Question: How do I get the ASCII value of a character as an int in Python?

Answer:
You are looking for:
```
```
ord()
```
```


Question:
I want to do some basic filtering on a file. Read it, do processing, write it back.

I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with:

from __future__ import with_statement

filename = "..." # or sys.argv...

with open(filename) as f:
    new_txt = # ...some translation of f.read()

open(filename, 'w').write(new_txt)

The with statement makes things shorter since I don't have to explicitly open and close the file.

Any other ideas ?

Answer:
This seems to work:
```
```
with open(filename, "r+") as f:
    new_txt = process(f.read())
    f.truncate(0)
    f.write(new_txt)
```
```


Question:
I have a search form on each of my pages. If I use form helper, it defaults to $_POST. I'd like the search term to show up in the URI:

http://example.com/search/KEYWORD

I've been on Google for about an hour, but to no avail. I've only found articles on how $_GET is basically disabled, because of the native URI convention. I can't be the first person to want this kind of functionality, am I? Thanks in advance!

Answer:
I don't know much about CodeIgniter, but it's PHP, so shouldn't
```
$_GET
```
still be available to you? You could format your URL the same way Google does:
```
mysite.com/search?q=KEYWORD
```
and pull the data out with
```
$_GET['q']
```
.
Besides, a search form seems like a bad place to use POST; GET is bookmarkable and doesn't imply that something is changing server-side.


Question:
I need a well tested Regular Expression (.net style preferred), or some other simple bit of code that will parse a USA/CA phone number into component parts, so:

3035551234122

1-303-555-1234x122

(303)555-1234-122

1 (303) 555 -1234-122

etc...

all parse into:

AreaCode: 303

Exchange: 555

Suffix: 1234

Extension: 122

Answer:
This is the one I use:
```
```
^(?:(?:[\+]?(?<CountryCode>[\d]{1,3}(?:[ ]+|[\-.])))?[(]?(?<AreaCode>[\d]{3})[\-/)]?(?:[ ]+)?)?(?<Number>[a-zA-Z2-9][a-zA-Z0-9 \-.]{6,})(?:(?:[ ]+|[xX]|(i:ext[\.]?)){1,2}(?<Ext>[\d]{1,5}))?$
```
```
I got it from
RegexLib
I believe.


Question: Would NTFS allocation blocks of 16KB or 32KB make compile time faster in comparison to the default 4KB?

Answer:
I can't imagine that would make much of a difference - disk block size is pretty far removed from compile speed. With the amount of caching a modern OS does, it seems unlikely to be significant.
The real answer, of course, can be found by measuring it. Getting similar conditions between different machines with different disk block sizes might be tricky, though.


Question:
Does anyone know how to programmaticly find out where the java classloader actually loads the class from?

I often work on large projects where the classpath gets very long and manual searching is not really an option.  I recently had a problem where the classloader was loading an incorrect version of a class because it was on the classpath in two different places.

So how can I get the classloader to tell me where on disk the actual class file is coming from?

Edit: What about if the classloader actually fails to load the class due to a version mismatch (or something else),  is there anyway we could find out what file its trying to read before it reads it?

Answer:
Assuming that you're working with a class named
```
MyClass
```
, the following should work:
```
```
MyClass.class.getClassLoader();
```
```
Whether or not you can get the on-disk location of the .class file is dependent on the classloader itself.  For example, if you're using something like BCEL, a certain class may not even have an on-disk representation.


Question:
I'm working on a JSP where I need to call methods on object that come from a Bean. The previous version of the page does not use JSTL and it works properly. My new version has a set up like this:

<jsp:useBean id="pageBean" scope="request" type="com.epicentric.page.website.PageBean" />
<c:set var="pageDividers" value="<%= pageBean.getPageDividers() %>" />
<c:set var="numColumns" value="${pageDividers.size()}" />

The variable pageDividers is a List object.

I'm encountering this issue: when I ask for pageDivider's size, an exception is thrown. I know this is a simple JTSL error -- what am I doing wrong?

The error message is:

The function size must be used with a prefix when a default namespace is not specified

How do I correctly access or call the methods of my pageDividers object?

Answer:
To access the property of a bean using EL you simply name the property (not invoke the method). So lets say you have a method called getSize() in the bean then
```
```
${pageDividers.size}
```
```
Notice no ().
EDIT:Sorry...made an error in the original post.


Question: How can I read an Open Office 3.0 spreadsheet (.ods) from Groovy?  I'd like to select specific columns from a named worksheet.  Ideally, it would be useful to add a 'where' clause, or other criteria clause.

Answer:
Might be something here at
Spring Factories
or here at
Groovy and JMX
. There is a forum for
Groovy and Open Office
.


Question: Are you aware of any open source libraries/projects that offer audio watermarking capability?

Answer:
check wikipedia:
http://en.wikipedia.org/wiki/Steganography#Implementations
section 3 of this site site is on audio:
http://www.binary-universe.net/
same author did a project on codeplex.
these also do audio:
StegHide
mpeStego


Question: I know that it is possible to check how much physical RAM is installed using GetPhysicallyInstalledSystemMemory or how much ram the operating system can see using GlobalMemoryStatusEx.  However, I am wondering if there is any way to check how much ram a user has installed by slot.  That is, to be able to programmatically tell the difference between 1x2GB of ram and 2x1GB of ram, thus checking if the computer can be upgraded easily via software.  Ideally, a way to check this without .Net.

Answer:
Reviewing the MSDN docs for the functions listed
here
, I see that the function checks with the SMBIOS table, which is referenced by a standard
here
It appears that you indeed can find the information you seek through the BIOS. You may have to install a driver to get that information out to your program.
Good luck!


Question: Does anyone have a good articles or tutorial on correctly using dispose and IDisposable.  I am trying to explain this to some junior dev and wanted to get some extra material, examples, etc.

Answer:
A good place to start is this MSDN article by Shawn Farkas
http://msdn.microsoft.com/en-us/magazine/cc163392.aspx
. The definitive article is by Joe Duffy at
http://www.bluebytesoftware.com/blog/2005/04/08/DGUpdateDisposeFinalizationAndResourceManagement.aspx
with some follow-up in
http://www.bluebytesoftware.com/blog/2008/02/18/IDisposableFinalizationAndConcurrency.aspx


Question:
Is there a simple way to parse a date that may be in MM/DD/yyyy, or M/D/yyyy, or some combination? i.e. the zero is optional before a single digit day or month.

To do it manually, one could use:

String[] dateFields = dateString.split("/");
int month = Integer.parseInt(dateFields[0]);
int day = Integer.parseInt(dateFields[1]);
int year = Integer.parseInt(dateFields[2]);

And validate with:

dateString.matches("\\d\\d?/\\d\\d?/\\d\\d\\d\\d")

Is there a call to SimpleDateFormat or JodaTime that would handle this?

Answer:
Yep, use setLenient:
```
```
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
df.setLenient(true);
System.out.println(df.parse("05/05/1999"));
System.out.println(df.parse("5/5/1999"));
```
```


Question: How do I copy a directory including sub directories excluding files or directories that match a certain regex on a Windows system?

Answer:
I don't know how to do an exclusion with a copy, but you could work something up along the lines of:
```
```
ls -R1 | grep -v <regex to exclude> | awk '{printf("cp %s /destination/path",$1)}' | /bin/sh
```
```


Question:
There are a whole raft of questions regarding payment processors for web applications but I haven't seen one yet for desktop applications. What are your experiences?

Perhaps to put this into a little context, the requirements:

Should be customisable

Should be available in Australia at least, if not world wide (less critical).

No storage of credit card details

Recurrent micro payments of varying amounts each time

1-click payment. It's ok for the user to be registered with the payment processor provider.

Answer:
Times may be a changing, but I don't think that you can get all of the above.
I do have some experience a couple years back with credit cards in North America.  At the time the company I worked for needed recurring billing for a different amount each month (much like your requirement). At the time, none of the providers I looked into allowed for recurring payments where the amount varied. This may have changed, but I do not know of one.
I suspect your options are either to store credit cards and process your own transactions (not too hard but a path you have to walk carefully) or use recurring billing with a constant amount.


Question: I am trying to create controller actions which will return either JSON or partial html depending upon a parameter. What is the best way to get the result returned to an MVC page asynchronously?

Answer:
In your action method, return Json(object) to return JSON to your page.
```
```
public ActionResult SomeActionMethod() {
  return Json(new {foo="bar", baz="Blech"});
}
```
```
Then just call the action method using Ajax. You could use one of the helper methods from the ViewPage such as
```
```
<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>
```
```
SomeMethod would be a javascript method that then evaluates the Json object returned.
If you want to return a plain string, you can just use the ContentResult:
```
```
public ActionResult SomeActionMethod() {
    return Content("hello world!");
}
```
```
ContentResult by default returns a text/plain as its contentType.
This is overloadable so you can also do:
```
```
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
```
```


Question:
I have this 'simplified' fortran code

real B(100, 200)
real A(100,200)

... initialize B array code.

do I = 1, 100
  do J = 1, 200
    A(J,I) = B(J,I)
  end do
end do

One of the programming gurus warned me, that fortran accesses data efficiently in column order, while c accesses data efficiently in row order.   He suggested that I take a good hard look at the code, and be prepared to switch loops around to maintain the speed of the old program.

Being the lazy programmer that I am, and recognizing the days of effort involved, and the mistakes I am likely to make, I started wondering if there might a #define technique that would let me convert this code safely, and easily.

Do you have any suggestions?

Answer:
Are you sure your FORTRAN guys did things right?
The code snippet you originally posted is already accessing the arrays in row-major order (which is 'inefficient' for FORTRAN, 'efficient' for C).
As illustrated by the snippet of code and as mentioned in your question, getting this 'correct' can be error prone.  Worry about getting the FORTRAN code ported to C first without worrying about details like this.  When the port is working - then you can worry about changing column-order accesses to row-order accesses (if it even really matters after the port is working).


Question: I'm a total amateur writing a small App to track to changes in folders. I imagine I'll be keeping information about the directories to watch in one datatable bound to a gridview, when the user clicks a button, the program will create FileSystemWatchers to keep an eye on the directories and they will send their event messages to another datatable bound to another gridview. Where in the wide wide world of OOP should I be declaring, initiating, and manipulating the Datatables? The main form, inside main, in a class, or should I "give up" and use Visual Studio to automagically create a DataSet and stick two tables in it?

Answer:
Well horses for courses. For a little utility app you would probably be better off using the VS "Visual/RAD" style of programming. Eg drag and drop tables etc on to the form, like most of the tutorials show.
Strictly speaking, and for a larger app, a more correct way would be to make a separate assembly(.dll) that handles data access and you call the classes within that assembly from the main form. This concept goes under a number of terms, but effectively you want to separate your concerns. In other words, let the UI handle UI interactions, have a separate assembly/project/whatever that handles database interactivity, and another separate assembly/project/whatever that handles business logic etc.
That last couple of sentences can mean different things to different people, and there is no 100% correct way to do things.
Some articles that may help:
link text
link text
link text


Question: I've used both and I've found MySql to have several frustrating bugs, limited support for: IDE integration, profiling, integration services, reporting, and even lack of a decent manager. Total cost of ownership of MSSQL Server is touted to be less than MySQL too (.net environment), but maintaining an open mind could someone point out any killer features of MySql?

Answer:
I've used MySQL in the past and I'm using MSSQL lately but I can't remember anything that MySQL has and MSSQL can't do.
I think the most killer feature of MySQL it's the simplicity. For some projects you just don't need all the power you can have with a huge system like MSSQL. I have an UNIX heritage and find the simple configuration file like my.ini a killer feature of MySQL.
Also the security system of MySQL is much less robust but it makes the job right for most of applications. I believe MySQL it's killer itself from this point of view, and should stay that way, letting young users being introduced to RDBMS with a simple view first. If your project gets big enough that you are considering switch to a more robust system, then MSSQL can pop as a possibility.
That's what happened to me.


Question:
I found this page describing the Muenchian method, but I think I'm applying it wrong.

Consider that this would return a set of ages:

/doc/class/person/descriptive[(@name='age')]/value

1..2..2..2..3..3..4..7

But I would like a nodeset only one node for each age.

1..2..3..4..7

Each of these seem to return all of the values, instead of unique values:

/doc/class/person/descriptive[(@name='age')][not(value=preceding-sibling::value)]/value
/doc/class/person/descriptive[(@name='age')]/value[not(value=preceding-sibling::value)]

What am I missing?

Answer:
Aren't you missing a reference to 'descriptive' right after the preceding-value? Some thing like the following:
```
```
/doc/class/person/descriptive[(@name='age')][not(value=preceding-sibling::descriptive[@name='age']/value)]/value
```
```
(Haven't tested it)


Question:
I need to do some large integer math.  Are there any classes or structs out there that represent a 128-bit integer and implement all of the usual operators?

BTW, I realize that decimal can be used to represent a 96-bit int.

Answer:
No, there's nothing in .NET <= 3.5. I'm hoping/expecting that
BigInteger
will make its return in .NET 4.0. (It was
cut from .NET 3.5
.)


Question: I have a case where a 3rd party ad is bleeding through my modal window implementation. I'd like to up the z-index of the modal overlay as high as possible so the ad won't show on top of it. Is there a limit to z-index values? I'm sure if there is it varies by browser. Anyone know?

Answer:
Not really, but you might consider the natural limitations of a system, like an int range. I'd
probably keep it under 32,767
.  I've definitely exceeded that in javascript while working on a similar problem, and didn't encounter any problems on the major browsers and platforms that I was concerned about at the time.
In the case of 3rd party ads and overlays, making sure that
wmode="transparent"
on the flash embed is a common problem along the same lines.  Also worth noting that IE has a bug with stacking z-indexes, so if you're not seeing success, make sure you're not hitting your head up against the wall with that one*.
I always like to keep to some kind of
convention
, and not use arbitrary figures.  For example, maybe everything in my
css falls between 0 and 10
.  Maybe dhtml stuff happens in the 100's place values, with a meaningful z-index for any given module.
*Sidenote:
The IE bug, to be specific, is that IE considers a new instance of document flow to be a new stacking context for z-index.  You need to make sure that your z-indexes aren't being lost in the DOM hierarchy when a child node that would normally be inheriting your z-index is being rendered it's own positioning context.


Question:
Someone told me that it's faster to concatenate strings with StringBuilder. I have changed my code but I do not see any Properties or Methods to get the final build string.

How can I get the string?

Answer:
Once you have completed the processing using the StringBuilder, use the ToString method to return the final result.
From MSDN:
```
```
using System;
using System.Text;

public sealed class App
{
    static void Main()
    {
        // Create a StringBuilder that expects to hold 50 characters.
        // Initialize the StringBuilder with "ABC".
        StringBuilder sb = new StringBuilder("ABC", 50);

        // Append three characters (D, E, and F) to the end of the StringBuilder.
        sb.Append(new char[] { 'D', 'E', 'F' });

        // Append a format string to the end of the StringBuilder.
        sb.AppendFormat("GHI{0}{1}", 'J', 'k');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());

        // Insert a string at the beginning of the StringBuilder.
        sb.Insert(0, "Alphabet: ");

        // Replace all lowercase k's with uppercase K's.
        sb.Replace('k', 'K');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());
    }
}

// This code produces the following output.
//
// 11 chars: ABCDEFGHIJk
// 21 chars: Alphabet: ABCDEFGHIJK
```
```


Question:
So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?

Example:

def burninate(b):
    c = []
    for i in range(3):
        c.append(b.pop())
    return c

a = range(6)
d = burninate(a)
print a, d

Output: [0, 1, 2] [5, 4, 3]

Desired output: [0, 1, 2, 3, 4, 5] [5, 4, 3]

Thanks!

Answer:
You can call
```
burninate()
```
with a copy of the list like this:
```
d = burninate(a[:])
```
or,
```
d = burninate(list(a))
```
The other alternative is to make a copy of the list in your method:
```
```
def burninate(b):
    c=[]
    b=b[:]
    for i in range(3):
        c.append(b.pop())
    return c

>>> a = range(6)
>>> b = burninate(a)
>>> print a, b
>>> [0, 1, 2, 3, 4, 5] [5, 4, 3]
```
```


Question: In my cross-platform architecture, I would like to act on a context menu click (right button click) during a mouse click event.  In Cocoa, can you detect that the user either Ctrl-Clicked or double-tapped on touchpad (right-click equivalent) DURING the mouseDown event?  I am aware of NSView's menuForEvent but do not wish to handle it here.

Answer:
If you're using AppKit, and you want to detect a right-click in your view, you should override
```
-[NSResponder rightMouseDown:]
```
.


Question:
I have a Rails app that sets a cookie and does a redirect to another server once the user is logged in. However, the cookie that the Rails app sets isn't seen by the server for some reason. I've tried setting http_only to false but I still can't even see the cookie unless the domain is the same as my Rails app. Here's the code I'm using to set the cookie:

cookies[:dev_appserver_login] =
  { :value => "#{email}:#{nick}:#{admin}:#{hsh}",
    :domain => "webserver-to-redirect-to",
    :expires => 30.days.from_now }

redirect_to session[:dest_url]

If I manually create a cookie with the Web Developer extension in Firefox it works fine, but not when Rails does it. Any ideas?

Answer:
What are the redirecting and redirected-to servers? You can only set ‘domain’ to the current hostname or a parent domain, so if you're on a.example.com and you're redirecting to b.example.com, you have to set ‘domain’ to .example.com,
not
b.example.com as implied in the code snippet.
(And open domains like the .com TLD aren't themselves allowed as domain values, so if you want to pass a cookie from a.example.com to b.somewhereelse.com you will need a more complicated solution probably involving changing the code on somewhereelse.com.)


Question:
I was just writing some quick code and noticed this complier error

Using the iteration variable in a lambda expression may have unexpected results.

  Instead, create a local variable within the loop and assign it the value of the iteration variable.

I know what it means and I can easily fix it, not a big deal.

But I was wondering why it is a bad idea to use a iteration variable  in a lambda?

What problems can I cause later on?

Answer:
Assuming you mean C# here.
It's because of the way the compiler implements closures. Using an iteration variable
can
cause a problem with accessing a modified closure (note that I said 'can' not 'will' cause a problem because sometimes it doesn't happen depending on what else is in the method, and sometimes you actually want to access the modified closure).
More info:
http://blogs.msdn.com/abhinaba/archive/2005/10/18/482180.aspx
Even more info:
http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx
http://blogs.msdn.com/oldnewthing/archive/2006/08/03/687529.aspx
http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx


Question: How do I determine the dependencies of a .NET application? Does Dependency Walker work with managed apps? I've downloaded the latest and tried profiling the app, but it just exits without much of an explanation. If it doesn't work with .NET, then is there some other tool that would help me debug a run-time DLL loading issue?

Answer:
Dependency walker works on normal win32 binaries. All .NET dll's and exe's have a small stub header part which makes them look like normal binaries, but all it basically says is "load the CLR" - so that's all that dependency walker will tell you.
To see which things your .NET app actually relies on, you can use the tremendously excellent
.NET reflector
from Red Gate. (EDIT: Note that .NET Reflector is now a paid product.
ILSpy
is free and open source and very similar.)
Load your DLL into it, right click, and chose 'Analyze' - you'll then see a "Depends On" item which will show you all the other dll's (and methods inside those dll's) that it needs.
It can sometimes get trickier though, in that your app depends on X dll, and X dll is present, but for whatever reason can't be loaded or located at runtime.
To troubleshoot those kinds of issues, Microsoft have an
Assembly Binding Log Viewer
which can show you what's going on
at runtime


Question:
I just finished a test as part of a job interview, and one question stumped me, even using Google for reference. I'd like to see what the StackOverflow crew can do with it:

The memset_16aligned function requires a 16-byte aligned pointer passed to it, or it will crash.

a) How would you allocate 1024 bytes of memory, and align it to a 16 byte boundary?

b) Free the memory after the memset_16aligned has executed.

{
   void *mem;
   void *ptr;

   // answer a) here

   memset_16aligned(ptr, 0, 1024);

   // answer b) here
}

Answer:
Original answer
```
```
{
    void *mem = malloc(1024+16);
    void *ptr = ((char *)mem+16) & ~ 0x0F;
    memset_16aligned(ptr, 0, 1024);
    free(mem);
}
```
```
Fixed answer
```
```
{
    void *mem = malloc(1024+15);
    void *ptr = ((uintptr_t)mem+15) & ~ (uintptr_t)0x0F;
    memset_16aligned(ptr, 0, 1024);
    free(mem);
}
```
```
Explanation as requested
The first step is to allocate enough spare space, just in case.  Since the memory must be 16-byte aligned (meaning that the leading byte address needs to be a multiple of 16), adding 16 extra bytes guarantees that we have enough space.  Somewhere in the first 16 bytes, there is a 16-byte aligned pointer.  (Note that
```
malloc()
```
is supposed to return a pointer that is sufficiently well aligned for
any
purpose.  However, the meaning of 'any' is primarily for things like basic types —
```
long
```
,
```
double
```
,
```
long double
```
,
```
long long
```
, and pointers to objects and pointers to functions.  When you are doing more specialized things, like playing with graphics systems, they can need more stringent alignment than the rest of the system — hence questions and answers like this.)
The next step is to convert the void pointer to a char pointer; GCC notwithstanding, you are not supposed to do pointer arithmetic on void pointers (and GCC has warning options to tell you when you abuse it).  Then add 16 to the start pointer.  Suppose
```
malloc()
```
returned you an impossibly badly aligned pointer: 0x800001.  Adding the 16 gives 0x800011. Now I want to round down to the 16-byte boundary — so I want to reset the last 4 bits to 0.  0x0F has the last 4 bits set to one; therefore,
```
~0x0F
```
has all bits set to one except the last four.  Anding that with 0x800011 gives 0x800010.  You can iterate over the other offsets and see that the same arithmetic works.
The last step,
```
free()
```
, is easy: you always, and only, return to
```
free()
```
a value that one of
```
malloc()
```
,
```
calloc()
```
or
```
realloc()
```
returned to you — anything else is a disaster.  You correctly provided
```
mem
```
to hold that value — thank you.  The free releases it.
Finally, if you know about the internals of your system's
```
malloc
```
package, you could guess that it might well return 16-byte aligned data (or it might be 8-byte aligned).  If it was 16-byte aligned, then you'd not need to dink with the values.  However, this is dodgy and non-portable — other
```
malloc
```
packages have different minimum alignments, and therefore assuming one thing when it does something different would lead to core dumps.  Within broad limits, this solution is portable.
Someone else mentioned
```
posix_memalign()
```
as another way to get the aligned memory; that isn't available everywhere, but could often be implemented using this as a basis.  Note that it was convenient that the alignment was a power of 2; other alignments are messier.
One more comment — this code does not check that the allocation succeeded.
Amendment
Windows Programmer
pointed out that you can't do bit mask operations on pointers, and, indeed, GCC (3.4.6 and 4.3.1 tested) does complain like that.  So, an amended version of the basic code — converted into a main program, follows.  I've also taken the liberty of adding just 15 instead of 16, as has been pointed out.  I'm using
```
uintptr_t
```
since C99 has been around long enough to be accessible on most platforms.  If it wasn't for the use of
```
PRIXPTR
```
in the
```
printf()
```
statements, it would be sufficient to
```
#include <stdint.h>
```
instead of using
```
#include <inttypes.h>
```
.
[This code includes the fix pointed out by
C.R.
, which was reiterating a point first made by
Bill K
a number of years ago, which I managed to overlook until now.]
```
```
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void memset_16aligned(void *space, char byte, size_t nbytes)
{
    assert((nbytes & 0x0F) == 0);
    assert(((uintptr_t)space & 0x0F) == 0);
    memset(space, byte, nbytes);  // Not a custom implementation of memset()
}

int main(void)
{
    void *mem = malloc(1024+15);
    void *ptr = (void *)(((uintptr_t)mem+15) & ~ (uintptr_t)0x0F);
    printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr);
    memset_16aligned(ptr, 0, 1024);
    free(mem);
    return(0);
}
```
```
And here is a marginally more generalized version, which will work for sizes which are a power of 2:
```
```
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void memset_16aligned(void *space, char byte, size_t nbytes)
{
    assert((nbytes & 0x0F) == 0);
    assert(((uintptr_t)space & 0x0F) == 0);
    memset(space, byte, nbytes);  // Not a custom implementation of memset()
}

static void test_mask(size_t align)
{
    uintptr_t mask = ~(uintptr_t)(align - 1);
    void *mem = malloc(1024+align-1);
    void *ptr = (void *)(((uintptr_t)mem+align-1) & mask);
    assert((align & (align - 1)) == 0);
    printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr);
    memset_16aligned(ptr, 0, 1024);
    free(mem);
}

int main(void)
{
    test_mask(16);
    test_mask(32);
    test_mask(64);
    test_mask(128);
    return(0);
}
```
```
To convert
```
test_mask()
```
into a general purpose allocation function, the single return value from the allocator would have to encode the release address, as several people have indicated in their answers.
Problems with interviewers
Uri
commented: Maybe I am having [a] reading comprehension problem this morning, but if the interview question specifically says: "How would you allocate 1024 bytes of memory" and you clearly allocate more than that. Wouldn't that be an automatic failure from the interviewer?
My response won't fit into a 300-character comment...
It depends, I suppose.  I think most people (including me) took the question to mean "How would you allocate a space in which 1024 bytes of data can be stored, and where the base address is a multiple of 16 bytes".  If the interviewer really meant how can you allocate 1024 bytes (only) and have it 16-byte aligned, then the options are more limited.
Clearly, one possibility is to allocate 1024 bytes and then give that address the 'alignment treatment'; the problem with that approach is that the actual available space is not properly determinate (the usable space is between 1008 and 1024 bytes, but there wasn't a mechanism available to specify which size), which renders it less than useful.
Another possibility is that you are expected to write a full memory allocator and ensure that the 1024-byte block you return is appropriately aligned.  If that is the case, you probably end up doing an operation fairly similar to what the proposed solution did, but you hide it inside the allocator.
However, if the interviewer expected either of those responses, I'd expect them to recognize that this solution answers a closely related question, and then to reframe their question to point the conversation in the correct direction.  (Further, if the interviewer got really stroppy, then I wouldn't want the job; if the answer to an insufficiently precise requirement is shot down in flames without correction, then the interviewer is not someone for whom it is safe to work.)
The world moves on
The title of the question has changed recently.  It was
Solve the memory alignment in C interview question that stumped me
.  The revised title (
How to allocate aligned memory only using the standard library?
) demands a slightly revised answer — this addendum provides it.
C11 (ISO/IEC 9899:2011) added function
```
aligned_alloc()
```
:
7.22.3.1 The
```
aligned_alloc
```
function
Synopsis
```
```
#include <stdlib.h>
void *aligned_alloc(size_t alignment, size_t size);
```
```
Description
The
```
aligned_alloc
```
function allocates space for an object whose alignment is
  specified by
```
alignment
```
, whose size is specified by
```
size
```
, and whose value is
  indeterminate. The value of
```
alignment
```
shall be a valid alignment supported by the implementation and the value of
```
size
```
shall be an integral multiple of
```
alignment
```
.
Returns
The
```
aligned_alloc
```
function returns either a null pointer or a pointer to the allocated space.
And POSIX defines
```
posix_memalign()
```
:
```
```
#include <stdlib.h>

int posix_memalign(void **memptr, size_t alignment, size_t size);
```
```
DESCRIPTION
The
```
posix_memalign()
```
function shall allocate
```
size
```
bytes aligned on a boundary specified by
```
alignment
```
, and shall return a pointer to the allocated memory in
```
memptr
```
. The value of
```
alignment
```
shall be a power of two multiple of
```
sizeof(void *)
```
.
Upon successful completion, the value pointed to by
```
memptr
```
shall be a multiple of
```
alignment
```
.
If the size of the space requested is 0, the behavior is implementation-defined; the value returned in
```
memptr
```
shall be either a null pointer or a unique pointer.
The
```
free()
```
function shall deallocate memory that has previously been allocated by
```
posix_memalign()
```
.
RETURN VALUE
Upon successful completion,
```
posix_memalign()
```
shall return zero; otherwise, an error number shall be returned to indicate the error.
Either or both of these could be used to answer the question now, but only the POSIX function was an option when the question was originally answered.
Behind the scenes, the new aligned memory function do much the same job as outlined in the question, except they have the ability to force the alignment more easily, and keep track of the start of the aligned memory internally so that the code doesn't have to deal with specially — it just frees the memory returned by the allocation function that was used.


Question:
I could use some advice on tracking down the cause of memory leaks in C#. I understand what is a memory leak and I get why they occur in C# but I'm wondering what tools/strategies have you used in the past to resolve them?

I am using .NET Memory Profiler and I've found that one of my huge main objects is staying in memory after I close the window it manages but I'm not sure what to do to severe all links to it.

If I'm not being clear enough just post an answer with a question and I'll edit my question in response. Thanks!

Answer:
Break into the debugger and then type this into the Immediate window:
```
```
.load C:\Windows\Microsoft.NET\Framework\v2.0.50727\sos.dll
```
```
The path to sos.dll varies. The way to find out the correct path is to look for mscorwks.dll in the Modules pane. Wherever that is loaded from is the correct path for sos.dll.
Then type this:
```
```
System.GC.Collect()
```
```
That will ensure anything not reachable is collected. Then type this:
```
```
!DumpHeap -type <some-type-name>
```
```
This will show you a table of all existing instances, with addresses. You can find out what is keeping an instance alive like this:
```
```
!gcroot <some-address>
```
```


Question:
I'm building an open source project that uses python and c++ in Windows.
I came to the following error message:

 ImportError: No module named win32con

The same happened in a "prebuilt" code that it's working ( except in my computer :P )

I think this is kind of "popular" module in python because I've saw several messages in other forums but none that could help me.

I have Python2.6, should I have that module already installed?
Is that something of VC++?

Thank you for the help.

I got this url http://sourceforge.net/projects/pywin32/  but I'm not sure what to do with the executable :S

Answer:
This module contains constants related to Win32 programming.  It is not part of the Python 2.6 release, but should be part of the download of the pywin32 project.
Edit:
I imagine that the executable is an installation program, though the last time I downloaded pywin32 it was just a zip file.


Question:
In response to a rightMouse event I want to call a function that displays a context menu, runs it, and responds to the selected menu item.  In Windows I can use TrackPopupMenu with the TPM_RETURNCMD flag.

What is the easiest way to implement this in Cocoa?  It seems NSMenu:popUpContextMenu wants to post an event to the specified NSView.  Must I create a dummy view and wait for the event before returning?  If so, how do I "wait" or flush events given I am not returning to my main ?

Answer:
The 'proper' way to do this in Cocoa is to have your menu item's target and action perform the required method. However, if you must do it within your initial call, you can use
```
[NSView nextEventMatchingMask:]
```
to continually fetch new events that interest you, handle them, and loop. Here's an example which just waits until the right mouse button is released. You'll probably want to use a more complex mask argument, and continually call
```
[NSView nextEventMatchingMask:]
```
until you get what you want.
```
```
NSEvent *localEvent = [[self window] nextEventMatchingMask: NSRightMouseUpMask];
```
```
I think you'll find the 'proper' way to go much easier.


Question:
We're using HAProxy as a load balancer at the moment, and it regularly makes requests to the downstream boxes to make sure they're alive using an OPTIONS request:

OPTIONS /index.html HTTP/1.0

I'm working with getting nginx set up as a reverse proxy with caching (using ncache).  For some reason, nginx is returning a 405 when an OPTIONS request comes in:

192.168.1.10 - - [22/Oct/2008:16:36:21 -0700] "OPTIONS /index.html HTTP/1.0" 405 325 "-" "-" 192.168.1.10

When hitting the downstream webserver directly, I get a proper 200 response.  My question is: how to you make nginx pass that response along to HAProxy, or, how can I set the response in the nginx.conf?

Answer:
In the httpchk option, you can specify the HTTP method like this:
```
```
httpchk GET http://example.com/check.php
```
```
You can also use POST, or a plain URI like /. I have it check PHP, since PHP runs external to Nginx.


Question:
I've got an application that needs quite a bit of data (1000s of records) to do appropriate testing.  The only way I've found to get a decent set of testable, sensible data is to use a subset of my production DB.  I've converted this to YAML fixtures in the normal `test/fixtures' location.

This works, but now I have a bunch of seemingly brittle tests and assertions that depend on their being a particular number of records that meet condition X...

example

def test_children_association
  p = Parent.find(1)
  assert_equal 18, p.children.count, "Parent.children isn't providing the right records"
end

This doesn't seem like a good idea to me, but I'm not sure if there is a better / accepted  way to test an application that needs a large hierarchy of data.

Answer:
The first thing I'd say is: what are you testing in that example? If it's an ordinary AR has_many association, then I wouldn't bother writing a test for it. All you're doing is testing that AR works.
A better example might be if you had a very complicated query or if there was other processing involved in getting the list of children records. When you get them back, rather than testing for a count you could iterate through the returned list and verify that the children match the criteria you're using.


Question:
I have a JSP page that will display the exact content of another web page on a different server. My understanding was that c:import  from the JSTL should be able to include content from files that are not part of the current web application.

I added c:import url="page on my server in a different application" and it works fine, but when I try to include a page from another server it fails.

Any suggestions as to what might be wrong?

EDIT: The exact error is: "The server encountered an internal error () that prevented it from fulfilling this request.". However, requesting a page from the same server, different app works...I get the content of the page.

Answer:
An exact code and how "it fails" would be a great help. All mind-readers are currently on vacation.
Meanwhile, take a look at
http://www.ibm.com/developerworks/java/library/j-jsp06173.html
```
```
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
...
<c:import
  url="http://www.truenorthguitars.com/Clients/Richman/index.htm" />
```
```


Question:
How do you insert/update a column through Linq To SQL and Linq To SQL use the default values?  In particular I'm concerned with a timestamp field.

I've tried setting that column to readonly and autogenerated, so it stopped trying to put in DateTime.MinValue, but it doesn't seem to be updating on updates.

Answer:
The database default value would only insert the value on creating the row.  It would do nothing for update, unless you want to add a triggger.
Alternately, you can add a partial method to your DataContext class.  Add a new file you your project:
```
```
public partial class YourDatabaseDataContext
{
    partial void InsertYourTable(YourTable instance)
    {
        instance.LastUpdateTime = DateTime.Now;

        this.ExecuteDynamicInsert(instance);
    }

    partial void UpdateYourTable(YourTable instance)
    {
        instance.LastUpdateTime = DateTime.Now;

        this.ExecuteDynamicUpdate(instance);
    }
```
```


Question:
I've just had to write a string reverse function in C# 2.0 (i.e. LINQ not available) and came up with this:

public string Reverse(string text)
{
    char[] cArray = text.ToCharArray();
    string reverse = String.Empty;
    for (int i = cArray.Length - 1; i > -1; i--)
    {
        reverse += cArray[i];
    }
    return reverse;
}

Personally I'm not crazy about the function and am convinced that there's a better way to do it. Is there?

Answer:
Have a look at the wikipedia entry
here
. They implement the String.Reverse extension method. This allows you to write code like this:
```
```
string s = "olleh";
s.Reverse();
```
```
They also use the ToCharArray/Reverse combination that other answers to this question suggest. The source code looks like this:
```
```
public static string Reverse(this string input)
{
    char[] chars = input.ToCharArray();
    Array.Reverse(chars);
    return new String(chars);
}
```
```


Question:
I am after a regular expression that validates a percentage from 0 100 and allows two decimal places.

Does anyone know how to do this or know of good web site that has example of common regular expressions used for client side validation in javascript?

@Tom - Thanks for the questions. Ideally there would be no leading 0's or other trailing characters.

Thanks to all those who have replied so far. I have found the comments really interesting.

Answer:
```
(100|[0-9]{1,2})(\.[0-9]{1,2})?
```
That should be the regex you want. I suggest you to read Mastering Regular Expression and download RegexBuddy or The Regex Coach.


Question:
I am progamatically creating a SharePoint site using

SPWeb spWeb = spSite.AllWebs.Add(...);

What code do I need run to set the spWeb to turn off the "Show pages in navigation" option?

Answer:

publishingWeb.IncludePagesInNavigation = false;

Answer:
Wasn't sure myself but I was able to locate
this
:
Modifying navigation is another common
  branding task since it affects what
  users can see and how they can proceed
  through a site hierarchy. The
  Microsoft.SharePoint.Publishing
  namespace exposes several classes that
  target the Publishing site
  infrastructure, such as PublishingWeb
  and PublishingPage. Using these
  classes, we can easily modify
  navigation for each site. If you want
  a child Web to display as a root level
  site in global navigation, first turn
  off inheritance from the parent site,
  like so:
```
```
publishingWeb.InheritGlobalNavigation = false;
```
```
You might also want to hide all site
  pages from global navigation. Setting
  IncludePagesInNavigation to false
  hides all pages in the site,
  regardless of whether the
  PublishingPage.IncludeInGlobalNavigation
  property is set to true
```
```
// do not show pages in navigation
publishingWeb.IncludePagesInNavigation = false;
```
```
If you are dealing with default sites
  that don't inherit from PublishingWeb,
  it's still possible to hide these
  sites from the global navigation bar.
  For example, if you create a site
  collection using the collaboration
  portal template and want to exclude
  the News site from global navigation,
  add that site to the
  __GlobalNavigationExcludes property of the site:
```
```
string globalNavExcludes = String.Empty;
SPWeb webSite = MSDNSiteCollection.RootWeb;
// _GlobalNavigationExcludes property contains a delimited string of
// GUIDs identifying the Id of each site to be excluded from global
// navigation

if (webSite.AllProperties.ContainsKey("__GlobalNavigationExcludes")) {
  globalNavExcludes =
    webSite.AllProperties["__GlobalNavigationExcludes"].ToString();
}

SPWeb newsSite = MSDNSiteCollection.AllWebs["News"];
// string is delimited "{GUID};{GUID};",
// use format code B to convert to string
globalNavExcludes += String.Concat(currentWeb.ID.ToString("B"), ";");

webSite.AllProperties["__GlobalNavigationExcludes"] = globalNavExcludes;
webSite.Update();
```
```
Adding navigation nodes directly to an
  SPNavigationNodeCollection is a good
  way to display only the nodes you want
  as well as to group nodes and links to
  external sites. Figure 10 shows how to
  add an internal link, external link,
  and a heading to the global navigation
  bar. This example addresses some of
  the properties of the SPNavigation
  class that affect whether the link
  opens in a new window and how to
  handle empty URLs.


Question:
When using SubSonic, do you return the data as a dataset or do you put that in a strongly typed custom collection or a generic object?

I ran through the subsonic project and for the four stored procs I have in my DB, it gave me a Sps.cs with 4 methods which return a StoredProcedure object.

If you used a MVC, do you usually use the StoredProcedure object or wrap that around your business logic and return a dataset, list, collection or something else?

Are datasets still the norm or is that replaced by something else?

Answer:
If the results of the stored procedure has the same schema as one of your tables, you can build a collection using this code (SubSonic 2.1):
```
```
ProductCollection coll = new ProductCollection();
coll.LoadAndCloseReader(SPs.GetProducts(1).GetReader());
```
```


Question:
%AX = (%AH + %AL)

So why not %EAX = (%SOME_REGISTER + %AX) for some register %SOME_REGISTER?

Answer:
In the old 8-bit days, there was the A register.
In the 16-bit days, there was the 16 bit AX register, which was split into two 8 bit parts, AH and AL, for those times when you still wanted to work with 8 bit values.
In the 32-bit days, the 32 bit EAX register was introduced, but the AX, AH, and AL registers were all kept. The designers did not feel it necessary to introduce a new 16 bit register that addressed bits 16 through 31 of EAX.


Question:
How do you handle update refresh rate from your worker function to your UI ?

Sending everything to the UI or maybe using a timer (from which side ? worker or UI ?)

Answer:
In the old 8-bit days, there was the A register.
In the 16-bit days, there was the 16 bit AX register, which was split into two 8 bit parts, AH and AL, for those times when you still wanted to work with 8 bit values.
In the 32-bit days, the 32 bit EAX register was introduced, but the AX, AH, and AL registers were all kept. The designers did not feel it necessary to introduce a new 16 bit register that addressed bits 16 through 31 of EAX.


Question:
Let's say we have 2 php variables:

$name = 'caption';

$url = 'http://domain.com/photo.jpg';

The input string of '{@url,<img src="," alt="{@name}" />}' should return:

'<img src="http://domain.com/photo.jpg" alt="caption" />'

The {tag} takes up to 3 parameters: {@variable[,text_before][,text_after]}.

What regex would be needed to make this happen? The tricky part is that a {@..} tag is nested within another.

Answer:
It's for a CMS. Admins can add column fields, then add template code for how it will be displayed on the listing page. The {@tags} are used to output the dynamic column values. This template code:
```
<p>Link: <a href="{@url}">{@name}</a> - {@date}</p>
```
would create a listing page like:
Link:
link one
- 2 July 2008
Link:
link two
- 14 June 2008
Link:
link three
- 9 February 2007
...
I figured that people might want to use column values within others, hence the "alt" tag example from the first post. So using regex for this would be a bad idea?


Question:
http://blogs.msdn.com/drnick/archive/2007/03/23/preventing-anonymous-access.aspx

Can someone clarify whether it is possible to use wsHttpBinding in WCF and disable anonymous access in IIS without transport (ssl) or message security being required?

Answer:
we want to use windows integrated security. If you disable anonymous access in IIS and allow just windows, you cannot seem to use wsHttpBinding with WCF without using some security mode (e.g. transprot security which requires ssl).
We only want to use windows authentication we don't necessarily want to use ssl for transport security.
I was a little amazed this wasn't possible out of the box (as seemed to be confirmed by my link) as it would seem quite a common scenario for intern applications.
We don't want to downgrade to basicHttpBinding which would support windows authentication only.


Question:
The large network (of small world graph type) I wish to deal with is dynamic in nature, new nodes are added and subtracted frequently. Presumably using D* over A* would be a better way to detect paths in this dynamic environment?

How solid is D*? has it had any real world experience? like a cryptographic algorithm - is  D* hardened by lots of peer review and testing? Would you use D* for this problem?

Answer:
As I understand, the first time you run D* it finds the same path as A* with nearly the same runtime.  However, when a node changes it's edge value or nodes are added A* recomputes ALL of the path while D* simply recomputes the inconsistent nodes the second time around rather than the whole thing.
Anthony Stentz's D* algorithm (original whitepaper
here
) has largely been deprecated by derivatives of his work.  D* Lite and LPA* are the most commonly found and are much easier to code/implement.
As far as real world experience,  Joseph Carsten and Art Rankin from NASA's Jet Propulsion Laboratory installed a version of Field D* using elements of D* Lite on the mars rovers "Spirit" and "Opportunity" (slideshow of rovers using D*
here
).  In Feburary 2007 it was used to fully navigate the mars rover autonomously.
alt text http://asm.arc.nasa.gov/Gallery/images/generic/rover.jpg
Apparently D* is really useful in the robotics domain because the robots on-board sensors are constantly re-evaluating edge values.  That would make it pretty "battle tested" in my own opinion.
Similarly, I found another
whitepaper
that mentions the use of the D* Lite algorithm in Mobile Gaming.
I'll end this answer by stating that I've never implemented D* before, only A*.  Because of the significant increase in complexity I would say that D* (or D* Lite) should only be used in cases where there is a significant and frequent changes in the graph.  You described your situation as being similar to that so I would say definately go for D* Lite.  If NASA uses it you could safely bet it has been thoroughly investigated.


Question:
I want to read all thumbnails from a folder with images in Windows XP.
But if I read image file to get thumbnail, it seems a bit slow, so I wish I can first read the windows image thumbnail cache:thumb.db.
Is there any lib in c++ or c to read thumbnails from thumb.db.

Answer:
The Thumbs.db file is stored in OLE
Compound Document
format, the same format that many Microsoft Office products use.
You could also try to look into
ThumbsDBLib
.  It is in C# but you can probably see what they do to read the data and convert it to C++.
Note: Windows Vista and later doesn't use Thumbs.db.  See the
IThumbnailCache interface
for Vista and later.
For Vista and later they are stored here: %homedrive%\Users\%username%\AppData\Local\Microsoft\Windows\Explorer


Question:
I am using a navigation controller, and I have the style set to :

navController.navigationBar.barStyle = UIBarStyleBlackTranslucent;

But when I run my program, the navigation controller looks like it is on top of a white background, not my background. When I push a controller, left or right, all my view, the current one, shifts to the top exactly the size of the navigation bar. And it is there where I can see my background through the navigation controller bar. Any ideas? When my barStyle is  set to opaque, everything looks fine. I was thinking on setting my view frame a negative 'y' value, but I think there should a more elegant way.

Answer:
I believe the UINavigationController assumes that your controller view frames don't include the area beneath the navigation bar.
UIBarStyleBlackTranslucent is more often used for UIToolbar, so Apple probably didn't make it easy to use it nicely with UINavigationBar. You'll probably need to abandon the UINavigationController, or start hacking the frames (careful with rotations), if you want to reliably render under the bar area.
Also, if your intention is to hide the navigation bar after a few seconds, you'll have a
much
easier time if you make it fade out (like the Photos app) instead of trying to slide it up (like Mobile Safari). Trust me on that one... that took me a
lot
of time to learn the hard way.


Question:
On an embedded target I use far pointers to access some parts of the memory map.

near pointer (without explicitely specifying __near):

unsigned int *VariableOnePtr;

Pointer to near pointer:
unsigned int **VariableOnePtrPtr;

far pointer:
unsigned int *__far VariableTwoPtr;

What is the correct way to declare a pointer to a far pointer? Does this pointer have to be a far pointer itself?

Answer:
I believe you would do this:
```
```
unsigned int * __far *VariableThreePtrPtr;
```
```
A far pointer to a far pointer would be:
```
```
unsigned int * __far * __far VariableFourPtrPtr;
```
```


Question: A lambda expression which takes a function (of one argument) and a number, and applies the function to twice the number.

Answer:
Applying the function to twice the number:
```
```
(lambda (f x) (f (* 2 x)))
```
```
Applying the function to the number twice (which is what you may have intended to ask):
```
```
(lambda (f x) (f (f x)))
```
```


Question: Why do computers use RGB (red, green, and blue) values for color composition rather than the primary hues, red, yellow, and blue?

Answer:
The hues of magenta, yellow, and cyan are primary for subtractive combination (e.g. paints or inks) rather than additive combination such as light where red, green, and blue are primary.
Wikipedia has more detail on the whys and wherefores
.


Question:
I have the following query:

SELECT c.*
FROM companies AS c
JOIN users AS u USING(companyid)
JOIN jobs AS j USING(userid)
JOIN useraccounts AS us USING(userid)
WHERE j.jobid = 123;

I have the following questions:

Is the USING syntax synonymous with ON syntax?

Are these joins evaluated left to right?  In other words, does this query say: x = companies JOIN users; y = x JOIN jobs; z = y JOIN useraccounts;

If the answer to question 2 is yes, is it safe to assume that the companies table has companyid, userid and jobid columns?

I don't understand how the WHERE clause can be used to pick rows on the companies table when it is referring to the alias "j"

Any help would be appreciated!

Answer:
SEE
http://dev.mysql.com/doc/refman/5.0/en/join.html
AND start reading here:
Join Processing Changes in MySQL 5.0.12
Beginning with MySQL 5.0.12, natural joins and joins with USING, including outer join variants, are processed according to the SQL:2003 standard. The goal was to align the syntax and semantics of MySQL with respect to NATURAL JOIN and JOIN ... USING according to SQL:2003. However, these changes in join processing can result in different output columns for some joins. Also, some queries that appeared to work correctly in older versions must be rewritten to comply with the standard.
These changes have five main aspects:
The way that MySQL determines the result columns of NATURAL or USING join operations (and thus the result of the entire FROM clause).
Expansion of SELECT * and SELECT tbl_name.* into a list of selected columns.
Resolution of column names in NATURAL or USING joins.
Transformation of NATURAL or USING joins into JOIN ... ON.
Resolution of column names in the ON condition of a JOIN ... ON.


Question: I am working on rails project and I am trying to get exceptions to be logged to the rails log files.  I know I can call logger.error $! to get the first line of the exception logged to the file.  But, I want to get the entire trace stack logged as well.  How do I log the entire trace back of an exception using the default rails logger?

Answer:
```
logger.error caller.join("\n")
```
should do the trick.


Question:
Taking over some code from my predecessor and I found a query that uses the Like operator:

SELECT * FROM suppliers
WHERE supplier_name like '%'+name+%';

Trying to avoid SQL Injection problem and parameterize this but I am not quite sure how this would be accomplished. Any suggestions ?

note, I need a solution for classic ADO.NET - I don't really have the go-ahead to switch this code over to something like LINQ.

Answer:
Simply parameterize your query:
```
```
SELECT * FROM suppliers WHERE supplier_name like '%' + @name + '%'
```
```
Now you can pass your "name" variable into the @name parameter and the query will execute without any danger of injection attacks. Even if you pass in something like "'' OR true --" it'll still work fine.


Question: I would like to determine the operating system of the host that my Java program is running programmatically (for example: I would like to be able to load different properties based on whether I am on a Windows or Unix platform). What is the safest way to do this with 100% reliability?

Answer:
You can use:
```
```
System.getProperty("os.name")
```
```
P.S. You may find this code useful:
```
```
class ShowProperties {
    public static void main(String[] args) {
        System.getProperties().list(System.out);
    }
}
```
```
All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)


Question:
The goal: Any language. The smallest function which will return whether a string is a palindrome. Here is mine in Python:

R=lambda s:all(a==b for a,b in zip(s,reversed(s)))

50 characters.

The accepted answer will be the current smallest one - this will change as smaller ones are found. Please specify the language your code is in.

Answer:
Here's mine; it's written in a domain-specific language I invented, called 'palindrome'.
```
```
p
```
```
Edit:
Less flippant version (i386 asm, AT&T syntax)
```
```
xor %eax, %eax
mov %esi, %edi
#cld    not necessary, assume DF=0 as per x86 ABI
repne scasb
scan:
    dec %edi
    cmpsb
    .byte 0x75, 6    #jnz (short) done
    dec %edi
    cmp %esi, %edi
    .byte 0x72, -9    #jb (short) scan
inc %eax
done:
```
```
16 bytes, string pointer goes in ESI, result is in EAX.


Question:
Is there someway to set the default file permission in Linux? That is, the file permission for a newly created file (regardless of the context for which it was created
). I know about putting umask in the shell startup but that only works for shell sessions. When I transfer files to a Linux box using pscp, the file is always created with permissions of 664 (rw-rw-r--). The has occurred across every flavor of Linux that I've used. This is especially annoying when I pscp a file to shared Linux machine (like my ISP). Until I can shell in and chmod the permission, the file is basically sitting there with read access for everyone, which is not exactly secure.

Answer:
Put the umask in the non-interactive shell startup (
```
.bash_profile
```
,
```
.zshenv
```
,
```
.tcshrc
```
depending on your shell). Then it'll run for non-login sessions.


Question:
I have GridView which I can select a row. I then have a button above the grid called Edit which the user can click to popup a window and edit the selected row. So the button will have Javascript code behind it along the lines of

function editRecord()
{
  var gridView = document.getElementById("<%= GridView.ClientID %>");
  var id = // somehow get the id here ???
  window.open("edit.aspx?id=" + id);
}

The question is how do I retrieve the selected records ID in javascript?

Answer:
1) change your javascript function to use a parameter
```
```
function editRecord(clientId)
{ ....
```
```
2) output the call in your editRecord button... if you want to avoid dealing with the .net generated ids, just use a simple
```
```
<input type="button" onclick="editRecord(your-rows-client-id-goes-here)" />
```
```


Question:
currently i obtain  the below result from the following C# line of code when in es-MX Culture

   Thread.CurrentThread.CurrentCulture =
     Thread.CurrentThread.CurrentUICulture = new
                CultureInfo("es-mx");

  <span><%=DateTime.Now.ToLongDateString()%></span>

miércoles, 22 de octubre de 2008

i would like to obtain the following

Miércoles, 22 de Octubre de 2008

do i need to Build my own culture?

Answer:
The pattern of LongDate for Spanish (Mexico) is
```
dddd, dd' de 'MMMM' de 'yyyy
```
according to
Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern
. I guess you just have to manually convert the initial letters of the day and month to uppercase or you can use
Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase
and then replace "De" with "de".


Question:
A couple of the options are:

$connection = {my db connection/object};

function PassedIn($connection) { ... }

function PassedByReference(&$connection) { ... }

function UsingGlobal() {
    global $connection;
    ...
}

So, passed in, passed by reference, or using global. I'm thinking in functions that are only used within 1 project that will only have 1 database connection. If there are multiple connections, the definitely passed in or passed by reference.

I'm thining passed by reference is not needed when you are in PHP5 using an object, so then passed in or using global are the 2 possibilities.

The reason I'm asking is because I'm getting tired of always putting in $connection into my function parameters.

Answer:
None of the above.
All the
```
mysql
```
functions take the database connection argument
optionally
. If you leave that argument out, the last connection by mysql_connect() is assumed.


Question:
Can anybody explain the idea behind JSP custom tag libraries and the JSP 2 tag files?

Are they just different ways to do the same thing?

How do they compare? What are their pros and cons, and which is better?

Answer:
Problems Developing Custom Tags
Traditional custom tags require Java programming
skills.
All but the simplest custom tags are not easy to write.
The purpose of JSP, in contrast to servlets, is to use
markup language to manage layout with embedded
dynamic content.
Having to write complex Java code
in custom tags that focus on markup language is going
backwards.
We might want to use the JSP expression language or
other custom tags when implementing a new custom
tag.
The Solution
JSP 2.0 Tag Files
Tag files are one of the important new concepts introduced with JSP 2.0.
Tag files permit easier and more rapid development of custom tags.
Tag files are developed using normal JSP syntax,including scripting elements, and used just like any other custom tag.
Each custom tag is a separate tag file.
How Do Tag Files Differ?
Written using JSP syntax.
Not all JSP directives are permitted in a tag file.
Supported by new tag file specific directives, actions and implicit objects.
Identified by either a
.tag
or
.tagx
suffix.
Intended to provide custom tag developers ease of development without loss of functionality.
One of the lead developers of JSTL has commented thatif she had the time, she would rewrite all of JSTL using tag files.


Question:
I keep hearing people complaining that C++ doesn't have garbage collection. I also hear that the C++ Standards Committee is looking at adding it to the language. I'm afraid I just don't see the point to it... using RAII with smart pointers eliminates the need for it, right?

My only experience with garbage collection was on a couple of cheap eighties home computers, where it meant that the system would freeze up for a few seconds every so often. I'm sure it has improved since then, but as you can guess, that didn't leave me with a high opinion of it.

What advantages could garbage collection offer an experienced C++ developer?

Answer:
The committee isn't adding garbage-collection, they are adding a couple of features that allow garbage collection to be more safely implemented. Only time will tell whether they actually have any effect whatsoever on future compilers. The specific implementations could vary widely, but will most likely involve reachability-based collection, which could involve a slight hang, depending on how it's done.
One thing is, though, no standards-conformant garbage collector will be able to call destructors - only to silently reuse lost memory.


Question:
This may be a simple fix - but I'm trying to sum together all the nodes (Size property from the Node class) on the binary search tree. Below in my BST class I have the following so far, but it returns 0:

    private long sum(Node<T> thisNode)
    {
        if (thisNode.Left == null && thisNode.Right == null)
            return 0;
        if (node.Right == null)
            return sum(thisNode.Left);
        if (node.Left == null)
            return sum(thisNode.Right);

        return sum(thisNode.Left) + sum(thisNode.Right);
    }

Within my Node class I have Data which stores Size and Name in their given properties. I'm just trying to sum the entire size. Any suggestions or ideas?

Answer:
Maybe you meant
```
```
if (thisNode.Left == null && thisNode.Right == null)
        return thisNode.Size;
```
```
?


Question:
I'm looking for syntatic examples or common techniques for doing regular expression style transformations on words instead of characters, given a procedural language.

For example, to trace copying, one would want to create a document with similar meaning but with different word choices.

I'd like to be able to concisely define these possible transformations that I can apply to a text stream.

Eg.  "fast noun" to "rapid noun", but "go fast." wouldn't get transformed (no noun afterwards.

Or:  "Alice will sing song"  to "song will be sung by Alice"

I'd expect this to be done in grammatical checkers, such as detecting passive voice.

A C# implementation for this sort of language-processing would be really neat, but I think the bulk of any effort is coming up with the right rules - Keeping the rules clear and understandable seems like a place to begin.

Answer:
A good place to start would be SIL's
CARLAStudio
for its "Computer Assisted Related Language Adaptation" suite. Alternatively SIL's
Adapt It
. SIL has a huge range of linguistic analysis software, which is the direction you appear to be going. It's certainly a big jump from regular expressions, which don't care about the meaning, to something that can handle linguistic analysis.


Question: I want to continuously sample from my PC's audio line in using C# (then process that data). What is the best way to do the sampling?

Answer:
There are no built-in libraries in the .NET framework for dealing with sound, but if you're on Win32, you can use an unmanaged library like DirectSound to do it.
Ianier Munoz shows
how to write a full-duplex audio player in C# using
waveIn
via P/Invoke
on CodeProject.  He mentions
Managed DirectSound
as a more general method.


Question:
I would like to send some keystrokes from a C++ program into another window.

For that reason I would like to have the user select the target window similar to how it is done in the Spy++ utility that comes with Visual Studio (drag a crosshair cursor over target window and have target window highlighted by a frame).

How is this dragging and selecting done in Windows? I am completely lost as to where I might start to look for a mechanism to implement this feature.

Answer:
Here's how it's usually done:
Capture the mouse using
SetCapture
. This will cause all mouse messages to be routed toward your app's window.
Handle the
WM_MOUSEMOVE
message. In your handler code, grab the window underneath the mouse using
WindowFromPoint
. That will get you the HWND of the window the mouse is currently over.
Now that you've got the window, you need a device context (HDC). You can get one using
GetWindowDC
for the specified window.
Now you can draw into the DC using typical GDI functions.
There are some things you have to look out for - cleanly erasing the selection rectangle and so forth, but that's one way to do it.
You could also draw into a screen DC to do this, but in any case you'll need the window handle in order to get the window rect.
If you Google around Spy++ source code you'll see a few examples of this technique.


Question:
If I have a source.c file with a struct:

struct a {
    int i;
    struct b {
        int j;
    }
};

How can this struct be used in another file (i.e. func.c)?

Should I create a new header file, declare the struct there and include that header in func.c?

Or should I define the whole struct in a header file and include that in both source.c and func.c?  How can the struct be declared extern in both files?

Should I typedef it? If so, how?

Answer:
a.h:
```
```
#ifndef A_H
#define A_H

struct a {
    int i;
    struct b {
        int j;
    }
};

#endif
```
```
there you go, now you just need to include a.h to the files where you want to use this structure.


Question:
Say I have the classic 4-byte signed integer, and I want something like

print hex(-1)

to give me something like

0xffffffff

In reality, the above gives me -0x1. I'm dawdling about in some lower level language, and python commandline is quick n easy.

So.. is there a way to do it?

Answer:
This will do the trick:
```
```
>>> print(hex (-1 & 0xffffffff))
0xffffffff
```
```
or, a variant that always returns fixed size (there may well be a better way to do this):
```
```
>>> def hex3(n):
...     return "0x%s"%("00000000%s"%(hex(n&0xffffffff)[2:-1]))[-8:]
...
>>> print hex3(-1)
0xffffffff
>>> print hex3(17)
0x00000011
```
```
Or, avoiding the hex() altogether, thanks to Ignacio and bobince:
```
```
def hex2(n):
    return "0x%x"%(n&0xffffffff)

def hex3(n):
    return "0x%s"%("00000000%x"%(n&0xffffffff))[-8:]
```
```


Question:
Now that Silverlight 2 has finally shipped. I'm wondering if anyone has put together any logging frameworks for it, maybe something like enterprise library logging or log4net? I'm interesting in something that can perform tracing client side and also log messages to the server.

So far the only project I have found is Clog on CodeProject. Has anyone used this? What were your thoughts on it?

Answer:
I am about to delve into something similar myself for a product we've written. I'm considering using PostSharp for Silverlight to add client-side logging as an aspect.
I have used the NLog project with great success before under the full .NET Framework and the Compact Framework so I'll most likely take the existing framework code and add some logging targets:
A standard System.Diagnostics target to enable capturing using DebugView, etc.
An asynchronous Web service target similar to the one in NLog.
An isolated storage target with deferred transfer to server semantics.
I've briefly looked at Clog and it seems to suffer from one major flaw - it can't log a connection failure. So assuming your Web server is online all the time, yes it will work, but when problems occur upstream or on the server itself, the logging data is all lost and might even crash your application.


Question:
Im creating a report using crystal report in vb.net.

The report contained a crosstab which I have 3 data:
1. Dealer - row field
2. Month - column
3. Quantity Sales - summarize field

How can I arrange this by ascending order based on the
Quantity Sales - summarize field?

thanks

Answer:
Depending on how you're working with it, you can adjust the input to order the data ascending.
```
```
SELECT customer, sum(amountdue) AS total FROM invoices
GROUP BY customer
ORDER BY total ASC
```
```
If you're doing in a way that you can't change that information, could you provide a little more insight?


Question:
The coding is done using VS2008
There are two divs in my page namely "dvLeftContent" and "dvRightContent".
I cannot statically set the height of the pages since "dvRightContent" have variable heights on various pages (Master Pages are used here)
Is there a client side function(javascript or jquery) that takes the height of the right div and assigns it to left div?

Answer:
Depending on how you're working with it, you can adjust the input to order the data ascending.
```
```
SELECT customer, sum(amountdue) AS total FROM invoices
GROUP BY customer
ORDER BY total ASC
```
```
If you're doing in a way that you can't change that information, could you provide a little more insight?


Question:
As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?

This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.

def alphCount(text):
  lowerText = text.lower()
  for letter in allTheLetters:
    print letter + ":", lowertext.count(letter)

Answer:
Something like this?
```
```
for letter in range(ord('a'), ord('z') + 1):
  print chr(letter) + ":", lowertext.count(chr(letter))
```
```


Question: I know that there are a lot of CUDA language bindings, such as PyCUDA, but are there any good bindings for .Net? The only one I've seen is this one, but I'd like to know if there are any others.

Answer:
Here's another library:
http://sourceforge.net/projects/brahma-fx/
Edit
: I've been looking at the documentation for the project you initially listed, and can say that the interface makes me think: what is the point of using .Net.  The project I've listed has a cleaner interface but no documentation.  The project you listed seems to be more dedicated in the development path ( a recent 2.1 release), but the SVN of Brahma isn't too old (5 wks).
Another poster listed the Accelerator framework.  It looks
very
promising, although its license is non-commercial (you must contact them if you intend to use it for any commercial work), and when I installed it, it said it installed right and I can't find it on my system (this could have been a Vista issue)!
EDIT
: I have looked into the various libraries, and can say here is my "recommendations":
If you are planning on using LINQ and only .Net 3.5, use Brahma.
If you are non-commercial in your goal, use the Accelerator project that the other poster gave (Tim, I believe).  It is higher level than the project you mentioned.
If you don't care about low-level details, but very active project and documentation is desired then go with the project you listed.


Question:
(mingw32, windows xp)
Hello, I am attempting to migrate from Java to c++. I am confused and frustrated about finding, installing, and compiling non-standard c++ libraries. in Java it's so convenient they stuffed every functionality and documentation ever needed in java's standard api. Is there a list of essential c++ library such as Threading, gui, networking, image\ audio processing, xml, etc.etc. in one place? or possibly, offered as a single package?

I tried installing QT library for weeks and it wont even compile. in Java i used to learn by trial-and-error to learn new aspect of functionality, but that would be impossible if i can't fetch and run new api in the first place.

please, i need your suggestion, originally i wanted to break free of Java's abstraction, but now i just want to be able to use c++ before I decided shooting myself in the head.

Answer:
The C++ standard library is extremely light. It contains nowhere near the functionality offered by the Java runtimes or by the .NET CLR.
The
Boost
libraries add a whole bunch of functionality to C++, but not much (if any) in the area of user interface.
For UI, there's the question of which platform you're targetting. If it's Win32, then you can use the straight Win32 API (mostly designed for C, but there are some C++ wrappers for parts of it). If you want cross-platform, then you're looking at QT or GTK (although there are others).
But, as Andrew already said: "why do you want to learn C++ anyway?". Don't get me wrong: I program in C++ for a living, and actually enjoy it (although I'm beginning to suspect a case of Stockholm Syndrome). If I had to start again, I'd go with a more modern language and environment (Java or C#; or Ruby or Python).


Question:
I want to write a odometer-like method in a C#-style-language, but not just using 0-9 for characters, but any set of characters. It will act like a brute-force application, more or less.

If I pass in a char-array of characters from 0 to J, and set length to 5, I want results like 00000, 00001, 00002... HJJJJ, IJJJJJ, JJJJJ.

Here is the base, please help me expand:

protected void Main()
{
    char[] chars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };

    BruteForce(chars, 5);
}

private void BruteForce(char[] chars, int length)
{
    // for-loop (?) console-writing all possible combinations from 00000 to JJJJJ
    // (when passed in length is 5)
    // TODO: Implement code...
}

Answer:
Google for permutations.
If however you are just dealing with that 'hex' range, just do the following:
```
```
for (int i = 0; i < (1 << 24); i++)
  string s = i.ToString("X6");
```
```


Question:
I need a little help on this subject.

I have a Web application written in ASP.NET plus I have the .bak file of the SQL Express database, my question is: How can I install this in a simple click and go way in the client?

how can I write a script that will create a new database, restore the bak file into that database, set up IIS and ... well, that's it :)

I do this all manually, and I do this a lot, so I was just asking if there is a way to prevent do all this steps manually.

Thanks.

Answer:
You could use
WiX
to create a .msi that you can use to install your application at your clients.  WiX takes a bit to get used to, but once you get the hang of it, you'll meet your needs above, and be able to extend them as your application grows or increases in complexity from the installation point of view.
I read your question to mean you have several clients where you install your application, if that is not the case, and your app exists in one place, there are better solutions, and better people to give them to you!


Question: what is the best practice for multilanguage website using DOM Manipulating with javascript? I build some dynamic parts of the website using javascript. My first thought was using an array with the text strings and the language code as index. Is this a good idea?

Answer:
When I've built multi-lingual sites before (not very large ones, so this might not scale too well), I keep a series of "language" files:
lang.en.js
lang.it.js
lang.fr.js
Each of the files declares an object which is basically just a map from key word to language phrase:
```
```
// lang.en.js
lang = {
    greeting : "Hello"
};

// lang.fr.js
lang = {
    greeting : "Bonjour"
};
```
```
Dynamically load one of those files and then all you need to do is reference the key from your map:
```
```
document.onload = function() {
    alert(lang.greeting);
};
```
```
There are, of course, many other ways to do this, and many ways to do this style but better: encapsulating it all into a function so that a missing phrase from your "dictionary" can be handled gracefully, or even do the whole thing using OOP, and let it manage the dynamic including of the files, it could perhaps even draw language selectors for you, etc.
```
```
var l = new Language('en');
l.get('greeting');
```
```


Question:
We are a small company and would like to know the best possible (and affordable) hardware and software configuration we ought to be using for our development environment. At this moment we are a team of four people who work remotely from different locations and each one of us uses a laptop and ADSL connection to work on our projects.

This question should help us identify a path towards optimizing our hardware and software so as to make the most of these development environments. Do we need to run everything locally on the laptops or some sort of distributed solution is possible? Which software versions do you recommend given that both Windows 2008 and SQL Server 2008 are available options? Do we use a central server or run these locally on our laptops?

We're a young team so any help would be welcome and much appreciated! Thanks!

Ym

Answer:
For a team, I would suggest that you set up the local environments (laptops) as development environments, with a local DB copy and running CF developer version.  Version control (VSS, Subversion, Git, etc.) is pretty much mandatory.
Have a testing/staging/QA server with the same configuration as the live version (as much as this is possible).  It should have its own CF license to follow the licensing agreement.  You should put checked-in code here for everyone to test and to check integration.  Several version control systems offer ways to automate this, or you could do this manually.
Production, obviously, should be its own thing.  I would suggest that you separate the database and app/web server on two separate boxes.
I know this might be a little more/less than you were asking, so feel free to ask for clarification.