Question:
which would you recommend?
which is faster, reliable?
apache mod_python or nginx/lighttpd FastCGI?

Answer:
Personally I've had it working with FastCGI for some time now (6 months or so) and the response times 'seem' quicker when loading a page that way vs mod___python. The critical reason for me though is that I couldn't see an obvious way to do multiple sites from the same apache / mod_python install whereas FastCGI was a relative no-brainer.
I've not conducted any particularly thorough experiments though :-)
[Edit]
Speaking from experience though, setting up FastCGI can be a bit of a pain the first time around. I keep meaning to write a guide..!


Question:
I am interested in mastering prefetch-related functions such as

_mm_prefetch(...)

so when I perform operations that loop over arrays, the memory bandwidth is fully utilized.  What are the best resources for learning about this?

I am doing this work in C using GCC 4 series on an intel linux platform.

Answer:
This
site
contains details on gcc prefetch support including prefetch options and functions and includes details on several architectures including Intel.  The gcc
manual
contains details on the
```
__builtin_prefetch
```
built-in function in section 5.46.


Question:
Is there any way of batch renaming files in sub directories?

For example:

Rename *.html to *.htm in a folder which has directories and sub directories.

Answer:
In Bash, you could do the following:
```
```
for x in $(find . -name \*.html); do
  mv $x $(echo "$x" | sed 's/\.html$/.htm/')
done
```
```


Question:
When I type uname -a, it gives the following output.

Linux mars 2.6.9-67.0.15.ELsmp #1 SMP Tue Apr 22 13:50:33 EDT 2008 i686 i686 i386 GNU/Linux

How can I know from this that the given OS is 32 or 64 bit?

This is useful when writing configure scripts, for example: what architecture am I building for?

Answer:
If you were running a 64 bit platform you would see x86_64 or something very similar in the output from
uname
-a
To get your specific machine hardware name run
```
```
uname -m
```
```
You can also call
```
```
getconf LONG_BIT
```
```
which returns either 32 or 64


Question:
Using vim 7.1, I recently heard you can debug php in VI.
But how?

Answer:
Put some content in the file /etc/issue
Some more details in
http://www.linuxfromscratch.org/blfs/view/svn/postlfs/logon.html
crap /etc/motd was the file i was trying to remember. Upvoting his answer :)


Question: Instead of hardcoding the default @author template I would like Eclipse to use user's real name taken from account information (in Linux - but Windows solution is also welcome). Entering it somewhere into Eclipse configuration would be acceptable, too, alas I can't find the right place.

Answer:
It seems that your best bet is to redefine the java
```
user.name
```
variable either at your command line, or using the
```
eclipse.ini
```
file in your eclipse install root directory.
This seems to work fine for me:
```
```
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Duser.name=Davide Inglima
-Xms40m
-Xmx512m
```
```
Update:
http://morlhon.net/blog/2005/09/07/eclipse-username/
is a dead link...
Here's a new one:
https://web.archive.org/web/20111225025454/http://morlhon.net:80/blog/2005/09/07/eclipse-username/


Question: I used the owner-drawn strategy on CMyListBox class which derives from CListBox. I only want the DrawItem() method to perform when I insert an item in the listbox. But the method is invoked many times. How can I change to invoke it whenever I need.

Answer:
The DrawItem() method is called whenever there is a requirement to draw any given item in the listbox.  If you do not respond to it you are likely to get a blank area in your list box, where the drawn data has been erased and you have not refreshed it.  If you really do not think the drawing is necessary, you could do something like
```
```
void CMyListBox::DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct )
{
   if (!m_DrawingEnabled)
     return;
}
```
```
Where m_DrawingEnabled is a member you maintain to stop unnecessary draws,


Question:
I'm working on a project that contains Thomas Brothers Map page and grid numbers.  Is there a way to programatically convert from this map page to a latitude & longitude?

An Example would be for the intersection of the US101 & I405 freeways.

ThomasBrothers: 561-3G   (page-grid)

Answer:
Not that I know of, but I don't have a lot of experience with Thomas bros maps.  Are you talking about printed version of the maps or is there a link somewhere to an online map?
If you just need a few lat/longs, then you can look up the locations that correspond to the grid and get the lats and longs manually at many websites, including
http://itouchmap.com/latlong.html
If you provide a link to a Thomas bros map that you are using, I might be able to help further.
By looking at the link above, you can determine that US 101 and I-405 has a latitude of  34.16073390017978 and a longitude of -118.46952438354492.


Question: We use Telerik's RadEditor for our content management system's WYSIWYG editor.  We need the find & replace functionality that is in the WYSIWYG editor to also be in the HTML editor.  The editor is pretty customizable, anyone know if there is a way to enable this or hack it in?

Answer:
There is an
example on their demo site for RadEditor ASP.NET Ajax
.
Just click on the 3rd button of the toolbar in order to test "Find and Replace".
Take a look at
this example page
too.
It defines this toolbar
```
```
...
<telerik:EditorSeparator />
<telerik:editortool name="FindAndReplace" />
<telerik:editortool name="TableWizard" />
<telerik:editortool name="LinkManager" />
<telerik:editortool name="PageProperties" />
<telerik:EditorSeparator />
...
```
```


Question:
What are the correct version numbers for C#? What came out when? Why can't I find any answers about C# 3.5?

This question is primarily to aid those who are searching for an answer using an incorrect version number, e.g. C# 3.5. The hope is that anyone failing to find an answer with the wrong version number will find this question and then search again with the right version number.

Answer:
C# language version history:
These are the
versions of C#
known about at the time of this writing:
C# 1.0
released with .NET 1.0 and VS2002 (January 2002)
C# 1.2
(bizarrely enough); released with .NET 1.1 and VS2003 (April 2003). First version to call
```
Dispose
```
on
```
IEnumerator
```
s which implemented
```
IDisposable
```
. A few other small features.
C# 2.0
released with .NET 2.0 and VS2005 (November 2005). Major new features: generics, anonymous methods, nullable types, and iterator blocks
C# 3.0
released with .NET 3.5 and VS2008 (November 2007). Major new features: lambda expressions, extension methods, expression trees, anonymous types, implicit typing (
```
var
```
), and query expressions
C# 4.0
released with .NET 4 and VS2010 (April 2010). Major new features: late binding (
```
dynamic
```
), delegate and interface generic variance, more
COM
support, named arguments, tuple data type and optional parameters
C# 5.0
released with .NET 4.5 and VS2012 (August 2012).
Major features
: async programming, and caller info attributes. Breaking change:
loop variable closure
.
C# 6.0
released with .NET 4.6 and VS2015 (July 2015). Implemented by
Roslyn
.
Features
: initializers for automatically implemented properties, using directives to import static members, exception filters, element initializers,
```
await
```
in
```
catch
```
and
```
finally
```
, extension
```
Add
```
methods in collection initializers.
C# 7.0
released with .NET 4.7 and VS2017 (March 2017). Major
new features
:
tuples
,
ref locals and ref return
,
pattern matching
(including pattern-based switch statements),
inline
```
out
```
parameter declarations
,
local functions
,
binary literals, digit separators
, and
arbitrary async returns
.
C# 7.1
released with VS2017 v15.3 (August 2017). New features:
async main
,
tuple member name inference
,
default expression
, and
pattern matching with generics
.
C# 7.2
released with VS2017 v15.5 (November 2017). New features:
private protected access modifier
,
Span<T>, aka interior pointer, aka stackonly struct
, and
everything else
.
C# 7.3
released with VS2017 v15.7 (May 2018). New features:
enum, delegate and
```
unmanaged
```
generic type constraints
.
```
ref
```
reassignment. Unsafe improvements:
```
stackalloc
```
initialization, unpinned indexed
```
fixed
```
buffers, custom
```
fixed
```
statements. Improved overloading resolution. Expression variables in initializers and queries.
```
==
```
and
```
!=
```
defined for tuples. Auto-properties' backing fields can now be targeted by attributes.
C# 8.0
released with .NET Core 3.0 and VS2019 v16.3 (September 2019). Major
new features
:
nullable reference-types
,
asynchronous streams
,
indices and ranges
,
readonly members
,
using declarations
,
default interface methods
,
static local functions
, and
enhancement of interpolated verbatim strings
.
C# 9.0
released with
.NET 5.0
and VS2019 v16.8 (November 2020). Major
new features
:
init-only properties
,
records
,
with-expressions
, data classes, positional records,
top-level programs
,
improved pattern matching
(simple type patterns, relational patterns, logical patterns), improved target typing (target-type
```
new
```
expressions, target typed
```
??
```
and
```
?
```
), and covariant returns. Minor features: relax ordering of
```
ref
```
and
```
partial
```
modifiers, parameter null checking, lambda discard parameters, native
```
int
```
s, attributes on local functions, function pointers, static lambdas, extension
```
GetEnumerator
```
, module initializers, and extending partial.
C# 10.0
released with .NET 6.0 (November 2021). Major
new features
: record structs, struct parameterless constructors, interpolated string handlers, global
```
using
```
directives, file-scoped namespace declarations, extended property patterns, const interpolated strings, mixed assignment and declaration in deconstruction, async method builders (via attributes) for individual methods, the
```
CallerArgumentExpression
```
attribute for parameters, enhanced
```
#line
```
pragmas.
C# 11.0
will be released with .NET 7.0 (Date to be annonced, already testable). Major
new features
: file-scoped types, generic math support, auto-default structs, pattern match
```
Span<char>
```
on a constant string, extended nameof scope, numeric
```
IntPtr
```
, UTF-8 string literals, required members,
```
ref
```
fields and
```
scoped ref
```
, raw string literals, improved method group conversion to delegate, warning wave 7, generic attributes, newlines in string interpolation expressions, list patterns
In response to the OP's question:
What are the correct version numbers for C#? What came out when? Why can't I find any answers about C# 3.5?
There is no such thing as C# 3.5 - the cause of confusion here is that the C# 3.0 is present in .NET 3.5. The language and framework are versioned independently, however - as is the CLR, which is at version 2.0 for .NET 2.0 through 3.5, .NET 4 introducing CLR 4.0, service packs notwithstanding. The CLR in .NET 4.5 has various improvements, but the versioning is unclear: in some places it may be referred to as CLR 4.5 (
this MSDN page
used to refer to it that way, for example), but the
```
Environment.Version
```
property still reports 4.0.xxx.
As of May 3, 2017, the C# Language Team created a history of C# versions and features on their GitHub repository:
Features Added in C# Language Versions
. There is also
a page that tracks upcoming and recently implemented language features
.


Question:
In Bash I'm executing a command and putting the result in a variable like this:

export var=`svn ls`

But if SVN fails for some reason--say it returns a non-zero error code--export still returns status code 0. How do I detect if the executed command fails?

Answer:
I had similar problem, it can be done like this:
```
rm -f error_marker_file
export var=`svn ls || touch error_marker_file`

[ -f error_marker_file ] && echo "error in executing svn ls"
```


Question:
The scriptaculous wiki has a demo (http://github.com/madrobby/scriptaculous/wikis/effect-slidedown) that shows the SlideDown effect in use. However I need to have the same link to slide down if a certain DIV is hidden and SlideUp if that DIV is showing.

How do I achieve this?

Thanks.

Answer:
Wrap it in a function, call the function instead.
```
```
function slideMe(myDiv) {

    if(Element.visible(myDiv)) {
    //slide up

    }

    else {

    //slide down

    }
}
```
```


Question:
I'm writing a bash script that needs to delete old files.

It's currently implemented using :

find $LOCATION -name $REQUIRED_FILES -type f -mtime +1 -delete

This will delete of the files older than 1 day.

However, what if I need a finer resolution that 1 day, say like 6 hours old? Is there a nice clean way to do it, like there is using find and -mtime?

Answer:
-mmin is for minutes.
Try looking at the man page.
```
```
man find
```
```
for more types.


Question:
I use Eclipse with "external" projects - i.e. projects created from existing source.

Poking around in the workspace files, I cannot find any reference to these projects. My question is: how does Eclipse keep track of these projects?

I'd like to be able to add such a project to the workspace automatically (by generating .project and .classpath files).

Answer:
Windows:
```
```
<workspace>\.metadata\.plugins\org.eclipse.core.resources\.projects\
```
```
Linux / osx:
```
```
<workspace>/.metadata/.plugins/org.eclipse.core.resources/.projects/
```
```
Your project can exist outside the workspace, but all Eclipse-specific
```
metadata
```
are stored in that
```
org.eclipse.core.resources\.projects
```
directory
As noted in
the comments
by
tk421storm
, and in
Jeegar Patel
's
answer
:
In order for manual changes to take effect, make sure to do
```
File -> Refresh
```
afterwards.


Question: I have a directory of files that I'd like to append file extension to as long as they don't have an existing, specified extension. So add .txt to all file names that don't end in .xyz. PowerShell seems like a good candidate for this, but I don't know anything about it. How would I go about it?

Answer:
Consider the DOS command FOR in a standard shell.
```
```
C:\Documents and Settings\Kenny>help for
Runs a specified command for each file in a set of files.

FOR %variable IN (set) DO command [command-parameters]

  %variable  Specifies a single letter replaceable parameter.
  (set)      Specifies a set of one or more files.  Wildcards may be used.
  command    Specifies the command to carry out for each file.
  command-parameters
             Specifies parameters or switches for the specified command.

...

In addition, substitution of FOR variable references has been enhanced.
You can now use the following optional syntax:

    %~I         - expands %I removing any surrounding quotes (")
    %~fI        - expands %I to a fully qualified path name
    %~dI        - expands %I to a drive letter only
    %~pI        - expands %I to a path only
    %~nI        - expands %I to a file name only
    %~xI        - expands %I to a file extension only
    %~sI        - expanded path contains short names only
    %~aI        - expands %I to file attributes of file
    %~tI        - expands %I to date/time of file
    %~zI        - expands %I to size of file
    %~$PATH:I   - searches the directories listed in the PATH
                   environment variable and expands %I to the
                   fully qualified name of the first one found.
                   If the environment variable name is not
                   defined or the file is not found by the
                   search, then this modifier expands to the
                   empty string
```
```


Question:
Sometimes it's difficult to describe some of the things that "us programmers" may think are simple to non-programmers and management types.

So...

How would you describe the difference between Managed Code (or Java Byte Code) and Unmanaged/Native Code to a Non-Programmer?

Answer:
"The specific term managed code is particularly pervasive in the Microsoft world."
Since I work in MacOS and Linux world, it's not a term I use or encounter.
The Brad Abrams "
What is Managed Code
" blog post has a definition that say things like ".NET Framework Common Language Runtime".
My point is this: it may not be appropriate to explain it the terms at all.  If it's a bug, hack or work-around, it's not very important.  Certainly not important enough to work up a sophisticated lay-persons description.  It may vanish with the next release of some batch of MS products.


Question:
I'm looking for a broad overview of what I need to do and in what order to migrate a W2003 Server to a virtual server environment. Specifically:

How does it work in general?
Do I need to prepare my disks in any way?
What do I install first? The toolkit? Virtual Server?
Can I install linux later?

etc.

Any pointers welcome!

Answer:
Depending on which virtualisation platform you're migrating to there are tools to perform physical to virtual conversions:
http://www.vmware.com/products/converter/
PlateSpin was the product that we were recommended when we virtualised a chunk of our hosting platform to Virtual Iron.
http://www.platespin.com/products/powerconvert/
It'll convert physical to Microsoft Virtual Server, Virtual Iron, VMware and Citrix XenServer amongst other capabilities.
In reality we just ran our internal server build process on the virgin VM's which gave us the opportunity to start out with fresh machines and without the configuration 'rot' that happens over time to servers of a particular vintage.


Question: At the moment I have a console application.  I would like to be able to exit the application, update through svn, recompile and then relaunch.  This is running under a Linux environment.  At the moment I'm not sure how I would be able to relaunch the application.  Is there a way to do this?

Answer:
Well, in code you need to put the sender's name in quotes, followed by the e-mail address.
```
```
new SmtpClient(...).Send("\"John Smith\" jsmith@somewhere.com", ...);
```
```
And...it looks like you can encode it into the attribute too...
```
```
<smtp from=""John Smith" <jsmith@somewhere.com>">
```
```


Question:
I'm trying to send the output to the console (or colouredconsole) ... which I'm hoping would (also?) go to the Visual Studio's Output window for any ASP.NET web site/app/mvc app.

It doesn't by default, but if I change the target to 'file' then it works for sure.

Can NLog output to the Output window for web apps?

Answer:
You can use this configuration file (nlog.config in the app path):
```
```
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <targets>
        <target name="debugger" xsi:type="Debugger" layout="${logger}::${message}"/>
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="debugger" />
  </rules>
</nlog>
```
```
See also:
https://github.com/NLog/NLog/wiki/Debugger-target
-Scott


Question: We are developing a desktop application(visual basic 6.0).We have our own logging framework. What are good practices? When we have a web application, then we can control the level of logging. How to go about in a desktop app?

Answer:
Any answer needs to be considered based on your environment:
Do your business rules (or laws)
require
certain activities to be logged?
Is security an issue?
Do actions need to be traceable?
Is the size of the log file (or the amount of disk space) an issue?
Is your motivation to record activity, to debug, or both?
With those in mind:
Consider allowing the user to select the verbosity, or "logging level."
Log all program errors and significant user errors.
Log any activities that affect system configuration or operation.
Log the start and end of user sessions.
Log the start and end of the application.
Consider logging the first time a significant activity occurs.
Other suggestions:
Include timestamps, either in each log or at the beginning of a "group" of logs, as best appropriate for your application.
If you're logging to a file, consider rotating the log (
i.e.
closing one file and opening a new one) when it reaches a certain size or age.
If the application contains several modules, include the name of the module in each log.
If more than one person uses the application (shared computer?), log the user ID at the beginning of each session.
Assign log "levels" based on the severity (Error, Warning, Info, Debug).  The
```
syslog
```
specification defines 7 "standard" levels that serve as a good reference.
Ask your customer what they expect to see in the log.


Question:
Is there a csh script/command to list all the files in source source tree which have line endings that show up as "^M" in emacs (under linux).

Thanks!

Answer:
```
```
find . -type f -exec grep $'\r' {} +
```
```
The
```
$'\r'
```
probably requires bash to function correctly.


Question: When posting example code or filing bug reports based on a real production app, it would be helpful to have some way to change the table and column names to not potentially give away information about the internals of the app.  Doing it by hand without breaking things is time consuming.  Does anything automatic exist?  Ideally it would use real English words so they are more easily referred to than random text strings.

Answer:
As long as you don't use real data, I don't see what the issue is.  Most apps are fairly obvious based on the requirements.  ie CRM system = (customer name, address, etc...) or (customer name, addressid, etc.. with some address table with parts of the address, etc...).  By knowing your schema I have no idea how you implement your app.  Generally without the stored procedures/program code it would be hard to steal any intellectual property.  Even if you were the NSA or something (InternetIP, PacketHeadingID, PacketDetailID, TimeStampID).  Even with the structure of the tables I still would have no information on how your system to log all the internet traffic actually works.  I also wouldn't know anything that is logged.
I don't know of anything off hand to do what you are requesting, but I would think it is fairly easy to write a script to do it on your own.  Look at the table columns and datatypes and call text columns "TextColumn1", int columns "IntColumn2", etc. and build a table of substitutions, then perform the substitutions globally in the script file.  I would think this is a fairly easy Python/Perl/PowerShell/Ruby/VbScript program.


Question: I'm planning to write an operating system and I don't know very much about operating systems. Are there any good resources or books to read in order for me to learn? What are your recommendations?

Answer:
Operating Systems Implementation Prentice Software
This book is written by Tanenbaum, the main guy behind Minix, which is what Linux was based on. It provides good overviews for basic OS concepts like memory management, file systems, processes, etc. The concepts in this book book are intimately tied to examples of the Minix OS, which is a good thing.
I think you should start by something like that.


Question:
I've tried variations of this, but had no luck other than the ability to start a cygwin window. (wrapped on ; for clarity)

Filename: "c:\cygwin\bin\bash.exe";
  Parameters: "-c c:/scripts/step1.sh paramX";
  Flags: shellexec waituntilterminated;
  StatusMsg: "Running the script..."

(this is for an internal install, thus cywin is installed, and all paths, scripts are known)

Answer:
I think you're going to need to make the whole thing part of a
```
cmd.exe
```
invocation, and then I'm not sure it will do exactly what you want/need.
I'm looking at Inno-Setup 5 documentation (may be out-of-date), but I don't think you need the
```
shellexec
```
or
```
waituntilterminated
```
flags.
Try something like
```
```
Filename: "cmd.exe"; Parameters: "/c c:\cygwin\bin\bash -c 'c:/scripts/step1.sh paramx'"
```
```
Untested, caveat emptor.


Question: Is there some way I can define String[int] to avoid using String.CharAt(int)?

Answer:
No, there isn't a way to do this.
This is a common question from developers who are coming to JavaScript from another language, where
operators can be defined or overridden
for a certain type.
In C++, it's not entirely out of the question to overload
```
operator*
```
on
```
MyType
```
, ending up with a unique asterisk operator for operations involving objects of type
```
MyType
```
.  The readability of this practice might still be called into question, but the language affords for it, nevertheless.
In JavaScript, this is simply not possible.  You will not be able to define a method which allows you to index chars from a
```
String
```
using brackets.
@Lee Kowalkowski
brings up a good point, namely that it is, in a way,
possible
to access characters using the brackets, because the brackets can be used to access members of a JavaScript
```
Array
```
.  This would involve creating a new
```
Array
```
, using each of the characters of the string as its members, and then accessing the
```
Array
```
.
This is probably a confusing approach.  Some implementations of JavaScript will provide access to a string via the brackets and some will not, so it's not standard practice.  The object may be confused for a string, and as JavaScript is a loosely typed language, there is already a risk of misrepresenting a type.  Defining an array solely for the purposes of using a different syntax from what the language already affords is only gong to promote this type of confusion.  This gives rise to
@Andrew Hedges
's question: "Why fight the language?"..
There are
useful patterns in JavaScript
for
legitimate function overloading
and
polymorphic inheritance
.  This isn't an example of either.
All semantics aside, the operators still haven't been overridden.
Side note:
Developers who are accustomed to the conventions of strong type checking and classical inheritance are sometimes confused by JavaScript's C-family syntax.  Under the hood, it is working in an unfamiliar way.  It's best to write JavaScript in clean and unambiguous ways, in order to prevent confusion.


Question: When I type git diff, I want to view the output with my visual diff tool of choice (SourceGear "diffmerge" on Windows). How do I configure git to do this?

Answer:
Since Git1.6.3, you can use the
git difftool script
: see
my answer below
.
May be this
article
will help you. Here are the best parts:
There are two different ways to specify an external diff tool.
The first is the method you used, by setting the GIT_EXTERNAL_DIFF variable. However, the variable is supposed to point to the full path of the executable. Moreover, the executable specified by GIT_EXTERNAL_DIFF will be called with a fixed set of 7 arguments:
```
```
path old-file old-hex old-mode new-file new-hex new-mode
```
```
As most diff tools will require a different order (and only some) of the arguments, you will most likely have to specify a wrapper script instead, which in turn calls the real diff tool.
The second method, which I prefer, is to
configure the external diff tool via "git
config"
. Here is what I did:
1) Create a wrapper script "git-diff-wrapper.sh" which contains something like
```
```
-->8-(snip)--
#!/bin/sh

# diff is called by git with 7 parameters:
# path old-file old-hex old-mode new-file new-hex new-mode

"<path_to_diff_executable>" "$2" "$5" | cat
--8<-(snap)--
```
```
As you can see, only the second ("old-file") and fifth ("new-file") arguments will be
passed to the diff tool.
2) Type
```
```
$ git config --global diff.external <path_to_wrapper_script>
```
```
at the command prompt, replacing  with the path to "git-diff-wrapper.sh", so your ~/.gitconfig contains
```
```
-->8-(snip)--
[diff]
    external = <path_to_wrapper_script>
--8<-(snap)--
```
```
Be sure to use the correct syntax to specify the paths to the wrapper script and diff
tool, i.e. use forward slashed instead of backslashes. In my case, I have
```
```
[diff]
    external = \"c:/Documents and Settings/sschuber/git-diff-wrapper.sh\"
```
```
in .gitconfig and
```
```
"d:/Program Files/Beyond Compare 3/BCompare.exe" "$2" "$5" | cat
```
```
in the wrapper script. Mind the trailing "cat"!
(I suppose the '
```
| cat
```
' is needed only for some programs which may not return a proper or consistent return status. You might want to try without the trailing cat if your diff tool has explicit return status)
(
Diomidis Spinellis
adds
in the comments
:
The
```
cat
```
command is required, because
```
diff(1)
```
, by default exits with an error code if the files differ.
Git expects the external diff program to exit with an error code only if an actual error occurred, e.g. if it run out of memory.
By piping the output of
```
git
```
to
```
cat
```
the non-zero error code is masked.
More efficiently, the program could just run
```
exit
```
with and argument of 0.)
That (the article quoted above) is the theory for external tool
defined through config file
(not through environment variable).
In practice (still for config file definition of external tool), you can refer to:
How do I setup DiffMerge with msysgit / gitk?
which illustrates the concrete settings of DiffMerge and WinMerge for MsysGit and gitk
How can I set up an editor to work with Git on Windows?
for the definition of Notepad++ as an external editor.


Question:
I'm trying to write a small script to change the current directory to my project directory:

#!/bin/bash
cd /home/tree/projects/java

I saved this file as proj, added execute permission with chmod, and copied it to /usr/bin. When I call it by:
proj, it does nothing. What am I doing wrong?

Answer:
Shell scripts are run inside a subshell, and each subshell has its own concept of what the current directory is. The
```
cd
```
succeeds, but as soon as the subshell exits, you're back in the interactive shell and nothing ever changed there.
One way to get around this is to use an alias instead:
```
```
alias proj="cd /home/tree/projects/java"
```
```


Question: Does anyone have a library or JavaScript snippet to validate the check digit of credit cards before the user hits Submit?

Answer:
The
jQuery Validation Plugin
has a
method
for validating credit card numbers.
There are other specific scripts:
JavaScript Credit Card Validation Function
Credit Card Validation
Most of them use the
Luhn algorithm
.


Question:
What's the difference between \n and \r (I know it has something to do with OS), and what's the best way to echo a line break that will work cross platform?

EDIT: In response to Jarod, I'll be using ths to echo a line break in a .txt log file, though I'm sure I'll be using it in the future for things such as echoing HTML makup onto a page.

Answer:
```
\n
```
is a Linux/Unix line break.
```
\r
```
is a classic Mac OS (non-OS X) line break. Mac OS X uses the above unix
```
\n
```
.
```
\r\n
```
is a Windows line break.
I usually just use
```
\n
```
on our Linux systems and most Windows apps deal with it ok anyway.


Question:
I'm looking for someone to explain how to drag and drop in javascript, I want a horizontal line with some customizable images in it.

I've had a look at the online tutorials for these but find them very hard to use.

Answer:
I would recommend that you look into one of the Javascript Frameworks out there. We use
prototype
with scriptaculous.
You can look at a demo for Drag and Drop in Scriptaculous
here
. And you can run through a tutorial
here
.
Or look into any of the other frameworks such as JQuery or Dojo.


Question:
I have a complex command that I'd like to make a shell/bash script of.  I can write it in terms of $1 easily:

foo $1 args -o $1.ext

I want to be able to pass multiple input names to the script. What's the right way to do it?

And, of course, I want to handle filenames with spaces in them.

Answer:
Use
```
"$@"
```
to represent all the arguments:
```
```
for var in "$@"
do
    echo "$var"
done
```
```
This will iterate over each argument and print it out on a separate line.  $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them:
```
```
sh test.sh 1 2 '3 4'
1
2
3 4
```
```


Question:
The symptom of the problem looks like "[0m[27m[24m[J[34;1" which on a terminal translates into the color blue.

-A

Answer:
The following should work in your .bash_profile or .bashrc
```
```
case $TERM in
xterm-color)
export PS1='\[\e]0;\W\007\]\[\e[34;1m\]\W\[\e[0m\]\$ '
;;
*)
export PS1='\W\$ '
;;
esac
```
```


Question: I am looking for suggestions on how to find the sizes (in bits) and range of floating point numbers in an architecture independent manner.  The code could be built on various platforms (AIX, Linux, HPUX, VMS, maybe Windoze) using different flags - so results should vary.  The sign, I've only seen as one bit, but how to measure the size of the exponent and mantissa?

Answer:
Have a look at the values defined in
```
float.h
```
. Those should give you the values you need.


Question:
POSIX environments provide at least two ways of accessing files.  There's the standard system calls open(), read(), write(), and friends, but there's also the option of using mmap() to map the file into virtual memory.

When is it preferable to use one over the other?  What're their individual advantages that merit including two interfaces?

Answer:
```
mmap
```
is great if you have multiple processes accessing data in a read only fashion from the same file, which is common in the kind of server systems I write.
```
mmap
```
allows all those processes to share the same physical memory pages, saving a lot of memory.
```
mmap
```
also allows the operating system to optimize paging operations.  For example, consider two programs; program
```
A
```
which reads in a
```
1MB
```
file into a buffer creating with
```
malloc
```
, and program B which
```
mmaps
```
the 1MB file into memory.  If the operating system has to swap part of
```
A
```
's memory out, it must write the contents of the buffer to swap before it can reuse the memory.  In
```
B
```
's case any unmodified
```
mmap
```
'd pages can be reused immediately because the OS knows how to restore them from the existing file they were
```
mmap
```
'd from.  (The OS can detect which pages are unmodified by initially marking writable
```
mmap
```
'd pages as read only and catching
seg faults
, similar to
Copy on Write
strategy).
```
mmap
```
is also useful for
inter process communication
.  You can
```
mmap
```
a file as read / write in the processes that need to communicate and then use synchronization primitives in the
```
mmap'd
```
region (this is what the
```
MAP_HASSEMAPHORE
```
flag is for).
One place
```
mmap
```
can be awkward is if you need to work with very large files on a 32 bit machine.  This is because
```
mmap
```
has to find a contiguous block of addresses in your process's address space that is large enough to fit the entire range of the file being mapped.  This can become a problem if your address space becomes fragmented, where you might have 2 GB of address space free, but no individual range of it can fit a 1 GB file mapping.  In this case you may have to map the file in smaller chunks than you would like to make it fit.
Another potential awkwardness with
```
mmap
```
as a replacement for read / write is that you have to start your mapping on offsets of the page size.  If you just want to get some data at offset
```
X
```
you will need to fixup that offset so it's compatible with
```
mmap
```
.
And finally, read / write are the only way you
can
work with some types of files.
```
mmap
```
can't be used on things like
pipes
and
ttys
.


Question:
How to calculate the length (in pixels) of a string in Java?

Preferable without using Swing.

EDIT:
I would like to draw the string using the drawString() in Java2D
and use the length for word wrapping.

Answer:
If you just want to use AWT, then use
```
Graphics.getFontMetrics
```
(optionally specifying the font, for a non-default one) to get a
```
FontMetrics
```
and then
```
FontMetrics.stringWidth
```
to find the width for the specified string.
For example, if you have a
```
Graphics
```
variable called
```
g
```
, you'd use:
```
```
int width = g.getFontMetrics().stringWidth(text);
```
```
For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.


Question:
I have a simple linux script:

#!/bin/sh
for i in `ls $1`
do
       echo $i
done

In my temp folder are 4 file: a.a, a.aa, a.ab and a.ac

When i call ./script temp/*.?? i get:

temp/a.aa

When i call ./script "temp/*.??" i get:

temp/a.aa
temp/a.ab
temp/a.ac

Why do the double quote change the result?

Answer:
Because without the quotes the shell is expanding your call to:
```
```
./script temp/a.aa temp/a.ab temp/a.ac
```
```
So
```
$1
```
is
```
temp/a.aa
```
instead of
```
temp/*.??
```
.


Question: I'm using Emacs with C# Mode and when I turn on the speedbar, no files show up by default.   I can choose "show all files" on the speedbar mode, but then every .cs file shows up with a '[?]' next to the name.   How do I properly configure speedbar so it shows up with .cs files by default?  How do I get the '[+]' next to each file so I can navigate inside the file?

Answer:
I used speedbar earlier and got really irritated. I now use
ECB
.
ECB
uses its own buffer for the tree and can optionally show the outline of the CS file in a separate buffer. They all fit in the same frame while Speedbar has its own frame.
I have some
custom stuff
setup for ECB. You can see it here.


Question: Does Ruby have a stepwise debugger, similar to Perl's "perl -d"?

Answer:
The
ruby-debug
(for ruby 1.8),
debugger
(for ruby 1.9),
byebug
(for ruby 2.0) and also the
trepanning
series all have an
```
-x
```
or
```
--trace
```
option. Inside the debuggers, the command
```
set linetrace
```
will turn on or off line tracing. Here is
the manual for ruby-debug
The original answer has been revised because the link to the datanoise article, alas, no longer works. Also added are the successors to ruby-debug


Question:
Compiling a program on Linux that calls POSIX timer functions (eg: timer_create, timer_settime) returns errors such as:

In function `foo':
timer.c:(.text+0xbb): undefined reference to `timer_create'
timer.c:(.text+0x187): undefined reference to `timer_settime'
collect2: ld returned 1 exit status

Which library do I need to link?

Answer:
This should be documented in the man page. Given it isn't add
```
-lrt
```
.


Question:
We have SQL Server 2005 running on Win2003/64, and we push it hard.  We generate real time reports on several tables with a couple million records using asp.net 3.5, and they will periodically time out.

I'd like to increase our memory from 8GB to 16GB or even 32GB to see how that helps, but I need to justify this to the pencil pushers before they will spend the money.  Can someone point me to some resources that will help me make my case and will get me some hard numbers to use?

Answer:
First find out what is really the problem and that the server is properly tuned for the queries you are running. It's very sad to waste the money on RAM to find out you are I/O bound.
After you gather data about the cause of the timeouts you should be able to convince the pencil wielders easily.
Some tuning/monitoring links:
http://www.brentozar.com/archive/2008/03/sql-server-2005-setup-checklist-part-1-before-the-install/
(check both articles)
http://www.sql-server-performance.com/
About I/O specifically:
http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/pdpliobp.mspx
http://searchsqlserver.techtarget.com/generic/0,295582,sid87_gci1307990,00.html
http://www.novicksoftware.com/Articles/sql-server-io-statistics.htm


Question:
From a programmer stuck in the web world...

What are the most common desktop development "frameworks" currently being used for desktop application development?

Is it realistic to write desktop software for both Windows and OS X?

Is it realistic to use the same base code to write the business/data layers for an application that will have a partial web UI as well as a desktop UI?

Answer:
Yes. You could use Java, Python/ Ruby etc with a cross platform UI framework, AIR etc etc.
Yes it is realistic. Build it on a client/server model and most of the code will fit either the desktop or web UI model.
If you went down the .NET root, you could use Silverlight for the web app, .NET server code for the backend and even Mono to enable you to develop for OS X.
If you took the Java route, Java runs within the browser, there is JavaFX coming soon that is a small flash-like version for browsers. It runs on just about all OS's and can handle the backend just fine.
Flex/ AIR offers an excellent way of developing desktop and web-based apps for OS X, Windows and Linux, but you'll need another language for the back-end. .NET, Java, PHP etc all work fine as the backend though.
Edit
At MrJeepster's request, here are details on interfacing an AIR frontend and .NET backend:
There are two ways you can interface AIR to a .NET backend: the DIY way and the remoting way.
The DIY way would involve defining your own (probably XML) data formats and using the low level HTTP request objects to communicate with a HTTP server, or even lower level socket classes to communicate with some other server.
The remoting way is all together easier as nice people have written a selection of free remoting packages:
http://www.adobe.com/devnet/flashremoting/articles/intro_flremoting_net.html
http://www.themidnightcoders.com/flashorb/gettingStarted.htm
http://www.fluorinefx.com/
Remoting involves sharing objects between the client and server. So you create some object on the AIR client, get the remoting framework to serialise it, transfer it to the server and deserialise it into a .NET object. The server then processes it and sends it, or a new object, back again via the same route.


Question: if i decide to use the 'publish' option for my ASP.NET website, instead of a Web Deployment Project, can i do custom msbuild things? Or do i need to stick with WDP's if i want to do custom msbuild stuff during compile/deployment.

Answer:
I think of the publish option as a part of the VS.NET toolset for developers to use to publish web sites on dev machines.  It isn't really built to be a real deployment.
If you need custom actions, a Web Deployment Project would be more suited to a real deployment that multiple people other than the developer run regularly and that you want created with each build.
I would also look at three other options:
PowerShell:
A good way to
script
against IIS, set up websites, etc.  You can even build cmdlets from OO code (like C#) that your script can call.  Many professional IT firms use it to deploy big web sites.
MSDeploy:
A new
deployment tool
for websites that can replicate a vroot over several servers.  Very good for having your golden image and then blasting it out to various places.
C# application:
If you are a more
advanced developer
, you can always write your own application that xcopies files (via Process) and uses WMI to configure IIS.  Harder, but you have complete control.


Question: Is there a PHP class/library that would allow me to query an XHTML document with CSS selectors? I need to scrape some pages for data that is very easily accessible if I could somehow use CSS selectors (jQuery has spoiled me!). Any ideas?

Answer:
After Googling further (initial results weren't very helpful), it seems there is actually a Zend Framework library for this, along with some others:
DOM-Query
phpQuery
pQuery
QueryPath
Simple HTML DOM Parser
Ultimate Web Scraper Toolkit
Zend-Dom


Question:
How do I create an Application Pool on IIS 6.0 using a PowerShell script?

This is what I have come up with so far ...

$appPool = [wmiclass] "root\MicrosoftIISv2:IIsApplicationPool"

Thanks

Answer:
It isn't the most obvious process, but here is what worked for me..
```
```
$AppPoolSettings = [wmiclass]'root\MicrosoftIISv2:IISApplicationPoolSetting'
$NewPool = $AppPoolSettings.CreateInstance()
$NewPool.Name = 'W3SVC/AppPools/MyAppPool'
$Result = $NewPool.Put()
```
```
You might get an error with the call to Put(), but calling it a second (or third) time should make it work.  This is due to an issue with PowerShell V1 and WMI.


Question:
I am writing an application using labview and need to use external code. I have read that using CINs are old fashioned and 'wrong' to use. Is this correct? Should I use shared dlls instead?

What are the advantages/disadvantages of both methods?

Answer:
I don't have personal experience of writing external code to be called by LabVIEW, but from the
NI knowledge base
: "When given the choice, a DLL is the choice to make."
The advantages they list include:
Many processes can share a single copy of the DLL in memory
Many applications can share a single copy of the DLL on disk
Modifying the functions in a DLL does not require a recompile of the calling application
Only certain (obsolete?) development environments are supported for creating CINs.
Potential disadvantages of DLLs are:
The first two items on the list above ;-)
You need to remember to include the DLL as a support file when building an application from LabVIEW
CIN code can be platform independent, while DLL/shared libraries may need rewriting for each platform.
I'm pretty sure that every time I have seen this discussion in several years of following LabVIEW lists and forums the advice has been the same: CINs are obsolete, use DLLs - just be aware of the potential issues they can cause.


Question:
Quick add on requirement in our project.  A field in our DB to hold a phone number is set to only allow 10 characters.  So, if I get passed "(913)-444-5555" or anything else, is there a quick way to run a string through some kind of special replace function that I can pass it a set of characters to allow?

Regex?

Answer:
Definitely regex:
```
```
string CleanPhone(string phone)
{
    Regex digitsOnly = new Regex(@"[^\d]");
    return digitsOnly.Replace(phone, "");
}
```
```
or within a class to avoid re-creating the regex all the time:
```
```
private static Regex digitsOnly = new Regex(@"[^\d]");

public static string CleanPhone(string phone)
{
    return digitsOnly.Replace(phone, "");
}
```
```
Depending on your real-world inputs, you may want some additional logic there to do things like strip out leading 1's (for long distance) or anything trailing an x or X (for extensions).


Question:
what's the quickest way to extract a 5 digit number from a string in c#.

I've got

string.Join(null, System.Text.RegularExpressions.Regex.Split(expression, "[^\\d]"));

Any others?

Answer:
Do you mean convert a string to a number?  Or find the first 5 digit string and then make it a number?  Either way, you'll probably be using
decimal.Parse
or int.Parse.
I'm of the opinion that Regular Expressions are the wrong approach.  A more efficient approach would simply to walk through the string looking for a digit, and then advancing 4 characters and seeing if they are all digits.  If they are, you've got your substring.  It's not as robust, no, but it doesn't have the overhead either.


Question: Vista's Resource Monitor includes a reading for "Hard Faults/sec". Is there an equivalent performance counter I can use in C# to get this reading? I've tried the "Page Faults/sec" under the memory category, but that appears to be something different.

Answer:
A hard fault is the same as a page fault.
Source: "
Windows Vista Performance and Reliability Monitoring Step-by-Step Guide
".
See section
Resource View details
, Label Memory (the 4th table):
A hard fault (also known as a page fault) occurs when the page of the referenced address is no longer in physical memory and has been swapped out or is available from a backing file on disk.


Question:
How do you get the caret position in a <textarea> using JavaScript?

For example: This is| a text

This should return 7.

How would you get it to return the strings surrounding the cursor / selection?

E.g.: 'This is', '', ' a text'.

If the word “is” is highlighted, then it would return 'This ', 'is', ' a text'.

Answer:
With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:
```
```
function getCaret(node) {
  if (node.selectionStart) {
    return node.selectionStart;
  } else if (!document.selection) {
    return 0;
  }

  var c = "\001",
      sel = document.selection.createRange(),
      dul = sel.duplicate(),
      len = 0;

  dul.moveToElementText(node);
  sel.text = c;
  len = dul.text.indexOf(c);
  sel.moveStart('character',-1);
  sel.text = "";
  return len;
}
```
```
(
complete code here
)
I also recommend you to check the jQuery
FieldSelection
Plugin, it allows you to do that and much more...
Edit:
I actually re-implemented the above code:
```
```
function getCaret(el) {
  if (el.selectionStart) {
    return el.selectionStart;
  } else if (document.selection) {
    el.focus();

    var r = document.selection.createRange();
    if (r == null) {
      return 0;
    }

    var re = el.createTextRange(),
        rc = re.duplicate();
    re.moveToBookmark(r.getBookmark());
    rc.setEndPoint('EndToStart', re);

    return rc.text.length;
  }
  return 0;
}
```
```
Check an example
here
.


Question: For example, I could just git pull and then git checkout HEAD-1. But is there a way of seeing the differences before deciding whether to git pull or not?

Answer:
Do a
```
git fetch
```
first to update your remote tracking branch. Then use
```
git log ..origin
```
to see what has changed in the "origin" branch. Then you can do a
```
git pull
```
if you are satisfied with the changes.


Question:
As a simple example, I want to write a CLI script which can print = across the entire width of the terminal window.

#!/usr/bin/env php
<?php
echo str_repeat('=', ???);

or

#!/usr/bin/env python
print '=' * ???

or

#!/usr/bin/env bash
x=0
while [ $x -lt ??? ]; do echo -n '='; let x=$x+1 done; echo

Answer:
```
tput cols
```
tells you the number of columns.
```
tput lines
```
tells you the number of rows.


Question: Should we use Generic Collection to improve safety and performance?

Answer:
Absolutely.
A conventional collection, such as the ArrayList, implicitly stores objects.
This means, that doing this:
```
```
ArrayList list = new ArrayList();
list.Add(5);
list.Add("FooBar");
```
```
Is legitimate code. This introduces a handful of issues.
Normally, you don't want to store different types in the same collection, and having compile time checking for this is nice.
When you store a value type (such as the integer 5 above), it must be boxed into a reference type before it can be stored in the collection.
When reading a value, you must cast it back from Object to the desired type.
However, you eliminate all of these issues by using a generic collection:
```
```
List<int> list = new List();
list.Add(5);
// Compile Time Error.
list.Add("FooBar")
```
```
You also gain intellisense support when working directly with indices of the collection, instead of just generic "object" intellisense.


Question:
I need to find two adjacent repeating digits in a string and replace with a single one. How to do this in Java. Some examples:

123345 should be 12345
 77433211 should be 74321

Answer:
using a regex:
```
```
var myString='123345'
myString.replace(/([0-9])\1/g,'$1')
```
```
that will match exactly 2 repeats.
```
```
'123334'.replace(/([0-9])\1+/g,'$1')
```
```


Question: Traditional logfile analytics tools (awstats, statcounter) or general web analytics (google analytics, yahoo web analytics) are not suitable for analyzing traffic on servlets. Is there a good alternative to log messages using a logging framework (log4j for example) and to write a custom analytics software for these?

Answer:
I suppose this is not the answer you hoped for but it is unavoidable that anyone with administrative rights will be able to browse and edit information in the database.
You cannot change this.
Perhaps you could consider WHY you want to prevent this kind of access?
I expect you want to prevent tampering or accidental corruption of the data?
If that is the reason then you can go a long way to prevent corruption by adding constraints to your database.  Add foreign key constraints, uniqueness constraints, everything that will help prevent data corruption.
Then an administrator would need to deliberately undo these constraints before they tamper, which would prevent most accidental corruption but of course not prevent malicious vandalism.
If you are concerned about protection of your intellectual property, you could encrypt the programmatic components (stored procedures and views and functions).  This kind of encryption is not very strong but prevents casual inspection.
Encryption is added by using the
```
```
WITH ENCRYPTION
```
```
clause in your CREATE or ALTER statements.


Question: How can I rename a Virtual Directory (or Web Application) in IIS 6.0/7.0 using VBScript?

Answer:
I assume you want to use a local shell script.
Try PowerShell, I think IIS7 has introduced
new administration tools
that look quite powerful. I
think
you could also use these scripts to manage IIS remotely via WMI.
It shouldn't be any more complicated then VBScript.
Another way would be to use VBScript to edit the IIS configuration files or create an
administration object
, but that doesn't really seem to be the way to go about it.
Hopefully this helps.


Question:
I'd like to automate the FTP download of a database backup file using PowerShell.  The file name includes the date so I can't just run the same FTP script every day.  Is there a clean way to do this built into PowerShell or using the .NET framework?

I want to use a secure FTP session.

Answer:
This isn't as simple as I wish it would be. There are three options that I know of.
.NET - You can use the .NET framework to do this in PowerShell, but it involves raw socket manipulation that I wouldn't want to do in a script. If I were going this route, then I would wrap up all the FTP junk into a DLL in C# and then use that DLL from PowerShell.
Manipulating a file - If you know the pattern of the name of the file that you need to get each day then you could just open your FTP script with PowerShell and change the name of the file in the script. Then run the script.
Pipe text to FTP - The last option is to use PowerShell to pipe information into and out of your FTP session. See
here
.


Question:
can two use cases extend  or include each other at the same time?
 A extend/include B  and B extend/include A

Answer:
I'm pretty sure the answer is "NO".
You've just described the digital equivalent fo the chicken and egg problem.
Circular references are [almost] always Bad Things (tm). The only place I know it to not be horrible is in the context of a linked list, in which each entry has a pointer to another of its own type.


Question: Why are there not more opensource easy to use charting libraries for Java?. The only successful opensource project in this area seems to be jfreechart, and it doesn't even have any documentation or examples available.

Answer:
There is JChart which is all open source.  I'm not sure exactly what you are graphing and how you are graphing it (servlets, swing, etc) so I would say just look at a couple different ones and see which works for you.
http://sourceforge.net/projects/jchart/
I've also used JGraph but I've only used their commercial version.  They do offer an open source version however:
https://github.com/jgraph/jgraphx


Question:
I've inherited someone else's monster of a BASH script.  The script was written in such a way that it uses a ridiculous amount of memory (around 1GB).  I can run it from a shell with out issue, but if I run it from cron I crashes with a sig fault.

Apart from digging into the poorly commented behemoth, is there a way to run it from cron with out running into the sig fault?

Cheers,

Steve

Answer:
When you run something using cron you'll encounter issues with the environment variables being different or simply not set as compared to your own variables when you manually execute. Often things like the PATH aren't set properly when cron executes something, so it's important to supply full paths to executables within the script, even for things such as perl or common commands that you thing
should
be found in the default PATH. Without more info it's hard to speculate on what precisely the problem is.


Question:
I have a git repository which tracks an svn repository. I cloned it using --stdlayout.

I created a new local branch via git checkout -b foobar

Now I want this branch to end up in …/branches/foobar in the svn repository.

How do I go about that?

(snipped lots of investigative text. see question history if you care)

Answer:
as of git v1.6.1,
```
git svn branch
```
is available.
From the git docs:
```
branch
        Create a branch in the SVN repository.

        -m, --message
            Allows to specify the commit message.

        -t, --tag
            Create a tag by using the tags_subdir instead of the branches_subdir
            specified during git svn init.
```
Previous versions of git do not provide a way to create an svn branch.


Question:
It seems that nginx is used with php, ruby and python.

Anyone has an example of how to setup nginx to work with jetty/tomcat in backend?

Thanks.

Answer:
nginx can forward via HTTP protocol, so just point it to the correct port and you're set:
```
```
server {
    location /anything {
        proxy_pass http://localhost:8080/whatever;
    }
}
```
```


Question:
This very simple code gives me tons of errors:

#include <iostream>
#include <string>

int main() {
    std::string test = " ";
    std::cout << test;
}

I tried to compile it on linux by typing gcc -o simpletest simpletest.cpp on the console. I can't see why it isn't working. What is happening?

Answer:
You declared your
```
main()
```
as returning an
```
int
```
yet you have no return statement.  Add
```
return 0;
```
and see if that helps.  If that doesn't solve your problem, try editing your post to include some representative lines from those errors your getting and maybe we can help you better.


Question:
once you have a commit that contains a submodule object, you pretty much cannot get git-svn to commit past it.

Any ideas, workarounds, anything that is not "don't use submodules with git-svn"?

So far the answer seems to be a big NO.

Is there any way to at least allow existing git commits containing submodule data to be committed to svn without the submodule data? Even if it means rewriting the tree.

Answer:
You'll need to replace the submodules with the
```
svn:externals
```
property to play nice with Subversion.
```
```
svn propset svn:externals [...]
```
```
I don't think there's any other way round it.


Question:
I just pasted some generated javadoc into an eclipse project, to discover none of the HTML is compliant.

There is even cases of closing tags that were never opened.

Is there some way to fix this? Maybe a "be compliant" option...

Answer:
After some googling, I discovered
XHTML Doclet 0.4
.
XHTML Doclet is a standards-compliant
  alternative to the Javadoc standard
  HTML doclet. The project revises the
  document structure to exclude outdated
  tags and inline styles, creates valid
  XHTML markup, and provides better
  hooks for more flexible CSS
  manipulation.
Looks like someone made a plugin.
Any better options?
Edit:
Here's the plugin's
Official page
as linked to by
Sun's Javadoc FAQ
.


Question:
I found piston seems a decent tool for managing rails plugins, but when I try to do piston convert for my project with git based plugins, it just went dead completely and seems its trying to look for .svn with svn tools.

I am on piston 1.4.0, is that git natively supported or I would have to build from edge?

Answer:
I'm using piston 1.9.x for exactly this reason - since 1.9, it has
supported Git importing
.
Instructions on installing can be found
here
.


Question:
Take the following function:

DataTable go() {
    return someTableAdapter.getSomeData();
}

When I set a breakpoint in this function, is there a possibility to inspect the returned value? go() is directly coupled to a datagrid in an .aspx page.

The only way to inspect the returned datatable is to use a temporary variable. However, that's a bit inconvenient. Isn't there another way?

Answer:
Not that I know of. Note that if you
do
add a variable, it will get removed by the compiler in release builds anyway...
Update:
This functionality has been added to VS2013
.
You can see the return values in the autos windows or use
```
$ReturnValue
```
in the watch/immediate window.
The value can only be seen directly after returning from the function, thus the easiest way to access it is by putting a breakpoint on the function call and step over (F10) the call.
Update for VS2015: boo! unfortunately, it doesn't appear to be in VS2015 (devenv v14)
Update for VS2017: it's back. (devenv v15)


Question:
When using wireframe fill mode in Direct3D, all rectangular faces display a diagonal running across due to the face being split in to two triangles. How do I eliminate this line? I also want to remove hidden surfaces. Wireframe mode doesn't do this.

I need to display a Direct3D model in isometric wireframe view. The rendered scene must display the boundaries of the model's faces but must exclude the diagonals.

Answer:
Getting rid of the diagonals is tricky as the hardware is likely to only draw triangles and it would be difficult to determine which edge is the diagonal. Alternatively, you could apply a wireframe texture (or a shader that generates a suitable texture). That would solve the hidden line issues, but would look odd as the thickness of the lines would be dependant on z distance.
Using line primitives is not trivial, although surfaces facing away from the camera can be easily removed, partially obscured surfaces would require manual clipping. As a final thought, do a two pass approach - the first pass draws the filled polygons but only drawing to the z buffer, then draw the lines over the top with suitable z bias. That would handle the partially obscured surface problem.


Question: What good ruby gem sources would you recommend, besides http://gems.rubyforge.org/ and http://gems.github.com/? It seems that RubyForge is missing most of the gems I look for these days...

Answer:
As far as I know, those two are it, with the primary being rubyforge, since that's the only source that a stock RubyGems install will search?  As popular as github is getting, gem developers still can't yet assume that github has been added as a gem source, and usually provide specific instructions like
```
```
gem sources -a http://gems.github.com
gem install person-gemname
```
```
or
```
```
gem install person-gemname --source http://gems.github.com
```
```
UPDATE
: gems.rubyforge.org, gems.github.com, and gemcutter.org have all been replaced by
```
rubygems.org
```


Question: Is there any way to catch all syscalls on Linux? The only solution I know of is using LD_PRELOAD à la fakeroot, but that only works for dynamically linked applications. Furthermore, this approach requires enumerating all syscalls which is something I'd like to avoid.

Answer:
You can trace a program. Think about how
```
strace
```
works. Hint: it doesn't use
```
LD_PRELOAD
```
tricks.


Question:
An svn repository I'm mirroring through git-svn has changed URL.

In vanilla svn you'd just do svn switch --relocate old_url_base new_url_base.

How can I do this using git-svn?

Simply changing the svn url in the config file fails.

Answer:
Git svn relies heavily on the svn URL. Every commit that is imported from svn has a
```
git-svn-id
```
that includes the svn URL.
A valid relocations strategy is to call
```
git-svn clone
```
on the new repository and merge the changes onto that new close. For a more detailed procedure, see this article:
http://www.sanityinc.com/articles/relocating-git-svn-repositories


Question: Does anybody know if there is a way to make autocompletion work in MySQL Command Line Client under Windows? It's working nicely under Linux for me, but  simply moves the cursor under Windows instead.

Answer:
It ought to work this way:
```
```
C:\> mysql --auto-rehash
```
```
Or configure your my.cnf:
```
```
[mysql]
auto-rehash
```
```
edit:
My apologies.  I have found some references that the tab-completion feature in mysql client works only on UNIX/Linux.  It does not work on Windows.
update:
The reason for this is mentioned briefly in MySQL
bug #4731
:
[31 Jul 2004 12:47] Sergei Golubchik
I just downloaded 4.0.15 - command
  completion in mysql.exe is NOT
  working, as expected. It was never
  working in mysql.exe because we were
  not able to make readline to compile
  with VC++.
mysqlc.exe is a cygwin build, and it is linked with readline.
Explanation:
GNU readline
is a standard open-source library for handling user input.  The MySQL team uses the readline library, but they are not its author.  From the above comment, I understand that they were unsuccessful in compiling the readline library on Windows with Microsoft Visual C++, the tool they use to build the MySQL product.  Some open-source projects have not been made fully compatible with the Microsoft Windows environment.
At one time in the past, the MySQL product provided an alternative client they called
```
mysqlc.exe
```
, which they compiled with the
cygwin
toolset on Windows, but they don't provide this anymore.  The cygwin toolset includes the readline library, so it was possible to compile the
```
mysqlc.exe
```
client with support for tab-completion.
So in theory, if you are really intrepid, you could download the cygwin toolset including the readline library, then download the MySQL source code and build it using cygwin.  Then you should have a mysql client program that can perform tab-completion.  But this sounds like a lot of work even for someone who is familiar with building MySQL from source.


Question: I was currently looking into memcached as way to coordinate a group of server, but came across Apache's ZooKeeper along the way. It looks interesting, and Yahoo uses it, so it shouldn't be bad, but I'd never heard of it before, so I'm kind of skeptical. Has anyone else given it a try? Any comments or ideas?

Answer:
ZooKeeper and Memcached have different purposes. You can use memcached to do server coordination, but you'll have to do most of this work yourself. Memcached only allows coordination in that it caches common data lookups to be used by multiple clients. From reading ZooKeeper's documentation, it has a much broader focus than this. ZooKeeper seems to provide support for server clustering, which isn't the same as the cache clustering memcached provides.
Have a look at Brad Fitzpatrick's Linux Journal
article
on memcached to get a better idea what I mean.


Question:
How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?

I'm trying to look for the source of the datetime module in particular, but I'm interested in a more general answer as well.

Answer:
The
```
sys.path
```
list contains the list of directories which will be searched for modules at runtime:
```
```
python -v
>>> import sys
>>> sys.path
['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', ... ]
```
```


Question:
I've uploaded a bunch of images to Amazon S3, and now want to add a Cache-Control header to them.

Can the header be updated without downloading the entire image? If so, how?

Answer:
It's beta functionality, but you can specify new meta data when you
copy an object
. Specify the same source and destination for the copy, and this has the effect of just updating the meta data on your object.
```
```
PUT /myObject HTTP/1.1
Host: mybucket.s3.amazonaws.com
x-amz-copy-source: /mybucket/myObject
x-amz-metadata-directive: REPLACE
x-amz-meta-myKey: newValue
```
```


Question:
So I'm looking for a pattern like this:

size='0x0'

In a log file, but I'm only interested in large sizes (4 digits or more). The following regex works great in EditPadPro (nice tool BTW)

size='0x[0-9a-fA-F]{4,}

But the same RegEx does not work in awk - seems like the repetition {4,} is messing it up. Same with WinGrep - any idea from the RegEx gurus? Thanks!

Answer:
I don't know of any elegant alternatives to the {4,} syntax, but if it is not working in your desired environment you could resort to this ugly hack:
```
```
size='0x[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]+
```
```
Hope this helps!
Adam


Question:
As far as i know the EAP editions of JBoss Application Server (AS) are just a bunch of community edition JBoss projects with some sugar.

So, what is the community edition of the JBoss Application Server that JBoss EAP 4.3.0 corresponds to?

Answer:
This response is really late but I came across the unanswered question in a Google search and I wanted to make sure there's a correct response.  I work for JBoss support so you can consider this a qualified answer.
JBoss EAP is the only commercially supported version of JBoss.  It contains JBoss AS and JBoss Seam.  EAP diverged (in terms of the svn branch it's built off) from JBoss AS around version 4.2.1 (not exactly, but close enough).  EAP has a 5-year lifetime and is tested and certified rigorously.  EAP has paid commercial support and patches (called CPs or cumulative patches) that are designed to maintain ABI/API stability over time while allowing for security issues and bugs to be fixed.  It is actually against policy to introduce a feature in a CP, but it happens on occasion.
If you're familiar with how
Red Hat Enterprise Linux
differs from
Fedora
, you can consider the difference to be quite similar.  The JBoss project/product split is much newer, though, so the differences are smaller.  Here's the official page describing what I've said.
http://www.jboss.com/products/community-enterprise
Cheers,
Chris


Question:
Background: I have a kubuntu laptop right now that I can't use wirelessly, i.e. I haven't got wireless assistant installed. But I have a windows laptop that I can download the debian packages seperately on a USB memory stick.

How do I install a debian package on the computer locally?

Answer:
Once you have the USB stick mounted:
```
```
dpkg --install /path/to/foo_VVV-RRR.deb
```
```
(where fooVVV-RRR.deb is the package's file name)
You can find more commands at the
Debian GNU/Linux FAQ
.
Side note: this is from the command line.  I'm not sure how to get synaptic to do it.


Question:
As title.

ruby test/functionals/whatevertest.rb doesn't work, that requires me to replace all require 'test_helper' to require File.dirname(__FILE__) + '/../test_helper'. For some reason most of those test templates have such issue, so I rather to see if there is a hack I could get around it.

Answer:
On Linux?  why not try
```
(cd test && ruby functionals/whatevertest.rb)
```
.  Note, the parentheses are important as otherwise your current directory will change to the subdirectory.  What it does is
```
fork
```
another shell, change to the subdirectory in it, and run the test.


Question:
I'm going to have my website hosted soon on a VPS or dedicated server (with Windows 2008), so I'm trying to plan ahead. I wonder whether the built-in SMTP server that comes with IIS7 is reliable enough for a production server or should I look for an alternative? I heard good things about hmailserver and best of all it's free, do you have any experience with using the bulit-in SMTP on a high traffic website.

Thanks a lot for any suggestions

Answer:
Maybe sending it via gmail is a good one :P
Ok serious.
IIS7 seems I heard to have some decent improvement.
If that's not doing it, I guess you could try free stuff like mailenable.
(No I can't find the evidence on the improvement on IIS SMTP, people who know about this please comment)
Long term you might end up split it to a linux based smtp though, that gives you some flexibility on server farming if it goes too insane.
And if its for any kind of mass mailing that might trigger spam server blocking, don't ever try to host it together with your other important stuff- you want to keep yourself have a back step if your server gets blocked.


Question: I need help converting WAV files to MP3 format in VB6. I did already find source code in C#, but I can't use that

Answer:
AFAIK, MP3 compression is under a patent, you can do that legally only by buying a license.
Or, like many other softwares, use the Lame DLL without distributing it but asking to download it in a site not under the same laws...
Somehow, that's how Opera does with GPL software: they don't provide spelling correction out of the box but they instruct to download and install aspell...
Note you can use free alternatives, like Ogg Vobis, it depends on your purpose.


Question:
Are there differences between the amount of syscalls in the major *NIX variants ?

Which syscalls would be supported universally ?

Answer:
Anything that is not a posix standard may be an additional system call, or it maybe additional library functionality above the system call layer. If your goal is to write portable code stick to posix, and use the c library (as opposed to direct system calls) as much as possible.
If you are just curious, they vary quite widely. You do not need to support much in the way of system calls in order to be posix compliant. It specifies interfaces you need to support, but whether you do that through calling into the kernel or jumping into a shared library is pretty much up to you.
Mac OS X does not even guarantee binary compatibility for system calls between releases, they consider them private interfaces between the system libraries and the OS. What most people consider to be system calls are actually small stubs in a dynamic library that call through to the kernel, and if you make the system calls directly instead of linking to that dynamic library and calling the stub functions then your code may break between OS releases.
That flexibility means a number of OSes implement system calls that are completely different from what they need to support posix, then deal with the differences in their libraries. For example, Linux's threading implementation is based around a system call called clone(), and they deal with much of the bookkeeping to make the pthreads interface work in their libraries.
So if your goal is to implement a standard library the does not link against anything else and works on multiple unixes, you may find things a bit tricky in some cases. If your goal is to write something that links against the standard libraries on various Unixes you can get a generally uniform interface.


Question:
Can any one tell me what files I need to submit to the Apple appstore when I submit my application?

As an example, do the Resource file, Digital Developer certificate files and others need to be submitted?

Please help me understand this process, or show me a resource on the web where I can learn more.

Answer:
This is pretty well documented by Apple in the "
iPhone Developer Program Portal User Guide
" -- see the Distribution section starting on page 28.
The only files you send them are screen-shots of your app, a large version of the icon and a zipped copy of your app. The resource file, certificate, etc. are all included in the copy of your app or used to build/sign your app.


Question: I have a Perl module that I would like to use from Java. Is there a way to call this code using either ActiveState Perl on Windows or the generic Perl that comes with Linux? I have found references to JPL but it doesn’t appear to be maintained anymore.

Answer:
Inline-Java
is the usual library to call java from Perl, and this
post propose a
org.perl.java
module which should allow calling Perl from Java, as asked.
However, because of the unpredictability of the JNI implementations for different
JVMs it is difficult to say what combinations of JVM and Perl will work. Typically, what is required is Perl with MULTIPLICITY, and threads compiled in. That means he uses a custom built Perl.
Otherwise,
Inline::Java::Callback
allows you to call Perl functions from Java. To do this you need to create an
```
org.perl.inline.java.InlinePerlCaller
```
object. Here is a example of a typical use:
```
```
use Inline Java => <<END ;
import java.util.* ;
import org.perl.inline.java.* ;

class Pod_regexp extends InlineJavaPerlCaller {
    public Pod_regexp() throws InlineJavaException {
    }

    public boolean match(String target, String pattern)
        throws InlineJavaException {
        try {
            String m = (String)CallPerlSub("main::regexp",
            new Object [] {target, pattern}) ;

            if (m.equals("1")){
            return true ;
        }
    }
    catch (InlineJavaPerlException pe){
        // $@ is in pe.GetObject()
    }

    return false ;
    }
}
END

my $re = new Pod_regexp() ;
my $match = $re->match("Inline::Java", "^Inline") ;
print($match . "n") ; # prints 1

sub regexp {
    my $target = shift ;
    my $pattern = shift ;

    return ($target =~ /$pattern/) ;
}
```
```


Question: I would like to be able to set "Extend my Windows desktop onto this monitor" via code. A PowerShell script would be ideal. WMI seems the way forward but I have zero knowledge in WMI.

Answer:
One first possible solution is... through the GUI (but without user interaction)
VB script
(also
described here
but in
Autoit
language):
```
```
Option Explicit
Dim WshShell, Dummy, Splash

On Error Resume Next

Set WshShell = WScript.CreateObject("WScript.Shell")

'Main
Call DoIt
WScript.Quit

Sub DoIt
wshshell.Run("%systemroot%\system32\control.exe desk.cpl,@0,3")

' Give Display Properties time to load
WScript.Sleep 1000
WshShell.SendKeys "2"
WScript.Sleep 10
WshShell.SendKeys "%E"
WScript.Sleep 500
WshShell.SendKeys "%A"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{ENTER}"
End Sub 'DoIt
```
```
In Autoit, that would be:
```
```
;
; — toggle-screen.au3
;

; exec cpanel app `display settings`
Run(”C:\WINDOWS\system32\control.exe desk.cpl,@0,3?”)

; wait for window to be active
WinWaitActive(”Display Settings”)

; select 2nd display
Send(”{TAB}”)
Send(”{DOWN}”)

; work back to the ‘extend desktop’ control
Send(”+{TAB}”)
Send(”+{TAB}”)
Send(”+{TAB}”)
Send(”+{TAB}”)
Send(”+{TAB}”)
Send(”+{TAB}”)
Send(”+{TAB}”)
Send(”+{TAB}”)
Send(”+{TAB}”)

; toggle ‘extend desktop’ control and apply
Send(”{SPACE}”)
Send(”{ENTER}”)

; wait for window to be active
WinWaitActive(”Display Settings”)

; accept
Send(”{TAB}”)
Send(”{ENTER}”)

;
; — E.O.F.
;
```
```


Question: I'm writing a Linux kernel module that needs to open and read files. What's the best way to accomplish that?

Answer:
assuming you can get pointers to the relavent function pointers to the
```
open
```
/
```
read
```
/
```
close
```
system calls, you can do something like this:
```
```
mm_segment_t fs = get_fs();
set_fs(KERNEL_DS);

fd = (*syscall_open)(file, flags, mode);
if(fd != -1) {
    (*syscall_read)(fd, buf, size);
    (*syscall_close)(fd);
}
set_fs(fs);
```
```
you will need to create the "
```
syscall_*
```
" function pointers I have shown though. I am sure there is a better way, but I believe that this would work.


Question:
I use the dark-blue2 color theme but it seems ugly under console.
So I want to use no color theme under terminal, what can I do then?

Answer:
Set a "TERM" variable corresponding to a monochrome terminal before launching Emacs. For example, if you are in an xterm, use:
```
```
TERM=xterm-mono emacs -nw
```
```
If by "console" you mean the Linux console in text mode, you can try using "vt100" (or "vt320") instead.


Question:
How would I go about having a CMake buildsystem, which scans for source files now using AUX_SOURCE_DIRECTORY, scan for header files too in the same directory, preferably using a similar command?

I didn't find an easy way to do this in the documentation yet, so I now have a crappy bash script to post-process my (CodeBlocks) project file...

Answer:
The documentation to AUX_SOURCE_DIRECTORY suggests that it was not intended to be used that way, so I'd rather doubt that what you're asking is possible. If you want an authoritative answer, you can reach the CMake developers at cmake@cmake.org (they're actually very nice to deal with).
I'd recommend strongly against using wildcards to specify what is included in the build. The build files should specify the exact contents of the libraries, and not depend on what happens to exist in the directory. It may be cumbersome at first (if you're used to wildcards, or IDE's which works the same way), but when you get used to it, you don't want to have it any other way.


Question: I'm brand new to jQuery and have some experience using Prototype. In Prototype, there is a method to "flash" an element — ie. briefly highlight it in another color and have it fade back to normal so that the user's eye is drawn to it. Is there such a method in jQuery? I see fadeIn, fadeOut, and animate, but I don't see anything like "flash". Perhaps one of these three can be used with appropriate inputs?

Answer:
Would a
pulse effect
(offline) JQuery plugin be appropriate for what you are looking for ?
You can add a duration for limiting the pulse effect in time.
As mentioned by
J-P
in the comments, there is now
his
updated pulse plugin
.
See his
GitHub repo
. And here is
a demo
.


Question: I am interested if there is a port for the server implementation.

Answer:
Windows Server ports:
memcached for Win32
Jellycan Code - memcached
Memcached .NET Client ports:
memcacheddotnet
enyim.com Memcached Client
BeIT


Question:
I have noticed that our VMWare VMs often have the incorrect time on them. No matter how many times I reset the time they keep on desyncing.

Has anyone else noticed this? What do other people do to keep their VM time in sync?

Edit: These are CLI linux VMs btw..

Answer:
The CPU speed varies due to power saving. I originally noticed this because VMware gave me a helpful tip on my laptop, but this page mentions the same thing:
Quote from :
VMWare tips and tricks
Power saving (SpeedStep, C-states, P-States,...)
Your power saving settings may interfere significantly with vmware's performance. There are several levels of power saving.
CPU frequency
This should not lead to performance degradation, outside of having the obvious lower performance when running the CPU at a lower frequency (either manually of via governors like "ondemand" or "conservative"). The only problem with varying the CPU speed while vmware is running is that the Windows clock will gain of lose time. To prevent this, specify your full CPU speed in kHz in /etc/vmware/config
host.cpukHz = 2167000


Question:
Do you have pseudocode for field validation of the following items in the UK? I am from the USA, so I only know the ones in the USA right now.

Address Line 1

Phone Number

Mobile Number (in case they have a special rule for this, which they might not)

Post Code

Answer:
Address line 1 could be almost anything. There aren't always house numbers.
Phone numbers: the length of an area code varies. I wouldn't like to swear whether the full length is constant, but I suspect it's always at least 10 digits. Mobile numbers typically (IME) start with 07 whereas landlines typeically start with 01 or 02. Special numbers (free, local rate etc) typically start with 08. I'll try to find a reference for this. (EDIT: Again, there's a good
Wikipedia article
.)
Wikipedia has a
good article about UK postcodes
, including regular expressions for them.


Question:
My schema specifies a namespace, but the documents don't. What's the simplest way to ignore namespace during JAXB unmarshalling (XML -> object)?

In other words, I have

<foo><bar></bar></foo>

instead of,

<foo xmlns="http://tempuri.org/"><bar></bar></foo>

Answer:
I believe you must
add the namespace
to your xml document, with, for example, the use of a
SAX filter
.
That means:
Define a ContentHandler interface with a new class which will intercept SAX events before JAXB can get them.
Define a XMLReader which will set the content handler
then link the two together:
```
```
public static Object unmarshallWithFilter(Unmarshaller unmarshaller,
java.io.File source) throws FileNotFoundException, JAXBException
{
    FileReader fr = null;
    try {
        fr = new FileReader(source);
        XMLReader reader = new NamespaceFilterXMLReader();
        InputSource is = new InputSource(fr);
        SAXSource ss = new SAXSource(reader, is);
        return unmarshaller.unmarshal(ss);
    } catch (SAXException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } catch (ParserConfigurationException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } finally {
        FileUtil.close(fr); //replace with this some safe close method you have
    }
}
```
```


Question: In PHP, is there an easy way to convert a number to a word? For instance, 27 to twenty-seven.

Answer:
I
found
some (2007/2008) source-code online and as it is copyright but I can use it freely and modify it however I want, so I place it here and re-license under CC-Wiki:
```
```
<?php
/**
 * English Number Converter - Collection of PHP functions to convert a number
 *                            into English text.
 *
 * This exact code is licensed under CC-Wiki on Stackoverflow.
 * http://creativecommons.org/licenses/by-sa/3.0/
 *
 * @link     http://stackoverflow.com/q/277569/367456
 * @question Is there an easy way to convert a number to a word in PHP?
 *
 * This file incorporates work covered by the following copyright and
 * permission notice:
 *
 *   Copyright 2007-2008 Brenton Fletcher. http://bloople.net/num2text
 *   You can use this freely and modify it however you want.
 */

function convertNumber($number)
{
    list($integer, $fraction) = explode(".", (string) $number);

    $output = "";

    if ($integer{0} == "-")
    {
        $output = "negative ";
        $integer    = ltrim($integer, "-");
    }
    else if ($integer{0} == "+")
    {
        $output = "positive ";
        $integer    = ltrim($integer, "+");
    }

    if ($integer{0} == "0")
    {
        $output .= "zero";
    }
    else
    {
        $integer = str_pad($integer, 36, "0", STR_PAD_LEFT);
        $group   = rtrim(chunk_split($integer, 3, " "), " ");
        $groups  = explode(" ", $group);

        $groups2 = array();
        foreach ($groups as $g)
        {
            $groups2[] = convertThreeDigit($g{0}, $g{1}, $g{2});
        }

        for ($z = 0; $z < count($groups2); $z++)
        {
            if ($groups2[$z] != "")
            {
                $output .= $groups2[$z] . convertGroup(11 - $z) . (
                        $z < 11
                        && !array_search('', array_slice($groups2, $z + 1, -1))
                        && $groups2[11] != ''
                        && $groups[11]{0} == '0'
                            ? " and "
                            : ", "
                    );
            }
        }

        $output = rtrim($output, ", ");
    }

    if ($fraction > 0)
    {
        $output .= " point";
        for ($i = 0; $i < strlen($fraction); $i++)
        {
            $output .= " " . convertDigit($fraction{$i});
        }
    }

    return $output;
}

function convertGroup($index)
{
    switch ($index)
    {
        case 11:
            return " decillion";
        case 10:
            return " nonillion";
        case 9:
            return " octillion";
        case 8:
            return " septillion";
        case 7:
            return " sextillion";
        case 6:
            return " quintrillion";
        case 5:
            return " quadrillion";
        case 4:
            return " trillion";
        case 3:
            return " billion";
        case 2:
            return " million";
        case 1:
            return " thousand";
        case 0:
            return "";
    }
}

function convertThreeDigit($digit1, $digit2, $digit3)
{
    $buffer = "";

    if ($digit1 == "0" && $digit2 == "0" && $digit3 == "0")
    {
        return "";
    }

    if ($digit1 != "0")
    {
        $buffer .= convertDigit($digit1) . " hundred";
        if ($digit2 != "0" || $digit3 != "0")
        {
            $buffer .= " and ";
        }
    }

    if ($digit2 != "0")
    {
        $buffer .= convertTwoDigit($digit2, $digit3);
    }
    else if ($digit3 != "0")
    {
        $buffer .= convertDigit($digit3);
    }

    return $buffer;
}

function convertTwoDigit($digit1, $digit2)
{
    if ($digit2 == "0")
    {
        switch ($digit1)
        {
            case "1":
                return "ten";
            case "2":
                return "twenty";
            case "3":
                return "thirty";
            case "4":
                return "forty";
            case "5":
                return "fifty";
            case "6":
                return "sixty";
            case "7":
                return "seventy";
            case "8":
                return "eighty";
            case "9":
                return "ninety";
        }
    } else if ($digit1 == "1")
    {
        switch ($digit2)
        {
            case "1":
                return "eleven";
            case "2":
                return "twelve";
            case "3":
                return "thirteen";
            case "4":
                return "fourteen";
            case "5":
                return "fifteen";
            case "6":
                return "sixteen";
            case "7":
                return "seventeen";
            case "8":
                return "eighteen";
            case "9":
                return "nineteen";
        }
    } else
    {
        $temp = convertDigit($digit2);
        switch ($digit1)
        {
            case "2":
                return "twenty-$temp";
            case "3":
                return "thirty-$temp";
            case "4":
                return "forty-$temp";
            case "5":
                return "fifty-$temp";
            case "6":
                return "sixty-$temp";
            case "7":
                return "seventy-$temp";
            case "8":
                return "eighty-$temp";
            case "9":
                return "ninety-$temp";
        }
    }
}

function convertDigit($digit)
{
    switch ($digit)
    {
        case "0":
            return "zero";
        case "1":
            return "one";
        case "2":
            return "two";
        case "3":
            return "three";
        case "4":
            return "four";
        case "5":
            return "five";
        case "6":
            return "six";
        case "7":
            return "seven";
        case "8":
            return "eight";
        case "9":
            return "nine";
    }
}
```
```


Question:
I keep stumbling on the format specifiers for the printf() family of functions.  What I want is to be able to print a double (or float) with a maximum given number of digits after the decimal point.  If I use:

printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);

I get

359.013
359.010

Instead of the desired

359.013
359.01

Can anybody help me?

Answer:
To get rid of the trailing zeros, you should use the "%g" format:
```
```
float num = 1.33;
printf("%g", num); //output: 1.33
```
```
After the question was clarified a bit, that suppressing zeros is not the only thing that was asked, but limiting the output to three decimal places was required as well. I think that can't be done with sprintf format strings alone. As
Pax Diablo
pointed out, string manipulation would be required.


Question:
So, lets say I have a number 123456.  123456 % 97 = 72.  How can I determine what two digits need to be added to the end of 123456 such that the new number % 97 = 1?  Note--it must always be two digits.

For example, 12345676 % 97 = 1.  In this case, I need to add the digits "76" to the end of the number.

(This is for IBAN number calculation.)

Answer:
```
```
x = 123456

x = x * 100
newX = x + 1 + 97 - (x % 97)
```
```
Edit: put the 100 in the wrong place


Question: Is there any c library to get a video from the webcam on linux?

Answer:
Your best bet is probably:
video4linux (V4L)
It's easy to use, and powerful.


Question:
How do I view the history of an individual file with complete details of what has changed?

git log -- [filename] shows me the commit history of a file, but how do I see the file content that changed?

Answer:
If you're using the
Git GUI
(on Windows):
Under the
```
Repository
```
menu, you can use
```
Visualize master's History
```
.
Highlight a commit in the top pane and a file in the lower right and you'll see the diff for that commit in the lower left.


Question:
Why do Linux distros have different package managers?

I find this very strange because other software such as text editors, desktop environments and graphics software (Inkscape, Blender, GIMP) are shared among distributions. Why not have a common setup tool?

Answer:
There are also many different text-editors, desktop-environments and so on. The different distributions share this only, because they provide all these programs.
But they have to decide for one package-manager. Different package-manager wouldn't know about software installed by another package-manager. So distributions decide for one or develop one themself, tailored to their specific needs.
Two very common package managers are RPM and apt, that are both used by different distributions.


Question: Using C or C++, After I decrypt a file to disk- how can I guarantee it is deleted if the application crashes or the system powers off and can't clean it up properly?  Using C or C++, on Windows and Linux?

Answer:
Try to avoid it completely:
If the file is sensitive, the best bet is to not have it written to disk in a decrypted format in the first place.
Protecting against crashes: Structured exception handling:
However, you could add structured exception handling to catch any crashes.
__try and __except
What if they pull the plug?:
There is a way to protect against this...
If you are on windows, you can use MoveFileEx and the option MOVEFILE_DELAY_UNTIL_REBOOT with a destination of NULL to delete the file on the next startup.  This will protect against accidental computer shutdown with an undeleted file.  You can also ensure that you have an exclusively opened handle to this file (specify no sharing rights such as FILE_SHARE_READ and use CreateFile to open it).  That way no one will be able to read from it.
Other ways to avoid the problem:
All of these are not excuses for having a decrypted file on disk, but:
You could also consider writing to a file that is larger than MAX_PATH via file syntax of \\?\.   This will ensure that the file is not browsable by windows explorer.
You should set the file to have the temporary attribute
You should set the file to have the hidden attribute


Question: If I'm reading a text file in shared access mode and another process truncates it, what is the easiest way to detect that?  (I'm excluding the obvious choice of refreshing a FileInfo object periodically to check its size)  Is there some convenient way to capture an event?  (Filewatcher?)

Answer:
There is,
It's called
FileSystemWatcher
.
If you are developing a windows forms application, you can drag-and-drop it from the toolbox.
Here's some usage example:
```
```
private void myForm_Load(object sender, EventArgs e)
{
    var fileWatcher = new System.IO.FileSystemWatcher();

    // Monitor changes to PNG files in C:\temp and subdirectories
    fileWatcher.Path = @"C:\temp";
    fileWatcher.IncludeSubdirectories = true;
    fileWatcher.Filter = @"*.png";

    // Attach event handlers to handle each file system events
    fileWatcher.Changed += fileChanged;
    fileWatcher.Created += fileCreated;
    fileWatcher.Renamed += fileRenamed;

    // Start monitoring!
    fileWatcher.EnableRaisingEvents = true;
}

void fileRenamed(object sender, System.IO.FileSystemEventArgs e)
{
    // a file has been renamed!
}

void fileCreated(object sender, System.IO.FileSystemEventArgs e)
{
    // a file has been created!
}

void fileChanged(object sender, System.IO.FileSystemEventArgs e)
{
    // a file is modified!
}
```
```
It's in System.IO and System.dll so you should be able to use it in most type of projects.


Question: I'm considering using Amazon's EC2 with a windows instance & SQL. I've seen some criticism of the perf of the SQL instances here. I'm wondering if any SOers have and first  hand experience and can comment on the performance.

Answer:
I've just fired up a 32bit Server 2003 m1 small instance with SQL 2005 Express on and had a quick play. Was just using the supplied machine disk, not an attached volume. After reading the article linked to in your post I was expecting performance to be horrific. It wasn't great, but wasn't bad either.
My 'tests' were rather simple. Created a table with an identity column, a few text (varchar) colomns and a few more integer foreign key columns with relationships to some basic lookups.
It took about a minute to insert 1 million records, and about a second to make updates to 200,000 row blocks of data using Like '% to force a table scan.
This doesn't tell us anything about what performance will be like under heavy load.
Conclusion: Not great, but could be worse - especially given the manner in which 'disks' are stored on aws. I don't think this is really the place for a big SQL Server installation, lots of small installations might be a more insteresting prospect.
I'd also be interested to see what performance was like with the db spead over lots of small attached volumes.
I'm hoping to use EC2 for an upcoming project and will be doing some more thorough testing over the next few weeks. - I'll post the results as they're available.
Looking forward to seeing what other peoples experiences have been..


Question:
I am trying to write a C program that uses dlysm, and I keep getting an undefined reference to dlysm. I think I need to set my -ldl flags but I have no idea how to do this.

I am very new to linux and setting variables. If this is what I need to do can someone help me out with the commands?

Answer:
Pass
```
-ldl
```
as a parameter to the compiler.
Example:
```
```
gcc myprog.c -o app -ldl
```
```


Question: I am creating menus in WPF programatically using vb.net.  Can someone show me how I can add separator bar to a menu in code?  No xaml please.

Answer:
WPF has a
Separator
control for just that purpose and it also separates your menu items when the appear on a toolbar. From the MSDN docs:
A Separator control draws a line,
  horizontal or vertical, between items
  in controls, such as ListBox, Menu,
  and ToolBar. Separator controls do not
  react to any keyboard, mouse, mouse
  wheel, or tablet input and cannot be
  enabled or selected.
In code:
```
```
using System.Windows.Controls;

//

Menu myMenu = new Menu();
myMenu.Items.Add(new Separator());
```
```