Question:
How do you stay up-to-date when it comes to new software versions? Above all, I mean minor updates (new version for your Joomla-Installation, forum-software, FTP-Client, ...).

Versiontracker, RSS-Feeds, Newsletter... what else? Anyone wrote a script crawling websites for new versions or something similar?

Answer:
Often your operating system will help you with these things, at least in (most distributions of) Linux. As soon as a piece of software is available as an installable package, and installed, your package management system will keep track of it and it will be possible to find out that a new version is available.
For instance, in
Gentoo Linux
, you would do the following from the command line to get a list of possible package updates:
```
```
emerge --sync && emerge -p world
```
```
The first command makes sure you have an up-to-date list of available packages, the latter compares all your installed packages (your "world") to the list, and reports back with one line per installable package. These lines contain the version you have, and the version available, so you can decide if it's worth upgrading.
There are probably several other ways of doing it, this is just what I use.


Question:
Is there a function in Common Lisp that takes a string as an argument and returns a keyword?

Example: (keyword "foo") -> :foo

Answer:
```
```
(intern "foo" "KEYWORD") -> :foo
```
```
See the
Strings section
of the
Common Lisp Cookbook
for other string/symbol conversions and a detailed discussion of symbols and packages.


Question:
I'm on OS X 10.5.5 (though it does not matter much I guess)

I have a set of text files with fancy characters like double backquotes, ellipsises ("...") in one character etc.

I need to convert these files to good old plain 7-bit ASCII, preferably without losing character meaning (that is, convert those ellipses to three periods, backquotes to usual "s etc.).

Please advise some smart command-line (bash) tool/script to do that.

Answer:
iconv
should do it, as far as I know. Not 100% certain about how it handles conversions where one input character should/could become several output characters, such as with the ellipsis example ... Something to try!
Update: I did try it, and it seems it doesn't work. It fails, possibly since it doesn't know how to express ellipsis (the test character I used) in a "smaller" encoding. Converting from UTF-8 to UTF-16 went fine. :/ Still, iconv might be worth investigating further.


Question:
How can I get tab completion to work for selecting CVS modules under Linux (preferably using bash) ?

For example, "cvs co " + tab would list the modules I can checkout. I've heard it's easy to do using zsh, but still I didn't manage to get it working either.

Also, how can I list all available modules (or repositories?) available in the CVSROOT?

Answer:
There is the
Bash completion
project.  It has some cvs completion in it, I'm not 100% if it can determine all the modules for checkout.  But it would be a good place to start.


Question:
I'm looking at the code for a phase accumulator, and I must be a simpleton because I don't get it.
The code is simple enough:

  Every Clock Tick do:
    accum = accum + NCO_param;
    return accum;

accum is a 32-bit register.  Obviously, at some point it will roll-over.

My question really is: How does this relate to the phase?

Answer:
This article
may help.
In the running step, the counter (properly called the phase accumulator) is instructed to advance by a certain increment on each pulse from the frequency reference. The output of the phase accumulator (the phase) is used to select each item in the data table in turn. Finally, the DAC converts this sequence of data to an analogue waveform.
In the running step, the counter
  (properly called the phase
  accumulator) is instructed to advance
  by a certain increment on each pulse
  from the frequency reference. The
  output of the phase accumulator (the
  phase) is used to select each item in
  the data table in turn. Finally, the
  DAC converts this sequence of data to
  an analogue waveform.
  To generate a periodic waveform, the
  circuit is set up so that one pass
  through the table takes a time equal
  to the period of the waveform. For
  example, if the reference frequency is
  1 MHz, and the table contains 1000
  entries, then a complete pass through
  the table with a phase increment of 1
  will take 1000 / 1 MHz = 1 ms, so the
  frequency of the output waveform will
  be 1/(1 ms) = 1 kHz.
This system can generate a higher
  output frequency simply by increasing
  the phase increment so that the
  counter runs through the table more
  quickly. In the example above, the
  phase increment is equal to 1, so the
  next possible frequency is obtained by
  setting the increment to 2, resulting
  in a doubling of output frequency. To
  obtain a finer control of frequency
  than this, the standard phase
  increment can be set to, say, 10. This
  then allows slightly higher or lower
  output frequencies. For example,
  increasing the increment to 11 would
  increase the output frequency by 10%,
  and reducing it to 9 would decrease
  the output frequency by the same
  proportion. The more precision
  required over the frequency, the more
  bits are needed in the counter.


Question:
I have noticed that my particular instance of Trac is not running quickly and has big lags.  This is at the very onset of a project, so not much is in Trac (except for plugins and code loaded into SVN).

Setup Info: This is via a SELinux system hosted by WebFaction.  It is behind Apache, and connections are over SSL.  Currently the .htpasswd file is what I use to control access.

Are there any recommend ways to improve the performance of Trac?

Answer:
It's hard to say without knowing more about your setup, but one easy win is to make sure that Trac is running in something like
```
mod_python
```
, which keeps the Python runtime in memory. Otherwise, every HTTP request will cause Python to run, import all the modules, and then finally handle the request. Using
```
mod_python
```
(or FastCGI, whichever you prefer) will eliminate that loading and skip straight to the good stuff.
Also, as your Trac database grows and you get more people using the site, you'll probably outgrow the default SQLite database. At that point, you should think about migrating the database to PostgreSQL or MySQL, because they'll be able to handle concurrent requests much faster.


Question:
I have a file with fields separated by pipe characters and I want to print only the second field.  This attempt fails:

$ cat file | awk -F| '{print $2}'
awk: syntax error near line 1
awk: bailing out near line 1
bash: {print $2}: command not found

Is there a way to do this?

Answer:
The pipe character needs to be escaped so that the shell doesn't interpret it.  A simple solution:
```
```
$ awk -F\| '{print $2}' file
```
```
Another choice would be to quote the character:
```
```
$ awk -F'|' '{print $2}' file
```
```


Question: What is the most efficient way to do this?

Answer:
A hex value is just RGB numbers represented in hexadecimal. So you just have to take each pair of hex digits and convert them to decimal.
Example:
```
```
#FF6400 = RGB(0xFF, 0x64, 0x00) = RGB(255, 100, 0)
```
```


Question:
Does anyone have experience with using very large heaps, 12 GB or higher in Java?

Does the GC make the program unusable?

What GC params do you use?

Which JVM, Sun or BEA would be better suited for this?

Which platform, Linux or Windows, performs better under such conditions?

In the case of Windows is there any performance difference to be had between 64 bit Vista and XP under such high memory loads?

Answer:
We have an application that we allocate 12-16 Gb for but it really only reaches 8-10 during normal operation.  We use the Sun JVM (tried IBMs and it was a bit of a disaster but that just might have been ignorance on our part...I have friends that swear by it--that work at IBM).  As long as you give your app breathing room, the JVM can handle large heap sizes with not too much GC.  Plenty of 'extra' memory is key.
Linux is almost always more stable than Windows and when it is not stable it is a hell of a lot easier to figure out why.  Solaris is rock solid as well and you get DTrace too :)
With these kind of loads, why on earth would you be using Vista or XP?  You are just asking for trouble.
We don't do anything fancy with the GC params.  We do set the minimum allocation to be equal to the maximum so it is not constantly trying to resize but that is it.


Question: How do I revert a modified file to its previous revision at a specific commit hash (which I determined via git log and git diff)?

Answer:
```
```
git checkout -- foo
```
```
That will reset
```
foo
```
to HEAD. You can also:
```
```
git checkout HEAD^ foo
```
```
for one revision back, etc.


Question: I want to allow users to paste <embed> and <object> HTML fragments (video players) via an HTML form. The server-side code is PHP. How can I protect against malicious pasted code, JavaScript, etc? I could parse the pasted code, but I'm not sure I could account for all variations. Is there a better way?

Answer:
I'm not really sure what parameters
```
EMBED
```
and
```
OBJECT
```
take as I've never really dealt with putting media on a page (which is actually kind of shocking to think about) but I would take a BB Code approach to it and do something like
```
[embed url="http://www.whatever.com/myvideo.whatever" ...]
```
and then you can parse out the URL and anything else, make sure they are legit and make your own
```
<EMBED>
```
tag.
edit:
Alright, something like this should be fine:
```
```
$youtube = '<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1"></param> </param><embed src="http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="425" height="344"></embed></object>';

$blip = '<embed src="http://blip.tv/play/AZ_iEoaIfA" type="application/x-shockwave-flash" width="640" height="510" allowscriptaccess="always" allowfullscreen="true"></embed>';

preg_match_all("/([A-Za-z]*)\=\"(.+?)\"/", $youtube, $matches1);
preg_match_all("/([A-Za-z]*)\=\"(.+?)\"/", $blip, $matches2);
print '
' . print_r($matches1, true). '
';
print '
' . print_r($matches2, true). '
';
```
```
This will output:
```
```
Array
(
[0] => Array
    (
        [0] => width="425"
        [1] => height="344"
        [2] => name="movie"
        [3] => value="http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1"
        [4] => src="http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1"
        [5] => type="application/x-shockwave-flash"
        [6] => allowfullscreen="true"
        [7] => width="425"
        [8] => height="344"
    )

[1] => Array
    (
        [0] => width
        [1] => height
        [2] => name
        [3] => value
        [4] => src
        [5] => type
        [6] => allowfullscreen
        [7] => width
        [8] => height
    )

[2] => Array
    (
        [0] => 425
        [1] => 344
        [2] => movie
        [3] => http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1
        [4] => http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1
        [5] => application/x-shockwave-flash
        [6] => true
        [7] => 425
        [8] => 344
    )
)

Array
(
[0] => Array
    (
        [0] => src="http://blip.tv/play/AZ_iEoaIfA"
        [1] => type="application/x-shockwave-flash"
        [2] => width="640"
        [3] => height="510"
        [4] => allowscriptaccess="always"
        [5] => allowfullscreen="true"
    )

[1] => Array
    (
        [0] => src
        [1] => type
        [2] => width
        [3] => height
        [4] => allowscriptaccess
        [5] => allowfullscreen
    )

[2] => Array
    (
        [0] => http://blip.tv/play/AZ_iEoaIfA
        [1] => application/x-shockwave-flash
        [2] => 640
        [3] => 510
        [4] => always
        [5] => true
    )
)
```
```
From then on it's pretty straight forward. For things like width/height you can verify them with
```
is_numeric
```
and with the rest you can run the values through
```
htmlentities
```
and construct your own
```
<embed>
```
tag from the information. I am pretty certain this would be safe. You can even make the full-fledged
```
<object>
```
one like YouTube (which I assume works in more places) with links from blip.tv, since you would have all the required data.
I am sure you may see some quirks with links from other video-sharing websites but this will hopefully get you started. Good luck.


Question:
I have a command that runs fine if I ssh to a machine and run it, but fails when I try to run it using a remote ssh command like :

ssh user@IP <command>

Comparing the output of "env" using both methods resutls in different environments. When I manually login to the machine and run env, I get much more environment variables then when I run :

ssh user@IP "env"

Any idea why ?

Answer:
There are different types of shells. The SSH command execution shell is a non-interactive shell, whereas your normal shell is either a login shell or an interactive shell. Description follows, from man bash:
```
A  login  shell  is  one whose first character of argument
       zero is a -, or one started with the --login option.

       An interactive shell is  one  started  without  non-option
       arguments  and  without the -c option whose standard input
       and error are both connected to terminals  (as  determined
       by  isatty(3)), or one started with the -i option.  PS1 is
       set and $- includes i if bash is interactive,  allowing  a
       shell script or a startup file to test this state.

       The  following  paragraphs  describe how bash executes its
       startup files.  If any of the files exist  but  cannot  be
       read,  bash reports an error.  Tildes are expanded in file
       names as described below  under  Tilde  Expansion  in  the
       EXPANSION section.

       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.  The --noprofile option may
       be used when the shell is started to inhibit  this  behav
       ior.

       When a login shell exits, bash reads and executes commands
       from the file ~/.bash_logout, if it exists.

       When an interactive shell that is not  a  login  shell  is
       started,  bash reads and executes commands from ~/.bashrc,
       if that file exists.  This may be inhibited by  using  the
       --norc  option.   The --rcfile file option will force bash
       to  read  and  execute  commands  from  file  instead   of
       ~/.bashrc.

       When  bash  is  started  non-interactively, to run a shell
       script, for example, it looks for the variable BASH_ENV in
       the  environment,  expands  its value if it appears there,
       and uses the expanded value as the name of a file to  read
       and  execute.   Bash  behaves  as if the following command
       were executed:
              if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
       but the value of the PATH variable is not used  to  search
       for the file name.
```


Question:
I have a java webapp that has to be deployed on either Win or Linux machines. I now want to add log4j for logging and I'd like to use a relative path for the log file as I don't want to change the file path on every deployment. The container will most likely be Tomcat but not necessarily.

What's the best way of doing this?

Answer:
Tomcat sets a catalina.home system property.  You can use this in your log4j properties file.  Something like this:
```
```
log4j.rootCategory=DEBUG,errorfile

log4j.appender.errorfile.File=${catalina.home}/logs/LogFilename.log
```
```
On Debian (including Ubuntu),
```
${catalina.home}
```
will not work because that points at /usr/share/tomcat6 which has no link to /var/log/tomcat6. Here just use
```
${catalina.base}
```
.
If your using another container, try to find a similar system property, or define your own.  Setting the system property will vary by platform, and container.  But for Tomcat on Linux/Unix I would create a setenv.sh in the CATALINA_HOME/bin directory.  It would contain:
```
```
export JAVA_OPTS="-Dcustom.logging.root=/var/log/webapps"
```
```
Then your log4j.properties would be:
```
```
log4j.rootCategory=DEBUG,errorfile

log4j.appender.errorfile.File=${custom.logging.root}/LogFilename.log
```
```


Question: Is there a way in Delphi to get the currect application's exe size in one or two lines of code?

Answer:
Unfortunatly it is not possible to do that with only one or two lines of code without using some library.
The easy part is getting the application's exe file. You can find it in
```
Application.ExeName
```
In general there are several possibilities for retrieving the file size:
Open the file and read the size of the stream. This can be accomplished using the 'old' Delphi functions
```
FileOpen
```
and
```
FileSize
```
, or with
```
TFileStream
```
(use the
```
size
```
property) or with Win32 API functions
```
CreateFile
```
and
```
GetFileSize
```
function. (Platform dependend!) Make sure you open the file with read-only access.
In a pure Win32 envinronment you can use
```
FindFirst
```
to get the file size. You can read it from
```
TSearchRec.FindData.nFileSizeLow
```
. If you want to be prepared for files larger than 2 GB (you should be) you have to use also the
```
nFileSizeHigh
```
part.
In Delphi.NET you can use the
```
System.IO.FileInfo
```
, like this:
```
FileInfo.Create(filename).Length
```
(one-liner)
In Linux you can use the
```
lstat64
```
function (Unit
```
Libc
```
) and get the size from
```
TStatBuf64.st_size
```
.  (two-liner if you don't count the variable declaration)
In the
JCL library
you can find many useful functions, including a simple function which returns the file size of a given file name. (It uses a method which suits the given platform)


Question:
How to represent the start and end times for one day?

Using October 23, 2008 as an example, is it start 2008-10-23 12:00:00 AM and end 2008-10-23 11:59:59 PM?

Answer:
I would like to cite a site,
http://www.cl.cam.ac.uk/~mgk25/iso-time.html
The international standard notation for the time of day is
```
```
hh:mm:ss
```
```
where hh is the number of complete hours that have passed since midnight (00-24), mm is the number of complete minutes that have passed since the start of the hour (00-59), and ss is the number of complete seconds since the start of the minute (00-60). If the hour value is 24, then the minute and second values must be zero.
Note: The value 60 for ss might sometimes be needed during an inserted leap second in an atomic time scale like Coordinated Universal Time (UTC). A single leap second 23:59:60 is inserted into the UTC time scale every few years as announced by the International Earth Rotation Service in Paris, to keep UTC from wandering away more than 0.9 s from the less constant astronomical time scale UT1, which is defined by the actual rotation of the earth. In practice you are not very likely to see a clock showing 23:59:60. Most synchronized clocks resynchronize again to UTC some time after a leap second has happened, or they temporarily slow down near the time of a leap seconds, to avoid any disruption that an out-of-range timestamp might otherwise cause.
An example time is
```
```
23:59:59
```
```
which represents the time one second before midnight.
As with the date notation, the separating colons can also be omitted as in
```
```
235959
```
```
and the precision can be reduced by omitting the seconds or both the seconds and minutes as in
```
```
23:59, 2359, or 23
```
```
It is also possible to add fractions of a second after a decimal dot or comma, for instance the time 5.8 ms before midnight can be written as
```
```
23:59:59.9942 or 235959.9942
```
```
As every day both starts and ends with midnight, the two notations 00:00 and 24:00 are available to distinguish the two midnights that can be associated with one date. This means that the following two notations refer to exactly the same point in time:
```
```
1995-02-04 24:00 = 1995-02-05 00:00
```
```
In case an unambiguous representation of time is required, 00:00 is usually the preferred notation for midnight and not 24:00. Digital clocks display 00:00 and not 24:00.
ISO 8601 does not specify, whether its notations specify a point in time or a time period. This means for example that ISO 8601 does not define whether 09:00 refers to the exact end of the ninth hour of the day or the period from 09:00 to 09:01 or anything else. The users of the standard must somehow agree on the exact interpretation of the time notation if this should be of any concern.
If a date and a time are displayed on the same line, then always write the date in front of the time. If a date and a time value are stored together in a single data field, then ISO 8601 suggests that they should be separated by a latin capital letter T, as in 19951231T235959.
A remark for readers from the U.S.:
The 24h time notation specified here has already been the de-facto standard all over the world in written language for decades. The only exception are a few English speaking countries, where still notations with hours between 1 and 12 and additions like “a.m.” and “p.m.” are in wide use. The common 24h international standard notation is widely used now even in England (e.g. at airports, cinemas, bus/train timetables, etc.). Most other languages do not even have abbreviations like “a.m.” and “p.m.” and the 12h notation is certainly hardly ever used on Continental Europe to write or display a time. Even in the U.S., the military and computer programmers have been using the 24h notation for a long time.
The old English 12h notation has many disadvantages like:
It is longer than the normal 24h notation.
It takes somewhat more time for humans to compare two times in 12h notation.
It is not clear, how 00:00, 12:00 and 24:00 are represented. Even encyclopedias and style manuals contain contradicting descriptions and a common quick fix seems to be to avoid “12:00 a.m./p.m.” altogether and write “noon”, “midnight”, or “12:01 a.m./p.m.” instead, although the word “midnight” still does not distinguish between 00:00 and 24:00 (midnight at the start or end of a given day).
It makes people often believe that the next day starts at the overflow from “12:59 a.m.” to “1:00 a.m.”, which is a common problem not only when people try to program the timer of VCRs shortly after midnight.
It is not easily comparable with a string compare operation.
It is not immediately clear for the unaware, whether the time between “12:00 a.m./p.m.” and “1:00 a.m./p.m.” starts at 00:00 or at 12:00, i.e. the English 12h notation is more difficult to understand.
Please consider the 12h time to be a relic from the dark ages when Roman numerals were used, the number zero had not yet been invented and analog clocks were the only known form of displaying a time. Please avoid using it today, especially in technical applications! Even in the U.S., the widely respected Chicago Manual of Style now recommends using the international standard time notation in publications.


Question: What's the best way (or tool) on the Windows (Vista) command line to get size and modification time for a file on a remote webserver, without downloading it?

Answer:
There is a
Win32 port of wget
that works decently.
PowerShell's
```
Invoke-WebRequest -Method Head
```
would work as well.


Question:
I have committed, and pushed, several patches:
A1-->A2-->A3-->A4 (HEAD)

Everyone's pulled these changesets into their local copy.

Now we want to "roll back" to A2, and continue developing from there - essentially throwing away A3 and A4. What's the best way to do this?

Answer:
You want
```
git-revert
```
and
```
git-reset
```
depending on how you want to treat A3 and A4. To remove all trace of A3 and A4, use
```
git-reset --hard
```
.
To keep A3 and A4 and record the fact you are reverting, use
```
git-revert
```
.
edit
: Aristotle Pagaltzis's
```
git-checkout
```
solution is superior, though for small reverts I don't see a problem with
```
git-revert
```
. None the less, I ask future upvotes be given to
Aristotle Pagaltzis's answer
I found
git magic
to be a good resource for git.


Question: I want to digest a multipart response in C++ sent back from a PHP script. Anyone know of a very lightweight MIME parser which can do this for me?

Answer:
I know this may be too little, too late, but I had a similar need.  I wanted a mime parser that just did the encoding and decoding of the MIME.  For the sake of completeness and for Google-ability I thought I should put my findings here.  Keep in mind that I was not interested in send and receiving mail, just encoding and decode MIME.  Here are the libraries I researched for C++ MIME:
http://www.vmime.org/
- Looks like too much. Contains pop, SMTP, tls, IMAP, could remove this.  Posix and windows.
http://codesink.org/mimetic_mime_library.html
- looks promising.  Very nice api for reading in and creating messages. Went with this one. Not too heavy.  Had to “fix” 2 things. First for multipart the code was just check for the string “multipart” and did not recognize “multipart/mixed” and did not write out the parts. Secondly, I had to hack the mimeentity write code.  It was just writing out the std::deque Field and since these are strings it seem to be doing so alphabetically.  This is problem because the MIME-version has to be the first field written out. So I fixed this. I also had to add support for Content-Length.
http://www.mozilla.org/mailnews/arch/libmime-description.html
- Hard time finding this.  Had to download the whole package. mailnews\mime\src
http://www.example-code.com/vcpp/smime.asp
- Didn’t consider because it had no source code and was windows specific.
http://httpd.apache.org/docs/2.2/mod/mod_mime.html
- Couldn’t find this C implementation.
I chose Mimetic for my needs although I had to add a few things to it.  None of the parsers I found handled the optional fields (Content-Length, etc..) very well.  I also needed it to support multiple platforms (Windows, Linux, etc..)


Question:
I would like to create an iPhone app that can open the google maps app and place a pin on the map.

I have the exact location of the pin, specified by its longitude and latitude.
I also have a name for the pin e.g. 'location 1' that should be displayed along with the pin.

I know that UIApplication:openURL can be used for this but I don't know the exact url format.

So, is there a way to do what I described above? If, yes, what is the correct url format?

Answer:
You can use a URL of the format:
http://maps.google.com/maps?q=Your+Location+name@latitude,longitude
http://maps.google.com/maps?q=This+is+near+Lake+Shore+Drive@41.9288,-87.6315


Question: For example, if I have a network spec like 172.20.10.0/24, "24" is the bitcount. What's the best way to convert that to a netmask like 0xffffff00 ?

Answer:
This is not a programming question, but in linux you can use whatmask.
```
```
whatmask 72.20.10.0/24
```
```
returns
```
```
IP Entered = ..................: 72.20.10.0
CIDR = ........................: /24
Netmask = .....................: 255.255.255.0
Netmask (hex) = ...............: 0xffffff00
Wildcard Bits = ...............: 0.0.0.255
------------------------------------------------
Network Address = .............: 72.20.10.0
Broadcast Address = ...........: 72.20.10.255
Usable IP Addresses = .........: 254
First Usable IP Address = .....: 72.20.10.1
Last Usable IP Address = ......: 72.20.10.254
```
```


Question:
I want to find a linux command that can return a part of the string. In most programming languages, it's the substr() function. Does bash have any command that can be used for this purpose. I want to be able to do something like this...
substr "abcdefg" 2 3 - prints cde.

Subsequent similar question:

Extract substring in Bash

Answer:
From the bash manpage:
```
```
${parameter:offset}
${parameter:offset:length}
        Substring  Expansion.   Expands  to  up  to length characters of
        parameter starting at the character  specified  by  offset.
[...]
```
```
Or, if you are not sure of having
```
bash
```
, consider using
```
cut
```
.


Question:
I've got the bare minimum to handle the Linux/MySQL parts of the stack, but I want to have a basic grasp of PHP before I dive in.  I'll be working on WordPress plugins, in case there's anything specifically interesting for that.

PS - any recommendations regarding recommended source control/IDEs would also be great, but I guess that's a separate question.

Answer:
For PHP books you can check
this
question, personally I like
Programming PHP
, IDEs, I can recommend you to try:
Eclipse PDT
Zend Studio for Eclipse
NetBeans for PHP
DevPHP
Vim
Vim actually it's not an IDE, but you can get omnicompletion, syntax coloring, debugging, and so on...
The
PHP Manual
it's also a really good place to start learning the language.


Question:
I have all the web pages of a website. My task is to change all HTML files to .asp files and change the links. I have about 280 HTML files.

Is there any software or web service which can read a website and show me the link structure of the site (to make my job easier) similar to a site map?

Answer:
If the links use relative paths, all you have to do is to change the .html file extensions to .asp and place the files on a server that can run ASP.
If they are absolute paths, you can get away with editing your hosts file to point the original domain to your own server and just place the untouched files on your server.
If you
really
need to replace the URLs, try a text editor like UltraEdit or Notepad++ (on Windows) that can do find/replace over files (and use regular expressions for the search phrase). Or you can use sed or Perl on Linux.


Question: I want a single number that represents the current date and time, like a Unix timestamp.

Answer:
Timestamp in milliseconds
To get the number of milliseconds since
Unix epoch
, call
```
Date.now
```
:
```
```
Date.now()
```
```
Alternatively, use the unary operator
```
+
```
to call
```
Date.prototype.valueOf
```
:
```
```
+ new Date()
```
```
Alternatively, call
```
valueOf
```
directly:
```
```
new Date().valueOf()
```
```
To support IE8 and earlier (see
compatibility table
), create a
shim
for
```
Date.now
```
:
```
```
if (!Date.now) {
    Date.now = function() { return new Date().getTime(); }
}
```
```
Alternatively, call
```
getTime
```
directly:
```
```
new Date().getTime()
```
```
Timestamp in seconds
To get the number of seconds since
Unix epoch
, i.e.
Unix timestamp
:
```
```
Math.floor(Date.now() / 1000)
```
```
Alternatively, using bitwise-or to floor is slightly faster, but also less readable and may break in the future (see explanations
1
,
2
):
```
```
Date.now() / 1000 | 0
```
```
Timestamp in milliseconds (higher resolution)
Use
```
performance.now
```
:
```
```
var isPerformanceSupported = (
    window.performance &&
    window.performance.now &&
    window.performance.timing &&
    window.performance.timing.navigationStart
);

var timeStampInMs = (
    isPerformanceSupported ?
    window.performance.now() +
    window.performance.timing.navigationStart :
    Date.now()
);

console.log(timeStampInMs, Date.now());
```
```


Question: I'm creating window using pure Win32 API (RegisterClass and CreateWindow functions). How can I specify a font for the window instead of system defined one?

Answer:
In case you superclass a standard common control that already has its own font handle, use this approach: Just create a font using
```
CreateFont
```
or
```
CreateFontIndirect
```
and set it using
```
WM_SETFONT
```
message (in MFC and ATL there would be a corresponding
```
SetFont
```
function). When the font is no longer needed, destroy the font using
```
DeleteObject
```
. Be sure to not destroy the window's previously set font.
In case you're writing a custom control that draws itself, just create a new font object using
```
CreateFont
```
or
```
CreateFontIndirect
```
and store it in your class somewhere. If you want to support third-party users, handle
```
WM_SETFONT
```
and
```
WM_GETFONT
```
to let the user set another font. When painting, use the current font object stored in your class.


Question: What's the best way to determine if the version of the JRE installed on a machine is high enough for the application which the user wants to run? Is there a way of doing it using java-only stuff? I'd like the solution to work on Windows/Linux/MacOSX - if the JRE version is too low a message should be displayed. Currently I'm getting an exception if i try to run it on Java 1.5 (the app is built for Java 1.6). If there's no universal solution, what's the best way to do it on Windows?

Answer:
An application built for a higher-version JRE will not run on a lower-version JRE. So you wouldn't be able to just add code to your application to check the JRE version - if the JRE version was incompatible, your JRE-version-checking code would not run in the first place.
What you'd have to do is have some sort of launcher application that is built for a lower-version JRE (1.3?) that checks the version and then launches your app if necessary. This sounds kind of kludgy to me.
What about checking the version during installation? Are you installing the app in a way that allows you to check environment variables, or do any sort of scripting?


Question:
Is there any performance impact or any kind of issues?
The reason I am doing this is that we are doing some synchronization between two set of DBs with similar tables and we want to avoid duplicate PK errors when synchronizing data.

Answer:
Yes, it's okay.
Note: If you have perfomance concerns you could use the "CACHE" option on "CREATE SEQUENCE":
"Specify how many values of the sequence the database preallocates and keeps in memory for faster access. This integer value can have 28 or fewer digits. The minimum value for this parameter is 2. For sequences that cycle, this value must be less than the number of values in the cycle. You cannot cache more values than will fit in a given cycle of sequence numbers. Therefore, the maximum value allowed for CACHE must be less than the value determined by the following formula:"
```
```
(CEIL (MAXVALUE - MINVALUE)) / ABS (INCREMENT)
```
```
"If a system failure occurs, all cached sequence values that have not been used in committed DML statements are lost. The potential number of lost values is equal to the value of the CACHE parameter."


Question:
I need a way to detect mouse/keyboard activity on Linux. Something similar to what any IM program would do. If no activity is detected for, say 5 minutes, it will set your IM status to "I'm not here right now".

Any help towards this is appreciated.

Thanks.

Answer:
Try executing
```
who -u -H
```
at the command line. It will tell you who's logged in and how long they've been idle. At least users logged in to a terminal; I don't think it works at all in X. Anyhow, with this information you can tell who's idle or not and take actions appropriately.
If you're in X you could create a script to run as a screen saver or something like that.


Question: I was wondering if there is a way for a network of N participants to agree that a number from 1 to M was chosen at random. (e.g. not influenced by any of the participants) This has been solved for values of n=2 and m=2 by the coin tossing protocol. Does anyone know of any solutions that can work for arbitrary values of N and M?

Answer:
Edit
Better algorithm (thanks wnoise):
Everyone picks a secret number from 0 to M-1
Everyone appends a load of random gunk to their number and hashes the result with a secure hash
Everyone tells everyone else this hash
Everyone tells everyone else their secret number, plus the random gunk they appended to it
Everyone verifies that the numbers and hashes+gunk match
Add all the secret numbers together modulo M, then adds 1 to get the final result
As a participant, I should be satisfied with this because I know that I had full influence over the final result - the final number could have been anything at all, depending on my choice of secret number. So since no-one else could predict my number, they couldn't have predicted the final result either.
Any way to reduce the messages from the 3M^2 that i suspect a broadcast approach would require?
I reckon that only the hash publication has to be a broadcast, but it's still O(M^2). I guess the only way around that would be to pre-exchange digital signature keys, or to have a trusted communication hub.
Edit2
- How safe is the hashing thing?
Possible attacks include:
If I can generate a hash collision then I have two secret numbers with the same hash. So once I know everyone else's secret numbers I can choose which of my secret numbers to reveal, thus selecting one of two possible results.
If I generate my secret number and random gunk using a PRNG, then an attacker trying to brute-force my hash doesn't have to try every possible number+gunk, only every possible seed for the PRNG.
I use the number+gunk that everyone reveals to determine information about their PRNGs - I could try to guess or brute-force the seeds, or calculate the internal state from the output. This helps me predict what numbers they will generate next time around, which narrows the search space for a brute-force attack.
Therefore, you should
Use a trusted, unbroken hashing algorithm.
Use a cryptographically secure random number generator that has a big seed / state, and try to seed it from a good source of entropy.


Question:
i have a 3 column datafile and i wanted to use splot to plot the same.
But what i want is that gnuplot plots first row (in some colour, say red) and then pauses for say 0.3 secs and then moves on to plotting next row (in other colour, not in red, say in green), pauses for 0.3 secs and then proceeds to next row....so on n so forth.

Any help will be greately appreciated.

thanks in advance

Regards Pankaj

Answer:
If you want to produce an animation, you better use specialized tools for it (like mplayer).
Use gnuplot to prepare all source images (first one with single row plotted, second - with two lines, etc), then use mplayer or convert (from imagemagic) to produce avi or animated GIF out of source files.
You can use the following shell snippet to produce partial copies of the input file, each with increasing number of lines.
```
```
file="your input file.dat"
lines=$(wc -l $file)
i=1
while [ $i -le $lines ] ; do
  head -${i} ${file} > ${file%.dat}-${i}lines.dat
done
```
```
Given somefile.dat this will produce files "somefile-1lines.dat", "somefile-2lines.dat", etc. Then you can use:
```
```
for f in *lines.dat ; do
  gnuplot ... $f
done
```
```
to plot them all in sequence.
If my assumption is wrong and all you really want is this pause, then you can try to set things up so that gnuplot will get data from stdin, and then use this scipt (name it paused-input.sh) to pipe input file with pauses after each line:
```
```
#!/bin/bash
while read l ; do
  echo "$l"
  sleep 1
done
```
```
Then invoke it like this:
```
```
(pause-input.sh | gnuplot ...) < somefile.dat
```
```


Question:
This is sort of a follow-up to this question.

If there are multiple blobs with the same contents, they are only stored once in the git repository because their SHA-1's will be identical.  How would one go about finding all duplicate files for a given tree?

Would you have to walk the tree and look for duplicate hashes, or does git provide backlinks from each blob to all files in a tree that reference it?

Answer:
The scripting answers from your linked question pretty much apply here too.
Try the following git command from the root of your git repository.
```
```
git ls-tree -r HEAD
```
```
This generates a recursive list of all 'blobs' in the current HEAD, including their path and their sha1 id.
git doesn't maintain back links from a blob to tree so it would be a scripting task (perl, python?) to parse a
```
git ls-tree -r
```
output and create a summary report of all sha1s that appear more than once in the list.


Question: With Windows 7 probably going to RTM next October (and DirectX 11 with it), would it be worth waiting for DirectX 11's explicit GPGPU features, meaning it will be cross-platform (ATI/Nvidia, not Windows/Linux/Mac/Whatever); or should I create a CUDA application now?

Answer:
From a learning point-of-view I think you would benefit from starting with CUDA now, since it will help you a lot with thinking in data-parallelism which is what the GPUs are good at. Then when/if you turn to DirectX 11, you have a good foundation for working with it, but it depends on the kind of time you have available (i.e. if you have time to experiment with stuff just for the learning experience).
Alternatively, the mac people are pushing for OpenCL (Open Compute Language) to be the general solution, though not much is known at this point. This is another technology you can wait for and check out.
The Microsoft PDC conference is held later this month, maybe they will announce some useful info on DX11 to help you make up your mind.
My general advice would be that I think there is a lot to learn now which you will be able to use later (with DX11 or OpenCL) but that you have to ask yourself if you are willing to learn some technology which might not make it in the long run. Anyways, these are just my thoughts, I don't have a huge amount of experience with CUDA yet.
On a highly speculative note, my gut feeling is that APIs such as CUDA won't survive for long and that DirectX and/or OpenCL are the only solutions which have a future (Unless they really botch their implementations, which I doubt).


Question: Safari on iPhone automatically creates links for strings of digits that appear to the telephone numbers.  I am writing a web page containing an IP address, and Safari is turning that into a phone number link.  Is it possible to disable this behavior for a whole page or an element on a page?

Answer:
You could try encoding them as HTML entities:
```
```
0 = 0
9 = 9
```
```


Question:
This is just a general question - I was sitting and waiting for a bit of software to compile (we use Incredibuild here but can still take 10/15 mins) and it got me wondering, does anyone know how long it took to compile Windows XP or Vista?

I did some googling but didn't really find any useful information

Answer:
Third-hand information I have is that it takes about a day to complete a Windows build. Which is more or less in line with attempting to build your favorite OSS Operating System from scratch.
Building a modern operating system is a complex and difficult task. The only reason why it doesn't take longer is because companies like Microsoft have build environments setup to help automate integration testings. Thus they can build a system with less manual effort than is involved in most OSS builds.
If you've like to get a feel for what it takes to build an operating system, might I recommend the free eBook:
Linux from Scratch
For a more automated build, try
Gentoo
. Both options should give you a better idea of the Operating System build process.


Question: I am building Windows apps for a few clients.  I read Joel on Software and took the Joel Test and realized I don't quite measure up.  One place I am lacking is automated builds.  What should I use to have automated builds?  I have Windows apps that use .NET 1.1, 2.0, and 3.5.  Also, I need to be able to build my .vdproj to create MSI's.  I am looking for something that is free and would work well for a one-man team.

Answer:
CruiseControl.Net
and
NAnt
are the standard tools (and open source too), so there will be a lot of community support available.
MSBuild
is now open source, too
It will be quite a lot of work to set it all up, but it will be very powerful and have lots of room for growth too.


Question:
What's the best way to initialize an array in PowerShell?

For example, the code

$array = @()
for($i=0; $i -lt 5;$i++)
{
    $array[$i] = $FALSE
}

generates the error

Array assignment failed because index '0' was out of range.
At H:\Software\PowerShell\TestArray.ps1:4 char:10
+         $array[$ <<<< i] = $FALSE

Answer:
The solution I found was to use the New-Object cmdlet to initialize an array of the proper size.
```
```
$array = new-object object[] 5
for($i=0; $i -lt $array.Length;$i++)
{
    $array[$i] = $FALSE
}
```
```


Question: I want to use jQuery to parse RSS feeds. Can this be done with the base jQuery library out of the box or will I need to use a plugin?

Answer:
Use jFeed
- a jQuery RSS/Atom plugin. According to the docs, it's as simple as:
```
```
jQuery.getFeed({
   url: 'rss.xml',
   success: function(feed) {
      alert(feed.title);
   }
});
```
```


Question:
I want to pause input in a shell script, and prompt the user for choices.

The standard Yes, No, or Cancel type question.

How do I accomplish this in a typical bash prompt?

Answer:
```
```
echo "Please enter some input: "
read input_variable
echo "You entered: $input_variable"
```
```


Question:
When you are monitoring the TFS build from Visual Studio (2008 or 2005), you can see where it is up to.

The issue is that I have some Post-Build custom steps I would like the developer to be able to see directly throught the UI. Those steps take some times and we can also get a "timing" of the build step.

Any idea how to have it displayed?

Answer:
This is the pattern that I normally use for adding steps to the build report in TFS 2008. (See
http://code.msdn.microsoft.com/buildwallboard/
for the full example that I usually use in my Team Build talks)
Basically, the magic is that there is a custom task provided for you in TFS2008 called "BuildStep".  Here is the section where I generate and MSI installer and build the appropriate build steps in the report:
```
```
<Target Name="PackageBinaries">

    <!-- create the build step -->
    <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
               BuildUri="$(BuildUri)"
               Message="Creating Installer"
               Condition=" '$(IsDesktopBuild)' != 'true' " >
      <Output TaskParameter="Id"
              PropertyName="InstallerStepId" />
    </BuildStep>

    <!-- Create the MSI file using WiX -->
    <MSBuild Projects="$(SolutionRoot)\SetupProject\wallboard.wixproj"
  Properties="BinariesSource=$(OutDir);PublishDir=$(BinariesRoot);Configuration=%(ConfigurationToBuild.FlavourToBuild)" >
    </MSBuild>

    <!-- If we sucessfully built the installer, tell TFS -->
    <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
               BuildUri="$(BuildUri)"
               Id="$(InstallerStepId)"
               Status="Succeeded"
               Condition=" '$(IsDesktopBuild)' != 'true' " />

    <!-- Note that the condition above means that we do not talk to TFS when doing a Desktop Build -->

    <!-- If we error during this step, then tell TFS we failed-->
    <OnError   ExecuteTargets="MarkInstallerFailed" />
  </Target>

  <Target Name="MarkInstallerFailed">
    <!-- Called by the PackageBinaries method if creating the installer fails -->
    <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
               BuildUri="$(BuildUri)"
               Id="$(InstallerStepId)"
               Status="Failed"
               Condition=" '$(IsDesktopBuild)' != 'true' " />
  </Target>
```
```
So initially, I create the build step and save the Id of the step in a propery called InstallerStepId.  After I have performed my task, I set the status of that step to Succeeded.  If any errors occur during the step then I set the status of that step to Failed.
Good luck,
Martin.


Question:
I have a git repository with multiple branches.

How can I know which branches are already merged into the master branch?

Answer:
You can use the
```
git merge-base
```
command to find the latest common commit between the two branches. If that commit is the same as your branch head, then the branch has been completely merged.
Note that
```
git branch -d
```
does this sort of thing already because it will refuse to delete a branch that
hasn't
already been completely merged.


Question:
I need to be able to launch a process and read the output into a variable.  Then based on the return of the command I can choose to show the full output or just a selected subset.

So to be clear, I want to launch a text based process (psexec actually) and read the output from that command (stdout, stderr, etc) into a variable rather than have it directly outputted to the console.

Answer:
You left off some details regarding what kind of process, but I think
this article
from the Powershell Team Blog has whatever you'd like to do, either from piping the executable's output somewhere or utilizing
```
System.Diagnostics.Process
```
.
Now that the second option sounds like what you want to do, you can use the
```
ProcessStartInfo
```
class to feed in
```
true
```
as the
```
RedirectStandardOutput
```
property, and then read from the
```
StandardOutput
```
property of the
```
Process
```
object to do whatever you want with the output.
```
StandardError
```
works identically.


Question: I was wondering if there was an alternative to itoa() for converting an integer to a string because when I run it in visual Studio I get warnings, and when I try to build my program under Linux, I get a compilation error.

Answer:
boost::lexical_cast
works pretty well.
```
```
#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
    std::string foo = boost::lexical_cast<std::string>(argc);
}
```
```


Question:
Very simple question, is there any cloud server enviroments avaliable these days for us .NET guys that rivals Amazons ec2?

EDIT:

PDC 2008 looks like there are some very interesting info, and only 4 days 2 hours  to wait :-). Looks like I need to get saving fast for the conference fee though.

Answer:
Hold your breath for
PDC 2008
and you'll see.  Also Amazon's EC2 service support for Windows images is in Beta.
AWS Windows Support Blog Post
Oct 23 Update
: AWS Windows Support Released To Production (
details here
)
Oct 27th Update
: So you held your breath and saw the Reddog folk become "Windows Azure" cloud services and Sitka - SQL Server Data Services.  Lots of activity to read and learn at MSDN, MS PDC site, Channel 9 etc.  Have fun!


Question: Is there a good, up-to-date listing anywhere that maps User-Agent HTTP Header strings --> operating systems?

Answer:
Here's a quick list... let me know if I missed one you are interested in.
http://www.geekpedia.com/code47_Detect-operating-system-from-user-agent-string.html
:
// Match user agent string with operating systems
Windows 3.11 =>
  Win16,
Windows 95 => (Windows 95)|(Win95)|(Windows_95),
Windows 98 => (Windows 98)|(Win98),
Windows 2000 => (Windows NT
  5.0)|(Windows 2000),
Windows XP => (Windows NT 5.1)|(Windows
  XP),
Windows Server 2003 => (Windows NT 5.2),
Windows Vista =>
  (Windows NT 6.0),
Windows 7 => (Windows NT 6.1),
Windows 8 => (Windows NT 6.2),
Windows 10 => (Windows NT 10.0),
Windows NT
  4.0 => (Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT),
Windows
  ME => Windows ME,
Open BSD => OpenBSD,
Sun OS => SunOS,
Linux => (Linux)|(X11),
Mac OS => (Mac_PowerPC)|(Macintosh),
QNX => QNX,
BeOS => BeOS,
OS/2 => OS/2,
Search
  Bot=>(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask
  Jeeves/Teoma)|(ia_archiver)


Question: Has anyone come up with a good way to share a set of Visual Studio Code Snippets (actual .snippet files that Visual studio uses) amongst a team of developers automatically?  It would be great for other developers on my team to benefit from shortcuts I've created for myself, and vice versa.

Answer:
I know this post is very old, but I found another good way (IMO) for sharing snippets, maybe in addition to the solution @Kevin Dente provided:
using git
!!
I shared successfully snippets and project templates creating an ad hoc git repository named
snippets.git
, I cloned it into the
MyDocuments\Visual Studio 2015\Code Snippets
folder and now I can add, edit or delete snippets from
MyDocuments\Visual Studio 2015\Code Snippets\Visual C#\My Code Snippets
(or
Visual Basic
folder), then commit and push to make them available to all other team members with the same configuration.
The principle is applicable also to the project templates, you can create a
templates.git
repository and clone it to the
MyDocuments\Visual Studio 2015\Templates
folder, then create the templates under the
MyDocuments\Visual Studio 2015\Templates\ProjectTemplates\Visual C#
folder (or
Visual Basic
folder).
This way the developers can periodically pull the two repositories and have up to date snippets and templates, available almost everywhere the git server is reachable (anyone said github? or bitbucket?).
Of course I am using Visual Studio 2015, but the method can be used with previous and, I think, future versions of Visual Studio.


Question:
Following on from this question what would be the best way to write a Char.IsHex() function in C#. So far I've got this but don't like it:

bool CharIsHex(char c) {
    c = Char.ToLower(c);
    return (Char.IsDigit(c) || c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f')
}

Answer:
From
my answer
to the question you linked to:
```
```
bool is_hex_char = (c >= '0' && c <= '9') ||
                   (c >= 'a' && c <= 'f') ||
                   (c >= 'A' && c <= 'F');
```
```


Question: What's the difference between Char.IsDigit() and Char.IsNumber() in C#?

Answer:
I found the answer:
Char.IsNumber() determines if a Char
  is of any numeric Unicode category.
  This contrasts with IsDigit, which
  determines if a Char is a radix-10
  digit.
Valid numbers are members of the
  following categories in
UnicodeCategory
:
```
DecimalDigitNumber
```
Decimal digit character, that is, a character in the range 0 through 9. Signified by the Unicode designation "Nd" (number, decimal digit). The value is 8.
```
LetterNumber
```
Number represented by a letter, instead of a decimal digit, for example, the Roman numeral for five, which is "V". The indicator is signified by the Unicode designation "Nl" (number, letter). The value is 9.
```
OtherNumber
```
Number that is neither a decimal digit nor a letter number, for example, the fraction ½. The indicator is signified by the Unicode designation "No" (number, other). The value is 10.
Conclusion
```
Char.IsDigit
```
:
Valid digits are members of the
```
DecimalDigitNumber
```
category only.
```
Char.IsNumber
```
:
Valid numbers are members of the
```
DecimalDigitNumber
```
,
```
LetterNumber
```
, or
```
OtherNumber
```
category.


Question:
If I want to check for the null string I would do

[ -z $mystr ]

but what if I want to check whether the variable has been defined at all? Or is there no distinction in Bash scripting?

Answer:
```
```
~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO=""
~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO="a"
~> if [ -z $FOO ]; then echo "EMPTY"; fi
~>
```
```
-z works for undefined variables too. To distinguish between an undefined and a defined you'd use the things listed
here
or, with clearer explanations,
here
.
Cleanest way is using expansion like in these examples. To get all your options check the Parameter Expansion section of the manual.
Alternate word:
```
```
~$ unset FOO
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
~$ FOO=""
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
DEFINED
```
```
Default value:
```
```
~$ FOO=""
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
~$ unset FOO
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
UNDEFINED
```
```
Of course you'd use one of these differently, putting the value you want instead of 'default value' and using the expansion directly, if appropriate.


Question: I need a cross platform solution for clearing the console in both Linux and Windows written in C++. Are there any functions in doing this? Also make note that I don't want the end-user programmer to have to change any code in my program to get it to clear for Windows vs Linux (for example if it has to pick between two functions then the decision has to be made at run-time or at compile-time autonomously).

Answer:
I know this isn't answering my own question but!
This works for Windows (
```
#include <windows.h>
```
):
```
```
void clrscr()
{
    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD coord = {0, 0};
    DWORD count;

    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(hStdOut, &csbi);

    FillConsoleOutputCharacter(hStdOut, ' ', csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

    SetConsoleCursorPosition(hStdOut, coord);
}
```
```


Question: Has anybody tried creating RawSocket in Android and have succeeded ?

Answer:
I havent actually created any raw sockets in Android but the java.net and javax.net packages shold do what you need,
java.net package overview
javax.net package overview


Question:
I'm trying to link an RPATH containing the special string $ORIGIN into an executable built using GCC with the Code::Blocks IDE. I've specified

-Wl,-R$ORIGIN

in the linker options for the project, but the command line output to GCC is wrong (stripped for clarity):

g++ -Wl,-R

What is the correct way to specify this argument for Code::Blocks?

Answer:
Whoever decided to make the token $ORIGIN is an evil bastard who deserves a special place in programmer hell. Since '$' is a special character for bash and other scripting languages like make, it screws everything up unless carefully escaped. Even worse, depending on which build environment you're using, the specifics of how to escape properly will likely change.
In bash, you need to stick a backslash in front of the $:
```
```
-Wl,-R\$ORIGIN
```
```
Code::Blocks apparently also treats the $ as special. Then, whatever subprocess controller Code::Blocks sends the command to treats the backslash as special. So, both the backslash and the $ need to be doubled up to get escaped properly. Therefore, in Code::Blocks linker settings, you need to specify:
```
```
-Wl,-R\\$$ORIGIN
```
```
...which outputs:
```
```
-Wl,-R\\$ORIGIN
```
```
...to the build log, but the shell actually gets sent:
```
```
-Wl,-R\$ORIGIN
```
```
...which as mentioned above produces the desired result.
What a pain.


Question:
I am working with some input that is in the possible forms

$1,200
20 cents/ inch
$10

Is there a way to parse these to numbers in VB?  Also printing these numbers?

EDIT: Regular expressions would be great.

EDIT: VB 6 in particular

Answer:
Ehh...Assuming all that you want is the digits, I would use a Regular Expression to simply replace any non-digit with "".
You would need to reference Microsoft VBScript Regular Expressions in your project. Then let's say that your text was in a variable called strTest. Here is some off the cuff untested code:
```
```
Dim oRE As Object
Set oRE = New VBScript_RegExp.RegExp
oRe.Pattern = "\D"
strTest = oRE.Replace(strTest, "")
```
```


Question: What tool or method do you recommend to find and replace values in your code? If code is on Linux/Unix, are find and grep the best method?

Answer:
I'm assuming you intend to rename a variable.
It depends on what the body of code is. For C#, Visual Studio's renaming tool is very good. Remember that for it to work reliably, you need the renaming to work hand in hand with the compiler/interpreter, so you can make sure you only make the change in the right scope.
If it is a very simple find/replace, surely the lowly notepad would do an OK job?


Question: Is there a way to mount a Linux directory from a different PC to your local Linux PC? How?

Answer:
You need to be a bit more specific.  You can use NFS.
Depending on what distro you're using, you simply edit the
```
/etc/exports
```
file on the remote machine to export the directories you want, then start your NFS daemon.
Then on the local PC, you mount it using the following command:
```
```
mount -t nfs {remote_pc_address}:/remote/dir /some/local/dir
```
```
Use the
```
man
```
utility for more information:
man exports
(Examples of configuring directories for export are on the bottom of this manual page.)


Question:
Is it possible to have all the computing capacity of all the hardware nodes allocated to one instance (for eg. one basic linux installation)?

How to manage the cloud?

Answer:
I think you're confusing cloud computing and grid computing here. Although they do have similarities.
Cloud computing is usually used to refer to solutions where data is stored somewhere on the internet and made available on any workstation that is online.
Grid computing is used to refer to applications where a lot of different agents solve parts of the same computing problem in parallel. (think Seti-at-home or folding-at-home)
But you can't use cloud or grid computing to just seamlessly run existing platforms. Both refer to architectures. There are a couple of platforms that are general implementations of these architectures but they're so different that you can't easilly run software on them that's not designed to run distributed.


Question:
Is there currently a way to host a shared Git repository in Windows?  I understand that you can configure the Git service in Linux with:

git daemon

Is there a native Windows option, short of sharing folders, to host a Git service?

EDIT:
I am currently using the cygwin install of git to store and work with git repositories in Windows, but I would like to take the next step of hosting a repository with a service that can provide access to others.

Answer:
Have you considered using the cygwin layer? See
this link
.


Question: As per RFC1035, dns names may contain \ddd \x and quote symbol. Please explain with examples about those.

Answer:
RFC1035
doesn't say that DNS
names
can contain those characters.  In section 5 (MASTER FILES) it says that the
file
that contains the RR information can contain those characters.  Specifically: "Because these files are text files several special encodings are
necessary to allow arbitrary data to be loaded."  There's text other than domains that can go into zone files.  For instance, the entry in a TXT record is free text, so you might want to put a binary character in it, represented with a \ddd string, etc.  You are also allowed to make comments, so you might use these "special encodings" in your comments.
There is support for internationalized domain names, but RFC1035 is from 1987, it wasn't talking about i18n domain names at that time.
EDIT:  I just reread it and I think I'm wrong.  The stuff above is technically about the file format.  However, this is also in the RFC in section 3.1:
```
```
Although labels can contain any 8 bit values in octets that make up a
label, it is strongly recommended that labels follow the preferred
syntax described elsewhere in this memo, which is compatible with
existing host naming conventions.  Name servers and resolvers must
compare labels in a case-insensitive manner (i.e., A=a), assuming ASCII
with zero parity.  Non-alphabetic codes must match exactly.
```
```
So, that says that any 8-bit char can be part of a label (where a label is that part of the domain name between dots).  This doc is describing the technical capability of the DNS protocol, though.  Common usage is a different thing.  In fact, in section "2.3.1. Preferred name syntax":
```
```
The following syntax will result in
fewer problems with many applications
that use domain names (e.g., mail,
TELNET).

<domain> ::= <subdomain> | " "

<subdomain> ::= <label> | <subdomain>
"." <label>

<label> ::= <letter> [ [ <ldh-str> ]
<let-dig> ]

<ldh-str> ::= <let-dig-hyp> |
<let-dig-hyp> <ldh-str>

<let-dig-hyp> ::= <let-dig> | "-"

<let-dig> ::= <letter> | <digit>

<letter> ::= any one of the 52
alphabetic characters A through Z in
upper case and a through z in lower
case

<digit> ::= any one of the ten digits
0 through 9
```
```
In other words, the DNS protocol was defined from the beginning to work with 8-bit ascii.  However, if you actually wanted your programs to be able to use the domains in the DNS, you should stick with [a-z-].
As for an example, I think this just meant you could have a DNS entry like this:
```
```
IHaveAn\020EmbeddedTab  IN A 172.24.3.1
```
```


Question:
In tcsh, I have the following script working:

#!/bin/tcsh
setenv X_ROOT /some/specified/path

setenv XDB    ${X_ROOT}/db
setenv PATH   ${X_ROOT}/bin:${PATH}

xrun -d xdb1 -i $1 > $2

What is the equivalent to the tcsh setenv function in Bash?

Is there a direct analog? The environment variables are for locating the executable.

Answer:
I think you're looking for
```
export
```
- though I could be wrong.. I've never played with tcsh before. Use the following syntax:
```
```
export VARIABLE=value
```
```


Question:
I am running GNU Emacs on Windows so entering:

M-x shell

launches the Windows command-line DOS shell. However, I would like to instead be able to run the Cygwin Bash Shell (or any other non-Windows shell) from within Emacs. How can this be easily done?

Answer:
I use XEmacs with Cygwin, and can run bash from XEmacs relatively easily.
Here's the relevant section from
```
init.el
```
```
```
;; Let's use CYGWIN bash...
;;
(setq binary-process-input t)
(setq w32-quote-process-args ?\")
(setq shell-file-name "bash") ;; or sh if you rename your bash executable to sh.
(setenv "SHELL" shell-file-name)
(setq explicit-shell-file-name shell-file-name)
(setq explicit-sh-args '("-login" "-i"))
```
```


Question:
I'd like to install Java on a Psion 5MX with GNU/Linux 16MB RAM machine, will it be possible?

Unfortunatly, "KVM must be installed by the manufacturer".

What I want is to be able to is to write basic Java code, test and sketch simple algorithms.
Important notes: I don't need the graphic part since I'll only use the console (no graphic server) but this will be inside a Debian.

Answer:
Please give us more details about the machine, besides the OS and the memory. Also give us details on what you hope to accomplish with Java on such an underpowered machine (Java has some big overhead in embedded places as compared to writing native code).
The answer is maybe. I've seen Java running on a machine with 4MB of RAM, but it was not running Linux (in fact there was no OS at all). Link:
Java on the Nintendo DS


Question: I've been getting some OutOfMemory errors lately in my application. Is it possible to detect ahead of time when the virtual machine is running low on memory? In other words to preemptively deal with OutOfMemory errors before they actually occur?

Answer:
I suggest that a better question is "Why is my application running out of memory?"
You may need to increase the memory available to the JVM at startup;
You may have a memory leak (objects that aren't getting released when they're no longer needed.)
More information on the application might also be helpful
Does it run continuously, 24x7x365?
Does it run once and exit?
Using performance monitoring/profiling tools to find the cause of the memory problem is really your best bet.


Question:
I have the following string expression in a PowerShell script:

"select count(*) cnt from ${schema}.${table} where ${col.column_name} is null"

The schema and table resolve to the values of $schema and $table, respectively. However, an empty string is supplied for ${col.column_name}. How can I dot into the member of a variable as part of a string substitution?

Answer:
How about:
```
```
"select count(*) cnt from $schema.$table where $($col.column_name) is null"
```
```


Question:
I want a Java IDE with a compiler for Linux and that does not require a a big amount of RAM.
I have 256 MB of ram, so my options are limited

Answer:
Does the 256MB of RAM also include program space, or will the code be stored elsewhere in flash or another memory type?
You can get embeddable java machines, and small java compilers for linux.  The IDE, however, is tricky as you don't merely say editor, but you want a whole integrated environment.
Since you have Java installed already, I suggest Eclipse.  It seems bulky and resource intensive on PCs, but you can cut it back significantly by removing features (classes) you don't want/need.
-Adam


Question: Is one more preferred, or performs better over the other?

Answer:
```
is_int()
```
returns true if the argument is an integer type,
```
ctype_digit()
```
takes a string argument and returns true if all the characters in the string are digits.
Example:
```
```
┌──────────┬───────────┬────────────────┐
│          │  is_int:  │  ctype_digit:  │
├──────────┼───────────┼────────────────┤
│ 123      │  true     │  false         │
├──────────┼───────────┼────────────────┤
│ 12.3     │  false    │  false         │
├──────────┼───────────┼────────────────┤
│ "123"    │  false    │  true          │
├──────────┼───────────┼────────────────┤
│ "12.3"   │  false    │  false         │
├──────────┼───────────┼────────────────┤
│ "-1"     │  false    │  false         │
├──────────┼───────────┼────────────────┤
│ -1       │  true     │  false         │
└──────────┴───────────┴────────────────┘
```
```


Question: What's the best cross-platform way to get file creation and modification dates/times, that works on both Linux and Windows?

Answer:
os.stat
In newer code you should probably use
os.path.getmtime()
(
thanks, Christian Oudard
).
But note that it returns a floating point value of
time_t
with fraction seconds (if your OS supports it).


Question:
How does the JVM handle a primitive "long", which is 64bits, on a 32bit processor?

Can it utilise mulitple cores in parallel when on a Multi-Core 32bit machine?

How much slower are 64bit operations on a 32bit machine?

Answer:
It may use multiple cores to run different threads, but it does not use them in parallel for 64 bit calculations.  A 64 bit long is basically stored as two 32 bit ints.  In order to add them, two additions are needed, keeping track of the carry bit.  Multiplication is kind of like multiplying two two-digit numbers, except each digit is in base 2^32 instead of base 10.  So on for other arithmetic operations.
Edit about speed: I can only guess about the speed difference.  An addition requires two adds instead of one, and a multiplication would (I think) require four multiplies instead of one.  However, I suspect that if everything can be kept in registers then the actual time for the computation would be dwarfed by the time required to go to memory twice for the read and twice for the write, so my guess is about twice as long for most operations.  I imagine that it would depend on the processor, the particular JVM implementation, the phase of the moon, etc.  Unless you are doing heavy number crunching, I wouldn't worry about it.  Most programs spend most of their time waiting for IO to/from the disk or network.


Question:
For my area, I get the updates from

ww.asp.net

code.google.com

www.webmasterworld.com

What others do you highly recommend?

Answer:
If you're into anything with Linux:
http://www.linux.com/feature
A List Apart
has some excellent web articles
If you want keep up with browsers,
Web Browsers News and Reviews
might help.
Finally,
PPK
, a javascript expert, often has some interesting links and blog posts.


Question:
I have an application running only on Windows and a batch file that launches it.
I want to invoke this batch file from Linux, meaning something like Linux batch will launch the windows batch with parameters and this in its turn run my application.

Can I do that? How?

Answer:
You could install an ssh server in the windows box (Cygwin has one), then from linux do something like:
```
```
ssh user@windows-box c:/path/to/batch.cmd
```
```
and that should launch your application in the windows box.


Question:
It's not quite a "programming" question, but I hope its related closely enough.

Do you know if it is possible to configure the browser in Linux (e.g. Firefox) to use Wine to create ActiveX objects? I would like to handle web pages that use:

var xmlDocument = new ActiveXObject( Msxml2.DOMDocument.4.0 )

etc. in Javascript.

Answer:
ActiveXObject is part of the Windows Script host, and not available in Linux unless you can use Wine to install it.
As a side issue, the actual ActiveXObject is an instance of a windows application, and not generally available in Linux (especially not the MS Office suite).
Links:
Windows Scripting Host
Wine
Edit: Had Wine confused with Mono. Fixed now.


Question:
I have sets of 5, 6 and 7 digit numbers. I need them to be displayed in the 000/000/000 format. So for example:

12345 would be displayed as 000/012/345

and

9876543 would be displayed as 009/876/543

I know how to do this in a messy way, involving a series of if/else statements, and strlen functions, but there has to be a cleaner way involving regex that Im not seeing.

Answer:
sprintf and modulo is one option
```
```
function formatMyNumber($num)
{
    return sprintf('%03d/%03d/%03d',
                   $num / 1000000,
                  ($num / 1000) % 1000,
                   $num % 1000);
}
```
```


Question:
During execution, how can a java program tell how much memory it is using?

I don't care how efficient it is!

Answer:
If you are have a java1.6 somewhere and your program is running in java 1.4.2, 1.5 or 1.6, you can launch a
visualVM session
, connect to your application, and follow the memory (and much more)
(The images are not displayed at the moment, so please refers to
Monitoring an application
for an illustration.)


Question:
My Program overrides public void paint(Graphics g, int x, int y); in order to draw some stings using g.drawString(someString, x+10, y+30);

Now someString can be quite long and thus, it may not fit on one line.

What is the best way to write the text on multiple line.
 For instance, in a rectangle (x1, y1, x2, y2)?

Answer:
java.awt.font.TextLayout
might be helpful. Here's a snippet of their example code:
```
```
Graphics2D g = ...;
   Point2D loc = ...;
   Font font = Font.getFont("Helvetica-bold-italic");
   FontRenderContext frc = g.getFontRenderContext();
   TextLayout layout = new TextLayout("This is a string", font, frc);
   layout.draw(g, (float)loc.getX(), (float)loc.getY());

   Rectangle2D bounds = layout.getBounds();
   bounds.setRect(bounds.getX()+loc.getX(),
                  bounds.getY()+loc.getY(),
                  bounds.getWidth(),
                  bounds.getHeight());
   g.draw(bounds);
```
```
Otherwise you could always use a Swing text element to do the job for you, just pass in the Graphics you want it to paint into.


Question:
I have to generate  two random sets of matrices
Each containing   3 digit numbers   ranging from 2 - 10

like that

matrix 1:  994,878,129,121

matrix 2:  272,794,378,212

the numbers in both matrices have to be  greater then 100 and  less then  999

BUT

the  mean for both matrices has to be in the ratio  of  1:2  or 2:3  what ever constraint the user inputs

my math skills are kind  of limited so any ideas how do i make this happen?

Answer:
In order to do this, you have to know how many numbers are in each list.  I'm assuming from your example that there are four numbers in each.
Fill the first list with four random numbers.
Calculate the mean of the first list.
Multiply the mean by 2 or by 3/2, whichever the user input.  This is the required mean of the second list.
Multiply by 4.  This is the required total of the second list.
Generate 3 random numbers.
Subtract the total of the three numbers in step 5 from the total in step 4.  This is the fourth number for the second list.
If the number in step 6 is not in the correct range, start over from step 5.
Note that the last number in the second list is not truly random, since it's based on the other values in the list.


Question: Basically I need to run the script with paths related to the shell script file location, how can I change the current directory to the same directory as where the script file resides?

Answer:
In Bash, you should get what you need like this:
```
```
#!/usr/bin/env bash

BASEDIR=$(dirname "$0")
echo "$BASEDIR"
```
```


Question:
I wanna see if there is an approach to pack a few plugins together as a meta plugin that install everything together automatically, works like a project template.

Why not a script? Because I want to put it in github so I don't have to worry about it when I am not with my own PC :) but of coz a script based solution is welcomed too.

Answer:
My solution (ruby script):
```
```
plugins = %w{
  http://url_to_plugin_1
  http://url_to_plugin_2
  http://url_to_plugin_3
  http://url_to_plugin_4
  http://url_to_plugin_5
}
plugins.each do | p |
  `ruby script/plugin install -x #{p}`
end
```
```
run from project root directory


Question: How can I use vimdiff to view the differences described in a diff file?

Answer:
Make a copy of the original file, apply the diff and then
```
```
vimdiff original_file patched_file
```
```
You could also look at
vim.org scripts
which have been written to deal with svn diff output. If you are generating your diff from a version control system then take a look at the
vcscommand.vim : CVS/SVN/SVK/git integration plugin
.


Question: For a load test of my application (under Linux), I'm looking for a tool that outputs data on stdout at a specific rate (like 100 bytes/s), so that I can pipe the output to netcat which sends it to my application. Some option for dd would be ideal, but I didn't find anything so far. It doesn't really matter what kind of data is printed (NUL bytes are OK). Any hints?

Answer:
If you're fine with getting all hundred bytes at a time, you could do a loop with
```
sleep
```
and plain old
```
echo
```
in the shell as a first attempt at least.


Question:
What is your favorite bug/issue tracking system? And why?

(Please answer this question only if you have used at least three different bug tracking systems for quite a long time. And please mention these systems as well.)

Answer:
Bugzilla
is not too bad.
Bugzilla is very adaptable to various situations. Known uses
currently include IT support queues, systems administration
deployment management, chip design and development problem
tracking (both pre-and-post fabrication), and software and
hardware bug tracking for luminaries such as Red Hat, NASA,
Linux-Mandrake, and VA Systems. Combined with systems such
as
CVS
, Bonsai, or
Perforce
SCM, Bugzilla provides a
powerful, easy-to-use solution to configuration management
and replication problems.
Bugzilla can dramatically increase the productivity and
accountability of individual employees by providing a
documented workflow and positive feedback for good
performance. How many times do you wake up in the morning,
remembering that you were supposed to do something today,
but you just can't quite remember? Put it in Bugzilla, and
you have a record of it from which you can extrapolate
milestones, predict product versions for integration, and
follow the discussion trail that led to critical decisions.
Ultimately, Bugzilla puts the power in your hands to improve
your value to your employer or business while providing a
usable framework for your natural attention to detail and
knowledge store to flourish.


Question:
We are currently having two UI design for internet and intranet the underlying reason being is that they both serve different purpose so they have different UI design.

But however users want to have a more synchronized look and feel between internet and intranet.

What are the reasons you all can think of in have different user interface/outlook for internet and intranet?

Answer:
There may be
more information
available on intranet.  Also the tone of the message might be targeted differently but you'd want to ask marketer about that. There might be less of a "sell" to the intranet.
Often
authentication
would be different and even integrated with domain.
Big difference for intranet is that often you don't need to design to the
lowest common denomitor
, i.e. what works across many browsers.  You might even be able to presume other things about the user's environment you would never be able to on the internet, therefore being able to develop against a
known target
.  Example, you might be able to assume every user runs linux, FF 3 and has flash or alternatively windows vista, IE8 and silverlight.


Question:
Emacs does not recognize my correct Python path. I think it is a general problem with Emacs not recognizing my environment variables. I have GNU Emacs 22.1.1 (i386-apple-darwin8.9.1, Carbon Version 1.6.0) of 2007-06-17 installed.

I have set PYTHONPATH in my ~/.bashrc. Maybe I should set it somewhere else?

Answer:
```
.bashrc
```
only gets read when a shell starts; it won't affect Carbon Emacs. Instead, use
```
setenv
```
in your
```
.emacs
```
:
```
```
(setenv "PYTHONPATH" "PATH_STRING_HERE")
```
```
You can set
```
PYTHONPATH
```
for the entire Mac OS session, by adding it to
```
~/.MacOSX/environment.plist
```
(more
here
). You probably don't want to do this unless you have XCode (and its property list editor) installed.
(
Via Procrastiblog
)


Question: How can I create EPS files in C#?  Are there any opensource libraries available or do I have to resort to the spec and do it by hand?

Answer:
```
.bashrc
```
only gets read when a shell starts; it won't affect Carbon Emacs. Instead, use
```
setenv
```
in your
```
.emacs
```
:
```
```
(setenv "PYTHONPATH" "PATH_STRING_HERE")
```
```
You can set
```
PYTHONPATH
```
for the entire Mac OS session, by adding it to
```
~/.MacOSX/environment.plist
```
(more
here
). You probably don't want to do this unless you have XCode (and its property list editor) installed.
(
Via Procrastiblog
)


Question: I've got an RSA private key in PEM format, is there a straight forward way to read that from .NET and instantiate an RSACryptoServiceProvider to decrypt data encrypted with the corresponding public key?

Answer:
You might take a look at
JavaScience's
source for
OpenSSLKey
There's code in there that does exactly what you want to do.
In fact, they have a lot of crypto source code
available here
.
Source code snippet:
```
```
//------- Parses binary ans.1 RSA private key; returns RSACryptoServiceProvider  ---
public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
        byte[] MODULUS, E, D, P, Q, DP, DQ, IQ ;

        // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
        MemoryStream  mem = new MemoryStream(privkey) ;
        BinaryReader binr = new BinaryReader(mem) ;    //wrap Memory Stream with BinaryReader for easy reading
        byte bt = 0;
        ushort twobytes = 0;
        int elems = 0;
        try {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                        binr.ReadByte();        //advance 1 byte
                else if (twobytes == 0x8230)
                        binr.ReadInt16();       //advance 2 bytes
                else
                        return null;

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102) //version number
                        return null;
                bt = binr.ReadByte();
                if (bt !=0x00)
                        return null;

                //------  all private key components are Integer sequences ----
                elems = GetIntegerSize(binr);
                MODULUS = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                E = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                D = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                P = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                Q = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                DP = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                DQ = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                IQ = binr.ReadBytes(elems) ;

                Console.WriteLine("showing components ..");
                if (verbose) {
                        showBytes("\nModulus", MODULUS) ;
                        showBytes("\nExponent", E);
                        showBytes("\nD", D);
                        showBytes("\nP", P);
                        showBytes("\nQ", Q);
                        showBytes("\nDP", DP);
                        showBytes("\nDQ", DQ);
                        showBytes("\nIQ", IQ);
                }

                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSAParameters RSAparams = new RSAParameters();
                RSAparams.Modulus =MODULUS;
                RSAparams.Exponent = E;
                RSAparams.D = D;
                RSAparams.P = P;
                RSAparams.Q = Q;
                RSAparams.DP = DP;
                RSAparams.DQ = DQ;
                RSAparams.InverseQ = IQ;
                RSA.ImportParameters(RSAparams);
                return RSA;
        }
        catch (Exception) {
                return null;
        }
        finally {
                binr.Close();
        }
}
```
```


Question:
Is there a way to get the Unicode Block of a character in python? The unicodedata module doesn't seem to have what I need, and I couldn't find an external library for it.

Basically, I need the same functionality as Character.UnicodeBlock.of() in java.

Answer:
I couldn't find one either.  Strange!
Luckily, the number of Unicode blocks is quite manageably small.
This implementation accepts a one-character Unicode string, just like the functions in
```
unicodedata
```
.  If your inputs are mostly ASCII, this linear search might even be faster than binary search using
```
bisect
```
or whatever.  If I were submitting this for inclusion in the Python standard library, I'd probably write it as a binary search through an array of statically-initialized
```
struct
```
s in C.
```
```
def block(ch):
  '''
  Return the Unicode block name for ch, or None if ch has no block.

  >>> block(u'a')
  'Basic Latin'
  >>> block(unichr(0x0b80))
  'Tamil'
  >>> block(unichr(0xe0080))

  '''

  assert isinstance(ch, unicode) and len(ch) == 1, repr(ch)
  cp = ord(ch)
  for start, end, name in _blocks:
    if start <= cp <= end:
      return name

def _initBlocks(text):
  global _blocks
  _blocks = []
  import re
  pattern = re.compile(r'([0-9A-F]+)\.\.([0-9A-F]+);\ (\S.*\S)')
  for line in text.splitlines():
    m = pattern.match(line)
    if m:
      start, end, name = m.groups()
      _blocks.append((int(start, 16), int(end, 16), name))

# retrieved from http://unicode.org/Public/UNIDATA/Blocks.txt
_initBlocks('''
# Blocks-12.0.0.txt
# Date: 2018-07-30, 19:40:00 GMT [KW]
# © 2018 Unicode®, Inc.
# For terms of use, see http://www.unicode.org/terms_of_use.html
#
# Unicode Character Database
# For documentation, see http://www.unicode.org/reports/tr44/
#
# Format:
# Start Code..End Code; Block Name

# ================================================

# Note:   When comparing block names, casing, whitespace, hyphens,
#         and underbars are ignored.
#         For example, "Latin Extended-A" and "latin extended a" are equivalent.
#         For more information on the comparison of property values,
#            see UAX #44: http://www.unicode.org/reports/tr44/
#
#  All block ranges start with a value where (cp MOD 16) = 0,
#  and end with a value where (cp MOD 16) = 15. In other words,
#  the last hexadecimal digit of the start of range is ...0
#  and the last hexadecimal digit of the end of range is ...F.
#  This constraint on block ranges guarantees that allocations
#  are done in terms of whole columns, and that code chart display
#  never involves splitting columns in the charts.
#
#  All code points not explicitly listed for Block
#  have the value No_Block.

# Property: Block
#
# @missing: 0000..10FFFF; No_Block

0000..007F; Basic Latin
0080..00FF; Latin-1 Supplement
0100..017F; Latin Extended-A
0180..024F; Latin Extended-B
0250..02AF; IPA Extensions
02B0..02FF; Spacing Modifier Letters
0300..036F; Combining Diacritical Marks
0370..03FF; Greek and Coptic
0400..04FF; Cyrillic
0500..052F; Cyrillic Supplement
0530..058F; Armenian
0590..05FF; Hebrew
0600..06FF; Arabic
0700..074F; Syriac
0750..077F; Arabic Supplement
0780..07BF; Thaana
07C0..07FF; NKo
0800..083F; Samaritan
0840..085F; Mandaic
0860..086F; Syriac Supplement
08A0..08FF; Arabic Extended-A
0900..097F; Devanagari
0980..09FF; Bengali
0A00..0A7F; Gurmukhi
0A80..0AFF; Gujarati
0B00..0B7F; Oriya
0B80..0BFF; Tamil
0C00..0C7F; Telugu
0C80..0CFF; Kannada
0D00..0D7F; Malayalam
0D80..0DFF; Sinhala
0E00..0E7F; Thai
0E80..0EFF; Lao
0F00..0FFF; Tibetan
1000..109F; Myanmar
10A0..10FF; Georgian
1100..11FF; Hangul Jamo
1200..137F; Ethiopic
1380..139F; Ethiopic Supplement
13A0..13FF; Cherokee
1400..167F; Unified Canadian Aboriginal Syllabics
1680..169F; Ogham
16A0..16FF; Runic
1700..171F; Tagalog
1720..173F; Hanunoo
1740..175F; Buhid
1760..177F; Tagbanwa
1780..17FF; Khmer
1800..18AF; Mongolian
18B0..18FF; Unified Canadian Aboriginal Syllabics Extended
1900..194F; Limbu
1950..197F; Tai Le
1980..19DF; New Tai Lue
19E0..19FF; Khmer Symbols
1A00..1A1F; Buginese
1A20..1AAF; Tai Tham
1AB0..1AFF; Combining Diacritical Marks Extended
1B00..1B7F; Balinese
1B80..1BBF; Sundanese
1BC0..1BFF; Batak
1C00..1C4F; Lepcha
1C50..1C7F; Ol Chiki
1C80..1C8F; Cyrillic Extended-C
1C90..1CBF; Georgian Extended
1CC0..1CCF; Sundanese Supplement
1CD0..1CFF; Vedic Extensions
1D00..1D7F; Phonetic Extensions
1D80..1DBF; Phonetic Extensions Supplement
1DC0..1DFF; Combining Diacritical Marks Supplement
1E00..1EFF; Latin Extended Additional
1F00..1FFF; Greek Extended
2000..206F; General Punctuation
2070..209F; Superscripts and Subscripts
20A0..20CF; Currency Symbols
20D0..20FF; Combining Diacritical Marks for Symbols
2100..214F; Letterlike Symbols
2150..218F; Number Forms
2190..21FF; Arrows
2200..22FF; Mathematical Operators
2300..23FF; Miscellaneous Technical
2400..243F; Control Pictures
2440..245F; Optical Character Recognition
2460..24FF; Enclosed Alphanumerics
2500..257F; Box Drawing
2580..259F; Block Elements
25A0..25FF; Geometric Shapes
2600..26FF; Miscellaneous Symbols
2700..27BF; Dingbats
27C0..27EF; Miscellaneous Mathematical Symbols-A
27F0..27FF; Supplemental Arrows-A
2800..28FF; Braille Patterns
2900..297F; Supplemental Arrows-B
2980..29FF; Miscellaneous Mathematical Symbols-B
2A00..2AFF; Supplemental Mathematical Operators
2B00..2BFF; Miscellaneous Symbols and Arrows
2C00..2C5F; Glagolitic
2C60..2C7F; Latin Extended-C
2C80..2CFF; Coptic
2D00..2D2F; Georgian Supplement
2D30..2D7F; Tifinagh
2D80..2DDF; Ethiopic Extended
2DE0..2DFF; Cyrillic Extended-A
2E00..2E7F; Supplemental Punctuation
2E80..2EFF; CJK Radicals Supplement
2F00..2FDF; Kangxi Radicals
2FF0..2FFF; Ideographic Description Characters
3000..303F; CJK Symbols and Punctuation
3040..309F; Hiragana
30A0..30FF; Katakana
3100..312F; Bopomofo
3130..318F; Hangul Compatibility Jamo
3190..319F; Kanbun
31A0..31BF; Bopomofo Extended
31C0..31EF; CJK Strokes
31F0..31FF; Katakana Phonetic Extensions
3200..32FF; Enclosed CJK Letters and Months
3300..33FF; CJK Compatibility
3400..4DBF; CJK Unified Ideographs Extension A
4DC0..4DFF; Yijing Hexagram Symbols
4E00..9FFF; CJK Unified Ideographs
A000..A48F; Yi Syllables
A490..A4CF; Yi Radicals
A4D0..A4FF; Lisu
A500..A63F; Vai
A640..A69F; Cyrillic Extended-B
A6A0..A6FF; Bamum
A700..A71F; Modifier Tone Letters
A720..A7FF; Latin Extended-D
A800..A82F; Syloti Nagri
A830..A83F; Common Indic Number Forms
A840..A87F; Phags-pa
A880..A8DF; Saurashtra
A8E0..A8FF; Devanagari Extended
A900..A92F; Kayah Li
A930..A95F; Rejang
A960..A97F; Hangul Jamo Extended-A
A980..A9DF; Javanese
A9E0..A9FF; Myanmar Extended-B
AA00..AA5F; Cham
AA60..AA7F; Myanmar Extended-A
AA80..AADF; Tai Viet
AAE0..AAFF; Meetei Mayek Extensions
AB00..AB2F; Ethiopic Extended-A
AB30..AB6F; Latin Extended-E
AB70..ABBF; Cherokee Supplement
ABC0..ABFF; Meetei Mayek
AC00..D7AF; Hangul Syllables
D7B0..D7FF; Hangul Jamo Extended-B
D800..DB7F; High Surrogates
DB80..DBFF; High Private Use Surrogates
DC00..DFFF; Low Surrogates
E000..F8FF; Private Use Area
F900..FAFF; CJK Compatibility Ideographs
FB00..FB4F; Alphabetic Presentation Forms
FB50..FDFF; Arabic Presentation Forms-A
FE00..FE0F; Variation Selectors
FE10..FE1F; Vertical Forms
FE20..FE2F; Combining Half Marks
FE30..FE4F; CJK Compatibility Forms
FE50..FE6F; Small Form Variants
FE70..FEFF; Arabic Presentation Forms-B
FF00..FFEF; Halfwidth and Fullwidth Forms
FFF0..FFFF; Specials
10000..1007F; Linear B Syllabary
10080..100FF; Linear B Ideograms
10100..1013F; Aegean Numbers
10140..1018F; Ancient Greek Numbers
10190..101CF; Ancient Symbols
101D0..101FF; Phaistos Disc
10280..1029F; Lycian
102A0..102DF; Carian
102E0..102FF; Coptic Epact Numbers
10300..1032F; Old Italic
10330..1034F; Gothic
10350..1037F; Old Permic
10380..1039F; Ugaritic
103A0..103DF; Old Persian
10400..1044F; Deseret
10450..1047F; Shavian
10480..104AF; Osmanya
104B0..104FF; Osage
10500..1052F; Elbasan
10530..1056F; Caucasian Albanian
10600..1077F; Linear A
10800..1083F; Cypriot Syllabary
10840..1085F; Imperial Aramaic
10860..1087F; Palmyrene
10880..108AF; Nabataean
108E0..108FF; Hatran
10900..1091F; Phoenician
10920..1093F; Lydian
10980..1099F; Meroitic Hieroglyphs
109A0..109FF; Meroitic Cursive
10A00..10A5F; Kharoshthi
10A60..10A7F; Old South Arabian
10A80..10A9F; Old North Arabian
10AC0..10AFF; Manichaean
10B00..10B3F; Avestan
10B40..10B5F; Inscriptional Parthian
10B60..10B7F; Inscriptional Pahlavi
10B80..10BAF; Psalter Pahlavi
10C00..10C4F; Old Turkic
10C80..10CFF; Old Hungarian
10D00..10D3F; Hanifi Rohingya
10E60..10E7F; Rumi Numeral Symbols
10F00..10F2F; Old Sogdian
10F30..10F6F; Sogdian
10FE0..10FFF; Elymaic
11000..1107F; Brahmi
11080..110CF; Kaithi
110D0..110FF; Sora Sompeng
11100..1114F; Chakma
11150..1117F; Mahajani
11180..111DF; Sharada
111E0..111FF; Sinhala Archaic Numbers
11200..1124F; Khojki
11280..112AF; Multani
112B0..112FF; Khudawadi
11300..1137F; Grantha
11400..1147F; Newa
11480..114DF; Tirhuta
11580..115FF; Siddham
11600..1165F; Modi
11660..1167F; Mongolian Supplement
11680..116CF; Takri
11700..1173F; Ahom
11800..1184F; Dogra
118A0..118FF; Warang Citi
119A0..119FF; Nandinagari
11A00..11A4F; Zanabazar Square
11A50..11AAF; Soyombo
11AC0..11AFF; Pau Cin Hau
11C00..11C6F; Bhaiksuki
11C70..11CBF; Marchen
11D00..11D5F; Masaram Gondi
11D60..11DAF; Gunjala Gondi
11EE0..11EFF; Makasar
11FC0..11FFF; Tamil Supplement
12000..123FF; Cuneiform
12400..1247F; Cuneiform Numbers and Punctuation
12480..1254F; Early Dynastic Cuneiform
13000..1342F; Egyptian Hieroglyphs
13430..1343F; Egyptian Hieroglyph Format Controls
14400..1467F; Anatolian Hieroglyphs
16800..16A3F; Bamum Supplement
16A40..16A6F; Mro
16AD0..16AFF; Bassa Vah
16B00..16B8F; Pahawh Hmong
16E40..16E9F; Medefaidrin
16F00..16F9F; Miao
16FE0..16FFF; Ideographic Symbols and Punctuation
17000..187FF; Tangut
18800..18AFF; Tangut Components
1B000..1B0FF; Kana Supplement
1B100..1B12F; Kana Extended-A
1B130..1B16F; Small Kana Extension
1B170..1B2FF; Nushu
1BC00..1BC9F; Duployan
1BCA0..1BCAF; Shorthand Format Controls
1D000..1D0FF; Byzantine Musical Symbols
1D100..1D1FF; Musical Symbols
1D200..1D24F; Ancient Greek Musical Notation
1D2E0..1D2FF; Mayan Numerals
1D300..1D35F; Tai Xuan Jing Symbols
1D360..1D37F; Counting Rod Numerals
1D400..1D7FF; Mathematical Alphanumeric Symbols
1D800..1DAAF; Sutton SignWriting
1E000..1E02F; Glagolitic Supplement
1E100..1E14F; Nyiakeng Puachue Hmong
1E2C0..1E2FF; Wancho
1E800..1E8DF; Mende Kikakui
1E900..1E95F; Adlam
1EC70..1ECBF; Indic Siyaq Numbers
1ED00..1ED4F; Ottoman Siyaq Numbers
1EE00..1EEFF; Arabic Mathematical Alphabetic Symbols
1F000..1F02F; Mahjong Tiles
1F030..1F09F; Domino Tiles
1F0A0..1F0FF; Playing Cards
1F100..1F1FF; Enclosed Alphanumeric Supplement
1F200..1F2FF; Enclosed Ideographic Supplement
1F300..1F5FF; Miscellaneous Symbols and Pictographs
1F600..1F64F; Emoticons
1F650..1F67F; Ornamental Dingbats
1F680..1F6FF; Transport and Map Symbols
1F700..1F77F; Alchemical Symbols
1F780..1F7FF; Geometric Shapes Extended
1F800..1F8FF; Supplemental Arrows-C
1F900..1F9FF; Supplemental Symbols and Pictographs
1FA00..1FA6F; Chess Symbols
1FA70..1FAFF; Symbols and Pictographs Extended-A
20000..2A6DF; CJK Unified Ideographs Extension B
2A700..2B73F; CJK Unified Ideographs Extension C
2B740..2B81F; CJK Unified Ideographs Extension D
2B820..2CEAF; CJK Unified Ideographs Extension E
2CEB0..2EBEF; CJK Unified Ideographs Extension F
2F800..2FA1F; CJK Compatibility Ideographs Supplement
E0000..E007F; Tags
E0100..E01EF; Variation Selectors Supplement
F0000..FFFFF; Supplementary Private Use Area-A
100000..10FFFF; Supplementary Private Use Area-B

# EOF
''')
```
```


Question: I'm in the process of adding CAPTCHA validation to one of my websites and need to know what open source solutions exist.  Please note strengths and weaknesses and what platform they work with.  I'm primarily interested in ASP.NET solutions but feel free to include PHP, Java, etc.

Answer:
ReCAPTCHA
is the same one StackOverflow uses. It has an
ASP.NET implementation
.
It uses a webservice to provide the captcha images; this is an university trying to digitize difficult to OCR texts. I'm not sure how easy it would be to replace this portion. There are many
open source client implementations
, as the API is
quite well documented
.


Question:
So far I've found the following components for building ASP.NET MVC views:

Yahoo UI (YUI)

Ext JS

Flexgrid (grid only)

What are the other options that are currently available which inlcude a nice grid component?

Answer:
JQuery
JQuery Pugins
There are some grid plugins, which I have not used:
FlexGrid
JQuery Grid plugin
Another JQuery Grid plugin


Question:
I want to setup a CRON that runs a PHP script that in turn moves XML file (holding non-sensitive information) from one server to another.

I have been given the proper username/password, and want to use SFTP protocol. The jobs will run daily. There is the potential that one server is Linux and the other is Windows.  Both are on different networks.

What is the best way to move that file?

Answer:
Why not use
shell_exec
and
scp
?
```
```
<?php
    $output = shell_exec('scp file1.txt dvader@deathstar.com:somedir');
    echo "<pre>$output</pre>";
?>
```
```


Question:
I'd like to create a table which has an integer primary key limited between 000 and 999. Is there any way to enforce this 3 digit limit within the sql?

I'm using sqlite3.
Thanks.

Answer:
You may be able to do so using a CHECK constraint.
But,
CHECK constraints are supported as of version 3.3.0. Prior to version 3.3.0, CHECK constraints were parsed but not enforced.
(from
here
)
So unless SQLite 3 = SQLite 3.3 this probably won't work