Question: There should be something akin to \w that can match any code-point in Letters or Marks category (not just the ASCII ones), and hopefully have filters like [[P*]] for punctuation, etc.

Answer:
Situation for ES 6
The ECMAScript language specification, edition 6 (also commonly known as ES2015), includes Unicode-aware regular expressions. Support must be enabled with the
```
u
```
modifier on the regex. See
Unicode-aware regular expressions in ES6
for a break-down of the feature and some caveats.
ES6 is widely adopted in both browsers and stand-alone Javascript runtimes such as Node.js, so using this feature won't require extra effort in most cases. Full compatibility list:
https://kangax.github.io/compat-table/es6/
Situation for ES 5 and below (legacy browsers)
There is
a transpiler named
regexpu
that translates ES6 Unicode regular expressions into equivalent ES5. It can be used as part of your build process.
Try it out online.
.
Even though JavaScript operates on Unicode strings, it does not implement Unicode-aware character classes and has no concept of POSIX character classes or Unicode blocks/sub-ranges.
Issues with Unicode in JavaScript regular expressions
Check your expectations here:
Javascript RegExp Unicode Character Class tester
(
Edit:
the original page is down,
the Internet Archive still has a copy
.)
Flagrant Badassery has an article on
JavaScript, Regex, and Unicode
that sheds some light on the matter.
Also read
Regex and Unicode
here on SO. Probably you have to build your own "punctuation character class".
Check out the
Regular Expression: Match Unicode Block Range
builder (
archived copy
), which lets you build a JavaScript regular expression that matches characters that fall in any number of specified Unicode blocks.
I just did it for the "General Punctuation" and "Supplemental Punctuation" sub-ranges, and the result is as simple and straight-forward as I would have expected it:
```
```
[\u2000-\u206F\u2E00-\u2E7F]
```
```
There also is
XRegExp
, a project that brings
Unicode support to JavaScript
by offering an alternative regex engine with extended capabilities.
And of course, required reading:
mathiasbynens.be - JavaScript has a Unicode problem
:


Question: I'm going to rebuild my Linux box [yet] again.  I have to create a few user groups, user accounts and install my standard packages.  Until now I've just used the GUI tools.  I was wondering if anyone has any recommendations on writing a script to create users, groups and install standard packages after I do a minimal install of my latest Fedora build?  Sometimes I run Ubuntu so I'd like the script to be somewhat generic.

Answer:
Fedora and Ubuntu use totally different package managers, so you won't be able to easily do it in any sort of generic way.
In CentOS (which is RedHat Enterprise Edition with the serial numbers filed off, and so therefore pretty close to Fedora), we did this
using Kickstart files
.  These files have a simple syntax that enabled you to specify users, groups and packages to install, and even to script some custom stuff.


Question:
Is there a way to set/change the keyboard input language in Java (eg from English to German)?

Example Use Case: Script to be used for playback is recorded (typed in) on a German keyboard. The automated playback is done on a English keyboard...fails if keyboard is not set to German automatically before script is run.

Answer:
The keyboard input map is managed entirely by the operating system on every platform that I'm familiar with.  Java provides no APIs for manipulating this in a cross-platform manner.  I would investigate native APIs that you could manipulate via
JNA
, or even (if you're feeling dirty) shelling out to call some platform-specific command which does what you need.
You're not going to find a solution within the JDK standard lib.


Question:
Can a Silverlight 2 enabled web page be managed from an Apache server? (I'm not actually interested in doing this but trying to understand Silverlight 2 a bit more.)

Assuming that I have IIS6 and Server 2003 what are the .NET version requirements to host a web site with Silverlight 2? Are .NET 3.0 and 3.5 required on the server? My thinking is not because this is a client side technology.

Answer:
The
system requirements for Microsoft Silverlight
and associated technologies are listed below.
```
```
* Windows
      o Operating System: Windows Vista; Windows XP Service Pack 2
      o Intel® Pentium® III 450MHz or faster processor (or equivalent)
      o 128MB of RAM
* Mac OS
      o Operating System: Apple Mac OS X 10.4.8 or above
      o Intel Core™ Duo 1.83GHz or faster processor
      o 128MB of RAM
* Linux. For the system requirements, please refer to the Mono Project's Moonlight Web site.
```
```


Question:
I know that lots of web hosting providers are offering FreeBSD, but how good is FreeBSD as a development platform?

Specifically, is Java 1.6 available in it?
Is there somthing specific that it offers with regard to tools that is not available under Linux?

Answer: Well, there's no Java 1.6 in the /usr/ports of the version I recently installed (latest version AFAIK).  The port of Netbeans is only up to 5.5 bundled.  At a minimum you'd have to go look around for more current versions.  Doesn't look promising as a fully kept up to date development platform.


Question: I know that I can  svn diff -r a:b repo  to view the changes between the two specified revisions.  What I'd like is a diff for every revision that changed the file.  Is such a command available?

Answer:
You could use
```
git-svn
```
to import the repository into a Git repository, then use
```
git log -p filename
```
. This shows each log entry for the file followed by the corresponding diff.


Question:
Does anyone have sample code to copy open (in-use and locked by another program) files using Volume Shadow Copy Service (VSS) API?

There was an article about this in The Delphi Magazine (September 2005). But that code is no longer available and even if it was, it's not current.

I am looking for sample code that works with current version of Volume Shadow Copy service libraries.

Answer:
there is a digital edition on usb stick of the "The Delphi Magazine".
you can order that on their webpage.
maybe someone has created a torrent of that stick.
update
i found that sample here:
http://www.google.com/codesearch/p?hl=de#XIdFp1PskBE/VSS/VssAPI.pas
Upper link is outdated, the header-files can also found here:
http://www.delphipraxis.net/998560-post3.html


Question:
I want to transform /foo/bar/.. to /foo

Is there a bash command which does this?

Edit: in my practical case, the directory does exist.

Answer:
Try
```
realpath
```
. Below is the source in its entirety, hereby donated to the public domain.
```
```
// realpath.c: display the absolute path to a file or directory.
// Adam Liss, August, 2007
// This program is provided "as-is" to the public domain, without express or
// implied warranty, for any non-profit use, provided this notice is maintained.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>
#include <limits.h>

static char *s_pMyName;
void usage(void);

int main(int argc, char *argv[])
{
    char
        sPath[PATH_MAX];

    s_pMyName = strdup(basename(argv[0]));

    if (argc < 2)
        usage();

    printf("%s\n", realpath(argv[1], sPath));
    return 0;
}

void usage(void)
{
    fprintf(stderr, "usage: %s PATH\n", s_pMyName);
    exit(1);
}
```
```


Question: How do I convert a DateTime structure to its equivalent RFC 822 date-time formatted string representation and parse this string representation back to a DateTime structure in .NET? The RFC-822 date-time format is used in a number of specifications such as the RSS Syndication Format.

Answer:
This is an implementation in C# of how to parse and convert a DateTime to and from its RFC-822 representation. The only restriction it has is that the DateTime is in Coordinated Universal Time (UTC). I agree that this is not very elegant code, but it does the job.
```
```
///
/// Provides methods for converting <see cref="DateTime"/> structures
/// to and from the equivalent RFC 822
/// string representation.
///
public class Rfc822DateTime
{
    //============================================================
    //  Private members
    //============================================================
    #region Private Members
    ///
    /// Private member to hold array of formats that RFC 822 date-time representations conform to.
    ///
    private static string[] formats = new string[0];
    ///
    /// Private member to hold the DateTime format string for representing a DateTime in the RFC 822 format.
    ///
    private const string format     = "ddd, dd MMM yyyy HH:mm:ss K";
    #endregion

    //============================================================
    //  Public Properties
    //============================================================
    #region Rfc822DateTimeFormat
    ///
    /// Gets the custom format specifier that may be used to represent a <see cref="DateTime"/> in the RFC 822 format.
    ///
    /// <value>A DateTime format string that may be used to represent a <see cref="DateTime"/> in the RFC 822 format.</value>
    /// <remarks>
    /// <para>
    /// This method returns a string representation of a <see cref="DateTime"/> that utilizes the time zone
    /// offset (local differential) to represent the offset from Greenwich mean time in hours and minutes.
    /// The <see cref="Rfc822DateTimeFormat"/> is a valid date-time format string for use
    /// in the <see cref="DateTime.ToString(String, IFormatProvider)"/> method.
    /// </para>
    /// <para>
    /// The RFC 822 Date and Time specification
    /// specifies that the year will be represented as a two-digit value, but the
    /// RSS Profile recommends that
    /// all date-time values should use a four-digit year. The <see cref="Rfc822DateTime"/> class
    /// follows the RSS Profile recommendation when converting a <see cref="DateTime"/> to the equivalent
    /// RFC 822 string representation.
    /// </para>
    /// </remarks>
    public static string Rfc822DateTimeFormat
    {
        get
        {
            return format;
        }
    }
    #endregion

    #region Rfc822DateTimePatterns
    ///
    /// Gets an array of the expected formats for RFC 822 date-time string representations.
    ///
    /// <value>
    /// An array of the expected formats for RFC 822 date-time string representations
    /// that may used in the <see cref="DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)"/> method.
    /// </value>
    /// <remarks>
    /// The array of the expected formats that is returned assumes that the RFC 822 time zone
    /// is represented as or converted to a local differential representation.
    /// </remarks>
    /// <seealso cref="ConvertZoneToLocalDifferential(String)"/>
    public static string[] Rfc822DateTimePatterns
    {
        get
        {
            if (formats.Length > 0)
            {
                return formats;
            }
            else
            {
                formats = new string[35];

                // two-digit day, four-digit year patterns
                formats[0]  = "ddd',' dd MMM yyyy HH':'mm':'ss'.'fffffff zzzz";
                formats[1]  = "ddd',' dd MMM yyyy HH':'mm':'ss'.'ffffff zzzz";
                formats[2]  = "ddd',' dd MMM yyyy HH':'mm':'ss'.'fffff zzzz";
                formats[3]  = "ddd',' dd MMM yyyy HH':'mm':'ss'.'ffff zzzz";
                formats[4]  = "ddd',' dd MMM yyyy HH':'mm':'ss'.'fff zzzz";
                formats[5]  = "ddd',' dd MMM yyyy HH':'mm':'ss'.'ff zzzz";
                formats[6]  = "ddd',' dd MMM yyyy HH':'mm':'ss'.'f zzzz";
                formats[7]  = "ddd',' dd MMM yyyy HH':'mm':'ss zzzz";

                // two-digit day, two-digit year patterns
                formats[8]  = "ddd',' dd MMM yy HH':'mm':'ss'.'fffffff zzzz";
                formats[9]  = "ddd',' dd MMM yy HH':'mm':'ss'.'ffffff zzzz";
                formats[10] = "ddd',' dd MMM yy HH':'mm':'ss'.'fffff zzzz";
                formats[11] = "ddd',' dd MMM yy HH':'mm':'ss'.'ffff zzzz";
                formats[12] = "ddd',' dd MMM yy HH':'mm':'ss'.'fff zzzz";
                formats[13] = "ddd',' dd MMM yy HH':'mm':'ss'.'ff zzzz";
                formats[14] = "ddd',' dd MMM yy HH':'mm':'ss'.'f zzzz";
                formats[15] = "ddd',' dd MMM yy HH':'mm':'ss zzzz";

                // one-digit day, four-digit year patterns
                formats[16] = "ddd',' d MMM yyyy HH':'mm':'ss'.'fffffff zzzz";
                formats[17] = "ddd',' d MMM yyyy HH':'mm':'ss'.'ffffff zzzz";
                formats[18] = "ddd',' d MMM yyyy HH':'mm':'ss'.'fffff zzzz";
                formats[19] = "ddd',' d MMM yyyy HH':'mm':'ss'.'ffff zzzz";
                formats[20] = "ddd',' d MMM yyyy HH':'mm':'ss'.'fff zzzz";
                formats[21] = "ddd',' d MMM yyyy HH':'mm':'ss'.'ff zzzz";
                formats[22] = "ddd',' d MMM yyyy HH':'mm':'ss'.'f zzzz";
                formats[23] = "ddd',' d MMM yyyy HH':'mm':'ss zzzz";

                // two-digit day, two-digit year patterns
                formats[24] = "ddd',' d MMM yy HH':'mm':'ss'.'fffffff zzzz";
                formats[25] = "ddd',' d MMM yy HH':'mm':'ss'.'ffffff zzzz";
                formats[26] = "ddd',' d MMM yy HH':'mm':'ss'.'fffff zzzz";
                formats[27] = "ddd',' d MMM yy HH':'mm':'ss'.'ffff zzzz";
                formats[28] = "ddd',' d MMM yy HH':'mm':'ss'.'fff zzzz";
                formats[29] = "ddd',' d MMM yy HH':'mm':'ss'.'ff zzzz";
                formats[30] = "ddd',' d MMM yy HH':'mm':'ss'.'f zzzz";
                formats[31] = "ddd',' d MMM yy HH':'mm':'ss zzzz";

                // Fall back patterns
                formats[32] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; // RoundtripDateTimePattern
                formats[33] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern;
                formats[34] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern;

                return formats;
            }
        }
    }
    #endregion

    //============================================================
    //  Public Methods
    //============================================================
    #region Parse(string s)
    ///
    /// Converts the specified string representation of a date and time to its <see cref="DateTime"/> equivalent.
    ///
    /// <param name="s">A string containing a date and time to convert.</param>
    /// <returns>
    /// A <see cref="DateTime"/> equivalent to the date and time contained in <paramref name="s"/>,
    /// expressed as Coordinated Universal Time (UTC).
    /// </returns>
    /// <remarks>
    /// The string <paramref name="s"/> is parsed using formatting information in the <see cref="DateTimeFormatInfo.InvariantInfo"/> object.
    /// </remarks>
    /// <exception cref="ArgumentNullException"><paramref name="s"/> is a null reference (Nothing in Visual Basic).</exception>
    /// <exception cref="ArgumentNullException"><paramref name="s"/> is an empty string.</exception>
    /// <exception cref="FormatException"><paramref name="s"/> does not contain a valid RFC 822 string representation of a date and time.</exception>
    public static DateTime Parse(string s)
    {
        //------------------------------------------------------------
        //  Validate parameter
        //------------------------------------------------------------
        if (String.IsNullOrEmpty(s))
        {
          throw new ArgumentNullException("s");
        }

        DateTime result;
        if (Rfc822DateTime.TryParse(s, out result))
        {
            return result;
        }
        else
        {
            throw new FormatException(String.Format(null, "{0} is not a valid RFC 822 string representation of a date and time.", s));
        }
    }
    #endregion

    #region ConvertZoneToLocalDifferential(string s)
    ///
    /// Converts the time zone component of an RFC 822 date and time string representation to its local differential (time zone offset).
    ///
    /// <param name="s">A string containing an RFC 822 date and time to convert.</param>
    /// <returns>A date and time string that uses local differential to describe the time zone equivalent to the date and time contained in <paramref name="s"/>.</returns>
    /// <exception cref="ArgumentNullException"><paramref name="s"/> is a null reference (Nothing in Visual Basic).</exception>
    /// <exception cref="ArgumentNullException"><paramref name="s"/> is an empty string.</exception>
    public static string ConvertZoneToLocalDifferential(string s)
    {
        string zoneRepresentedAsLocalDifferential   = String.Empty;

        //------------------------------------------------------------
        //  Validate parameter
        //------------------------------------------------------------
        if (String.IsNullOrEmpty(s))
        {
          throw new ArgumentNullException("s");
        }

        if(s.EndsWith(" UT", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" UT") + 1) ), "+00:00");
        }
        else if (s.EndsWith(" GMT", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" GMT") + 1 ) ), "+00:00");
        }
        else if (s.EndsWith(" EST", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" EST") + 1)), "-05:00");
        }
        else if (s.EndsWith(" EDT", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" EDT") + 1)), "-04:00");
        }
        else if (s.EndsWith(" CST", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" CST") + 1)), "-06:00");
        }
        else if (s.EndsWith(" CDT", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" CDT") + 1)), "-05:00");
        }
        else if (s.EndsWith(" MST", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" MST") + 1)), "-07:00");
        }
        else if (s.EndsWith(" MDT", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" MDT") + 1)), "-06:00");
        }
        else if (s.EndsWith(" PST", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" PST") + 1)), "-08:00");
        }
        else if (s.EndsWith(" PDT", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" PDT") + 1)), "-07:00");
        }
        else if (s.EndsWith(" Z", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" Z") + 1)), "+00:00");
        }
        else if (s.EndsWith(" A", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" A") + 1)), "-01:00");
        }
        else if (s.EndsWith(" M", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" M") + 1)), "-12:00");
        }
        else if (s.EndsWith(" N", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" N") + 1)), "+01:00");
        }
        else if (s.EndsWith(" Y", StringComparison.OrdinalIgnoreCase))
        {
            zoneRepresentedAsLocalDifferential  = String.Concat(s.Substring(0, (s.LastIndexOf(" Y") + 1)), "+12:00");
        }
        else
        {
            zoneRepresentedAsLocalDifferential  = s;
        }

        return zoneRepresentedAsLocalDifferential;
    }
    #endregion

    #region ToString(DateTime utcDateTime)
    ///
    /// Converts the value of the specified <see cref="DateTime"/> object to its equivalent string representation.
    ///
    /// <param name="utcDateTime">The Coordinated Universal Time (UTC) <see cref="DateTime"/> to convert.</param>
    /// <returns>A RFC 822 string representation of the value of the <paramref name="utcDateTime"/>.</returns>
    /// <exception cref="ArgumentException">The specified <paramref name="utcDateTime"/> object does not represent a <see cref="DateTimeKind.Utc">Coordinated Universal Time (UTC)</see> value.</exception>
    public static string ToString(DateTime utcDateTime)
    {
        if (utcDateTime.Kind != DateTimeKind.Utc)
        {
            throw new ArgumentException("utcDateTime");
        }

        return utcDateTime.ToString(Rfc822DateTime.Rfc822DateTimeFormat, DateTimeFormatInfo.InvariantInfo);
    }
    #endregion

    #region TryParse(string s, out DateTime result)
    ///
    /// Converts the specified string representation of a date and time to its <see cref="DateTime"/> equivalent.
    ///
    /// <param name="s">A string containing a date and time to convert.</param>
    /// <param name="result">
    /// When this method returns, contains the <see cref="DateTime"/> value equivalent to the date and time
    /// contained in <paramref name="s"/>, expressed as Coordinated Universal Time (UTC),
    /// if the conversion succeeded, or <see cref="DateTime.MinValue">MinValue</see> if the conversion failed.
    /// The conversion fails if the s parameter is a null reference (Nothing in Visual Basic),
    /// or does not contain a valid string representation of a date and time.
    /// This parameter is passed uninitialized.
    /// </param>
    /// <returns>true if the <paramref name="s"/> parameter was converted successfully; otherwise, false.</returns>
    /// <remarks>
    /// The string <paramref name="s"/> is parsed using formatting information in the <see cref="DateTimeFormatInfo.InvariantInfo"/> object.
    /// </remarks>
    public static bool TryParse(string s, out DateTime result)
    {
        //------------------------------------------------------------
        //  Attempt to convert string representation
        //------------------------------------------------------------
        bool wasConverted   = false;
        result              = DateTime.MinValue;

        if (!String.IsNullOrEmpty(s))
        {
            DateTime parseResult;
            if (DateTime.TryParseExact(Rfc822DateTime.ConvertZoneToLocalDifferential(s), Rfc822DateTime.Rfc822DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult))
            {
                result          = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc);
                wasConverted    = true;
            }
        }

        return wasConverted;
    }
    #endregion
}
```
```


Question:
private JButton jBtnDrawCircle = new JButton("Circle");
private JButton jBtnDrawSquare = new JButton("Square");
private JButton jBtnDrawTriangle = new JButton("Triangle");
private JButton jBtnSelection = new JButton("Selection");

How do I add action listeners to these buttons, so that from a main method I can call actionperformed on them, so when they are clicked I can call them in my program?

Answer:
Your best bet is to review the
Java Swing tutorials
, specifically the
tutorial on Buttons
.
The short code snippet is:
```
```
jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );
```
```


Question: I'm using MediaTemple's (dv) hosting service. How do I determine what mail-server is installed? Should I use the shell? If so, what command would be used?

Answer:
Go to the shell and type this command:
```
```
telnet <hostname> 25
```
```
This will come back with a line like so:
```
```
220 example.com ESMTP Exim 4.69 Thu, 13 Nov 2008 10:06:01 +1100
```
```
as you can see, this sever is running EXIM.
Then type QUIT to exit back to the shell.
UPDATE:
Some hosts use a different address for their email server, if you are on Linux, you can type the following command to get a list of mail servers for a given domain:
```
```
dig -t MX example.com
```
```


Question: Does anyone know of any method in Rails by which an associated object may be frozen. The problem I am having is that I have an order model with many line items which in turn belong to a product or service. When the order is paid for, I need to freeze the details of the ordered items so that when the price is changed, the order's totals are preserved.

Answer:
I worked on an online purchase system before. What you want to do is have an Order class and a LineItem class. LineItems store product details like price, quantity, and maybe some other information you need to keep for records. It's more complicated but it's the only way I know to lock in the details.
An Order is simply made up of LineItems and probably contains shipping and billing addresses. The total price of the Order can be calculated by adding up the LineItems.
Basically, you freeze the data before the person makes the purchase. When they are added to an order, the data is frozen because LineItems duplicate nessacary product information. This way when a product is removed from your system, you can still make sense of old orders.
You may want to look at a rails plugin call 'AASM' (formerly, acts as state machine) to handle the state of an order.
Edit: AASM can be found here http://github.com/rubyist/aasm/tree/master


Question:
I cloned a Git master and made a lot of changes on the clone. I have since committed these changes on the clone and now want the master to be a carbon copy of what is on the clone.

I've tried Git push on the clone to push the changes to the master - but nothing I do updates the master.

How can I make the master an exact copy of what is on the clone? What is the command workflow of updating the clone and having the master sync with the clone?

Answer:
There are 2 kinds of git repository, bare and non-bare. A non bare repository is any repository which has a 'working copy' i.e. some part of the repository currently checked out.
You
can
push into a non-bare repository, but it won't update the checked out working copy even if the checked out branch is the same as the branch you pushed. This is because the checked out copy might have changes that aren't committed, and git won't ever destroy changes without you explicitly asking (usually such commands have a --hard argument)
Read
Why won't I see changes in the remote repo after "git push"?
and
How would I use "git push" to sync out of a firewalled host?
for a full description of the problem and a potential solution. Word of warning, if you've pushed into a remote repo, any non-committed changes in that remote-repo will have to be discarded.
Generally it sounds like the approach you want isn't really adopted by gitters, because it doesn't really match the distributed repository mentality. It's your own responsibility to make sure your copy of the repo is up to date.


Question:
Why does the select statement below return two different values ?

declare @tempDec decimal
set @tempDec = 1.0 / (1.0 + 1.0)
select @tempDec, 1.0 / (1.0 + 1.0)

Answer:
I found out from a coworker just as I posted this.
You need to specify the default precision and scale.
This works in this scenario:
declare @tempDec decimal(3,2)
From MSDN:
decimal[ (p[ , s] )] and numeric[ (p[ , s] )]
Fixed precision and scale numbers. When maximum precision is used, valid values are from - 10^38 +1 through 10^38 - 1. The SQL-92 synonyms for decimal are dec and dec(p, s). numeric is functionally equivalent to decimal.
p (precision)
The maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. The precision must be a value from 1 through the maximum precision of 38. The default precision is 18.
s (scale)
The maximum number of decimal digits that can be stored to the right of the decimal point. Scale must be a value from 0 through p. Scale can be specified only if precision is specified. The default scale is 0; therefore, 0 <= s <= p. Maximum storage sizes vary, based on the precision.


Question: How do I output colored text to the terminal in Python?

Answer:
For Windows you cannot print to console with colors unless you're using the
Win32
API.
For Linux it's as simple as using print, with the escape sequences outlined here:
Colors
For the character to print like a box, it really depends on what font you are using for the console window. The pound symbol works well, but it depends on the font:
```
```
#
```
```


Question:
I'm writing a simple program to browse the local network and pass on filenames to mplayer using "system". However, sometimes filenames contain spaces or quotes.
Obviously I could write my own function to escape those, but I'm not sure exactly what characters do or do not need escaping.

Is there a function available in the CRT or somewhere in the linux headers to safely escape a string to pass to the command line ?

Answer:
While i don't know a function that does this, you can surround each of your arguments with
```
'...'
```
, and replace any
```
'
```
in the original argument by
```
'"'"'
```
. like
```
system("mplayer 'foo'\"'\"' bar'");
```
will give a single argument to mplayer which is
```
foo
```
'
```
bar
```
and which is allowed to contain strange things like
```
"
```
or
```
\n
```
. Note the escaping before
```
"
```
above (
```
\"
```
) is only to make it valid C++.
You should consider using a function that accepts the arguments each separate, thus avoiding such issues. Wikipedia has a good article on this about the famous fork-and-exec pattern.
http://en.wikipedia.org/wiki/Fork-exec


Question:
How to convert last 3 digits of number into 0

example 3444678 to 3444000

I can do like

(int)(3444678/1000) * 1000= 3444000

But division and multiplication could be costly...

Any other solution????

Answer:
You could try
```
```
n - (n % 1000)
```
```
but the modulus operator might be as costly as a division. In any case, this sounds an awful lot like a micro-optimization. Is this really your bottleneck?


Question:
How do I execute a command every time after ssh'ing from one machine to another?

e.g

ssh mymachine
stty erase ^H

I'd rather just have "stty erase ^H" execute every time after my ssh connection completes.

This command can't simply go into my .zshrc file.  i.e. for local sessions, I can't run the command (it screws up my keybindings).  But I need it run for my remote sessions.

Answer:
Assuming a linux target, put it in your
```
.profile
```


Question:
We have an home-brewed XMPP server and I was asked what is our server's MSL (Maximum Segment Lifetime).

What does it mean and how can I obtain it? Is it something in the Linux /proc TCP settings?

Answer:
This looks like it can answer your question:
http://seer.support.veritas.com/docs/264886.htm
I suggest that you ask why someone asked you this and find out how that applies to XMPP.
TCP/IP Illustrated volume 1 is online and describes 2MSL in more detail:
Here
MSL is also described in the TCP
RFC 793
as mentioned in
wikipedia


Question:
Does anyone have experience deploying GWT apps to EC2?

If I were to install tomcat or apache on a ec2 instance, could I have users connect directly to a url pointing there?

Would that be cost effective, or would java hosting services be best?

Is there any downside to hosting the edge HTTP server on a regular hosting service and have that direct requests to EC2? Performance ever an issue here?

Answer:
Yes, you can host pretty much whatever you want, as you effectively have a dedicated Linux machine at your command.
As I last recall, the basic rate for an EC2 instance, on their "low end box" worked out to around $75/month, so you can use that as a benchmark against other vendors. That also assumed that the machine is up 24x7 (since you pay for it by the hour).
The major downside of an EC2 instance is simply that it can "go away" at any time, and when it does, any data written to your instance will "go away" as well.
That means you need to set it up so that you can readily restart the server, but also you need to offline any data that you generate and wish to keep (either to one of Amazons other services, like S3, or to some other external service). That will incur some extra costs depending on volume.
Finally, you will also be billed for any traffic to the service.
The thing to compare it against is another "Virtual Server" from some other vendor. There is a lot of interesting things that can be done with EC2, but it may well be easier to go with a dedicated Virtual hosting service if you're just using a single machine.


Question:
I need a javascript regex pattern to match a person's height to check if the input is valid. Here are some sample input:

5' 9"

6'

5'8"

Any ideas?

Answer:
Something like:
```
```
\d'(?:\s*\d+'')?
```
```
The second part refers to optional part of the heigth.
Remove the + if you want only one digit.
```
```
\b\d'(?:\s*\d+'')?\b
```
```
can also be used to detect that pattern within a text (avoid detecting 1234'45 as an heigth for... a person?!)
You can test that regexp
here for javascript
.


Question:
Windows NLB works great and removes computer from the cluster when the computer is dead.

But what happens if the application dies but the server still works fine? How have you solved this issue?

Thanks

Answer:
By not using NLB.
Hardware load balancers often have configurable "probe" functions to determine if a server is responding to requests. This can be by accessing the real application port/URL, or some specific "healthcheck" URL that returns only if the application is healthy.
Other options on these look at the queue/time taken to respond to requests
Cisco put it like this:
The Cisco CSM continually monitors server and application availability
  using a variety of probes, in-band
  health monitoring, return code
  checking, and the Dynamic Feedback
  Protocol (DFP). When a real server or
  gateway failure occurs, the Cisco CSM
  redirects traffic to a different
  location. Servers are added and
  removed without disrupting
  service—systems easily are scaled up
  or down.
(from here:
http://www.cisco.com/en/US/products/hw/modules/ps2706/products_data_sheet09186a00800887f3.html#wp1002630
)


Question:
What is the recommended way to embed PDF in HTML?

iFrame?

Object?

Embed?

What does Adobe say itself about it?

In my case, the PDF is generated on the fly, so it can't be uploaded to a third-party solution prior to flushing it.

Answer:
Probably the best approach is to use the
PDF.JS
library. It's a pure
HTML5
/
JavaScript
renderer for PDF documents without any third-party plugins.
Online demo:
https://mozilla.github.io/pdf.js/web/viewer.html
GitHub:
https://github.com/mozilla/pdf.js


Question:
With Linux/GCC/C++, I'd like to record something to stderr whenever malloc/free/new/delete are called.  I'm trying to understand a library's memory allocations, and so I'd like to generate this output while I'm running unit tests.  I use valgrind for mem leak detection, but I can't find an option to make it just log allocations.

Any ideas?  I'm looking for the simplest possible solution.  Recompiling the library is not an option.

Answer:
This article
(scroll down to the bottom) provides a very clear and concise description of how to override the global
```
new
```
and
```
delete
```
operators in C++ (note that it doesn't provide an example for
```
new[]
```
, but it's similar in concept).
As far as overriding malloc and free, since you're working on Linux and with GCC, the easiest method is to use
```
malloc_hook
```
and
```
free_hook
```
.
Here
is a very good description of how these functions work.


Question: What are the differences between git pull and git fetch?

Answer:
In the simplest terms,
```
git pull
```
does a
```
git fetch
```
followed by a
```
git merge
```
.
```
git fetch
```
updates your remote-tracking branches under
```
refs/remotes/<remote>/
```
. This operation is safe to run at any time since it never changes any of your local branches under
```
refs/heads
```
.
```
git pull
```
brings a local branch up-to-date with its remote version, while also updating your other remote-tracking branches.
From the Git documentation for
```
git pull
```
:
In its default mode,
```
git pull
```
is shorthand for
```
git fetch
```
followed by
```
git merge FETCH_HEAD
```
.


Question:
How do I get a patch from a commit in order to send it to another developer? And how do I best avoid a merge conflict with this patch when merging our trees at a later date?

If you know how please explain how to do this in your VCS of choice such as subversion, git, Mercurial, bzr or etc.

Answer:
In SVN you can simply make your changes then before commiting, pipe the output of the svn diff to a file as such
```
```
svn diff > mypatch.diff
```
```
you can then revert your changes and apply the patch at a later date using
```
```
patch -p0 -i mypatch.diff
```
```
As always don't blindly apply patches to your code and always inspect them first.
You may also find that the patch will break your source code if the source files have changed significantly enough since the patch was taken.
You also can not guarantee that there will not be merge conflicts when you attempt to check in the code.


Question: Can somebody tell me how to use the printWhenExpression of JasperReports?

Answer:
Do you have an error relative to boolean ?
Because you need to use Boolean instead of the primitive type.
So:
```
```
$F{mesure} != "PH"
($F{userfd4}).equals("1") ? true : false
```
```
would give
```
cannot cast from boolean to Boolean
```
.
```
```
( $F{mesure}.startsWith("PH") ? Boolean.TRUE:Boolean.FALSE )
($F{userfd4}).equals("1") ? Boolean.TRUE : Boolean.FALSE
```
```
would be correct.
See also this
example
Update Nov 2015 (7 years later)
Petter Friberg
points out
in the comments
:
In
jasper report
6.0 this is not need:
You can return either
```
boolean
```
or
```
Boolean
```
a simple expression like
```
$F{fieldName}.equals("hello")
```
will work.
You can see a demo of that command in
```
demo/samples/tableofcontents/reports/TocPart.jrxml
```
```
```
<reportElement style="Sans_Bold" positionType="Float" x="50" y="0" width="100" height="15" isRemoveLineWhenBlank="true" uuid="db8b68c6-4430-4199-8967-3ab5c077cb56">
    <property name="local_mesure_unitx" value="pixel"/>
    <property name="com.jaspersoft.studio.unit.x" value="px"/>
    <printWhenExpression><![CDATA[$F{level} == 1]]></printWhenExpression>
</reportElement>
```
```


Question: Has anyone got the steps to compile darwin libraries on gcc for arm on ubuntu?

Answer:
There is a
site
that provides patches for and arm darwin kernel.
Darwin on ARM develops and provides patches for the Apple Darwin-xnu kernel sources so that it can be cross-compiled to run on an ARM processor.
This ubuntu
forum entry
shows how to install the arm-linux-gcc cross compiler.
Put the two together and you should get what you asked for.


Question:
I'm looking for a way to monitor certain Windows services (on Windows Server 2003) and restart if necessary. The services are on different servers and include mainly SQL Server services (e.g. SQL Server Agent), but also some proprietary services.

Email alerts sent out if a service has stopped would be very useful as well.

Answer:
They may be some dedicated tools out there, but I just want to point out the
wmic
tool.
```
```
wmic /node:[hostname] service list
```
```
is able to list the services of any computer
```
```
WMIC SERVICE where caption='TELNET' CALL STARTSERVICE
```
```
would restart the telnet service.
If you encapsulate wmic in a script language (able to send email), you can have the monitoring tool you are looking for.


Question: I am using ActiveState Perl 5.6 on a Windows 2003 Server, and am having some memory leak issues.  Are there any good tools (or even bad tools which would give a clue) which I would be able to use to help find them.

Answer:
All perl program memory leaks will either be an XS holding onto a reference, or a circular data structure.
Devel::Cycle
is a great tool for finding circular references, if you know what structures are likely to contain the loops.
Devel::Peek
can be used to find objects with a higher-than-expected reference count.
If you don't know where else to look,
Devel::LeakTrace::Fast
could be a good first place, but you'll need a perl built for debugging.
If you suspect the leak is inside XS-space, it's much harder, and
Valgrind
will probably be your best bet.
Test::Valgrind
may help you lower the amount of code you need to search, but this won't work on Windows, so you'd have to port (at least the leaky portion) to Linux in order to do this.


Question:
I need to have a string, based on an integer, which should always have 5 digits.

Example:

myInteger = 999
formatedInteger = "00999"

What is the best way of doing this in classic ASP?

Answer:
Something like this is what I've seen most of the time:
```
```
function PadNumber(number, width)
   dim padded : padded = cStr(number)

   while (len(padded) < width)
       padded = "0" & padded
   wend

   PadNumber = padded
end function

PadNumber(999, 5) '00999
```
```


Question:
As a primarily Windows developer, perhaps I'm missing something cultural in the Linux community, but it has always confused me.

When downloading something that the files are first put into a .tar archive then zipped. Why the two-step process? Doesn't zipping achieve the file grouping? Is there some other benefit that I'm not aware of?

Answer:
```
bzip
```
and
```
gzip
```
work on single files, not groups of files. Plain old
```
zip
```
(and
```
pkzip
```
) operate on groups of files and have the concept of the archive built-in.
The *nix philosophy is one of the small tools that do specific jobs very well and can be chained together. That's why there are two tools here that have specific tasks, and they're designed to fit well together. It also means you can use tar to group files and then you have a choice of a compression tool (
```
bzip
```
,
```
gzip
```
, etc).


Question:
I am trying to write a bash script for testing that takes a parameter and sends it through curl to web site.  I need to url encode the value to make sure that special characters are processed properly.  What is the best way to do this?

Here is my basic script so far:

#!/bin/bash
host=${1:?'bad host'}
value=$2
shift
shift
curl -v -d "param=${value}" http://${host}/somepath $@

Answer:
If you don't want to depend on Perl you can also use sed. It's a bit messy, as each character has to be escaped individually. Make a file with the following contents and call it
```
urlencode.sed
```
```
```
s/%/%25/g
s/ /%20/g
s/ /%09/g
s/!/%21/g
s/"/%22/g
s/#/%23/g
s/\$/%24/g
s/\&/%26/g
s/'\''/%27/g
s/(/%28/g
s/)/%29/g
s/\*/%2a/g
s/+/%2b/g
s/,/%2c/g
s/-/%2d/g
s/\./%2e/g
s/\//%2f/g
s/:/%3a/g
s/;/%3b/g
s//%3e/g
s/?/%3f/g
s/@/%40/g
s/\[/%5b/g
s/\\/%5c/g
s/\]/%5d/g
s/\^/%5e/g
s/_/%5f/g
s/`/%60/g
s/{/%7b/g
s/|/%7c/g
s/}/%7d/g
s/~/%7e/g
s/      /%09/g
```
```
To use it do the following.
```
```
STR1=$(echo "https://www.example.com/change&$ ^this to?%checkthe@-functionality" | cut -d\? -f1)
STR2=$(echo "https://www.example.com/change&$ ^this to?%checkthe@-functionality" | cut -d\? -f2)
OUT2=$(echo "$STR2" | sed -f urlencode.sed)
echo "$STR1?$OUT2"
```
```
This will split the string into a part that needs encoding, and the part that is fine, encode the part that needs it, then stitches back together.
You can put that into a sh script for convenience, maybe have it take a parameter to encode, put it on your path and then you can just call:
```
```
urlencode https://www.exxample.com?isThisFun=HellNo
```
```
source


Question:
I'm using git-svn to work against my company's central Subversion repository. We've recently created a new feature branch in the central repo.

How do I tell Git about it? When I run git branch -r I can only see the branches that existed when I ran fetch against the Subversion repo to initialize my Git repo?

Answer:
It appears I just needed to
```
git svn fetch
```
; somehow I had convinced myself that would fetch the entire repo instead of just the changes.


Question:
I want to stress test a web service method by calling it several thousand times in quick succession. The method has a single string parameter that I will vary on each call.

I'm planning on writing a Powershell script to loop and call this method a number of times.

Is there a better way to do this?

Answer:
If you run call after call - it's not going to help you too much, as it will not show you how the service behaves under a heavy load of many simultaneous connections.
Go with some multi-threaded solution (I do not know if powershell has this).
Some opensource testing tools are listed
here
. Just set your web service to accept GET requests as well, not only SOAP(default), so you can form the urls.


Question: I need a tool to measure a website's performance that's free and does not require any changes to be made to the code (jsp asp pages). All help is appreciated.

Answer:
For performance measurement I recommend you
YSlow
, it's a Firefox add-on integrated with
Firebug
, it analyzes your web pages and tells you why they're slow based on the
rules for high performance web sites
.
Screenshot
Also with the Firebug Network Monitoring tab, you can see which resources are taking more time and bandwidth to download:
(source:
getfirebug.com
)


Question: Can anyone provide some pseudo code for a roulette selection function? How would I implement this: I don't really understand how to read this math notation.I want General algorithm to this.

Answer:
There are 2 steps to this: First create an array with all the values on the wheel. This can be a 2 dimensional array with colour as well as number, or you can choose to add 100 to red numbers.
Then simply generate a random number between 0 or 1 (depending on whether your language starts numbering array indexes from 0 or 1) and the last element in your array.
Most languages have built-in random number functions. In VB and
```
VBScript
```
the function is
```
RND()
```
. In Javascript it is
```
Math.random()
```
Fetch the value from that position in the array and you have your random roulette number.
Final note
: don't forget to seed your random number generator or you will get the same sequence of draws every time you run the program.


Question:
I have a rails app that uses heavily js (over 1MB total). I'd like to compress them in order to reduce the overall load time of the site.

I did a fast search and found that most browsers accept compressed content.

I'd like to know what can I do to make my rails app send compressed content and thus make the user experience better.

Answer:
You should always have the web server proxying to your mongrels handle the serving of static content and it's compression. Requests for static content should never be passed to the mongrels.
e.g. with nginx it's simply a matter of adding gzip directives to your config file.
http://topfunky.net/svn/shovel/nginx/conf/nginx.conf
```
# output compression saves bandwidth
  gzip            on;
  gzip_http_version 1.0;
  gzip_comp_level 2;
  gzip_proxied any;
  gzip_types      text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
```


Question:
The fuser command lets me know which processes are using a file or directory.

I'm looking for command that does the opposite:  lets me know which files are being used by a process.

Update

Forgot to mention that it's for a Solaris system.

Answer:
```
```
lsof -p <pid>
```
```
From
here
lsof stands for “
LiSt Open Files
”. This shell command seems deceptively simple: It lists information about files opened by processes on a UNIX box.
Despite its (apparent) modest mission statement, lsof is actually one of the most powerful and useful UNIX commands. Its raw power comes from one of UNIX’s design principle often described as ”in UNIX everything is a file”. What this means is that the lsof concept of an open file not only covers regular files but also the following:
Directories
Streams or network files (for example, Internet or UNIX domain sockets and NFS files)
Native libraries (for example, .soor .dylibdynamic libraries linked to a process)
Block and character special files (for example, disk volume, external hard drive, console, or mouse)
Pipes
Wait, I Cannot Find lsof on My System!
lsof is such a popular tool that it has been ported to pretty much all UNIX dialects (Linux, Mac OS X, BSD, Solaris, and so on). If it is unavailable on your box, use your usual package management system to install it. You can find lsof packages for Solaris on
Sun Freeware
.


Question: How do you traverse a folder structure using C# without falling into the trap of junction points?

Answer:
For those that don't know: A junction point behaves similarly to a symbolic link for a folder on linux. The trap that is mentioned happens when you set up a recursive folder structure, like this:
```
```
given folder /a/b
let /a/b/c point to /a
then
/a/b/c/b/c/b becomes valid folder locations.
```
```
I suggest a strategy like this one. On windows you are limited to a maximum length on the path string, so a recursive solution probably won't blow the stack.
```
```
private void FindFilesRec(
    string newRootFolder,
    Predicate<FileInfo> fileMustBeProcessedP,
    Action<FileInfo> processFile)
{
    var rootDir = new DirectoryInfo(newRootFolder);
    foreach (var file in from f in rootDir.GetFiles()
                         where fileMustBeProcessedP(f)
                         select f)
    {
        processFile(file);
    }

    foreach (var dir in from d in rootDir.GetDirectories()
                        where (d.Attributes & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint
                        select d)
    {
        FindFilesRec(
            dir.FullName,
            fileMustBeProcessedP,
            processFile);
    }
}
```
```


Question:
I have created a windows installer for a windows forms app as an MSI.
I have published this and put it in a zip file and sent it to the client.
When they try to run the installer they get the message
'The publisher could not be verified. Are you sure you want to run this software?’

Is there a setting or something i need to do to stop this message appearing when the client clicks on the installer?

Cheers

Answer:
Is this a certificate issue? I haven't had to do this with msi (I usually use ClickOnce, which makes this very easy), but a quick search shows things like
this
or on MSDN
here
.
Note that your certificate would have to be in the clients trust chain - i.e. indirectly from someone "pucka".


Question:
I often access shared network folders in Powershell to grab files etc. But if the share requires a username/password, Powershell does not prompt me for these, unlike Windows Explorer. If I connect to the folder first in Windows Explorer, Powershell will then allow me to connect.

How can I authenticate myself in Powershell?

Answer:
This is not a PowerShell-specific answer, but you could authenticate against the share using "NET USE" first:
```
```
net use \\server\share /user:<domain\username> <password>
```
```
And then do whatever you need to do in PowerShell...


Question:
Is there a way to edit the log message of a certain revision in Subversion? I accidentally wrote the wrong filename in my commit message which could be confusing later.

I've seen How do I edit an incorrect commit message in Git?, but the solution to that question doesn't seem to be similar for Subversion (according to svn help commit).

Answer:
Essentially you have to have admin rights (directly or indirectly) to the repository to do this.  You can either configure the repository to allow all users to do this, or you can modify the log message directly on the server.
See
this part
of the
Subversion FAQ
(emphasis mine):
Log messages are kept in the
  repository as properties attached to
  each revision.
By default, the log
  message property (svn:log) cannot be
  edited once it is committed
. That is
  because changes to revision properties
  (of which svn:log is one) cause the
  property's previous value to be
  permanently discarded, and Subversion
  tries to prevent you from doing this
  accidentally. However, there are a
  couple of ways to get Subversion to
  change a revision property.
The first way is for the repository
  administrator to enable revision
  property modifications. This is done
  by creating a hook called
  "pre-revprop-change" (see this section
  in the Subversion book for more
  details about how to do this). The
  "pre-revprop-change" hook has access
  to the old log message before it is
  changed, so it can preserve it in some
  way (for example, by sending an
  email). Once revision property
  modifications are enabled, you can
  change a revision's log message by
  passing the --revprop switch to svn
  propedit or svn propset, like either
  one of these:
```
```
$svn propedit -r N --revprop svn:log URL
$svn propset -r N --revprop svn:log "new log message" URL
```
```
where N
  is the revision number whose log
  message you wish to change, and URL is
  the location of the repository. If you
  run this command from within a working
  copy, you can leave off the URL.
The second way of changing a log
  message is to use svnadmin setlog.
This must be done by referring to the
  repository's location on the
  filesystem. You cannot modify a remote
  repository using this command.
```
```
$ svnadmin setlog REPOS_PATH -r N FILE
```
```
where REPOS_PATH is the repository
  location, N is the revision number
  whose log message you wish to change,
  and FILE is a file containing the new
  log message. If the
  "pre-revprop-change" hook is not in
  place (or you want to bypass the hook
  script for some reason), you can also
  use the --bypass-hooks option.
  However, if you decide to use this
  option, be very careful. You may be
  bypassing such things as email
  notifications of the change, or backup
  systems that keep track of revision
  properties.


Question:
I want to check if a variable has a valid year using a regular expression. Reading the bash manual I understand I could use the operator =~

Looking at the example below, I would expect to see "not OK" but I see "OK". What am I doing wrong?

i="test"
if [ $i=~"200[78]" ]
then
  echo "OK"
else
  echo "not OK"
fi

Answer:
It was changed between 3.1 and 3.2:
This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.
Quoting the string argument to the [[ command's  =~ operator now forces string matching, as with the other pattern-matching operators.
So use it without the quotes thus:
```
```
i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi
```
```


Question: I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux.

Answer:
Just put this in the first line of your script :
```
```
#!/usr/bin/env python
```
```
Make the file executable with
```
```
chmod +x myfile.py
```
```
Execute with
```
```
./myfile.py
```
```


Question:
I have to run a local shell script (windows/Linux) on a remote machine.

I have SSH configured on both machine A and B. My script is on machine A which will run some of my code on a remote machine, machine B.

The local and remote computers can be either Windows or Unix based system.

Is there a way to run do this using plink/ssh?

Answer:
```
```
<hostA_shell_prompt>$ ssh user@hostB "ls -la"
```
```
That will prompt you for password, unless you have copied your hostA user's public key to the authorized_keys file on the home of user .ssh's directory. That will allow for passwordless authentication (if accepted as an auth method on the ssh server's configuration)


Question:
Can Unicode characters be encoded and decoded with Base64?

I have attempted to encode the string 'الله', but when I decoded it all I got was '????'.

Answer:
Of course they can. It depends on how your language or Base64 routine handles Unicode input. For example, Python's
```
b64
```
routines expect an encoded string (as Base64 encodes binary to text, not Unicode codepoints to text).
```
```
Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'ûñö'
>>> import base64
>>> base64.b64encode(a)
'w7vDscO2'
>>> base64.b64decode('w7vDscO2')
'\xc3\xbb\xc3\xb1\xc3\xb6'
>>> print '\xc3\xbb\xc3\xb1\xc3\xb6'
ûñö
>>>
>>> u'üñô'
u'\xfc\xf1\xf4'
>>> base64.b64encode(u'\xfc\xf1\xf4')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/base64.py", line 53, in b64encode
    encoded = binascii.b2a_base64(s)[:-1]
UnicodeEncodeError: 'ascii' codec can't encode characters in position
0-2: ordinal not in range(128)
>>> base64.b64encode(u'\xfc\xf1\xf4'.encode('utf-8'))
'w7zDscO0'
>>> base64.b64decode('w7zDscO0')
'\xc3\xbc\xc3\xb1\xc3\xb4'
>>> print base64.b64decode('w7zDscO0')
üñô
>>> a = 'الله'
>>> a
'\xd8\xa7\xd9\x84\xd9\x84\xd9\x87'
>>> base64.b64encode(a)
'2KfZhNmE2Yc='
>>> b = base64.b64encode(a)
>>> print base64.b64decode(b)
الله
```
```


Question: I need in a bash script to get details about a file when I know the inode.The system is Linux.

Answer:
You can use
```
find
```
with a combination of
```
-inum
```
and
```
-xdev
```
. This gives you the file's names (it can have more than one name), and from them you can find whatever information you want.


Question:
What system do you recommend for implementing "automatic updates" for some java (desktop) application? I'd also want to have module/plugin installation and update. Think Eclipse and Firefox.

I'm aware of Eclipse RCP's OSGi stuff, and also NetBeans RCP has something here. Do one have to buy wholly into their respective RCP stuff to use their module and automatic update systems?

Are there other options?

Answer:
Have you looked at the
Java Web Start
? It checks for updated module on the server and downloads it only if required otherwise things are cached locally on the client PC and starts from there.


Question:
I have a function that takes another function as a parameter. If the function is a member of a class, I need to find the name of that class. E.g.

def analyser(testFunc):
    print testFunc.__name__, 'belongs to the class, ...

I thought

testFunc.__class__

would solve my problems, but that just tells me that testFunc is a function.

Answer:
I'm not a Python expert, but does this work?
```
```
testFunc.__self__.__class__
```
```
It seems to work for bound methods, but in your case, you may be using an unbound method, in which case this may work better:
```
```
testFunc.__objclass__
```
```
Here's the test I used:
```
```
Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import hashlib
>>> hd = hashlib.md5().hexdigest
>>> hd
<built-in method hexdigest of _hashlib.HASH object at 0x7f9492d96960>
>>> hd.__self__.__class__
<type '_hashlib.HASH'>
>>> hd2 = hd.__self__.__class__.hexdigest
>>> hd2
<method 'hexdigest' of '_hashlib.HASH' objects>
>>> hd2.__objclass__
<type '_hashlib.HASH'>
```
```
Oh yes, another thing:
```
```
>>> hd.im_class
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute 'im_class'
>>> hd2.im_class
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'method_descriptor' object has no attribute 'im_class'
```
```
So if you want something bulletproof, it should handle
```
__objclass__
```
and
```
__self__
```
too. But your mileage may vary.


Question:
I need to set a system environment variable from a Bash script that would be available outside of the current scope.  So you would normally export environment variables like this:

export MY_VAR=/opt/my_var

But I need the environment variable to be available at a system level though.  Is this possible?

Answer:
Not really - once you're running in a subprocess you can't affect your parent.
There two possibilities:
Source
the script rather than run it (see
source .
):
```
```
source {script}
```
```
Have the script output the export commands, and eval that:
```
```
eval `bash {script}`
```
```
Or
:
```
```
eval "$(bash script.sh)"
```
```


Question:
I'm looking for a good ocaml parsing library that isn't a derivative of flex/bison. Ideally, I'd like a monadic combinator library along the lines of parsec, but I can't find anything.

I would use haskell, but making llvm bindings for haskell is proving more tiresome than I originally thought.

Cheers,

Duane

Answer:
Here's one library
, via Google. (Which also brought up
this
and
this
, which lists several more relevant-sounding libraries.)
When I wrote a combinator parser in ML, it turned out rather cumbersome to use because of the value restriction and eager evaluation, which forced you to eta-expand your grammar rules. Ocaml is said to be more relaxed about the value restriction, though -- maybe you'll be spared some of that pain.


Question:
When you run top and see all running processes, I've always wanted to know just what everything actually means.  e.g. all the various single-letter state codes for a running process (R = Running, S = Sleeping, etc...)

Where can I find this?

Answer:
You can use the command
```
man top
```
to look up the states:
```
```
D = uninterruptible sleep
I = idle
R = running
S = sleeping
T = stopped by job control signal
t = stopped by debugger during trace
Z = zombie
```
```


Question:
I've got two branches that are fully merged together.

However, after the merge is done, I realise that one file has been messed up by the merge (someone else did an auto-format, gah), and it would just be easier to change to the new version in the other branch, and then reinsert my one line change after bringing it over into my branch.

So what's the easiest way in Git to do this?

Answer:
Run this from the branch where you want the file to end up:
```
```
git checkout otherbranch myfile.txt
```
```
General formulas:
```
```
git checkout <commit_hash> <relative_path_to_file_or_dir>
git checkout <remote_name>/<branch_name> <file_or_dir>
```
```
Some notes (from comments):
Using the commit hash, you can pull files from any commit
This works for files and directories
Overwrites the file
```
myfile.txt
```
and
```
mydir
```
Wildcards don't work, but relative paths do
Multiple paths can be specified
An alternative:
```
```
git show commit_id:path/to/file > path/to/file
```
```


Question: When using topfunky's RStakeout, the color in the result of the spec command is lost. This happens even when adding the --color flag.

Answer:
You have to set the environment variable
```
AUTOTEST
```
to true. Spec detects whether it is being run by a process and disables color if it is (to make the output easier to parse).
To set the environment variable in bash:
```
```
export AUTOTEST=true
```
```
or in fish:
```
```
set -x AUTOTEST true
```
```
(the -x exports the variable)


Question:
I accidentally committed an unwanted file (filename.orig while resolving a merge) to my repository several commits ago, without me noticing it until now. I want to completely delete the file from the repository history.

Is it possible to rewrite the change history such that filename.orig was never added to the repository in the first place?

Answer:
This is what
```
git filter-branch
```
was designed for.


Question:
If I have a query such as SELECT * from authors where name = @name_param, is there a regex to parse out the parameter names (specifically the "name_param")?

Thanks

Answer:
This is tricky because params can also occur inside quoted strings.
```
```
SELECT * FROM authors WHERE name = @name_param
  AND string = 'don\'t use @name_param';
```
```
How would the regular expression know to use the first
```
@name_param
```
but not the second?
It's a problem that can be solved, but it's not practical to do it in a single regular expression.  I had to handle this in Zend_Db, and what I did was first strip out all quoted strings and delimited identifiers, and then you can use regular expressions on the remainder.
You can see the code, because it's open-source.
See functions
```
_stripQuoted()
```
and
```
_parseParameters()
```
.
https://github.com/zendframework/zf1/blob/136735e776f520b081cd374012852cb88cef9a88/library/Zend/Db/Statement.php#L200
https://github.com/zendframework/zf1/blob/136735e776f520b081cd374012852cb88cef9a88/library/Zend/Db/Statement.php#L140


Question:
I run an OpenSuse server that uploads zipped source code backups to a Microsoft FTP server every night. I have written a Bash script that does this through a cron job.

I want to delete backed up files that are older than a certain date. How could I do this?

Answer:
```
```
IF object_id('a_table') IS NULL
BEGIN
    CREATE TABLE a_table (
        col1 int not null,
        col2 int null
    )
END
```
```


Question:
What is the regular expression for a decimal with a precision of 2?

Valid examples:

123.12
2
56754
92929292929292.12
0.21
3.1

Invalid examples:

12.1232
2.23332
e666.76

The decimal point may be optional, and integers may also be included.

Answer:
Valid regex tokens vary by implementation. A generic form is:
```
```
[0-9]+(\.[0-9][0-9]?)?
```
```
More compact:
```
```
\d+(\.\d{1,2})?
```
```
Both assume that both have at least one digit before and one after the decimal place.
To require that the whole string is a number of this form, wrap the expression in start and end tags such as (in Perl's form):
```
```
^\d+(\.\d{1,2})?$
```
```
To match numbers without a leading digit before the decimal (
```
.12
```
) and whole numbers having a trailing period (
```
12.
```
) while excluding input of a single period (
```
.
```
), try the following:
```
```
^(\d+(\.\d{0,2})?|\.?\d{1,2})$
```
```
Added
Wrapped the fractional portion in
```
()?
```
to make it optional.  Be aware that this excludes forms such as
```
12.
```
Including that would be more like
```
^\d+\\.?\d{0,2}$
```
.
Added
Use
```
^\d{1,6}(\.\d{1,2})?$
```
to stop repetition and give a restriction to whole part of the decimal value.


Question:
Windows Forms:

For System.Drawing there is a way to get the font height.

Font font = new Font("Arial", 10 , FontStyle.Regular);
float fontHeight = font.GetHeight();

But how do you get the other text metrics like average character width?

Answer:
Use Graphics.MeasureString Method
```
```
private void MeasureStringMin(PaintEventArgs e)
{

    // Set up string.
    string measureString = "Measure String";
    Font stringFont = new Font("Arial", 16);

    // Measure string.
    SizeF stringSize = new SizeF();
    stringSize = e.Graphics.MeasureString(measureString, stringFont);

    // Draw rectangle representing size of string.
    e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);

    // Draw string to screen.
    e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}
```
```


Question: We have a JavaScript construct that will play .wav files within Firefox on Windows and MacOSX, but it does not work for Red Hat Linux.  What extension do I need?

Answer:
Firefox 3.1 will support
Firefox 3.5,  supports the
```
<audio>
```
tag, a standard tag to deal with sound. If you use that, you'll need no extensions.
Unfortunately, that will only work with the latest browsers (Firefox 3, for example, is the latest stable version and yet does not support this tag. You may have trouble making it work with Internet Explorer too).


Question:
I need to do the following for hundreds of files:
Append the name of the file (which may contain spaces) to the end of each line in the file.

It seems to me there should be some way to do this:

sed -e 's/$/FILENAME/' *

where FILENAME represents the name of the current file.  Is there a sed variable representing the current filename?  Or does anyone have a different solution using bash, awk, etc.?

Answer:
You could do it with a bash script
```
```
for i in *
do
  sed -e "s/\$/$i/" "$i"
done
```
```
One-liner version:
```
```
for i in * ; do sed -e "s/\$/$i/" "$i" ; done
```
```
Edit:
If you want to
replace
the contents of the file with the new, name-appended lines, do this:
```
```
TFILE=`mktemp`
for i in *
do
  sed -e "s/\$/$i/" "$i" > $TFILE
  cp -f $TFILE "$i"
done
rm -f $TFILE
```
```


Question: Are there any successor products on DOS, Windows or Linux?

Answer:
There are quite a few Clipper compilers available:
Harbour
,
CLIP
, and
xHarbour
, to name a few of the free ones.


Question:
Is there any way to access the Windows Event Log from a java class. Has anyone written any APIs for this, and would there be any way to access the data from a remote machine?

The scenario is:

I run a process on a remote machine, from a controlling Java process.
This remote process logs stuff to the Event Log, which I want to be able to see in the controlling process.

Thanks in advance.

Answer:
On the Java side, you'll need a library that allows you to make native calls. Sun offers
JNI
, but it sounds like sort of a pain. Also consider:
https://github.com/twall/jna/
http://johannburkard.de/software/nativecall/
http://www.jinvoke.com/
On the Windows side, the function you're after is
OpenEventLog
. This should allow you to access a remote event log. See also
Querying for Event Information
.
If that doesn't sound right, I also found this for parsing the log files directly (not an approach I'd recommend but interesting nonetheless):
http://msdn.microsoft.com/en-us/library/bb309026.aspx
http://objectmix.com/java/75154-regarding-windows-event-log-file-parser-java.html


Question:
Some repository clones I have allow me to do this:

% git pull
% git push

But other repositories require me to type:

% git pull origin master
% git push origin master

I think I am missing something in the latter case - does anyone know what is (not) going on here?  I am using the latest git version, just obviously not using it well.

Answer:
If you cd into your repository directory and then open up your
.git/config
file in an editor.
Append this to the end of the file:
```
```
[branch "master"]
     remote = origin
     merge = refs/heads/master
```
```
This is pretty much just an alias so git knows by default to pull from origin master.


Question:
I know I can access environment variables in PowerShell using $Env. For example, I can access FOO with $Env:FOO.

I can't figure out how to access the environment variable called FOO.BAR.

$Env:FOO.BAR doesn't work. How can I access this from within PowerShell?

Answer:
Use the .NET method to get the variable:
```
```
[Environment]::GetEnvironmentVariable("FOO.BAR")
```
```


Question:
When configuring the bash on OSX via ~/.profile it seems to completely ignore it as soon as ~/.bash_profile exists. If this is correct and expected behavior, should I add my extra configuration stuff to ~/.bash_profile as well or use it instead of ~/.profile?

Thanks in advance.

Answer:
It's expected behaviour. See
here
When bash is invoked as an interactive
  login shell, or as a non-interactive
  shell with the --login option, it
  first reads and executes commands from
  the file /etc/profile, if that file
  exists. After reading that file, it
  looks for ~/.bash_profile,
  ~/.bash_login, and ~/.profile, in that
  order, and reads and executes commands
  from the first one that exists and is
  readable.
So only the first readable one counts.
As for which you should use, it's up to you - unless there are corporate policies or something else that creates a specific one, or relies on a specific one existing.


Question:
Is there something similar to sprintf() in C#?

I would for instance like to convert an integer to a 2-byte byte-array.

Something like:

int number = 17;
byte[] s = sprintf("%2c", number);

Answer:
```
```
string s = string.Format("{0:00}", number)
```
```
The first 0 means "the first argument" (i.e. number); the 00 after the colon is the format specifier (2 numeric digits).
However, note that .NET strings are UTF-16, so a 2-character string is 4 bytes, not 2
(edit: question changed from
```
string
```
to
```
byte[]
```
)
To get the bytes, use
```
Encoding
```
:
```
```
byte[] raw = Encoding.UTF8.GetBytes(s);
```
```
(obviously different encodings may give different results; UTF8 will give 2 bytes for this data)
Actually, a shorter version of the first bit is:
```
```
string s = number.ToString("00");
```
```
But the
```
string.Format
```
version is more flexible.


Question: What is the equivalent of /dev/null on Windows?

Answer:
I think you want
```
NUL
```
, at least within a command prompt or batch files.
For example:
```
```
type c:\autoexec.bat > NUL
```
```
doesn't create a file.
(I
believe
the same is true if you try to create a file programmatically, but I haven't tried it.)
In PowerShell, you want
```
$null
```
:
```
```
echo 1 > $null
```
```