Question:
I am trying to figure out what is the 'grafts' in the Git.

For example, in one of the latest comments here, Tobu suppose to use git-filter-branch and .git/info/grafts to join two repositories.

But I don't understand why I need these grafts? It seems, that all work without last two commands.

Answer:
From
Git Wiki
:
Graft points or grafts enable two
  otherwise different lines of
  development to be joined together. It
  works by letting users record fake
  ancestry information for commits. This
  way you can make git pretend the set
  of parents a commit has is different
  from what was recorded when the commit
  was created.
Reasons for Using Grafts
Grafts can be useful when moving
  development to git, since it allows
  you to make cloning of the old history
  imported from another SCM optional.
  This keeps the initial clone for users
  who just wants to follow the latest
  version down while developers can have
  the full development history
  available.
When Linus started using git for
  maintaining his kernel tree there
  didn't exist any tools to convert the
  old kernel history. Later, when the
  old kernel history was imported into
  git from the bkcvs gateway, grafts was
  created as a method for making it
  possible to tie the two different
  repositories together.


Question: I guess I need to know what I need in the classpath (what jar) in order to execute WebSphere 6.1 ant tasks. If someone can provide an example that would be perfect.

Answer:
The Actual Websphere Ant tasks are defined in
```
wsanttasks.jar
```
.
A possible path for linux Systems is
```
/opt/IBM/WebSphere/AppServer/lib/wsanttasks.jar
```
However I doubt that you will be successfull just by including that, as I do remember trying it once and it failed because of dependecies.
However, it is not impossible to do it as
```
ws_ant
```
is just a wrapper script which adds
all the required classpaths and calls the inbuilt ant
. So if you have time to look into the
```
ws_ant
```
script you will be able to get all the required classpath's.
By the way is there any special reason why you want to avoid
```
ws_ant
```
, that will surely make your life simple.


Question:
I'm working on a configuration script for a JNI wrapper. One of the configuration parameters is the path to jni.h. What's a good quick-and-dirty Autoconf test for whether this parameter is set correctly for C++ compilation? You can assume you're running on Linux and g++ is available.

Alternatively, is there a way to get javah (or a supporting tool) to give me this path directly?

Answer:
Checking for headers is easy; just use
```
AC_CHECK_HEADER
```
. If it's in a weird place (i.e., one the compiler doesn't know about), it's entirely reasonable to expect users to set
```
CPPFLAGS
```
.
The hard part is actually locating
```
libjvm
```
. You typically don't want to link with this; but you may want to default to a location to
```
dlopen
```
it from if
```
JAVA_HOME
```
is not set at run time.
But I don't have a better solution than requiring that
```
JAVA_HOME
```
be set at configure time. There's just too much variation in how this stuff is deployed across various OSes (even just Linux distributions). This is what I do:
```
```
AC_CHECK_HEADER([jni.h], [have_jni=yes])
AC_ARG_VAR([JAVA_HOME], [Java Runtime Environment (JRE) location])
AC_ARG_ENABLE([java-feature],
              [AC_HELP_STRING([--disable-java-feature],
                              [disable Java feature])])
case $target_cpu in
     x86_64) JVM_ARCH=amd64 ;;
     i?86)   JVM_ARCH=i386 ;;
     *)      JVM_ARCH=$target_cpu ;;
esac
AC_SUBST([JVM_ARCH])
AS_IF([test X$enable_java_feature != Xno],
[AS_IF([test X$have_jni != Xyes],
       [AC_MSG_FAILURE([The Java Native Interface is required for Java feature.])])
AS_IF([test -z "$JAVA_HOME"],
[AC_MSG_WARN([JAVA_HOME has not been set.  JAVA_HOME must be set at run time to locate libjvm.])],
[save_LDFLAGS=$LDFLAGS
LDFLAGS="-L$JAVA_HOME/lib/$JVM_ARCH/client -L$JAVA_HOME/lib/$JVM_ARCH/server $LDFLAGS"
AC_CHECK_LIB([jvm], [JNI_CreateJavaVM], [LIBS=$LIBS],
             [AC_MSG_WARN([no libjvm found at JAVA_HOME])])
LDFLAGS=$save_LDFLAGS
])])
```
```


Question:
How can I dock a CControlBar derived window to the middle of a splitter window (CSplitterWnd)?  I would like the bar to be repositioned whenever the splitter is moved.

To make it a little clearer as to what I'm after, imagine the vertical ruler in the Dialog Editor in Visual Studio (MFC only).  It gets repositioned whenever the tree view is resized.

Answer:
Serge,
I apologize, I wasn't very clear.  The splitter would be between the resource view and the ruler bar.  It would looke like this:
Resource View | Vertical ruler | View
In any case, I found the (now obvious) answer: split the main frame into three windows:
```
```
m_wndSplitter.CreateStatic(this, 1, 3);

m_wndLeftPane.Create(&m_wndSplitter,WS_CHILD|WS_VISIBLE,m_wndSplitter.IdFromRowCol(0, 0));
m_ruler.Create(&m_wndSplitter,WS_CHILD|WS_VISIBLE,m_wndSplitter.IdFromRowCol(0, 1));

m_wndSplitter.CreateView(0, 2, pContext->m_pNewViewClass, CSize(300, 0), pContext);
SetActiveView((CScrollView*)m_wndSplitter.GetDlgItem(m_wndSplitter.IdFromRowCol(0, 2)));
```
```


Question: Can someone please provide an implementation of a C function that gets invoked to dump the current stack? It's for a x86 linux system.  It can be invoked in 2 ways: explicitly by another function, or after a crash (probably as a trap/int handler).  The output can be either to the screen or to a file, as indicated by a parameter (handle).  A clear explanation/comments of how the stack is unwound would obviously be very helpful.  Thank you.

Answer:
following on Adam's answer, the source code that shows how to perform the actual stack backtracing is in gnu libc's backtrace(), under /libc/debug/backtrace.c  - not sure if the full link below will be accepted by stackoverflow's html filters...
http://cvs.savannah.gnu.org/viewvc/*checkout*/libc/debug/backtrace.c?root=libc&revision=1.1.2.1&content-type=text%2Fplain


Question:
Here's a link to Windows documentation.

Basically I would like to get similar data, but on Linux. If not all is possible, then at least some parts.

Answer:
Look at the pseudo-files under
```
/proc/<PID>/
```
. Maybe you can find what you need there.
Look at
```
man 5 proc
```
, or failing that the kernel documentation. However, I don't see much that looks promising. Sorry.


Question:
This seems very noisy to me. Five lines of overhead is just too much.

m_Lock.EnterReadLock()
Try
    Return m_List.Count
Finally
    m_Lock.ExitReadLock()
End Try

So how would you simply this?

Answer:
I ended up doing this, but I'm still open to better ways or flaws in my design.
```
```
Using m_Lock.ReadSection
    Return m_List.Count
End Using
```
```
This uses this extension method/class:
```
```
<Extension()> Public Function ReadSection(ByVal lock As ReaderWriterLockSlim) As ReadWrapper
    Return New ReadWrapper(lock)
End Function

Public NotInheritable Class ReadWrapper
    Implements IDisposable

    Private m_Lock As ReaderWriterLockSlim
    Public Sub New(ByVal lock As ReaderWriterLockSlim)
        m_Lock = lock
        m_Lock.EnterReadLock()
    End Sub
    Public Sub Dispose() Implements IDisposable.Dispose
        m_Lock.ExitReadLock()
    End Sub

End Class
```
```


Question:
I would like to write a driver to talk to my Suunto t3 watch in Python on a Mac. My day job is doing basic web work in C# so my familiarity with Python and developing on a Mac is limited.

Can you suggest how one would start doing driver development in general and then more specifically on a Mac. I.e. how to easily see what data is being transmitted to the device? I have Python 2.5 (MacPorts) up and running.

Answer:
If the watch supports a
standard USB device class specification
such as HID or serial communication, there might already be a Macintosh driver for it built into the OS. Otherwise, you're going to have to get information about the vendor commands used to communicate with it from one of three sources: the manufacturer; reverse engineering the protocol used by the Windows driver; or from others who have already reverse engineered the protocol in order to support the device on Linux or BSD.
USB is a packet-based bus and it's very important to understand the various transaction types. Reading the
USB specification
is a good place to start.
You can see what data is being transmitted to the device using a USB bus analyzer, which is an expensive proposition for a hobbyist but is well within the reach of most businesses doing USB development. For example, the
Catalyst Conquest
is $1199. Another established manufacturer is
LeCroy (formerly CATC)
. There are also software USB analyzers that hook into the OS's USB stack, but they don't show all of the traffic on the bus, and may not be as reliable.
I'm not a Mac expert, so take this paragraph with a grain of salt: Apple has a driver development kit called the
I/O Kit
, which apparently requires you to write your driver in C++, unless they also have some sort of user-mode driver framework. If you're writing it in Python, it will probably be more like a Python library that interfaces to someone else's (Apple's?) generic USB driver.


Question:
Where can I find a free, very quick, and reliable implementation of FFT in C#?

That can be used in a product? Or are there any restrictions?

Answer:
AForge.net
is a free (open-source) library with Fast Fourier Transform support. (See Sources/Imaging/
ComplexImage.cs
for usage, Sources/Math/
FourierTransform.cs
for implemenation)


Question: I have a web site using apache httpd as the server and mysql as the backend. It publishes a "thought for the day" that has gotten so popular that the server is crashing due to the number of requests. Since the same page is been requested (the thought only changes once a day), is it possible to put a caching server in front of my main server, so that when the same request is made by different clients, the caching server returns the page without having to go to the database?

Answer:
Absolutely.  There are many products that will work well for this.  Apache itself can be configured to function this way although, if you are on Linux or UNIX, Squid is the better option as it is specifically designed to do this very job.
On Windows, MS has always offered cache/proxy products that will do this function.  Currently this is ISA Server 2006.  Although this is dramatically overkill for this type of application.
Squid
is my recommendation.


Question: In C/C++, how would I turn a blocking socket into a non blocking socket in both WinSocks and *nix; so that select() would work correctly. You can use the pre-processor for the platform specific code.

Answer:
On linux:
```
```
fcntl(fd, F_SETFL, O_NONBLOCK);
```
```
Windows
:
```
```
u_long on = 1;
ioctlsocket(fd, FIONBIO, &on);
```
```


Question: I want my Ruby program to do different things on a Mac than on Windows. How can I find out on which system my program is running?

Answer:
Either
```
```
irb(main):002:0> require 'rbconfig'
=> true
irb(main):003:0> Config::CONFIG["arch"]
=> "i686-linux"
```
```
or
```
```
irb(main):004:0> RUBY_PLATFORM
=> "i686-linux"
```
```


Question: We want to be able to advance our business by utilizing both of the power of KOFAX and SharePoint 2007. Any pointers Development-wise?

Answer:
We looked into doing something like this a couple of years ago. We were thinking of having printed documents scanned in, converted with OCR, and organized digitally in a type of repository.
We actually did an analysis of OCR tools and repository / collaboration tools and which would be the easiest to integrate. We checked out Kofax, OCR for AnyDoc, and a couple of others on the OCR side, and SharePoint WSS, SharePoint MOSS, Hyland OnBase, SAP Collaboration Manager, and Documentum on the repository / collaboration side.
Your idea is good, and there are variants of it in use in banking and other industries. As for the integration, in my experience if you're using SharePoint, it should be pretty easy with Kofax if you leverage the API's on both sides and get creative with simple web parts and iFrames.
KA


Question:
I'm about to deal with managing and running my first Internet connected Apache webserver and I was wondering if there are any sys admins and developers out there that would like to share some of their knowledge regarding security and optimization tips for running Apache webserver.

Maybe you can share your top five (or ten) list of things you immediately do after installing Apache webserver (on a Linux box).

Any help very much appreciated.

Answer:
Ensure the Apache process isn't running as root.
Be sure to be on the latest stable release
If the box is
directly connected to the internet
ensure you have thought about all
other services, like ssh.
Carefully inspect your local firewall rules, tighten it down. (See iptables)
Don't turn on options you don't understand or don't plan to use
Consider subscribing to an Apache security mailing list so you'll learn right away of any critical patches


Question:
I need to be able to merge two (very simple) JavaScript objects at runtime.  For example I'd like to:

var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }

obj1.merge(obj2);

//obj1 now has three properties: food, car, and animal

Is there a built in way to do this?  I do not need recursion, and I do not need to merge functions, just methods on flat objects.

Answer:
ECMAScript 2018 Standard Method
You would use
object spread
:
```
```
let merged = {...obj1, ...obj2};
```
```
```
merged
```
is now the union of
```
obj1
```
and
```
obj2
```
. Properties in
```
obj2
```
will overwrite those in
```
obj1
```
.
```
```
/** There's no limit to the number of objects you can merge.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = {...obj1, ...obj2, ...obj3};
```
```
Here is also the
MDN documentation
for this syntax. If you're using babel you'll need the
babel-plugin-transform-object-rest-spread
plugin for it to work.
ECMAScript 2015 (ES6) Standard Method
```
```
/* For the case in question, you would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects you can merge.
 *  All objects get merged into the first object.
 *  Only the object in the first argument is mutated and returned.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);
```
```
(see
MDN JavaScript Reference
)
Method for ES5 and Earlier
```
```
for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
```
```
Note that this will simply add all attributes of
```
obj2
```
to
```
obj1
```
which might not be what you want if you still want to use the unmodified
```
obj1
```
.
If you're using a framework that craps all over your prototypes then you have to get fancier with checks like
```
hasOwnProperty
```
, but that code will work for 99% of cases.
Example function:
```
```
/**
 * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
 * @param obj1
 * @param obj2
 * @returns obj3 a new object based on obj1 and obj2
 */
function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}
```
```


Question:
int x = n / 3;  // <-- make this faster

// for instance

int a = n * 3; // <-- normal integer multiplication

int b = (n << 1) + n; // <-- potentially faster multiplication

Answer:
I don't know if it's faster but if you want to use a bitwise operator to perform binary division you can use the shift and subtract method described at
this page
:
Set quotient to 0
Align leftmost digits in dividend and divisor
Repeat:
If that portion of the dividend above the divisor is greater than or equal to the divisor:
Then subtract divisor from that portion of the dividend and
Concatentate 1 to the right hand end of the quotient
Else concatentate 0 to the right hand end of the quotient
Shift the divisor one place right
Until dividend is less than the divisor:
quotient is correct, dividend is remainder
STOP


Question:
See also:

  How can I see which Git branches are tracking which remote / upstream branch?

How can I find out which remote branch a local branch is tracking?

Do I need to parse git config output, or is there a command that would do this for me?

Answer:
I use
EasyGit (a.k.a. "eg")
as a super lightweight wrapper on top of (or along side of) Git.  EasyGit has an "info" subcommand that gives you all kinds of super useful information, including the current branches remote tracking branch.  Here's an example (where the current branch name is "foo"):
```
pknotz@s883422: (foo) ~/workspace/bd
$ eg info
Total commits:      175
Local repository: .git
Named remote repositories: (name -> location)
  origin -> git://sahp7577/home/pknotz/bd.git
Current branch: foo
  Cryptographic checksum (sha1sum): bd248d1de7d759eb48e8b5ff3bfb3bb0eca4c5bf
  Default pull/push repository: origin
  Default pull/push options:
    branch.foo.remote = origin
    branch.foo.merge = refs/heads/aal_devel_1
  Number of contributors:        3
  Number of files:       28
  Number of directories:       20
  Biggest file size, in bytes: 32473 (pygooglechart-0.2.0/COPYING)
  Commits:       62
```


Question:
Is it possible to check a bash script syntax without executing it?

Using Perl, I can run perl -c 'script name'. Is there any equivalent command for bash scripts?

Answer:
```
```
bash -n scriptname
```
```
Perhaps an obvious caveat: this validates syntax but won't check if your bash script tries to execute a command that isn't in your path, like
```
ech hello
```
instead of
```
echo hello
```
.


Question:
How can I extract the whole line in a row, for example, row 3.
These data are saved in my text editor in linux.
Here's my data:

1,julz,kath,shiela,angel
2,may,ann,janice,aika
3,christal,justine,kim
4,kris,allan,jc,mine

I want output like:

3,christal,justine,kim

Answer:
You can assign the diamond operator on your filehandle to a list, each element will be a line or row.
```
```
open $fh, "myfile.txt";
my @lines = <$fh>;
```
```
EDIT:
This solution grabs all the lines so that you can access any one you want, e.g. row 3 would be
```
$lines[2]
```
... If you really only want one specific line, that'd be a different solution, like the other answerers'.


Question: I've been using JSch for a couple of weeks now.  It seems to work okay, but its API is a little bit cumbersome.  I'm also a little off put by its total lack of documentation (not even javadoc style comments).  Has anyone used a good Java SSH2 library that they'd recommend.  I'm particularly interested in SCP file transfer and issuing commands to a remote Linux box programmatically via the SSH protocol.

Answer:
This will work if there is only one member in the array:
```
```
<?php
 echo current(returnsAnArray());
 ?>
```
```


Question:
What is the best way to keep your configuration files (e.g httpd.conf, my.cnf, .bashrc ...) under version control?
In adition to the versioning benefit, I want the solution to work as backup as well, so that I can bring a brand new server and checkout (or export) the config files out of SVN directly

A good touch will be to store the config file`s original path as well.

Answer:
I do this for several machines, ranging from old Solaris 8 boxes to Mac OS X, and I have a really simple layout:
In my repository I have the following:
```
```
<root>/common
  /.emacs.d
  /.bash_common
  /scripts # platform-independent binary tools

<root>/linux
  .bashrc
  .emacs
  ...

<root>/solaris
  .bashrc
  .emacs
  ...

<root>/osx
  .bashrc
  .emacs
  ...
```
```
Each of the OS homedirs has an svn:externals reference to .emacs.d, .bash_common, and scripts, so those are not duplicated.
In addition, I have a .bash_hostconfig in the linux and solaris directories with host-specific path configuration and such, because I have a very different setup at work than I do at home (FC5-8 and RHEL3-5, depending on where I am).
So, between these things, I have a pretty simple process for getting up and running on a new machine:  I simply check out the /$platform into a temporary directory, and then overwrite everything in $HOME with those files.  I don't need to store the original path, because it's always relative to $HOME this way.


Question:
I just started using Log Parser Lizard to examine my IIS and Event logs.

What UI tool do you use on top of LogParser 2.2 to view your log files on production?

Answer:
Sadly when it comes to Log Parser, I do it CLI, not GUI.  I have not had great need to do lots of parsing (though I probably should since resource utilization is occasionally a problem) so I've always used the SQL-like syntax of LogParser straight up.
Other app teams at my work use
Log4Net Dashboard
, which apparently parses log4net logs, event viewer, and other stuff in one web based interface.  I've not gotten around to checking it out, but other people seem to like it.
For web logs I'm actually starting to look at
awstats
for my parsing needs so I can see my data in a more visual format.


Question: Does anyone know of a way, in Java, to convert an earth surface position from lat, lon to UTM (say in WGS84)? I'm currently looking at Geotools but unfortunately the solution is not obvious.

Answer:
I was able to use Geotools 2.4 to get something that works, based on some
example code
.
```
```
double utmZoneCenterLongitude = ...  // Center lon of zone, example: zone 10 = -123
int zoneNumber = ...                 // zone number, example: 10
double latitude, longitude = ...     // lat, lon in degrees

MathTransformFactory mtFactory = ReferencingFactoryFinder.getMathTransformFactory(null);
ReferencingFactoryContainer factories = new ReferencingFactoryContainer(null);

GeographicCRS geoCRS = org.geotools.referencing.crs.DefaultGeographicCRS.WGS84;
CartesianCS cartCS = org.geotools.referencing.cs.DefaultCartesianCS.GENERIC_2D;

ParameterValueGroup parameters = mtFactory.getDefaultParameters("Transverse_Mercator");
parameters.parameter("central_meridian").setValue(utmZoneCenterLongitude);
parameters.parameter("latitude_of_origin").setValue(0.0);
parameters.parameter("scale_factor").setValue(0.9996);
parameters.parameter("false_easting").setValue(500000.0);
parameters.parameter("false_northing").setValue(0.0);

Map properties = Collections.singletonMap("name", "WGS 84 / UTM Zone " + zoneNumber);
ProjectedCRS projCRS = factories.createProjectedCRS(properties, geoCRS, null, parameters, cartCS);

MathTransform transform = CRS.findMathTransform(geoCRS, projCRS);

double[] dest = new double[2];
transform.transform(new double[] {longitude, latitude}, 0, dest, 0, 1);

int easting = (int)Math.round(dest[0]);
int northing = (int)Math.round(dest[1]);
```
```


Question: I've been using htmldoc for a while, but I've run into some fairly serious limitations. I need the end solution to work on a Linux box. I'll be calling this library/utility/application from a Perl app, so any Perl interfaces would be a bonus.

Answer:
I wont claim this is the "best" solution but it is "a" solution i have used.
HTML Input -->
HTML 2 PS
-->
PS 2 PDF
--> PDF Output


Question:
Sometime I see many application such as msn, windows media player etc that are single instance applications (when user executes while application is running a new application instance will not created).

In C#, I use Mutex class for this but I don't know how to do this in Java.

Answer:
If I believe this
article
, by :
having the first instance attempt to open a listening socket on the localhost interface.  If it's able to open the socket, it is assumed that this is the first instance of the application to be launched.  If not, the assumption is that an instance of this application is already running.  The new instance must notify the existing instance that a launch was attempted, then exit.  The existing instance takes over after receiving the notification and fires an event to the listener that handles the action.
Note:
Ahe
mentions in the comment that using
```
InetAddress.getLocalHost()
```
can be tricky:
it does not work as expected in DHCP-environment because address returned depends on whether the computer has network access.
Solution was to open connection with
```
InetAddress.getByAddress(new byte[] {127, 0, 0, 1})
```
;
Probably related to
bug 4435662
.
I also found
bug 4665037
which reports than Expected results of
```
getLocalHost
```
: return IP address of machine, vs. Actual results : return
```
127.0.0.1
```
.
it is surprising to have
```
getLocalHost
```
return
```
127.0.0.1
```
on Linux but not on windows.
Or you may use
```
ManagementFactory
```
object. As explained
here
:
The
```
getMonitoredVMs(int processPid)
```
method receives as parameter the current application PID, and catch the application name that is called from command line, for example, the application was started from
```
c:\java\app\test.jar
```
path, then the value variable is "
```
c:\\java\\app\\test.jar
```
". This way, we will catch just application name on the line 17 of the code below.
After that, we search JVM for another process with the same name, if we found it and the application PID is different, it means that is the second application instance.
JNLP offers also a
```
SingleInstanceListener
```


Question:
Im trying to squeeze some extra performance from searching through a table with many rows.
My current reasoning is that if I can throw away some of the seldom used member from the searched table thereby reducing rowsize the amount of pagesplits and hence IO should drop giving a benefit when data start to spill from memory.

Any good resource detailing such effects?
Any experiences?

Thanks.

Answer:
I don't now what else you tried to increase performance, this seems like grasping at straws to me. That doesn't mean that it isn't a valid approach. From my experience the benefit can be significant. It's just that it's usually dwarfed by other kinds of optimization.
However, what you are looking for are iostatistics. There are several methods to gather them. A quite good introduction can be found
->here
.


Question:
I am a self-taught embedded developer. I mostly use AVRs programmed in C and ASM, but I have dabbled with other systems. I am looking to move onto more complex devices like CPLDs and FPGAs, but I have no idea where to start. So my one and a half questions are:

Do you prefer VHDL or Verilog and why?

What is a good way for one with no prior experience in HDLs get started in learning such a beast?

Answer:
Buy a cheap starter kit from Xilinx or Altera (the two big FPGA players). A Xilinx Spartan3 starter kit is $200.
I personally prefer VHDL. It is strongly typed and has more advanced features than Verilog. VHDL is more popular in Europe and Verilog is dominating in the US.
Buy a book (e.g. Peter Ashendens The Designers Guide to VHDL) and start simulating your designs in a free simulator. ModelSim from Mentor Graphis is a good one and there are free versions available (with crippled simulation speed).
Make up some interesting project (mini cpu, vga graphics, synthesizer) and start designing. Always simulate and make sure your design works before putting your design into the hardware ...
If you have no background in digital electronics buy a book in that subject as well.


Question:
How can I programmatically lock/unlock, or otherwise prevent/enable editing, a source file on Linux using C++.

I want to be able to lock source file so that if I open it in an editor it will not allow me to save back to the same source file.

I am thinking of maybe changing the permissions to read-only (and change it back to read-write later): how do I do that from C++?

Answer:
Try man fchmod:
```
NAME
       chmod, fchmod - change permissions of a file

SYNOPSIS
       #include <sys/types.h>
       #include <sys/stat.h>

       int chmod(const char *path, mode_t mode);
       int fchmod(int fildes, mode_t mode);
```


Question:
I wrote the wrong thing in a commit message.

How can I change the message? The commit has not been pushed yet.

Answer:
Amending the most recent commit message
```
```
git commit --amend
```
```
will open your editor, allowing you to change the commit message of the most recent commit. Additionally, you can set the commit message directly in the command line with:
```
```
git commit --amend -m "New commit message"
```
```
…however, this can make multi-line commit messages or small corrections more cumbersome to enter.
Make sure you don't have any working copy changes
staged
before doing this or they will get committed too. (
Unstaged
changes will not get committed.)
Changing the message of a commit that you've already pushed to your remote branch
If you've already pushed your commit up to your remote branch, then - after amending your commit locally (as described above) - you'll also
need to force push the commit
with:
```
```
git push <remote> <branch> --force
# Or
git push <remote> <branch> -f
```
```
Warning: force-pushing will overwrite the remote branch with the state of your local one
. If there are commits on the remote branch that you don't have in your local branch, you
will
lose those commits.
Warning: be cautious about amending commits that you have already shared with other people.
Amending commits essentially
rewrites
them to have different
SHA
IDs, which poses a problem if other people have copies of the old commit that you've rewritten. Anyone who has a copy of the old commit will need to synchronize their work with your newly re-written commit, which can sometimes be difficult, so make sure you coordinate with others when attempting to rewrite shared commit history, or just avoid rewriting shared commits altogether.
Perform an interactive rebase
Another option is to use interactive rebase.
This allows you to edit any message you want to update even if it's not the latest message.
In order to do a Git squash, follow these steps:
```
```
// n is the number of commits up to the last commit you want to be able to edit
git rebase -i HEAD~n
```
```
Once you squash your commits - choose the
```
e/r
```
for editing the message:
Important note about interactive rebase
When you use
```
git rebase -i HEAD~n
```
there can be
more
than n commits. Git will "collect" all the commits in the last n commits, and if there was a merge somewhere in between that range you will see all the commits as well, so the outcome will be n + .
Good tip:
If you have to do it for more than a single branch and you might face conflicts when amending the content, set up
```
git rerere
```
and let Git resolve those conflicts automatically for you.
Documentation
git-commit(1) Manual Page
git-rebase(1) Manual Page
git-push(1) Manual Page


Question:
I have a poorly designed database. One of the most important tables has 11,000+ entries. We would like to expand our system, and I am wondering if this table grew to 5x its size, would this be a problem? It's 15360 kB in size... if that matters.

I'm using phpMyAdmin, the server is a Fedora Linux box (nothing fancy), The load is light. It stores just about everything our system uses.

Answer:
What DBMS? What server? What load? What application?
Besides: 11.000 records are nothing, really. Even in MS Access. :-)
EDIT:
So I assume you use a fairly recent MySQL with MyISAM tables. In theory, you can go ahead and fill the table into the millions of records. Depending on how you work with them (lots of joins / or not, lots of queries/updates/deletes / or not), you don't need to do anything special. Put a proper index on the table and you should be fine.


Question:
On Windows NTFS there is a nice but mostly unused feature called
"Alternate Data Streams" (ADS) which I recently used in a hobby-dev project.

On Mac HFS+ there is also a similarly nice but mostly unused feature called "named forks".

I am thinking of porting this project to Linux, but I do not know if any Filesystem on linux has such a feature?

Answer:
Most Linux file systems have
```
extended attributes
```
. I'm not familiar with NTFS streams, so I can't compare the two. Most file systems need to be mounted with flags to enable the extended attributes, so this may not work generically for anyone's system. They are usually abbreviated as
```
xattr
```
or
```
xattrs
```
.


Question:
I need to write a digital oscilloscope type application.  There are many great static graphing controls out there, but I need something that can graph 16 traces processing 4000 samples per second.

Is anyone aware of a high speed graphing control for .NET?  I'll even take MFC since that can be wrapped into a .NET control.

Thanks for the help!

Answer:
Have you looked at
GraphViz
? I've seen it used in oscilloscope applications, but I'm not positive it will handle the speed you're looking for. GraphViz doesn't take a 'live feed' of instructions like some of the GDI+ controls I've seen.
There are some
.NET wrappers
for it
.


Question:
Error message:

fatal: git checkout: updating paths is incompatible with switching branches/forcing

How to get past this Git checkout error?

Answer:
By explicitly specifying “
```
git checkout HEAD $blah
```
” instead of just saying “
```
git checkout $blah
```
”, assuming you did want to check out a file.
You don’t say what you were trying nor what you typed, however, so no one can give you anything but a blind guess.


Question:
Is it even possible?

Basically, there's a remote repository from which I pull using just:

git pull

Now, I'd like to preview what this pull would change (a diff) without touching anything on my side. The reason is that thing I'm pulling might not be "good" and I want someone else to fix it before making my repository "dirty".

Answer:
I think
git fetch
is what your looking for.
It will pull the changes and objects without committing them to your local repo's index.
They can be merged later with
git merge
.
Man Page
Edit: Further Explination
Straight from the
Git- SVN Crash Course
link
Now, how do you get any new changes from a remote repository? You fetch them:
```
```
git fetch http://host.xz/path/to/repo.git/
```
```
At this point they are in your repository and you can examine them using:
```
```
git log origin
```
```
You can also diff the changes. You can also use
git log HEAD..origin
to see just the changes you don't have in your branch.  Then if would like to merge them - just do:
```
```
git merge origin
```
```
Note that if you don't specify a branch to fetch, it will conveniently default to the tracking remote.
Reading the man page is honestly going to give you the best understanding of options and how to use it.
I'm just trying to do this by examples and memory, I don't currently have a box to test out on. You should look at:
```
```
git log -p //log with diff
```
```
A fetch can be undone with
git reset --hard
(
link
) , however all uncommitted changes in your tree will be lost as well as the changes you've fetched.


Question:
I'm trying to get this simple PowerShell script working, but I think something is fundamentally wrong. ;-)

ls | ForEach { "C:\Working\tools\custom-tool.exe" $_ }

I basically want to get files in a directory, and pass them one by one as arguments to the custom tool.

Answer:
```
```
ls | %{C:\Working\tools\custom-tool.exe $_}
```
```
As each object comes down the pipeline the tool will be run against it.  Putting quotes around the command string causes it to be... a string!  The local variable "$_" it then likely doesn't know what to do with so pukes with an error.


Question:
Every time I use the "at" command, I get this message:

warning: commands will be executed using /bin/sh

What is it trying to warn me about? More importantly, how do I turn the warning off?

Answer:
It serves as a good warning to those of us that don't use bash as our shell, because we we'll forget that a feature that's in our day-to-day shell isn't going to be available when this code is run at the appointed time.
i.e.
```
```
username@hostname$ at 23:00
warning: commands will be executed using /bin/sh
at> rm **/*.pyc
at> <EOT>
job 1 at 2008-10-08 23:00
```
```
The use of '**' there is perfectly valid zsh, but not /sbin/sh! It's easy to make these mistakes if you're used to using a different shell, and it's your responsibility to remember to do the right thing.


Question:
I'm testing the speed of some queries in MySQL. The database is caching these queries making it difficult for me to get reliable results when testing how fast these queries are.

Is there a way to disable caching for a query?

System: MySQL 4 on Linux webhosting, I have access to PHPMyAdmin.

Thanks

Answer:
Try using the
SQL_NO_CACHE
(MySQL 5.7) option in your query.
(MySQL 5.6 users click
HERE
)
eg.
```
```
SELECT SQL_NO_CACHE * FROM TABLE
```
```
This will stop MySQL caching the results, however be aware that other OS and disk caches may also impact performance. These are harder to get around.


Question:
Is there a manual for cross-compiling a C++ application from Linux to Windows?

Just that. I would like some information (links, reference, examples...) to guide me to do that.

I don't even know if it's possible.

My objective is to compile a program in Linux and get a .exe file that I can run under Windows.

Answer:
The basics are not too difficult:
```
```
sudo apt-get install mingw32
cat > main.c <<EOF
int main()
{
  printf("Hello, World!");
}
EOF
i586-mingw32msvc-cc main.c -o hello.exe
```
```
Replace
```
apt-get
```
with
```
yum
```
, or whatever your Linux distro uses. That will generate a
```
hello.exe
```
for Windows.
Once you get your head around that, you could use
autotools
, and set
```
CC=i586-mingw32msvc-cc
```
```
```
CC=i586-mingw32msvc-cc ./configure && make
```
```
Or use
CMake and a toolchain file
to manage the build. More difficult still is adding native cross libraries. Usually they are stored in
```
/usr/cross/i586-mingw32msvc/{include,lib}
```
and you would need to add those paths in separately in the configure step of the build process.


Question:
AFAIK, Currency type in Delphi Win32 depends on the processor floating point precision. Because of this I'm having rounding problems when comparing two Currency values, returning different results depending on the machine.

For now I'm using the SameValue function passing a Epsilon parameter = 0.009, because I only need 2 decimal digits precision.

Is there any better way to avoid this problem?

Answer:
To avoid possible issues with currency rounding in Delphi use 4 decimal places.
This will ensure that you never having rounding issues when doing calcualtions with very small amounts.
```
"Been there. Done That. Written the unit tests."
```


Question: Is there any free tool available for creating and editing PNG Images?

Answer:
The GIMP
(GNU Image Manipulation Program).
It's free, open source and runs on Windows and Linux (and maybe Mac?).


Question: A friend of mine has embedded a google earth plugin into a C# user control. All works fine but when you close the window we recieve and "Unspecified Error" with the option to continue running the scripts or not. From our tracking it down it appears this is being cause by a script that google is dropping onto the page. Any ideas?

Answer:
We have now tried this in both IE and FF. Works fine. Any ideas why the error only comes up on close? can we somehow disable it? here is our code.
```
```
<meta http-equiv="content-type" content="text/html; charset=utf-8" />

```
```


Question: I'm looking for a XPath library to query over XML documents in FF, IE, Opera and Safari... and couldn't find one. Have you seen any?

Answer:
You could use the basic
XPath plug-in for jQuery
to get XPath query-ing functionality.
Also, you could consider reading this
article on XPath XML processing
(again with jQuery)


Question:
I need to convert the punycode NIATO-OTABD to nñiñatoñ.

I found a text converter in JavaScript the other day, but the punycode conversion doesn't work if there's a dash in the middle.

Any suggestion to fix the "dash" issue?

Answer:
I took the time to create the punycode below. It it based on the C code in RFC 3492. To use it with domain names you have to remove/add
```
xn--
```
from/to the input/output to/from decode/encode.
The
```
utf16-class
```
is necessary to convert from JavaScripts internal character representation to unicode and back.
There are also
```
ToASCII
```
and
```
ToUnicode
```
functions to make it easier to convert between puny-coded IDN and ASCII.
```
```
//Javascript Punycode converter derived from example in RFC3492.
//This implementation is created by some@domain.name and released into public domain
var punycode = new function Punycode() {
    // This object converts to and from puny-code used in IDN
    //
    // punycode.ToASCII ( domain )
    //
    // Returns a puny coded representation of "domain".
    // It only converts the part of the domain name that
    // has non ASCII characters. I.e. it dosent matter if
    // you call it with a domain that already is in ASCII.
    //
    // punycode.ToUnicode (domain)
    //
    // Converts a puny-coded domain name to unicode.
    // It only converts the puny-coded parts of the domain name.
    // I.e. it dosent matter if you call it on a string
    // that already has been converted to unicode.
    //
    //
    this.utf16 = {
        // The utf16-class is necessary to convert from javascripts internal character representation to unicode and back.
        decode:function(input){
            var output = [], i=0, len=input.length,value,extra;
            while (i < len) {
                value = input.charCodeAt(i++);
                if ((value & 0xF800) === 0xD800) {
                    extra = input.charCodeAt(i++);
                    if ( ((value & 0xFC00) !== 0xD800) || ((extra & 0xFC00) !== 0xDC00) ) {
                        throw new RangeError("UTF-16(decode): Illegal UTF-16 sequence");
                    }
                    value = ((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
                }
                output.push(value);
            }
            return output;
        },
        encode:function(input){
            var output = [], i=0, len=input.length,value;
            while (i < len) {
                value = input[i++];
                if ( (value & 0xF800) === 0xD800 ) {
                    throw new RangeError("UTF-16(encode): Illegal UTF-16 value");
                }
                if (value > 0xFFFF) {
                    value -= 0x10000;
                    output.push(String.fromCharCode(((value >>>10) & 0x3FF) | 0xD800));
                    value = 0xDC00 | (value & 0x3FF);
                }
                output.push(String.fromCharCode(value));
            }
            return output.join("");
        }
    }

    //Default parameters
    var initial_n = 0x80;
    var initial_bias = 72;
    var delimiter = "\x2D";
    var base = 36;
    var damp = 700;
    var tmin=1;
    var tmax=26;
    var skew=38;
    var maxint = 0x7FFFFFFF;

    // decode_digit(cp) returns the numeric value of a basic code
    // point (for use in representing integers) in the range 0 to
    // base-1, or base if cp is does not represent a value.

    function decode_digit(cp) {
        return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;
    }

    // encode_digit(d,flag) returns the basic code point whose value
    // (when used for representing integers) is d, which needs to be in
    // the range 0 to base-1. The lowercase form is used unless flag is
    // nonzero, in which case the uppercase form is used. The behavior
    // is undefined if flag is nonzero and digit d has no uppercase form.

    function encode_digit(d, flag) {
        return d + 22 + 75 * (d < 26) - ((flag != 0) << 5);
        //  0..25 map to ASCII a..z or A..Z
        // 26..35 map to ASCII 0..9
    }
    //** Bias adaptation function **
    function adapt(delta, numpoints, firsttime ) {
        var k;
        delta = firsttime ? Math.floor(delta / damp) : (delta >> 1);
        delta += Math.floor(delta / numpoints);

        for (k = 0; delta > (((base - tmin) * tmax) >> 1); k += base) {
                delta = Math.floor(delta / ( base - tmin ));
        }
        return Math.floor(k + (base - tmin + 1) * delta / (delta + skew));
    }

    // encode_basic(bcp,flag) forces a basic code point to lowercase if flag is zero,
    // uppercase if flag is nonzero, and returns the resulting code point.
    // The code point is unchanged if it is caseless.
    // The behavior is undefined if bcp is not a basic code point.

    function encode_basic(bcp, flag) {
        bcp -= (bcp - 97 < 26) << 5;
        return bcp + ((!flag && (bcp - 65 < 26)) << 5);
    }

    // Main decode
    this.decode=function(input,preserveCase) {
        // Dont use utf16
        var output=[];
        var case_flags=[];
        var input_length = input.length;

        var n, out, i, bias, basic, j, ic, oldi, w, k, digit, t, len;

        // Initialize the state:

        n = initial_n;
        i = 0;
        bias = initial_bias;

        // Handle the basic code points: Let basic be the number of input code
        // points before the last delimiter, or 0 if there is none, then
        // copy the first basic code points to the output.

        basic = input.lastIndexOf(delimiter);
        if (basic < 0) basic = 0;

        for (j = 0; j < basic; ++j) {
            if(preserveCase) case_flags[output.length] = ( input.charCodeAt(j) -65 < 26);
            if ( input.charCodeAt(j) >= 0x80) {
                throw new RangeError("Illegal input >= 0x80");
            }
            output.push( input.charCodeAt(j) );
        }

        // Main decoding loop: Start just after the last delimiter if any
        // basic code points were copied; start at the beginning otherwise.

        for (ic = basic > 0 ? basic + 1 : 0; ic < input_length; ) {

            // ic is the index of the next character to be consumed,

            // Decode a generalized variable-length integer into delta,
            // which gets added to i. The overflow checking is easier
            // if we increase i as we go, then subtract off its starting
            // value at the end to obtain delta.
            for (oldi = i, w = 1, k = base; ; k += base) {
                    if (ic >= input_length) {
                        throw RangeError ("punycode_bad_input(1)");
                    }
                    digit = decode_digit(input.charCodeAt(ic++));

                    if (digit >= base) {
                        throw RangeError("punycode_bad_input(2)");
                    }
                    if (digit > Math.floor((maxint - i) / w)) {
                        throw RangeError ("punycode_overflow(1)");
                    }
                    i += digit * w;
                    t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;
                    if (digit < t) { break; }
                    if (w > Math.floor(maxint / (base - t))) {
                        throw RangeError("punycode_overflow(2)");
                    }
                    w *= (base - t);
            }

            out = output.length + 1;
            bias = adapt(i - oldi, out, oldi === 0);

            // i was supposed to wrap around from out to 0,
            // incrementing n each time, so we'll fix that now:
            if ( Math.floor(i / out) > maxint - n) {
                throw RangeError("punycode_overflow(3)");
            }
            n += Math.floor( i / out ) ;
            i %= out;

            // Insert n at position i of the output:
            // Case of last character determines uppercase flag:
            if (preserveCase) { case_flags.splice(i, 0, input.charCodeAt(ic -1) -65 < 26);}

            output.splice(i, 0, n);
            i++;
        }
        if (preserveCase) {
            for (i = 0, len = output.length; i < len; i++) {
                if (case_flags[i]) {
                    output[i] = (String.fromCharCode(output[i]).toUpperCase()).charCodeAt(0);
                }
            }
        }
        return this.utf16.encode(output);
    };

    //** Main encode function **

    this.encode = function (input,preserveCase) {
        //** Bias adaptation function **

        var n, delta, h, b, bias, j, m, q, k, t, ijv, case_flags;

        if (preserveCase) {
            // Preserve case, step1 of 2: Get a list of the unaltered string
            case_flags = this.utf16.decode(input);
        }
        // Converts the input in UTF-16 to Unicode
        input = this.utf16.decode(input.toLowerCase());

        var input_length = input.length; // Cache the length

        if (preserveCase) {
            // Preserve case, step2 of 2: Modify the list to true/false
            for (j=0; j < input_length; j++) {
                case_flags[j] = input[j] != case_flags[j];
            }
        }

        var output=[];

        // Initialize the state:
        n = initial_n;
        delta = 0;
        bias = initial_bias;

        // Handle the basic code points:
        for (j = 0; j < input_length; ++j) {
            if ( input[j] < 0x80) {
                output.push(
                    String.fromCharCode(
                        case_flags ? encode_basic(input[j], case_flags[j]) : input[j]
                    )
                );
            }
        }

        h = b = output.length;

        // h is the number of code points that have been handled, b is the
        // number of basic code points

        if (b > 0) output.push(delimiter);

        // Main encoding loop:
        //
        while (h < input_length) {
            // All non-basic code points < n have been
            // handled already. Find the next larger one:

            for (m = maxint, j = 0; j < input_length; ++j) {
                ijv = input[j];
                if (ijv >= n && ijv < m) m = ijv;
            }

            // Increase delta enough to advance the decoder's
            // <n,i> state to <m,0>, but guard against overflow:

            if (m - n > Math.floor((maxint - delta) / (h + 1))) {
                throw RangeError("punycode_overflow (1)");
            }
            delta += (m - n) * (h + 1);
            n = m;

            for (j = 0; j < input_length; ++j) {
                ijv = input[j];

                if (ijv < n ) {
                    if (++delta > maxint) return Error("punycode_overflow(2)");
                }

                if (ijv == n) {
                    // Represent delta as a generalized variable-length integer:
                    for (q = delta, k = base; ; k += base) {
                        t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;
                        if (q < t) break;
                        output.push( String.fromCharCode(encode_digit(t + (q - t) % (base - t), 0)) );
                        q = Math.floor( (q - t) / (base - t) );
                    }
                    output.push( String.fromCharCode(encode_digit(q, preserveCase && case_flags[j] ? 1:0 )));
                    bias = adapt(delta, h + 1, h == b);
                    delta = 0;
                    ++h;
                }
            }

            ++delta, ++n;
        }
        return output.join("");
    }

    this.ToASCII = function ( domain ) {
        var domain_array = domain.split(".");
        var out = [];
        for (var i=0; i < domain_array.length; ++i) {
            var s = domain_array[i];
            out.push(
                s.match(/[^A-Za-z0-9-]/) ?
                "xn--" + punycode.encode(s) :
                s
            );
        }
        return out.join(".");
    }
    this.ToUnicode = function ( domain ) {
        var domain_array = domain.split(".");
        var out = [];
        for (var i=0; i < domain_array.length; ++i) {
            var s = domain_array[i];
            out.push(
                s.match(/^xn--/) ?
                punycode.decode(s.slice(4)) :
                s
            );
        }
        return out.join(".");
    }
}();

// Example of usage:
domain.oninput = function() {
    var input = domain.value
    var ascii = punycode.ToASCII(input)
    var display = punycode.ToUnicode(ascii)
    domain_ascii.value = ascii
    domain_display.value = display
}
```
```
```
```

Try with your own data

Input domain

<input id="domain" type="text">

Ascii: <output id="domain_ascii">

Display: <output id="domain_display">

```
```
Licence:
From RFC3492:
Disclaimer and license
Regarding this entire document or any portion of it (including the pseudocode and C code), the author makes no guarantees and is not responsible for any damage resulting from its use. The author grants irrevocable permission to anyone to use, modify, and distribute it in any way that does not diminish the rights of anyone else to use, modify, and distribute it, provided that redistributed derivative works do not contain misleading author or version information. Derivative works need not be licensed under similar terms.
I put my work in this punycode and utf16 in the public domain. It would be nice to get an email telling me in what project you use it.
The scope of the code
Each TLD has rules for which code points are allowed. The scope of the code below is to encode and decode a string between punycode and the internal encoding used by javascript regardes of those rules.
Depending on your use case, you may need to filter the string.
For example, 0xFE0F: Variation Selector-16, an invisible code point that specifies that the previous character should be displayed with emoji presentation.
If you search for "allowed code points in IDN" you should find several projects that can help you filter the string.


Question:
I need to compare strings in shell:

var1="mtu eth0"

if [ "$var1" == "mtu *" ]
then
    # do something
fi

But obviously the "*" doesn't work in Shell. Is there a way to do it?

Answer:
```
bash
```
Shortest fix:
```
```
if [[ "$var1" = "mtu "* ]]
```
```
Bash's
```
[[ ]]
```
doesn't get glob-expanded, unlike
```
[ ]
```
(which must, for historical reasons).
```
bash --posix
```
Oh, I posted too fast.  Bourne shell, not Bash...
```
```
if [ "${var1:0:4}" == "mtu " ]
```
```
```
${var1:0:4}
```
means the first four characters of
```
$var1
```
.
```
/bin/sh
```
Ah, sorry.  Bash's POSIX emulation doesn't go far enough; a true original Bourne shell doesn't have
```
${var1:0:4}
```
.  You'll need something like mstrobl's solution.
```
```
if [ "$(echo "$var1" | cut -c0-4)" == "mtu " ]
```
```


Question:
In bash the ampersand (&) can be used to run a command in the background and return interactive control to the user before the command has finished running. Is there an equivalent method of doing this in Powershell?

Example of usage in bash:

 sleep 30 &

Answer:
I've used the solution described here
http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!130.entry
successfully in PowerShell v1.0.  It definitely will be easier in PowerShell v2.0.


Question: Is there a simple and lightweight program to search over a text file and replace a string with regex?

Answer:
For searching:
grep
- simple and fast. Included with Linux,
here
's a Windows version, not sure about Mac.
For replacing:
sed
.
Here
's a Windows version, not sure about Mac.
Of course, if you want to actually open up a file and see its contents while you search and replace, you can use
emacs
for that. Or
ConTEXT
. Or
vim
. Or what have you. ;)
See also
this question
.


Question:
I want to delete a folder that contains thousands of files and folders. If I use Windows Explorer to delete the folder it can take 10-15 minutes (not always, but often). Is there a faster way in Windows to delete folders?

Other details:

I don't care about the recycle bin.

It's an NTFS drive.

Answer:
Using Windows Command Prompt:
```
```
rmdir /s /q folder
```
```
Using Powershell:
```
```
powershell -Command "Remove-Item -LiteralPath 'folder' -Force -Recurse"
```
```
Note that in more cases
```
del
```
and
```
rmdir
```
wil leave you with leftover files, where Powershell manages to delete the files.


Question: How is Oracle date implemented? Is it stored as milliseconds or something like that?

Answer:
An Oracle DATE stores the date and time to the second.  An Oracle TIMESTAMP stores the date and time to up to 9 digits of subsecond precision, depending on the available hardware.
Both are implemented by storing the various components of the date and the time in a packed binary format.  From the
Oracle Concepts Guide section on dates
Oracle uses its own internal format to
  store dates. Date data is stored in
  fixed-length fields of seven bytes
  each, corresponding to century, year,
  month, day, hour, minute, and second.
You can use the
DUMP()
function to see the internal representation of any particular date (or any other value for that matter), but that's probably more than you need (or want) to know.


Question:
I'd like to be able to run my aliases from my .bashrc in the "Run Application" dialog that comes up when you hit Alt+F2 in Ubuntu/Gnome.

Does anyone know how to do this?

Answer:
http://www.freedesktop.org/wiki/Specifications
is probably a good place to start. I find these quite hard to follow most of the time, but sometimes you can figure it out. Specifically, the "Desktop Entry Specification".
Also, I don't think you'll be able to use any aliases from
```
.bashrc
```
, at least not without writing some kind of wrapper script. I think it needs to be an executable file. Of course, you could just use the good old symlinks- to- same + what's- my- name trick...
(Which, for reference, goes like this:
Make a script which uses its own name as a parameter.
Make symlinks to said script using the parameter values as the link names.)
Investigating...
Some casual investigation reveals that creating these is fairly simple if you use Nautilus, (at least the version I have):
Bring up the context menu for some random file, and use "Open With"->"Open with Other Application".
Unfold the "Use a custom command" and type in something like:
```
xterm -e 'bash -c "unzip -l %f; sleep 5"'
```
This results in
the command being run (so don't type
```
rm -rf
```
)
a file in
```
~/.local/share/applications/
```
called
```
xterm-usercreated.desktop
```
Here at least, I get the follow file:
```
```
[Desktop Entry]
Encoding=UTF-8
Name=xterm
MimeType=application/zip;
Exec=xterm -e 'bash -c "unzip -l %f; sleep 5"' %f
Type=Application
Terminal=false
NoDisplay=true
```
```
4: Looking at the system xterm .desktop I find this:
```
```
[Desktop Entry]
Type=Application
Encoding=UTF-8
Name=XTerm
GenericName=
Comment=XTerm: terminal emulator for X
Icon=/usr/share/pixmaps/xterm-color_32x32.xpm
Exec=xterm
Terminal=false
Categories=X-Debian-Applications-Terminal-Emulators;
```
```
5: Editing the .usercreated.desktop file to this:
```
```
[Desktop Entry]
Type=Application
Encoding=UTF-8
Name=xtermz
Exec=xterm -e 'bash -c "unzip -l %f; sleep 5"' %f
Terminal=false
Categories=X-Local-WTF
```
```
6: Run xdg-desktop-menu forceupdate --mode user
7: "xtermz" now shows up in the list... Success!
8: Yuck! This also makes it appear in the main menu, under "Other". Weird!
Some notes:
In my Debian/testing,
```
xdg-desktop-menu
```
and friends (notably
```
xdg-icon-resource
```
) live in the
```
xdg-utils
```
package.
You should be able to create a
```
.desktop
```
file from scratch.
You should be able to install the
```
.desktop
```
file using
```
xdg-desktop-menu install
```
blah blah


Question:
In my database, I would like to store a decimal score. A score can have a value from 0 to 10, and values in between, such as 2.3 or 9.4.

I recently learned that int only stores whole numbers and not decimals. I found out that you could use either double or decimal, but what I would like to know is if there is any difference at all?

I'm currently using decimal.

Answer:
Decimals are more precise, doubles are more efficient, usually.
With decimal you can set how many digits you want to use before and after the decimal point.
Edit:
You can set digit count for decimal
and
double, my bad.
Decimals are better for things like money calculations where exactitude is absolutely necessary. Doubles are better suited for your specific case where the exactitude of the score is not critical.
See the
overview of numeric types
in the MySQL documentation for more information.


Question: The last cross platform desktop development I did was Java/Swing.  What about flex?

Answer:
I've used
RealBasic from RealSoftware
for a few things just to play with it.  It can get expensive if you need the pro version.  It will allow you to build a stand alone binary for Linux, MacOS X, or Windows.  I'm more of a server side guy but it was pretty straight forward to create the few tools I wanted to try making with it.


Question:
I am looking for a way to take a user uploaded image that is currently put in a temporary location ex: /tmp/jkhjkh78 and create a php image from it, autodetecting the format.

Is there a more clever way to do this than a bunch of try/catching with imagefromjpeg, imagefrompng, etc?

Answer:
You can call a system command (if you're under linux/unix),
```
file
```
if you like:
```
```
kender@eira:~$ file a
a: JPEG image data, EXIF standard 2.2
```
```


Question:
Is it possible to call into COM objects via x86 assembly language? If so, how?

Why would I want to do this? Let's say I've got two programs that I don't have source for - all I've got are the binaries. One of them implements a COM interface, the other doesn't. I want to inject code into the first program to call into the second using this COM interface, and this requires me to use x86 assembly.

Answer:
Of course it's possible - in effect that's what the C/C++ compiler does.
But why in God's name would you want to do this?  If it were for educational value, then surely doing the COM stuff by hand in straight C would do the trick.
Given the updated question, I'd suggest that you write the COM stuff in a DLL and inject that DLL into the program you want to patch, then patch in simple x86 code into the program to call your DLL that does the heavy lifting.  I don't recall the techniques for injecting a DLL into the address space of a process, but there are at least a couple.  The AppInit registry setting (or something like that) is one.
However, I think that most of the avenues for injecting code into a process are considered security flaws (and have often been used by malware), so I suspect that Microsoft may have removed many if not most (or all) from more recent service packs or OS versions.


Question:
When I use ApacheBench to test https, the error is returned, "ssl handshake failed".

How can I use ApacheBench to test https?

Answer:
ApacheBench doesn't seem to be capable of ignoring certificate problems (at least some of them) so I wrote this script:
```
```
#!/bin/bash
K=200;
HTTPSA='https://192.168.1.103:443/'
date +%M-%S-%N>wgetres.txt
for (( c=1; c<=$K; c++ ))
do
    wget --no-check-certificate --secure-protocol=SSLv3 --spider $HTTPSA
done
date +%M-%S-%N>>wgetres.txt
```
```
It's not as precise as AB, but gives the idea. Does well in comparison tests.


Question:
How do you keep the spoken languages strings in your program up to date?
Is there an inexpensive way?  Where can you find people to do the conversions over time?

Answer:
There are companies which will translate resource files in the standard formats for fees; I think that's how most large companies do it.
I asked a similar question recently
here
about the best way to structure code in a project to support this, with my additional desire to preserve the readable strings in code. This is not standard, though... usually you would put all the string resources into a separate file and refer to them by ID in the code, and have the file translated.
See .rc files for Windows C++, .resx files for .NET, not sure what exists for Linux/Mac/other, but I'm sure there are equivalents.


Question:
What are my options when it comes to implementing page compression is asp.net.Right now I have a custom home grown httpmodule and its not very mature.

Google links me to MbCompression. The project has few views and downloads which discourages me a bit.

Edit: I am under shared hosting, which limits my access to IIS settings

Answer:
There are companies which will translate resource files in the standard formats for fees; I think that's how most large companies do it.
I asked a similar question recently
here
about the best way to structure code in a project to support this, with my additional desire to preserve the readable strings in code. This is not standard, though... usually you would put all the string resources into a separate file and refer to them by ID in the code, and have the file translated.
See .rc files for Windows C++, .resx files for .NET, not sure what exists for Linux/Mac/other, but I'm sure there are equivalents.


Question: itoa() is a really handy function to convert a number to a string. Linux does not seem to have itoa(), is there an equivalent function or do I have to use sprintf(str, "%d", num)?

Answer:
EDIT: Sorry, I should have remembered that this machine is decidedly non-standard, having plugged in various non-standard
```
libc
```
implementations for academic purposes ;-)
As
```
itoa()
```
is indeed non-standard, as mentioned by several helpful commenters, it is best to use
```
sprintf(target_string,"%d",source_int)
```
or (better yet, because it's safe from buffer overflows)
```
snprintf(target_string, size_of_target_string_in_bytes, "%d", source_int)
```
.  I know it's not quite as concise or cool as
```
itoa()
```
, but at least you can Write Once, Run Everywhere (tm) ;-)
Here's the old (edited) answer
You are correct in stating that the default
```
gcc libc
```
does not include
```
itoa()
```
, like several other platforms, due to it not technically being a part of the standard.  See
here
for a little more info.  Note that you have to
```
```
#include <stdlib.h>
```
```
Of course you already know this, because you wanted to
use
```
itoa()
```
on Linux after presumably using it on another platform, but... the code (stolen from the link above) would look like:
Example
```
```
/* itoa example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i;
  char buffer [33];
  printf ("Enter a number: ");
  scanf ("%d",&i);
  itoa (i,buffer,10);
  printf ("decimal: %s\n",buffer);
  itoa (i,buffer,16);
  printf ("hexadecimal: %s\n",buffer);
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);
  return 0;
}
```
```
Output:
```
```
Enter a number: 1750
decimal: 1750
hexadecimal: 6d6
binary: 11011010110
```
```
Hope this helps!


Question:
I need to programmatically get a list of running applications as shown in the "Applications" tab inside the Windows Task Manager using PowerShell or VBScript.

All I could find so far is how to list processes using VBScript and WMI.

Answer:
This should do the trick:
```
```
Set Word = CreateObject("Word.Application")
Set Tasks = Word.Tasks
For Each Task in Tasks
   If Task.Visible Then Wscript.Echo Task.Name
Next
Word.Quit
```
```
http://msdn.microsoft.com/en-us/library/bb212832.aspx


Question:
I thought this would be really simple, but it's presenting some difficulties. If I have

std::string name = "John";
int age = 21;

How do I combine them to get a single string "John21"?

Answer:
Common Answer:
itoa()
This is bad.
```
itoa
```
is non-standard, as pointed out
here
.


Question: What are the differences between pipes in Windows and Linux?

Answer:
One difference that I know of, is that named pipes under Linux are actual entries in the filesystem (you'll see it in a directory listing, they have a special type), whereas on Windows they are stored in some magical repository somewhere (they are all accessed via the path "\\.\pipe\".
Secondly, in Linux you can just write/read from pipes as if they were any other file, using standard file IO methods. Whereas on windows, you have to use the special 'Pipe' functions which are part of the Win32 API.
I like linux's method better, because it lets me use pipes with any app I want. Eg:
```
```
mkfifo pipe.wav
decodeMP3 song.mp3 --out pipe.wav &
encodeAVI video.mpeg pipe.wav --out video.avi
```
```
This lets me pipe the output of the MP3 decoder directly into the video decoder, instead of having to first decode the entire MP3 into a WAV file on disk. It's handy if you have a dual-core CPU, because then you are running both operations at once, for a nice speedup.


Question:
I created a simple class with a DependencyProperty. When setting the value, I observe that ValidateValueCallback is called before CoerceValueCallback.

On wpftutorial and in other books, it is stated that coercion is called before validation.

Answer:
One difference that I know of, is that named pipes under Linux are actual entries in the filesystem (you'll see it in a directory listing, they have a special type), whereas on Windows they are stored in some magical repository somewhere (they are all accessed via the path "\\.\pipe\".
Secondly, in Linux you can just write/read from pipes as if they were any other file, using standard file IO methods. Whereas on windows, you have to use the special 'Pipe' functions which are part of the Win32 API.
I like linux's method better, because it lets me use pipes with any app I want. Eg:
```
```
mkfifo pipe.wav
decodeMP3 song.mp3 --out pipe.wav &
encodeAVI video.mpeg pipe.wav --out video.avi
```
```
This lets me pipe the output of the MP3 decoder directly into the video decoder, instead of having to first decode the entire MP3 into a WAV file on disk. It's handy if you have a dual-core CPU, because then you are running both operations at once, for a nice speedup.


Question:
How can I determine the name of the Bash script file inside the script itself?

Like if my script is in file runme.sh, then how would I make it to display "You are running runme.sh" message without hardcoding that?

Answer:
```
```
me=`basename "$0"`
```
```
For reading through a symlink
1
, which is usually not what you want (you usually don't want to confuse the user this way), try:
```
```
me="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")"
```
```
IMO, that'll produce confusing output.  "I ran foo.sh, but it's saying I'm running bar.sh!?  Must be a bug!"   Besides, one of the purposes of having differently-named symlinks is to provide different functionality based on the name it's called as (think gzip and gunzip on some platforms).
1
That is, to resolve symlinks such that when the user executes
```
foo.sh
```
which is actually a symlink to
```
bar.sh
```
, you wish to use the resolved name
```
bar.sh
```
rather than
```
foo.sh
```
.


Question: Has anyone implemented a very large EAV or open schema style database in SQL Server?  I'm wondering if there are performance issues with this and how you were able to overcome those obstacles.

Answer: I'm not an expert on EAV, but several more experienced developers than I have commented that Magento's open-source e-commerce framework is slow primarily because of the EAV architecture through MySQL. The most obvious disadvantage can't easily be overcome. That being the difficulty with which it is to troubleshoot where and how information is represented for entities and attribute values as the size of the application increases. The second argument against EAV I have heard is that it requires table joins that get into low double digits, but it was commented that using InnoDB over MyISAM improved the performance some (or it could be vice-versa, but I can't remember totally).


Question:
How can I distribute a standalone Python application in Linux?

I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on.

Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)?
Is there a free, opensource one?

Answer:
Nope.
Python is notoriously flaky with respect to different setups. The only sane way to deploy a python app is to ship the whole bundle of interpreter and libraries that you are relying on with your code. That will most likely work.
Update 2019: I stand by this. Virtualenv is a way of packaging libraries and interpreters together. Tox is a testing tool to test that interpreter/dependency matrix. Docker is a widely used way of then deploying the bundle.


Question: I love the Ruby RSpec BDD development style.  Are there any good tools for doing this with C/C++?

Answer:
cspec
is for C.  Presumably it will work with C++.  There is a list of tools for various languages on the
Behavior Driven Development Wikipedia page
.


Question:
I know we can use tools like JProfiler etc.
Is there any tutorial on how to configure it to display the memory usage just by remote monitoring?

Any idea?

Answer:
you have VisualGC, it's not very advanced but you can see the memory usage of your application (garbage,old, perm etc...)
http://java.sun.com/performance/jvmstat/visualgc.html
to resume :
you launch a daemon monitoring on the remote machine (
http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jstatd.html
, see the security parapraph)
```
```
JAVA_HOME/bin/jstatd -J-Djava.security.policy=jstatd.all.policy
```
```
with a file here called
jstatd.all.policy
containing :
```
```
grant codebase "file:${java.home}/../lib/tools.jar" {
permission java.security.AllPermission;
};
```
```
on the remote machine you got the pid of your application to debug with the jps tool :
http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jps.html#jps
finally on your local machine you launch the visualgc :
```
```
visualgc the_pid@remote_machine_address
```
```


Question: I want to make a JavaScript application that's not open source, and thus I wish to learn how to can obfuscate my JS code? Is this possible?

Answer:
Obfuscation:
Try
YUI Compressor
.  It's a very popular tool, built, enhanced and maintained by the Yahoo UI team.
You may also use:
Google Closure Compiler
UglifyJS
```
UPDATE: This question was originally asked on 2008, and The mentioned technologies are deprecated. you can use:
```
terser
- more information in
web.dev
.
Private String Data:
Keeping string values private is a different concern, and obfuscation won't really be of much benefit.  Of course, by packaging up your source into a garbled, minified mess, you have a light version of
security
through
obscurity
.  Most of the time, it's your user who is viewing the source, and the string values on the client are intended for their use, so that sort of private string value isn't often necessary.
If you really had a value that you never wanted a user to see, you would have a couple of options.  First, you could do some kind of encryption, which is decrypted at page load.  That would probably be one of the most secure options, but also a lot of work which may be unnecessary.  You could probably base64 encode some string values, and that would be easier.. but someone who really wanted those string values could
easily decode them
.  Encryption is the only way to truly prevent anyone from accessing your data, and most people find that to be more security than they need.
Sidenote:
Obfuscation in Javascript has been known to cause some bugs. The obfuscators are getting a little better about it, but many outfits decide that they see enough benefit from
minifying
and
gzipping
, and the added savings of obfuscation
isn't always worth the trouble
.  If you're trying to protect your source, maybe you'll decide that it's worth your while, just to make your code harder to read.
JSMin
is a good alternative.


Question: I have to implement the VinPower application.  They offer a Java version, a C dll and an ActiveX dll, if anyone has an idea on where I could begin, I'd appreciate it.

Answer:
A quick Google search shows that there is
Vinpower
and there is
VinPOWER
. To which one are you referring?
When you say "implement", are you looking at writing your own library that does the same thing as an existing product? Or did you mean to say "integrate" where you need to use a third party library within your existing project?
If your goal is to integrate, and the vendor supplies different versions of the library for different interfaces, I would pick the one that would be easiest to integrate with your existing project. For example, if your code is already in Java then I would pick the Java version of their library. If your code is in Visual Basic, then you might be best off with the ActiveX dll.


Question: I'm developing non-interactive cpu-bound application which does only computations, almost no IO. Currently it works too long and while I'm working on improving the algorithm, I also think if it can give any benefit to change language or platform. Currently it is C++ (no OOP so it is almost C) on windows compiled with Intel C++ compiler. Can switching to ASM help and how much? Can switching to Linux and GCC help?

Answer:
Switching to ASM is not going to help much, unless you're very good at it and/or have a specific critical path routine which you know you can do better. As several people have remarked, modern compilers are just better in most cases at taking advantages of caching/etc. than anyone can do by hand.
I'd suggest:
Try a different compiler, and/or different optimization options
Run a code coverage/analysis utility, and figure out where the critical paths are, and work on optimizing those in the code
C++ should be able to give you very near the best possible performance from the code, so I wouldn't recommend switching the language. Depending on the app, you may be able to get better performance on multi code/processor systems using multiple thread, as another suggestion.


Question:
I need to pad the output of an integer to a given length.

For example, with a length of 4 digits, the output of the integer 4 is "0004" instead of "4". How can I do this in C# 2.0?

Answer:
Use the string.Format command.
```
```
output = String.Format("{0:0000}", intVariable);
```
```
More details:
http://msdn.microsoft.com/en-us/library/fht0f5be.aspx


Question: How are arrays manipulated in D?

Answer:
Here
you can find a complete reference of array manipulations in D.


Question:
How can I determine if I'm running on a 32bit or a 64bit version of matlab?

I have some pre-compiled mex-files which need different path's depending on 32/64bit matlab.

Answer:
Does this really work? Which version of matlab are you using?
As far as I'm aware the 64 bit platforms end with "64" not 86. From the matlab site
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/computer.html
I don't think that computer will ever return GLNXA86 but GLNXA64 instead.
So this question is specific to GNU Linux 32bit or 64bit version.
If you are testing for any 64bit platform then you probably need to test the last 2 characters to find "64" i.e. something like
```
```
if regexp(computer,'..$','match','64'),
   % setup 64bit options
else,
   % 32bit options
end
```
```


Question:
I noticed when a file is executed on Windows (.exe or .dll), it is locked and cannot be deleted, moved or modified.

Linux, on the other hand, does not lock executing files and you can delete, move, or modify them.

Why does Windows lock when Linux does not? Is there an advantage to locking?

Answer:
I think linux / unix doesn't use the same locking mechanics because they are built from the ground up as a multi-user system - which would expect the possibility of multiple users using the same file, maybe even for different purposes.
Is there an advantage to locking?  Well, it could possibly reduce the amount of pointers that the OS would have to manage, but now a days the amount of savings is pretty negligible. The biggest advantage I can think of to locking is this: you save some user-viewable ambiguity. If user a is running a binary file, and user b deletes it, then the actual file has to stick around until user A's process completes.  Yet, if User B or any other users look on the file system for it, they won't be able to find it - but it will continue to take up space.  Not really a huge concern to me.
I think largely it's more of a question on backwards compatibility with window's file systems.


Question: Where is the location of my oracle event log (on a default Linux installation)?

Answer:
```
```
select value from v$parameter where name = 'background_dump_dest'
```
```


Question:
I'm in a Microsoft IE environment, but I want to use cygwin for a number of quick scripting tasks.

How would I configure it to use my windows proxy information?  Ruby gems, ping, etc are all trying to make direct connections.  How can I get them to respect the proxy information that IE and firefox use?

Answer:
I doubt that your corporate firewall allows PING, but the others all appear to be one form of http or another.  On a Linux system, you can set your HTTP proxy as an environment variable, so in bash, type:
```
```
export http_proxy=http://www.myproxy.com:3128
```
```
There is a similar environment variable for FTP (ftp_proxy).


Question:
What are the minimum OS requirements for each of the .Net frameworks?  E.g. for which version is it impossible to run each OS on:

Windows 95

Windows 98

Windows 98SE

Windows ME

Windows NT 3.x

Windows NT 4

Windows 2000

I believe all .Net frameworks are compatible w/ XP, Vista, Windows Server 2003, and Windows Server 2008 (please correct me on that if wrong).

Answer:
Microsoft .NET framework is supported on Windows 98 and up starting at version 1.0, with the following exceptions:
```
```
Windows NT
Windows Server 2003 (Itanium-based)
```
```
As an added note, I've been able to run .NET IL Portable Executables on platforms up to version 2.0 fairly reliably through Mono on Linux based machines.  Though it does run better if it is compiled in Mono.  For odd some reason, PE's compiled with the Mono package are closer to the written standards of the .NET IL than when compiled with the Microsoft .NET compilers.
.NET 2.0 states on MSDN that it is compatible with Windows 98
.NET 3.0/3.5 requires XP or above
:
```
```
Microsoft Windows 2003 Server Service Pack 1 (SP1)
Windows XP SP2
Windows Vista *
```
```


Question: My rails app is in a svn repository, but several of the plugins are installed through git and later added to the svn repo.  How can I update these plugins?  I can't seem to get script/plugin update to do anything.  I'd really like to update activemerchant to get rid of the Inflector warnings.

Answer:
You should just be able to navigate to the plugin's directory and hit:
```
git pull
```
. I'm pretty sure that
```
script/install plugin
```
just checks the code out from the git repo.


Question:
How do I set gc.reflogExpire so that items will never expire?

What other time interval formats does it accept?

The man page says that you can set it to "90 days or 3 months," but doesn't specify what format it expects.

Answer:
I’m not sure where the format is documented, if at all, but
```
git reflog
```
uses the
```
approxidate
```
function from
```
date.c
```
to parse the expiry time. One of the possible values is “never.”


Question:
Is there a standard way to see how much stack space your app has and what the highest watermark for stack usage is during a run?

Also in the dreaded case of actual overflow what happens?

Does it crash, trigger an exception or signal? Is there a standard or is it different on all systems and compilers?

I'm looking specifically for Windows, Linux and Macintosh.

Answer:
On
Windows
a stack overflow
exception
will be generated.
The following windows code illustrates this:
```
```
#include <stdio.h>
#include <windows.h>

void StackOverFlow()
{
  CONTEXT context;

  // we are interested control registers
  context.ContextFlags = CONTEXT_CONTROL;

  // get the details
  GetThreadContext(GetCurrentThread(), &context);

  // print the stack pointer
  printf("Esp: %X\n", context.Esp);

  // this will eventually overflow the stack
  StackOverFlow();
}

DWORD ExceptionFilter(EXCEPTION_POINTERS *pointers, DWORD dwException)
{
  return EXCEPTION_EXECUTE_HANDLER;
}

void main()
{
  CONTEXT context;

  // we are interested control registers
  context.ContextFlags = CONTEXT_CONTROL;

  // get the details
  GetThreadContext(GetCurrentThread(), &context);

  // print the stack pointer
  printf("Esp: %X\n", context.Esp);

  __try
  {
    // cause a stack overflow
    StackOverFlow();
  }
  __except(ExceptionFilter(GetExceptionInformation(), GetExceptionCode()))
  {
    printf("\n****** ExceptionFilter fired ******\n");
  }
}
```
```
When this exe is run the following output is generated:
```
```
Esp: 12FC4C
Esp: 12F96C
Esp: 12F68C
.....
Esp: 33D8C
Esp: 33AAC
Esp: 337CC

****** ExceptionFilter fired ******
```
```


Question:
How can you round any number (not just integers > 0) to N significant digits?

For example, if I want to round to three significant digits, I'm looking for a formula that could take:

1,239,451 and return 1,240,000

12.1257 and return 12.1

.0681 and return .0681

5 and return 5

Naturally the algorithm should not be hard-coded to only handle N of 3, although that would be a start.

Answer:
SUMMARY:
```
```
double roundit(double num, double N)
{
    double d = log10(num);
    double power;
    if (num > 0)
    {
        d = ceil(d);
        power = -(d-N);
    }
    else
    {
        d = floor(d);
        power = -(d-N);
    }

    return (int)(num * pow(10.0, power) + 0.5) * pow(10.0, -power);
}
```
```
So you need to find the decimal place of the first non-zero digit, then save the next N-1 digits, then round the Nth digit based on the rest.
We can use log to do the first.
```
```
log 1239451 = 6.09
log 12.1257 = 1.08
log 0.0681  = -1.16
```
```
So for numbers > 0, take the ceil of the log. For numbers < 0, take the floor of the log.
Now we have the digit
```
d
```
: 7 in the first case, 2 in the 2nd, -2 in the 3rd.
We have to round the
```
(d-N)
```
th digit. Something like:
```
```
double roundedrest = num * pow(10, -(d-N));

pow(1239451, -4) = 123.9451
pow(12.1257, 1)  = 121.257
pow(0.0681, 4)   = 681
```
```
Then do the standard rounding thing:
```
```
roundedrest = (int)(roundedrest + 0.5);
```
```
And undo the pow.
```
```
roundednum = pow(roundedrest, -(power))
```
```
Where power is the power calculated above.
About accuracy: Pyrolistical's answer is indeed closer to the real result. But note that you can't represent 12.1 exactly in any case. If you print the answers as follows:
```
```
System.out.println(new BigDecimal(n));
```
```
The answers are:
```
```
Pyro's: 12.0999999999999996447286321199499070644378662109375
Mine: 12.10000000000000142108547152020037174224853515625
Printing 12.1 directly: 12.0999999999999996447286321199499070644378662109375
```
```
So, use Pyro's answer!


Question:
Especially when considering a fresh Rails project, what does your version control and deployment workflow look like? What tools do you use?

I'm interested in answers for Mac, *nix and Windows work machines. Assume a *nix server.

I'll edit for clarity if need be.

Answer:
Create a copy of my personal Rails 2.1.1 template with preinstalled plugins and frozen gems.
Change DB passwords, session secret/name and
```
deploy.rb
```
.
Create a private or public repository on GitHub as needed.
Push the empty rails project to GitHub.
SSH to Server and configure apache (copy Virtual Host file and mongrel config files from old project)
Create empty database on MySQL server
```
cap deploy:setup && cap deploy:cold
```
If everything works so far: Start developing and committing to GitHub.
```
cap deploy
```
as needed.
Update:
Don't forget to write tests for
everything
you do!


Question:
Anyone visiting a torrent tracker is sure to find droves of "cracked" programs ranging from simple shareware to software suites costing thousands of dollars.  It seems that as long as the program does not rely on a remote service (e.g. an MMORPG) that any built-in copy protection or user authentication is useless.

Is it effectively not possible to prevent a cracker from circumventing the copy protection?  Why?

Answer:
Copy-protection is like security -- it's impossible to achieve 100% perfection but you can add layers that make it successively more difficult to crack.
Most applications have some point where they ask (themselves), "Is the license valid?"  The hacker just needs to find that point and alter the compiled code to return "yes."  Alternatively, crackers can use brute-force to try different license keys until one works.  There's also social factors -- once one person buys the tool they might post a valid license code on the Internet.
So, code obfuscation makes it more difficult (but not impossible) to find the code to alter.  Digital signing of the binaries makes it more difficult to change the code, but still not impossible.  Brute-force methods can be combated with long license codes with lots of error-correction bits.  Social attacks can be mitigated by requiring a name, email, and phone number that is
part of the license code itself
.  I've used that method to great effect.
Good luck!


Question:
I know that it does consider ' ' as NULL, but that doesn't do much to tell me why this is the case.  As I understand the SQL specifications, ' ' is not the same as NULL -- one is a valid datum, and the other is indicating the absence of that same information.

Feel free to speculate, but please indicate if that's the case.  If there's anyone from Oracle who can comment on it, that'd be fantastic!

Answer:
Indeed, I have had nothing but difficulties in dealing with Oracle, including invalid datetime values (cannot be printed, converted or anything, just looked at with the DUMP() function) which are
allowed
to be inserted into the database, apparently through some buggy version of the client as a binary column!  So much for protecting database integrity!
Oracle handling of NULLs links:
http://digitalbush.com/2007/10/27/oracle-9i-null-behavior/
http://jeffkemponoracle.com/2006/02/empty-string-andor-null.html


Question:
I am writing a program in Python that will act as a server and accept data from a client, is it a good idea to impose a hard limit as to the amount of data, if so why?

More info:
So certain chat programs limit the amount of text one can send per send (i.e. per time user presses send) so the question comes down to is there a legit reason for this and if yes, what is it?

Answer:
What is your question exactly?
What happens when you do receive on a socket is that the current available data in the socket buffer is immediately returned. If you give receive (or read, I guess), a huge buffer size, such as 40000, it'll likely never return that much data at once. If you give it a tiny buffer size like 100, then it'll return the 100 bytes it has immediately and still have more available. Either way, you're not imposing a limit on how much data the client is sending you.


Question:
Example. 123456, and we want the third from the right ('4') out.

The idea in practise is to access each digit seperately (ie. 6 5 4 3 2 1).

C/C++/C# preferred.

Answer:
In C you could do something like the following, where n=0 would indicate the rightmost digit
```
```
char nthDigitFromRight(int x,int n)
{
    char str[20];
    sprintf(str,"%020d",x);
    return(str[19 - x]);
}
```
```
Change [19-x] to [20-x] if you want n=1 for rightmost digit.


Question: I would like to access the work items in our TFS programmatically. Shouldn't there be an obvious command line tool to extract such information? Or a WebService I can just call? I already have checked into using Excel - this is neat, but I want more hardcore...

Answer:
Take a look at the TFS API (
http://msdn.microsoft.com/en-us/library/bb130146(VS.80).aspx
).  Access to the same code used by Microsoft to create the Visual Studio integration and their version control command line tool (
tf.exe
).
You can also take a look at the power tools.
tfpt.exe
is the power tool command line and has many other advanced features.  That said - you can do pretty much what you want with the SDK.
The new version of the power tools will be out soon, and that looks to have
Powershell support
coming
Enjoy!


Question: I have an alert script that I am trying to keep from spamming me so I'd like to place a condition that if an alert has been sent within, say the last hour, to not send another alert.  Now I have a cron job that checks the condition every minute because I need to be alerted quickly when the condition is met but I don't need to get the email every munite until I get the issue under control.  What is the best way to compare time in bash to accomplish this?

Answer:
Use "test":
```
```
if test file1 -nt file2; then
   # file1 is newer than file2
fi
```
```
EDIT: If you want to know when an event occurred, you can use "touch" to create a file which you can later compare using "test".


Question:
I am running both maven inside the m2eclipse plugin, windows command line and my cygwin command line.

cygwin's bash shell dumps artifacts into the cygwin /home/me/.m2 directory

but m2eclipse & windows shell (on vista) uses /Users/me/Documents/.m2

Is it possible to tell the mvn command to use one central .m2 directory ?

Thanks

Answer:
Sure, several ways.  The most typical is to specify this in your settings.xml file:
http://maven.apache.org/settings.html
```
```
<settings xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository>/my/secret/repository</localRepository>
</settings>
```
```


Question: Can we somehow extend the RuleSetDialog class and host in our windows application?

Answer:
You can not extend the RuleSetDialog class (since it is sealed), but you can host it in your app:
RuleSetDialog Class
Hosting the workflow rules designer
Rules Engine via Windows Workflow Foundation
Filtering Intellisense lists in the WF RuleSetDialog
Windows Workflow Foundation Rules for Generic Types
Tweaking RuleSetDialog to Resize
PowerShell Rules Engine: How-To Technical Details


Question:
How do I get the full width result for the *nix command "ps"?

I know we can specify something like --cols 1000 but is there anyway I can
the columns and just print out everything?

Answer:
Try
```
ps -w -w aux
```
. The -w option sets the output to wide, and doing it twice makes the width unlimited. The "aux" part makes it show more information, and is (afaik) pretty standard mode to use. This is of course platform-dependant, the above works with procps version 3.2.7 on Linux.


Question:
I'm converting some Windows batch files to Unix scripts using sh. I have problems because some behavior is dependent on the %~dp0 macro available in batch files.

Is there any sh equivalent to this? Any way to obtain the directory where the executing script lives?

Answer:
Yes, you can! It's in the arguments. :)
look at
```
```
${0}
```
```
combining that with
```
```
{$var%Pattern}
Remove from $var  the shortest part of $Pattern that matches the back end of $var.
```
```
what you want is just
```
```
${0%/*}
```
```
I recommend the
Advanced Bash Scripting Guide
(that is also where the above information is from).
Especiall the part on
Converting DOS Batch Files to Shell Scripts
might be useful for you. :)
If I have misunderstood you, you may have to combine that with the output of "pwd". Since it only contains the path the script was called with!
Try the following script:
```
```
#!/bin/bash
called_path=${0%/*}
stripped=${called_path#[^/]*}
real_path=`pwd`$stripped
echo "called path: $called_path"
echo "stripped: $stripped"
echo "pwd: `pwd`"
echo "real path: $real_path
```
```
This needs some work though.
I recommend using Dave Webb's approach unless that is impossible.


Question:
I came across PHP way of doing the trick:

my_bool reconnect = 1;
mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);

but no luck with MySQLdb (python-mysql).

Can anybody please give a clue? Thanks.

Answer:
If you are using ubuntu Linux there was a patch added to the python-mysql package that added the ability to set that same MYSQL_OPT_RECONNECT option (see
here
).  I have not tried it though.
Unfortunately, the patch was later removed due to a conflict with autoconnect and transations (described
here
).
The comments from that page say:
1.2.2-7 Published in intrepid-release on 2008-06-19
python-mysqldb (1.2.2-7) unstable; urgency=low
[ Sandro Tosi ]
  * debian/control
    - list items lines in description starts with 2 space, to avoid reformat
      on webpages (Closes: #480341)
[ Bernd Zeimetz ]
  * debian/patches/02_reconnect.dpatch:
    - Dropping patch:
      Comment in Storm which explains the problem:
```
```
# Here is another sad story about bad transactional behavior. MySQL
    # offers a feature to automatically reconnect dropped connections.
    # What sounds like a dream, is actually a nightmare for anyone who
    # is dealing with transactions. When a reconnection happens, the
    # currently running transaction is transparently rolled back, and
    # everything that was being done is lost, without notice. Not only
    # that, but the connection may be put back in AUTOCOMMIT mode, even
    # when that's not the default MySQLdb behavior. The MySQL developers
    # quickly understood that this is a terrible idea, and removed the
    # behavior in MySQL 5.0.3. Unfortunately, Debian and Ubuntu still
    # have a patch right now which *reenables* that behavior by default
    # even past version 5.0.3.
```
```


Question:
I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.

I've seen mentioned a few places that python is good for this kind of thing. How can I use Python to replace shell scripting, AWK, sed and friends?

Answer:
I suggest the awesome online book
Dive Into Python
.  It's how I learned the language originally.
Beyond teaching you the basic structure of the language, and a whole lot of useful data structures, it has a good chapter on
file handling
and subsequent chapters on
regular expressions
and more.


Question:
I'm looking for a regex that can pull out quoted sections in a string, both single and double quotes.

IE:

"This is 'an example', \"of an input string\""

Matches:

an example

of an input string

I wrote up this:

 [\"|'][A-Za-z0-9\\W]+[\"|']

It works but does anyone see any flaws with it?

EDIT: The main issue I see is that it can't handle nested quotes.

Answer:
It works but doesn't match other characters in quotes (e.g., non-alphanumeric, like binary or foreign language chars). How about this:
```
```
[\"']([^\"']*)[\"']
```
```
My C# regex is a little rusty so go easy on me if that's not exactly right :)


Question:
What's the shortest Perl one-liner that  print out the first 9 powers of a hard-coded 2 digit decimal (say, for example, .37), each on its own line?

The output would look something like:

1
0.37
0.1369
[etc.]

Official Perl golf rules:

Smallest number of (key)strokes wins

Your stroke count includes the command line

Answer:
```
```
perl -e "for(my $i = 1; $i < 10; $i++){ print((.37**$i). \"\n\"); }"
```
```
Just a quick entry. :)
Fixed to line break!