q:
I have a web system which has a classical parent-children menu saved in a database, with fields id as the PK, and parent_id to pointing to the owning menu. (Yes, I know this doesn't scale very well, but that's another topic).

So for these records (id-parent_id pairs):

0-7 0-4 4-9 4-14 4-16 9-6

I have this tree:

0
├ 7
└ 4
  ├ 9
  | └ 6
  ├ 14
  └ 16

I'm needing to hide a top node, so I have to make a list of all the childrens of that certain node, i.e. for 4, they will be (9, 6, 14, 16). Order doesn't matters.

I'm confused... does this fits into the classical tree problems? or is it a graph one?

How can I compose this structure and solve this problem using php?

[A]
This is the perfect chance to use recursion!
Pseudo-code:
```
```
nodeList = {}
enumerateNodes(rootNode, nodeList);

function enumerateNodes(node, nodeList) {
   nodeList += node;
   foreach ( childnode in node.children ) {
       enumerateNodes(childnode, nodeList);
   }
}
```
```
Edit: Didn't notice that your tree is in the adjacent list format. I would probably just build that into an actual tree datastructure before I started working with it. Just loop through all pairs (creating nodes the first time you see them) and linking them. I
think
it should be easy...


q: Why does Leopard mangle some symbols with $non_lazy_ptr?  More importantly what is the best method to fix undefined symbol errors because a symbol has been mangled with $non_lazy_ptr?

[A]
From:
Developer Connection - Indirect Addressing
Indirect addressing is the name of the code generation technique that allows symbols defined in one file to be referenced from another file, without requiring the referencing file to have explicit knowledge of the layout of the file that defines the symbol. Therefore, the defining file can be modified independently of the referencing file. Indirect addressing minimizes the number of locations that must be modified by the dynamic linker, which facilitates code sharing and improves performance.
When a file uses data that is defined in another file, it creates symbol references. A symbol reference identifies the file from which a symbol is imported and the referenced symbol. There are two types of symbol references: nonlazy and lazy.
Nonlazy symbol references are resolved (bound to their definitions) by the dynamic linker when a module is loaded.
A nonlazy symbol reference is essentially a symbol pointer—a pointer-sized piece of data. The compiler generates nonlazy symbol references for data symbols or function addresses.
Lazy symbol references are resolved by the dynamic linker the first time they are used (not at load time). Subsequent calls to the referenced symbol jump directly to the symbol’s definition.
Lazy symbol references are made up of a symbol pointer and a symbol stub, a small amount of code that directly dereferences and jumps through the symbol pointer. The compiler generates lazy symbol references when it encounters a call to a function defined in another file.

s: huggingface

c: devops

d: intermediate


q:
I read the Git manual, FAQ, Git - SVN crash course, etc. and they all explain this and that, but nowhere can you find a simple instruction like:

SVN repository in: svn://myserver/path/to/svn/repos

Git repository in: git://myserver/path/to/git/repos

git-do-the-magic-svn-import-with-history \
svn://myserver/path/to/svn/repos \
git://myserver/path/to/git/repos

I don't expect it to be that simple, and I don't expect it to be a single command. But I do expect it not to try to explain anything - just to say what steps to take given this example.

[A]
Magic:
```
```
$ git svn clone http://svn/repo/here/trunk
```
```
Git and SVN operate very differently.  You need to learn Git, and if you want to track changes from SVN upstream, you need to learn
```
git-svn
```
.  The
```
git-svn
```
main page has a good examples section
:
```
```
$ git svn --help
```
```


q:
For example, if I have a page located in Views/Home/Index.aspx and a JavaScript file located in Views/Home/Index.js, how do you reference this on the aspx page?

The example below doesn't work even though the compiler says the path is correct

<script src="Index.js" type="text/javascript"></script>

The exact same issue has been posted here in more detail:
http://forums.asp.net/p/1319380/2619991.aspx

If this is not currently possible, will it be in the future? If not, how is everyone managing their javascript resources for large Asp.net MVC projects? Do you just create a folder structure in the Content folder that mirrors your View folder structure? YUCK!

[A]
You can use the VirtualPathUtility.ToAbsolute method like below to convert the app relative url of the .js file to an absolute one that can be written to the page:
```
```
<script type="text/javascript" src="<%=VirtualPathUtility.ToAbsolute("~/Views/Home/Index.js") %>"></script>
```
```


q: In your experience, how often should Oracle database statistics be run? Our team of developers recently discovered that statistics hadn't been run our production box in over 2 1/2 months. That sounds like a long time to me, but I'm not a DBA.

[A]
Whenever the data changes "significantly".
If a table goes from 1 row to 200 rows, that's a significant change.  When a table goes from 100,000 rows to 150,000 rows, that's not a terribly significant change.  When a table goes from 1000 rows all with identical values in commonly-queried column X to 1000 rows with nearly unique values in column X, that's a significant change.
Statistics store information about item counts and relative frequencies -- things that will let it "guess" at how many rows will match a given criteria.  When it guesses wrong, the optimizer can pick a
very
suboptimal query plan.


q: When working with tables in Oracle, how do you know when you are setting up a good index versus a bad index?

[A]
Here's a great SQL Server article:
http://www.sql-server-performance.com/tips/optimizing_indexes_general_p1.aspx
Although the mechanics won't work on Oracle, the tips are very apropos (minus the thing on clustered indexes, which don't quite work the same way in Oracle).


q:
What are the characteristics of a multitasking operating system?

What makes it multitasking?

Are there non-multitasking operating systems?

[A]
A multi tasking operating systems is:
An operating system that gives you the perception of 2 or more tasks/jobs/processes running at the same time.  It does this by dividing system resources amongst these tasks/jobs/processes.  And switching between the tasks/jobs/processes while they are executing very fast over and over again.
Yes there are non multi tasking operating systems, example: commodore 64's OS (Commodore BASIC 2.0).  Probably some custom made software for some companies.  Perhaps like an ATM machine, or movie theater stub ticket system.


q:
Can databases (MySQL in particular, any SQL--MS, Oracle, Postgres--in general) do mass updates, and figure out on their own what the new value should be? Say for example I've got a database with information about a bunch of computers, and all of these computers have drives of various sizes--anywhere from 20 to 250 GB. Then one day we upgrade every single computer by adding a 120 GB hard drive. Is there a way to say something like

update computers set total_disk_space = (whatever that row's current total_disk_space is plus 120)

[A]
Yeah:
```
```
update computers set total_disk_space = total_disk_space + 120;
```
```


q: The documentation with the module itself is pretty thin, and just tends to point to MOP.

[A]
First you should read through the
Manual
if you haven't already. Then you can go on to read the
Cookbook
.
I think the docs are actually pretty good these days, as long as you read the right ones. You
really
shouldn't bother looking at most of the docs for any class name starting with "
```
Moose::Meta
```
" unless you're interested in Moose's introspection features. I've tried to make this more obvious in the Moose.pm docs, which as of 0.57 tell you to read the
Manual
and
Cookbook
first.
If you're coming from a background of doing Perl 5 OO "the old school way", I'd also suggest taking a look at the
```
Moose::Manual::Unsweetened
```
document, which compares Moose to equivalent Perl 5 "by hand" code.


q:
I have a method that can return either a single object or a collection of objects. I want to be able to run object.collect on the result of that method whether or not it is a single object or a collection already. How can i do this?

profiles = ProfileResource.search(params)
output = profiles.collect do | profile |
    profile.to_hash
end

If profiles is a single object, I get a NoMethodError exception when I try to execute collect on that object.

[A]
```
```
profiles = [ProfileResource.search(params)].flatten
output = profiles.collect do |profile|
    profile.to_hash
end
```
```


q:
In a multitasking operating system context, sometimes you hear the term round-robin scheduling. What does it refer to?

What other kind of scheduling is there?

[A]
Round Robin Scheduling
If you are a host in a party of 100 guests, round-robin scheduling would mean that you spend 1 minute (a fixed amount) per guest. You go through each guest one-by-one, and after 100 minutes, you would have spent 1 minute with each guest. More on
Wikipedia
.
There are many other types of scheduling, such as priority-based (i.e. most important people first), first-come-first-serve, earliest-deadline-first (i.e. person leaving earliest first), etc. You can start off by googling for scheduling algorithms or check out
scheduling at Wikipedia


q:
What, at a minimum, should an application health-monitoring system do for you (the developer) and/or your boss (the IT Manager) and/or the operations (on-call) staff?

What else should it do above the minimum requirements?

Is monitoring the 'infrastructure' applications (ms-exchange, apache, etc.) sufficient or do individual user applications, web sites, and databases also need to be monitored?

if the latter, what do you need to know about them?

ADDENDUM: thanks for the input, i was really looking for application-level monitoring not infrastructure monitoring, but it is good to know about both

[A]
Minimum: make sure it is running :)
However, some other stuff would be very useful. For example, the CPU load, RAM usage and (in multiuser systems) which user is running what. Also, for applications that access network, a list of network connections for each app. And (if you have access to client computer(s)) it would be cool to be able to see the 'window title' of the app - maybe check each 2-3 minutes  if it changed and save it. Also, a list of files open by the application could be very useful, but it is not a must.


q:
I'd like to write a simple C# application to monitor the line-in audio and give me the current (well, the rolling average) beats per minute.

I've seen this gamedev article, and that was absolutely no help. I went through and tried to implement what he was doing but it just wasn't working.

I know there have to be tons of solutions for this, because lots of DJ software does it, but I'm not having any luck in finding any open-source library or instructions on doing it myself.

[A]
This is by no means an easy problem. I'll try to give you an overview only.
What you could do is something like the following:
Compute the average (root-mean-square) loudness of the signal over blocks of, say, 5 milliseconds. (Having never done this before, I don't know what a good block size would be.)
Take the Fourier transform of the "blocked" signal, using the FFT algorithm.
Find the component in the transformed signal that has the largest magnitude.
A Fourier transform is basically a way of computing the strength of all frequencies present in the signal. If you do that over the "blocked" signal, the frequency of the beat will hopefully be the strongest one.
Maybe you need to apply a filter first, to focus on specific frequencies (like the bass) that usually contain the most information about the BPM.


q:
I have a div with two images and an h1. All of them need to be vertically aligned within the div, next to each other. One of the images needs to be absolute positioned within the div.

What is the CSS needed for this to work on all common browsers?

<div id="header">
  <img src=".." ></img>
  <h1>testing...</h1>
  <img src="..."></img>
</div>

[A]
```
```
<div id="header" style="display: table-cell; vertical-align:middle;">
```
```
...
or CSS
```
```
.someClass
{
   display: table-cell;
   vertical-align:middle;
}
```
```
Browser Coverage


q:
(sorry I should have been clearer with the code the first time I posted this. Hope this makes sense)

File "size_specification.rb"

class SizeSpecification
  def fits?
  end
end

File "some_module.rb"

require 'size_specification'

module SomeModule
  def self.sizes
    YAML.load_file(File.dirname(__FILE__) + '/size_specification_data.yml')
  end
end

File "size_specification_data.yml

---
- !ruby/object:SizeSpecification
  height: 250
  width: 300

Then when I call

SomeModule.sizes.first.fits?

I get an exception because "sizes" are Object's not SizeSpecification's so they don't have a "fits" function.

[A]
On second reading I'm a little confused, you seem to want to mix the class into module, which is porbably not so advisable.  Also is the YAML supposed to load an array of the SizeSpecifications?
It appears to be that you're not mixing the Module into your class.  If I run the test in irb then the require throws a LoadError. So I assume you've put two files together, if not dump it.
Normally you'd write the functionality in the module, then mix that into the class.  so you may modify your code like this:
```
```
class SizeSpecification
  include SomeModule
  def fits?
  end
end
```
```
Which will allow you to then say:
```
```
SizeSpecification::SomeModule.sizes
```
```
I think you should also be able to say:
```
```
SizeSpecification.sizes
```
```
However that requires you to take the self off the prefix of the sizes method definition.
Does that help?


q: What is the best method to transfer data from sales table to sales history table in sql server 2005. sales history table will be used for reporting.

[A]
Bulkcopy is fast and it will not use the transaction log. One batch run at the end of the day.
Deleting the copied records from your production server is a different situation that needs to be planed on that server's maintenance approach/plans. Your reporting server solution should not interfere with or affect the production server.
Keep in mind that your reporting server is not meant to be a backup of the data but rather a copy made exclusively for reporting purposes.
Also check on the server settings of your reporting server to be on
Simple recovery model
.


q: I've set up Passenger in development (Mac OS X) and it works flawlessly. The only problem came later: now I have a custom GEM_HOME path and ImageMagick binaries installed in "/usr/local". I can put them in one of the shell rc files that get sourced and this solves the environment variables for processes spawned from the console; but what about Passenger? The same application cannot find my gems when run this way.

[A]
I've run into this issue as well.  It
appears
that Passenger doesn't passthrough values set using the
```
SetEnv
```
apache directive - which is unfortunate.
Perhaps it might be possible to set environment variables in your environment.rb or boot.rb (assuming you're talking about a Rails app; I'm not familiar with Rack but presumably it has similar functionality)


q:
I'm trying to replace some bespoke message queues with ActiveMQ, and I need to talk to them (a lot) from Perl.  ActiveMQ provides a Stomp interface and Perl has Net::Stomp, so this seems like it should be fine, but it's not.

Even if I send a BEGIN command over Stomp, messages sent with SEND are immediately published, and if I ABORT the transaction, nothing happens.

I can't find any clear answers suggesting that suggest it's not possible, that is is possible, or that there's a relevant bit of configuration.  Also, Stomp doesn't seem to be a great protocol for checking for error responses from the server.

Am I out of luck?

[A]
BTW the best place to ask Perl/ActiveMQ/Stomp questions is the
ActiveMQ user forum
as lots of Perl-Stomp folks hang out there.
The trick with STOMP transactions is to make sure each message you send or each acknowledgement you make includes the transaction ID header. See the
transaction handling section of the STOMP protocol
.
The reason for this is that with STOMP you could have many transactions taking place at the same time if your client is multi threaded - along with some non-transacted operations.


q: I want to use Apple's or RedHat's built-in Apache but I want to use Perl 5.10 and mod_perl.  What's the least intrusive way to accomplish this?  I want the advantage of free security patching for the vendor's Apache, dav, php, etc., but I care a lot about which version of Perl I use and what's in my @INC path.  I don't mind compiling my own mod_perl.

[A]
You'll want to look into
mod_so


q:
I have determined that my JSON, coming from the server, is valid (making the ajax call manually), but I would really like to use JQuery. I have also determined that the "post" URL, being sent to the server, is correct, using firebug. However, the error callback is still being triggered (parse error). I also tried datatype: text.

Are there other options that I should include?

$(function() {
    $("#submit").bind("click", function() {
        $.ajax({
            type: "post",
            url: "http://myServer/cgi-bin/broker" ,
            datatype: "json",
            data: {'start' : start,'end' : end},
            error: function(request,error){
                alert(error);
            },
            success: function(request) {
                alert(request.length);
            }
        }); // End ajax
    }); // End bind
}); // End eventlistener

[A]
Here are a few suggestions I would try:
1) the 'datatype' option you have specified should be 'dataType' (case-sensitive I believe)
2) try using the 'contentType' option as so:
```
```
contentType: "application/json; charset=utf-8"
```
```
I'm not sure how much that will help as it's used in the request to your post url, not in the response.
See this article for more info:
http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax
(It's written for asp.net, but may be applicable)
3) Triple check the output of your post url and run the output through a JSON validator just to be absolutely sure it's valid and can be parsed into a JSON object.
http://www.jsonlint.com
Hope some of this helps!


q:
I'm considering Altova MapForce (or something similar) to produce either XSLT and/or a Java or C# class to do the translation. Today, we pull data right out of the database and manually build an XML string that we post to a webservice.

Should it be db -> (internal)XML -> XSLT -> (External)XML? What do you folks do out there in the wide world?

[A]
I would use one of the out-of-the-box XML serialization classes to do your internal XML generation, and then use XSLT to transform to the external XML.  You might generate a schema as well to enforce that the translation code (whatever will drive your XSLT translation) continues to get the XML it is expecting for translation in case of changes to the object breaks things.
There are a number of XSLT editors on the market that will help you do the mappings, but I prefer to just use a regular XML editor.


q: I am writing a web application that requires user interaction via email.  I'm curious if there is a best practice or recommended source for learning about processing email.  I am writing my application in Python, but I'm not sure what mail server to use or how to format the message or subject line to account for automated processing.  I'm also looking for guidance on processing bouncebacks.

[A]
There are some pretty serious concerns here for how to send email automatically, and here are a few:
Use an email library. Python includes one called 'email'. This is your friend, it will stop you from doing anything tragically wrong. Read an example from
the Python Manual
.
Some points that will stop you from getting blocked by spam filters:
Always send from a valid email address. You must be able to send email to this address and have it received (it can go into /dev/null after it's received, but it must be possible to /deliver/ there). This will stop spam filters that do Sender Address Verification from blocking your mail.
The email address you send from on the server.sendmail(fromaddr, [toaddr]) line will be where bounces go. The From: line in the email is a totally different address, and that's where mail will go when the user hits 'Reply:'. Use this to your advantage, bounces can go to one place, while reply goes to another.
Send email to a local mail server, I recommend postfix. This local server will receive your mail and be responsible for sending it to your upstream server. Once it has been delivered to the local server, treat it as 'sent' from a programmatic point of view.
If you have a site that is on a static ip in a datacenter of good reputation, don't be afraid to simply relay the mail directly to the internet. If you're in a datacenter full of script kiddies and spammers, you will need to relay this mail via a public MTA of good reputation, hopefully you will be able to work this out without a hassle.
Don't send an email in only HTML. Always send it in Plain and HTML, or just Plain. Be nice, I use a text only email client, and you don't want to annoy me.
Verify that you're not running SPF on your email domain, or get it configured to allow your server to send the mail. Do this by doing a TXT lookup on your domain.
```
```
$ dig google.com txt
...snip...
;; ANSWER SECTION:
google.com.     300 IN  TXT "v=spf1 include:_netblocks.google.com ~all"
```
```
As you can see from that result, there's an SPF record there. If you don't have SPF, there won't be a TXT record. Read more about
SPF on wikipedia
.
Hope that helps.


q:
I have a two tables joined with a join table - this is just pseudo code:

Library
Book
LibraryBooks

What I need to do is if i have the id of a library, i want to get all the libraries that all the books that this library has are in.

So if i have Library 1, and Library 1 has books A and B in them, and books A and B are in Libraries 1, 2, and 3, is there an elegant (one line) way todo this in rails?

I was thinking:

l = Library.find(1)
allLibraries = l.books.libraries

But that doesn't seem to work. Suggestions?

[A]
Perhaps:
```
```
l.books.map {|b| b.libraries}
```
```
or
```
```
l.books.map {|b| b.libraries}.flatten.uniq
```
```
if you want it all in a flat array.
Of course, you should really define this as a method on Library, so as to uphold the noble cause of encapsulation.


q: How do you get all the classes in a namespace through reflection in C#?

[A]
```
```
using System.Reflection;
using System.Collections.Generic;
//...

static List<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();

    List<string> namespacelist = new List<string>();
    List<string> classlist = new List<string>();

    foreach (Type type in asm.GetTypes())
    {
        if (type.Namespace == nameSpace)
            namespacelist.Add(type.Name);
    }

    foreach (string classname in namespacelist)
        classlist.Add(classname);

    return classlist;
}
```
```
NB: The above code illustrates what's going on.  Were you to implement it, a simplified version can be used:
```
```
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
//...

static IEnumerable<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();
    return asm.GetTypes()
        .Where(type => type.Namespace == nameSpace)
        .Select(type => type.Name);
}
```
```


q:
In the vxWorks RTOS, there is a shell that allows you to issue command to your embedded system.

The documentation refers to kernel shell, host shell and target shell. What is the difference between the three?

[A]
The target shell and kernel shell are the same.  They refer to a shell that runs on the target. You can connect to the shell using either a serial port, or a telnet session.
A task runs on the target and parses all the commands received and acts on them, outputting data back to the port.
The host shell is a process that runs on the development station. It communicates with the debug agent on the target.  All the commands are actually parsed on the host and only simplified requests are sent to the target agent:
Read/Write Memory
Set/Remove Breakpoints
Create/Delete/Suspend/Resume Tasks
Invoke a function
This results in less real-time impact to the target.
Both shells allow the user to perform low level debugging (dissassembly, breakpoints, etc..) and invoke functions on the target.


q:
This is my first real question of need for any of those Gridview experts out there in the .NET world.

I an creating a Gridview from codebehind and I am holding a bunch of numerical data in the columns.  Although, I do add the comma in the number fields from codebehind.  When I load it to the Gridview, I have the sorting ability turned on, BUT the gridview chooses to ALPHA sort rather than sorting numerically because I add in those commas.

So I need help.  Anyone willing to give this one a shot?  I need to change some of my columns in the gridview to numerical sort rather than the alpha sort it is using.

[A]
If you do end up implementing your own comparer and sorting them as strings, the algorithm for treating numbers 'properly' is called Natural Sorting. Jeff wrote a pretty good entry on it here:
Sorting for Humans : Natural Sort Order
You can find a pretty good implementation in C# here:
http://www.codeproject.com/KB/string/NaturalSortComparer.aspx


q:
This question may be too product specifc but I'd like to know if anyone is exporting bug track data from HP Quality Center.

HP Quality Center (QC) has an old school COM API but I'd rather use a web service or maybe even screen scraper to export the data into an excel spreadsheet.

In any case, what's the best way to export bug tracking data from hosted HP Quality Center?

[A]
You can use this QC API Code to modify bugs/requirements.
```
```
TDAPIOLELib.TDConnection connection = new TDAPIOLELib.TDConnection();
connection.InitConnectionEx("http://SERVER:8080/qcbin");
connection.Login("USERNAME", "PASSWORD");
connection.Connect("QCDOMAIN", "QCPROJECT");
TDAPIOLELib.BugFactory bugFactory = connection.BugFactory as TDAPIOLELib.BugFactory;
TDAPIOLELib.List bugList = bugFactory.NewList("");
foreach (TDAPIOLELib.Bug bug in bugList)
{
  // View / Modify the properties
  // bug.ID, bug.Name, etc.
  // Save them when done
  // bug.Post();
}
```
```


q: We have an application which needs to use Direct3D. Specifically, it needs at least DirectX 9.0c version 4.09.0000.0904. While this should be present on all newer XP machines it might not be installed on older XP machines. How can I programmatically (using C++) determine if it is installed? I want to be able to give an information message to the user that Direct3D will not be available.

[A] According to the DirectX 9.0 SDK (summer 2004) documentation, see the GetDXVer SDK sample at \Samples\Multimedia\DXMisc\GetDXVer.


q:
I have a list of timesheet entries that show a start and stop time. This is sitting in a MySQL database. I need to create bar charts based on this data with the 24 hours of the day along the bottom and the amount of man-hours worked for each hour of the day.

For example, if Alice worked a job from 15:30 to 19:30 and Bob worked from 12:15 to 17:00, the chart would look like this:

I have a WTFey solution right now that involves a spreadsheet going out to column DY or something like that. The needed resolution is 15-minute intervals.

I'm assuming this is something best done in the database then exported for chart creation. Let me know if I'm missing any details. Thanks.

[A]
I came up with a pseudocode solution, hope it helps.
```
```
create an array named timetable with 24 entries
initialise timetable to zero

for each user in SQLtable
  firsthour = user.firsthour
  lasthour = user.lasthour

  firstminutes = 4 - (rounded down integer(user.firstminutes/15))
  lastminutes = rounded down integer(user.lastminutes/15)

  timetable(firsthour) = timetable(firsthour) + firstminutes
  timetable(lasthour) = timetable(lasthour) + lastminutes

  for index=firsthour+1 to lasthour-1
    timetable(index) = timetable(index) + 4
  next index

next user
```
```
Now the timetable array holds the values you desire in 15 minute granularity, ie. a value of 4 = 1 hour, 5 = 1 hour 15 minutes, 14 = 3 hours 30 minutes.


q:
How do I convert a datetime string in local time to a string in UTC time?

I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.

Clarification:  For example, if I have 2008-09-17 14:02:00 in my local timezone (+10), I'd like to generate a string with the equivalent UTC time: 2008-09-17 04:02:00.

Also, from http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.

[A]
```
```
def local_to_utc(t):
    secs = time.mktime(t)
    return time.gmtime(secs)

def utc_to_local(t):
    secs = calendar.timegm(t)
    return time.localtime(secs)
```
```
Source:
http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html
Example usage from
bd808
: If your source is a
```
datetime.datetime
```
object
```
t
```
, call as:
```
```
local_to_utc(t.timetuple())
```
```


q:
The situation is this:

You have a Hibernate context with an
object graph that has some lazy
loading defined.

You want to use
the Hibernate objects in your UI as
is without having to copy the data
somewhere.

There are different UI
contexts that require different
amounts of data.

The data is too
big to just eager load the whole
graph each time.

What is the best means to load all the appropriate objects in the object graph in a configurable way so that they can be accessed without having to go back to the database to load more data?

Any help.

[A]
Let's say you have the Client and at one point you have to something with his Orders and maybe he has a Bonus for his Orders.
Then I would define a Repository with a fluent interface that will allow me to say something like :
```
```
new ClientRepo().LoadClientBy(id)
                .WithOrders()
                .WithBonus()
                .OrderByName();
```
```
And there you have the client with everything you need. It's preferably that you know in advance what you will need for the current operation. This way you can avoid unwanted trips to the database.(new devs in your team will usually do this - call a property and not be aware of the fact that it's actually a call to the DB)


q: Since the Google App Engine Datastore is based on Bigtable and we know that's not a relational database, how do you design a database schema/data model for applications that use this type of database system?

[A]
As GAE builds on how data is managed in Django there is a lot of info on how to address similar questions in the Django documentation (for example see
here
, scroll down to 'Your first model').
In short you design you db model as a regular object model and let GAE sort out all of the object-relational mappings.


q:
We have two tasks (T1 and T2) in our vxWorks embedded system that have the same priority (110).

How does the regular vxWorks scheduler deal with this if both tasks are ready to run?

Which task executes first?

[A]
The task that will run first is the task that is spawned first as realized by the VxWorks scheduler task. VxWorks uses
priority-based scheduling
by default. So in your case, since T1 and T2 have the same priority, whichever one gets the CPU first will continue to run indefinitely until it is explicitly blocked (using
taskSuspend
or
taskDelay
), at which time the other READY task will execute until it is blocked, and so on. This ought to be controlled by semaphores or mutexes (mutices?)
The main problem with priority-based scheduling is illuminated by this exact problem. How do we determine how long to let these tasks run? The fact that they have the same priority complicates things. Another concern is that VxWorks tasks that have high priority (lower number means higher priority) can preempt your application which you must be prepared for in your code. These problems can be solved by using
round-robin scheduling
. The additional problems posed by round-robin scheduling and the solutions are all described
here
.


q:
What are the stack and heap?

Where are they located physically in a computer's memory?

To what extent are they controlled by the OS or language run-time?

What is their scope?

What determines their sizes?

What makes one faster?

[A]
Stack:
Stored in computer RAM just like the heap.
Variables created on the stack will go out of scope and are automatically deallocated.
Much faster to allocate in comparison to variables on the heap.
Implemented with an actual stack data structure.
Stores local data, return addresses, used for parameter passing.
Can have a stack overflow when too much of the stack is used (mostly from infinite or too deep recursion, very large allocations).
Data created on the stack can be used without pointers.
You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.
Usually has a maximum size already determined when your program starts.
Heap:
Stored in computer RAM just like the stack.
In C++, variables on the heap must be destroyed manually and never fall out of scope. The data is freed with
```
delete
```
,
```
delete[]
```
, or
```
free
```
.
Slower to allocate in comparison to variables on the stack.
Used on demand to allocate a block of data for use by the program.
Can have fragmentation when there are a lot of allocations and deallocations.
In C++ or C, data created on the heap will be pointed to by pointers and allocated with
```
new
```
or
```
malloc
```
respectively.
Can have allocation failures if too big of a buffer is requested to be allocated.
You would use the heap if you don't know exactly how much data you will need at run time or if you need to allocate a lot of data.
Responsible for memory leaks.
Example:
```
```
int foo()
{
  char *pBuffer; //<--nothing allocated yet (excluding the pointer itself, which is allocated here on the stack).
  bool b = true; // Allocated on the stack.
  if(b)
  {
    //Create 500 bytes on the stack
    char buffer[500];

    //Create 500 bytes on the heap
    pBuffer = new char[500];

   }//<-- buffer is deallocated here, pBuffer is not
}//<--- oops there's a memory leak, I should have called delete[] pBuffer;
```
```


q: I want to run text through a filter to ensure it is all UTF-8 encoded.  What is the recommended way to do this with PHP?

[A]
Your question is unclear, are you trying to encode something?  If so
utf8_encode
is your friend.  Are you trying to determine if it doesn't need to be encoded?  If so,
utf8_encode
is still your friend, because you can check that the result is the same as the input!


q:
I'm sure there were several, but the one I was thinking of would display a nice text screen when you crashed the computer thoroughly.

The Text was "Well smoke me a kipper."

[A]
No one else has answered this, so I'll answer the part I can: the original Macintosh debugger was
MacsBug
.
So far as the kipper quote goes, the only thing that comes to mind is the
Pathogen
computer virus.


q:
I have the following (pretty standard) table structure:

Post <-> PostTag <-> Tag

Suppose I have the following records:

PostID Title
1,     'Foo'
2,     'Bar'
3,     'Baz'

TagID Name
1,    'Foo'
2,    'Bar'

PostID TagID
1      1
1      2
2      2

In other words, the first post has two tags, the second has one and the third one doesn't have any.

I'd like to load all posts and it's tags in one query but haven't been able to find the right combination of operators. I've been able to load either posts with tags only or repeated posts when more than one tag.

Given the database above, I'd like to receive three posts and their tags (if any) in a collection property of the Post objects. Is it possible at all?

Thanks

[A]
I've answered this in another post :
About eager loading
. In your case it would probably be something like :
```
```
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Post>(p => p.PostTag);
options.LoadWith<PostTag>(pt => pt.Tag);
```
```
Though be careful - the DataLoadOptions must be set BEFORE ANY query is sent to the database - if not, an exception is thrown (no idea why it's like this in Linq2Sql - probably will be fixed in a later version).


q: I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage.  The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters.  I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last word before 200 chars.

[A]
By using the
wordwrap
function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line:
```
```
substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n"));
```
```
One thing this oneliner doesn't handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like:
```
```
if (strlen($string) > $your_desired_width)
{
    $string = wordwrap($string, $your_desired_width);
    $string = substr($string, 0, strpos($string, "\n"));
}
```
```
The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here a version which solves this problem:
```
```
function tokenTruncate($string, $your_desired_width) {
  $parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
  $parts_count = count($parts);

  $length = 0;
  $last_part = 0;
  for (; $last_part < $parts_count; ++$last_part) {
    $length += strlen($parts[$last_part]);
    if ($length > $your_desired_width) { break; }
  }

  return implode(array_slice($parts, 0, $last_part));
}
```
```
Also, here is the PHPUnit testclass used to test the implementation:
```
```
class TokenTruncateTest extends PHPUnit_Framework_TestCase {
  public function testBasic() {
    $this->assertEquals("1 3 5 7 9 ",
      tokenTruncate("1 3 5 7 9 11 14", 10));
  }

  public function testEmptyString() {
    $this->assertEquals("",
      tokenTruncate("", 10));
  }

  public function testShortString() {
    $this->assertEquals("1 3",
      tokenTruncate("1 3", 10));
  }

  public function testStringTooLong() {
    $this->assertEquals("",
      tokenTruncate("toooooooooooolooooong", 10));
  }

  public function testContainingNewline() {
    $this->assertEquals("1 3\n5 7 9 ",
      tokenTruncate("1 3\n5 7 9 11 14", 10));
  }
}
```
```
EDIT :
Special UTF8 characters like 'à' are not handled. Add 'u' at the end of the REGEX to handle it:
```
$parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);
```


q:
I have a string which is like this:

this is "a test"

I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:

['this', 'is', 'a test']

PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.

[A]
You want
```
split
```
, from the built-in
```
shlex
```
module.
```
```
>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']
```
```
This should do exactly what you want.
If you want to preserve the quotation marks, then you can pass the
```
posix=False
```
kwarg.
```
```
>>> shlex.split('this is "a test"', posix=False)
['this', 'is', '"a test"']
```
```


q:
If you were writing a new application from scratch today, and wanted it to scale to all the cores you could throw at it tomorrow, what parallel programming model/system/language/library would you choose?  Why?

I am particularly interested in answers along these axes:

Programmer productivity / ease of use (can mortals successfully use it?)

Target application domain (what problems is it (not) good at?)

Concurrency style (does it support tasks, pipelines, data parallelism, messages...?)

Maintainability / future-proofing (will anybody still be using it in 20 years?)

Performance (how does it scale on what kinds of hardware?)

I am being deliberately vague on the nature of the application in anticipation of getting good general answers useful for a variety of applications.

[A]
For .NET application I choose "
.NET Parallel Extensions (PLINQ)
" it's extremely easy to use and allows me to parallelize existing code in minutes.
It's simple to learn
Used to perform complex operations over large arrays of objects, so I can't comment on other applications
Supports tasks and piplines
Should be supported for a next couple of years, but who knows for sure?
CTP version has some performance issues, but already looks very promising.
Mono
will likely get
support for PLINQ, so it could be a cross-platform solution as well.


q: Can you provide an example of a byte buffer transferred between two java classes via UDP datagram?

[A]
Hows' this ?
```
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class Server {

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(new InetSocketAddress(5000));
        byte[] message = new byte[512];
        DatagramPacket packet = new DatagramPacket(message, message.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(), packet.getOffset(), packet.getLength()));
    }
}
```
```
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class Client {

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket();
        socket.connect(new InetSocketAddress(5000));
        byte[] message = "Oh Hai!".getBytes();
        DatagramPacket packet = new DatagramPacket(message, message.length);
        socket.send(packet);
    }
}
```


q:
My friends and I are starting a game like Pokemon and we wanted to know how will we add monsters to the game?  We're using VisualBasic because my friend's brother said it would be easier.

So far we can put pictures of the monsters on the screen and you can click to attack and stuff.

Right now when we want to add a monster we have to make a new window.  This will take us a long time to make all the windows for each type of monster.  Is there a tool or something to make this go faster?  How do game companies do this?

[A]
I'd suggest making a list of all the attributes you would need for each monster and store all of that in a database like
MySQL
. This way you don't need to make windows for each monster, only each time a monster appears (in which case you'd just get the necessary info from the database).
If you're not familiar with any database, check out the
MySQL tutorial
to get up and going.


q: Desinging web application and for reporting iam using crystal reports.sometimes the crystal reports gives runtimes error. What can i do to make my report faster. Retrieving around 1MB of data. It is the month end sales report. what is the best method to solve this issue.

[A]
1Mb sounds like far too much data for a report -
I would try to filter it down more on the server


q: How do I do a diff of two strings or arrays in Ruby?

[A]
diff.rb is what you want, which is available at
http://users.cybercity.dk/~dsl8950/ruby/diff.html
via internet archive:
http://web.archive.org/web/20140421214841/http://users.cybercity.dk:80/~dsl8950/ruby/diff.html


q: I am currently programming a scheduling application which loosely based on iCalendar standard. Does anyone knows in which property can I store the event creator's information? By browsing through the iCalendar RFC 2445, I find this property: Organizer. can I store the event creator's information in the property even if he/she is the only person involved in the event? or there is already a field to store the event creator's information???!

[A]
```
ORGANIZER;CN="Sally Example":mailto:sally@example.com
```
Looks like the answer


q:
Java is one of my programming languages of choice.  I always run into the problem though of distributing my application to end-users.

Giving a user a JAR is not always as user friendly as I would like and using Java WebStart requires that I maintain a web server.

What's the best way to distribute a Java application?  What if the Java application needs to install artifacts to the user's computer?  Are there any good Java installation/packaging systems out there?

[A]
For simple Java apps I like to use Jar's.  It is very simple to distribute one file that a user can just click on (Windows), or
```
```
java -jar jarname.jar
```
```
IMHO, jar is the way to go when simplicity is a main requirement.


q:
Our team is setting up nightly and continuous integration builds.  We own Team Foundation Server and could use Team Foundation Build.  I'm more familiar with CC.Net and lean that way but management sees all the money spent on TFS and wants to use it.

Some things I like better about CC.Net is the flexibility of notifications as well as the ease of implementing custom scripts.

If you have experience with both products, which do you prefer and why?

[A]
We've been using CruiseControl.net since June '07 and it's worked great for us.  Best part, it integrates to SVN easily which is a far superior source control provider.
So our setup is:
Cruise Control.Net
SVN
Trac
- for bug reports and project management (integrates perfectly with SVN)
nunit - for unit testing
We've had some major parallel development going and the branching and merging experience was spectacular.  If you have the choice I'd go with the setup above!


q:
This is somewhat similar to this question.

However, rather than wanting to hide a column all together, I am just looking to hide the column on the List.aspx page.

My specific example is that fields that are long (or at least nvarchar(MAX)) automatically hide from the List.aspx page as is but are still visible on the Edit.aspx page.

I would like to replicate this behaviour for other (shorter) columns.

Is this possible?

[A]
You can create a custom page for the particular table you want to change.  There's an example
here
.
Within your custom page, you can then set
```
AutoGenerateColumns="false"
```
within the
```
asp:GridView
```
control, and then define exactly the columns you want, like this:
```
```
<Columns>
    ...
    <asp:DynamicField DataField="Product" HeaderText="Product" />
    <asp:DynamicField DataField="Colour" HeaderText="Colour" />
</Columns>
```
```


q:
I can't seem to find much documentation on X-Sendfile or example code for PHP (there is some rails code).

Anyone used it before and would mind giving a quick snippet of code and a brief description?

[A]
X-Sendfile is an HTTP header, so you want something like this:
```
```
header("X-Sendfile: $filename");
```
```
Your web server picks it up if correctly configured.  Here's some more details:
http://www.jasny.net/articles/how-i-php-x-sendfile/


q:
I want to use javascript to insert some elements into the current page.
Such as this is the original document:
<p>Hello world!</p>

Now I want to insert an element in to the text so that it will become:

<p>Hello <span id=span1>new</span> world!</p>

I need the span tag because I want to handle it later.Show or hide.
But now problem comes out, if the original page has already defined a strange CSS style on all <span> tags, the "new" I just inserted will not appear to be the same as "Hello" and "world". How can I avoid this? I want the "new" be exactly the same as the "Hello" and "world".

[A]
Include the class definition that's defined in CSS on your JavaScript version of the
```
<span>
```
tag as well.
```
```
<span class="class_defined_in_css">
```
```
(where this
```
<span>
```
tag would be part of your JavaScript code.)


q:
Application frameworks such as DotNetNuke, Eclipse, Websphere and so forth are available today which offer customizable frameworks that can be used as dashboard applications.  Do you use these or do you and your peers keep writing amazing, modular, maintainable dashboard frameworks which you support yourselves?

Are there any good web based, OS independent frameworks out there that you suggest using to build your own enterprise class infrastructure around?

[A]
The one I use is Oracle Application Development Framework. It's a complete, fully supported framework, and Oracle use it themselves to build their own enterprise applications. It comes with a lot of JSF components that are very easy to bind to the underlying data objects.
I'd recommend this  for all Java applications that need database data.
You find a discussion of it on the Oracle Wiki:
http://wiki.oracle.com/page/ADF+Methodology+-+Work+in+Progressent


q: How can I get all implementations of an interface through reflection in C#?

[A]
Do you mean all interfaces a Type implements?
Like this:
```
```
ObjX foo = new ObjX();
Type tFoo = foo.GetType();
Type[] tFooInterfaces = tFoo.GetInterfaces();
foreach(Type tInterface in tFooInterfaces)
{
  // do something with it
}
```
```
Hope tha helpts.


q: How do I preview a url using ajax? I have seen this done with search engine plug ins and would like to learn how to do this. Specifically, I would like to be able to mouse over a link and see the preview of the webpage using ajax.

[A]
There's the
easy
solution, the
hard
solution, and the
use-a-library
solution.
use-a-library
: I prefer always doing the use-a-library solution unless you have a darn good reason otherwise.  One possible site which wraps the "hard solution" as a service for you:
http://thumbnails.iwebtool.com/demo/
easy
: The easy solution is to just load the target webpage as a downscaled AJAXy window.  You can use many of the Lightbox-class plugins for this task, particularly the ones which allow you to target arbitrary HTTP content for the Lightbox window.
GreyBox
is my favorite of those which I have used before.
Lightbox Gone Wild
is also nice.
hard
: Then there is the hard solution: you need to render the web page server side, cache the rendering as an image, and then serve up that image using Lightbox-esque Javascript (which is trivial next to the other requirements).  How you would go about doing this is outside the scope of this box.  Why would you do it this way?  The preview generates MUCH faster for the client, and it hermetically seals the client's session away from things which might bust it in the target website -- poorly behaving Javascript and/or malware can cause Really Bad Things when you open them, even in an AJAXy window-within-a-window.


q:
I have video durations stored in HH:MM:SS format. I'd like to display it as HH hours, MM minutes, SS seconds. It shouldn't display hours if it's less than 1.

What would be the best approach?

[A]
Something like this?
```
```
$vals = explode(':', $duration);

if ( $vals[0] == 0 )
   $result = $vals[1] . ' minutes, ' . $vals[2] . ' seconds';
else
   $result = $vals[0] . 'hours, ' . $vals[1] . ' minutes, ' . $vals[2] . ' seconds';
```
```


q:
In C++0x I would like to write a function like this:

template <typename... Types>
void fun(typename std::tuple<Types...> my_tuple) {
    //Put things into the tuple
}

I first tried to use a for loop on int i and then do:

get<i>(my_tuple);

And then store some value in the result. However, get only works on constexpr.

If I could get the variables out of the tuple and pass them to a variadic templated function I could recurse through the arguments very easily, but I have no idea how to get the variables out of the tuple without get. Any ideas on how to do that? Or does anyone have another way of modifying this tuple?

[A]
Since the "i" in
```
```
get<i>(tup)
```
```
needs to be a compile-time constant, template instantiation is used to "iterate" (actually recurse) through the values.  Boost tuples have the "length" and "element" meta-functions that can be helpful here -- I assume C++0x has these too.


q: Is there a quick way to find every match of a regular expression in Ruby? I've looked through the Regex object in the Ruby STL and searched on Google to no avail.

[A]
Using
```
scan
```
should do the trick:
```
```
string.scan(/regex/)
```
```


q:
I am having trouble deciding on whether to classify my application as 'real time' or 'near real time', or perhaps even something else.

The software receives data immediately as it is generated from the source, then based on certain rules, raises an alert when certain conditions are met. It takes the approach of checking the last 30 seconds of data every 30 seconds to see whether the criteria for a rule has been met.

Is that real time? What are the thresholds for the definitions of real time vs. near real-time?

EDIT

I think this is a duplicate of Define realtime on the web for business.

Please decide if the above thread is insufficient to answer your question.

[A] I am in agreement with John, in your scenario you are looking at least 30 seconds of delay, I would say that it is nearly real time.


q:
Code I have:

cell_val = CStr(Nz(fld.value, ""))
Dim iter As Long
For iter = 0 To Len(cell_val) - 1 Step 1
    If Asc(Mid(cell_val, iter, 1)) > 127 Then
        addlog "Export contains ascii character > 127"
    End If
Next iter

This code doesn't work. Anyone know how to do this? I've simply got no idea with VB or VBA.

[A]
I believe your problem is that in VBA string indexes start at 1 and not at 0. Try the following:
```
```
For iter = 1 To Len(cell_val)
    If Asc(Mid(cell_val, iter, 1)) > 127 Then
        addlog "Export contains ascii character > 127"
    End If
Next
```
```


q: What are futures? It's something to do with lazy evaluation.

[A]
A Future encapsulates a deferred calculation, and is commonly used to shoehorn lazy evaluation into a non-lazy language. The first time a future is evaluated, the code required to evaluate it is run, and the future is replaced with the result.
Since the future is replaced, subsequent evaluations do not execute the code again, and simply yield the result.


q:
I need to concatenate two String arrays in Java.

void f(String[] first, String[] second) {
    String[] both = ???
}

Which is the easiest way to do this?

[A]
Here's a simple method that will concatenate two arrays and return the result:
```
```
public <T> T[] concatenate(T[] a, T[] b) {
    int aLen = a.length;
    int bLen = b.length;

    @SuppressWarnings("unchecked")
    T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
    System.arraycopy(a, 0, c, 0, aLen);
    System.arraycopy(b, 0, c, aLen, bLen);

    return c;
}
```
```
Note that it will not work with primitive data types, only with object types.
The following slightly more complicated version works with both object and primitive arrays. It does this by using
```
T
```
instead of
```
T[]
```
as the argument type.
It also makes it possible to concatenate arrays of two different types by picking the most general type as the component type of the result.
```
```
public static <T> T concatenate(T a, T b) {
    if (!a.getClass().isArray() || !b.getClass().isArray()) {
        throw new IllegalArgumentException();
    }

    Class<?> resCompType;
    Class<?> aCompType = a.getClass().getComponentType();
    Class<?> bCompType = b.getClass().getComponentType();

    if (aCompType.isAssignableFrom(bCompType)) {
        resCompType = aCompType;
    } else if (bCompType.isAssignableFrom(aCompType)) {
        resCompType = bCompType;
    } else {
        throw new IllegalArgumentException();
    }

    int aLen = Array.getLength(a);
    int bLen = Array.getLength(b);

    @SuppressWarnings("unchecked")
    T result = (T) Array.newInstance(resCompType, aLen + bLen);
    System.arraycopy(a, 0, result, 0, aLen);
    System.arraycopy(b, 0, result, aLen, bLen);

    return result;
}
```
```
Here is an example:
```
```
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, concatenate(new int[] { 1, 2 }, new int[] { 3 }));
Assert.assertArrayEquals(new Number[] { 1, 2, 3f }, concatenate(new Integer[] { 1, 2 }, new Number[] { 3f }));
```
```


q:
I need to know how to turn on Code Coverage when running TFS builds on a solution with a .testrunconfig file.

There is an option in the testrunconfig file that is for code coverage, but when running a TFS build there is no code coverage results.

I am running my tests using the *Tests.dll mask and NOT using Test Lists (.vsmdi).

[A]
How are you running the tests?  Are you using a .vsmdi file or just specifying that you run all tests in *Tests.dll assemblies?
If it is the latter and you are using TFS 2008, then you need to add the following to the and of the first PropertyGroup in your TFSBuild.proj file for the build.
```
```
<RunConfigFile>$(SolutionRoot)\TestRunConfig.testrunconfig</RunConfigFile>
```
```
This points the build at your .testrunconfig so it can pick up the instructions to run code coverage.


q:
The title is pretty much self explanatory. Given two dates what is the best way of finding the number of week days using PHP? Week days being Monday to Friday.

For instance, how would I find out that there are 10 week days in between 31/08/2008 and 13/09/2008?

[A]
One way would be to convert the dates to unix timestamps using strtotime(...), subtracting the results and div'ing with 86400 (24*60*60):
```
```
$dif_in_seconds = abs(strtotime($a) - strtotime($b));
$daysbetween = $dif_in_seconds / 86400;
```
```
ETA: Oh.. You meant weekdays as in Mon-Fri.. Didn't see that at first..


q: Please consider both commercial and free debuggers. Would like to see also the pros and cons for each.

[A]
I haven't used it myself, so I can't comment on the pros/cons , but one commercial alternative is
TotalView
.
There is also
DDD
that gives you a frontend to GDB, but i guess you have already tried/used that?


q:
public class Test {
    public static void main(String[] args) {

    }
}

class Outer {
    void aMethod() {
        class MethodLocalInner {
            void bMethod() {
                System.out.println("Inside method-local bMethod");
            }
        }
    }
}

Can someone tell me how to print the message from bMethod?

[A]
You can only instantiate
```
MethodLocalInner
```
within
```
aMethod
```
. So do
```
```
void aMethod() {

    class MethodLocalInner {

            void bMethod() {

                    System.out.println("Inside method-local bMethod");
            }
    }

    MethodLocalInner foo = new MethodLocalInner(); // Default Constructor
    foo.bMethod();

}
```
```


q:
While refactoring some old code I have stripped out a number of public methods that should actually of been statics as they a) don't operate on any member data or call any other member functions and b) because they might prove useful elsewhere.

This led me to think about the best way to group 'helper' functions together.  The Java/C# way would be to use a class of static functions with a private constructor, e.g.:

class Helper
{
private:
  Helper() { }
public:
  static int HelperFunc1();
  static int HelperFunc2();
};

However, being C++ you could also use a namespace:

namespace Helper
{
  int HelperFunc1();
  int HelperFunc2();
}

In most cases I think I would prefer the namespace approach but I wanted to know what the pros and cons of each approach are.  If used the class approach for example, would there be any overheads?

[A]
The main advantage to using a namespace is that you can reopen it and add more stuff later, you can't do that with a class.  This makes this approach better for loosely coupled helpers (for example you could have a Helpers namespace for your entire library, much like all of STL is in ::std)
The main advantage of a class is that you can nest it inside the class using it, you can't nest a namespace in a class.  This makes this approach better for tightly coupled helpers.
You won't have any extra overhead having them in a class vs a namespace.


q:
Events are synchronous in C#. I have this application where my main form starts a thread with a loop in it that listens to a stream. When something comes along on the stream an event is fired from the loop to the main form.

If the main form is slow or shows a messagebox or something the loop will be suspended. What is the best way around this? By using a callback and invoke on the main form?

[A]
Since you're using a form, the easier way is to use the
BackgroundWorker
component.
The BackgroundWorker class allows you
  to run an operation on a separate,
  dedicated thread. Time-consuming
  operations like downloads and database
  transactions can cause your user
  interface (UI) to seem as though it
  has stopped responding while they are
  running. When you want a responsive UI
  and you are faced with long delays
  associated with such operations, the
  BackgroundWorker class provides a
  convenient solution.


q:
What is the difference between == and ===?

How exactly does the loosely == comparison work?

How exactly does the strict === comparison work?

What would be some useful examples?

[A]
Difference between
```
==
```
and
```
===
```
The difference between the loosely
```
==
```
equal operator and the strict
```
===
```
identical operator is exactly explained in the
manual
:
Comparison Operators
Example
Name
Result
$a ==  $b
Equal
TRUE if $a is equal to $b after type juggling.
$a === $b
Identical
TRUE if $a is equal to $b, and they are of the same type.
Loosely
```
==
```
equal comparison
If you are using the
```
==
```
operator, or any other comparison operator which uses loosely comparison such as
```
!=
```
,
```
<>
```
or
```
==
```
, you always have to look at the
context
to see what, where and why something gets converted to understand what is going on.
Converting rules
Converting to boolean
Converting to integer
Converting to float
Converting to string
Converting to array
Converting to object
Converting to resource
Converting to NULL
Type comparison table
As reference and example you can see the comparison table in the
manual
:
TRUE
FALSE
1
0
-1
"1"
"0"
"-1"
NULL
array()
"php"
""
TRUE
TRUE
FALSE
TRUE
FALSE
TRUE
TRUE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
TRUE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
TRUE
TRUE
FALSE
TRUE
1
TRUE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
0
FALSE
TRUE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
TRUE
FALSE
TRUE
TRUE
-1
TRUE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
"1"
TRUE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
"0"
FALSE
TRUE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
"-1"
TRUE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
NULL
FALSE
TRUE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
TRUE
TRUE
FALSE
TRUE
array()
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
TRUE
FALSE
FALSE
"php"
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
""
FALSE
TRUE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
TRUE
Strict
```
===
```
identical comparison
If you are using the
```
===
```
operator, or any other comparison operator which uses strict comparison such as
```
!==
```
or
```
===
```
, then you can always be sure that the types won't
magically
change, because there will be no converting going on. So with strict comparison the type and value have to be the same, not only the value.
Type comparison table
As reference and example you can see the comparison table in the
manual
:
Strict comparisons with
```
===
```
TRUE
FALSE
1
0
-1
"1"
"0"
"-1"
NULL
array()
"php"
""
TRUE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
1
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
0
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
-1
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
"1"
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
"0"
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
"-1"
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
NULL
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
array()
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
"php"
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
""
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
Editor's note
- This was properly quoted previously, but is more readable as a markdown table. This is not plagiarism


q: How do I register a custom protocol with Windows so that when clicking a link in an email or on a web page my application is opened and the parameters from the URL are passed to it?

[A]
The MSDN link is nice, but the security information there isn't complete. The handler registration should contain "%1", not %1. This is a security measure, because some URL sources incorrectly decode %20 before invoking your custom protocol handler.
PS. You'll get the entire URL, not just the URL parameters. But the URL might be subject to some mistreatment, besides the already mentioned %20->space conversion. It helps to be conservative in your URL syntax design. Don't throw in random // or you'll get into the mess that file:// is.


q:
I may be wrong, but if you are working with SmtpClient.SendAsync in ASP.NET
2.0 and it throws an exception, the thread processing the request waits
indefinitely for the operation to complete.

To reproduce this problem, simply use an invalid SMTP address for the host
that could not be resolved when sending an email.

Note that you should set Page.Async = true to use SendAsync.

If Page.Async is set to false and Send throws an exception the thread
does not block, and the page is processed correctly.

TIA.

[A]
Note that you should set Page.Async = true to use SendAsync.
Please explain the rationale behind this. Misunderstanding what Page.Async does may be the cause of your problems.
Sorry, I was unable to get an example working that reproduced the problem.
See
http://msdn.microsoft.com/en-us/magazine/cc163725.aspx
(WICKED CODE: Asynchronous Pages in ASP.NET 2.0)
EDIT:
Looking at your code example, I can see that you're not using
```
RegisterAsyncTask()
```
and the
```
PageAsyncTask
```
class. I think you must do this when executing asynchronous tasks on a Page where
```
@Async
```
is set to true. The example from MSDN Magazine looks like this:
```
```
protected void Page_Load(object sender, EventArgs e)
{
    PageAsyncTask task = new PageAsyncTask(
        new BeginEventHandler(BeginAsyncOperation),
        new EndEventHandler(EndAsyncOperation),
        new EndEventHandler(TimeoutAsyncOperation),
        null
        );
    RegisterAsyncTask(task);
}
```
```
Inside
```
BeginAsyncOperation
```
, then, should you send a mail asynchronously.


q: Does anyone know how to get/set the call divert settings in codes running on Windows mobile 5/6? I am new to windows mobile development and wonder if there is anyway to do it using C# and .NET CF?

[A]
I assume you mean call forwarding?  In general terms, the
Telephony API (TAPI)
is used for programmatically controlling the phone interface.  Call forwarding is specifically handled by
TSPI_lineForward
.
Microsoft does not offer any built-in or SDK tools for managed developers to use TAPI, and the structures TAPI uses are cumbersome and difficult to P/Invoke.  There are a some
3rd-party libraries
that do provide some level of TAPI interaction that you might also investigate.


q:
In the process of learning TinyOS I have discovered that I am totally clueless about makefiles.

There are many optional compile time features that can be used by way of declaring preprocessor variables.

To use them you have to do things like:

CFLAGS="-DPACKET_LINK"        this enables a certain feature.

and

CFLAGS="-DPACKET_LINK" "-DLOW_POWER" enables two features.

Can someone dissect these lines for me and tell me whats going on? Not in terms of TinyOS, but in terms of makefiles!

[A]
Somewhere in the makefile the CFLAG will be used in compilation line like this:
```
$(CC) $(CFLAGS) $(C_INCLUDES) $<
```
and eventually in the execution will be translated to :
```
gcc -DPACKET_LINK -DLOW_POWER -c filename.c -o filename.o
```
This define will be passed to the source code as it was define in the header file


q: One of the best tips for using vim that I have learned so far has been that one can press Ctrl+C or Ctrl+[ instead of the Esc key. However I use a dvorak keyboard so Ctrl+[ is a little out of reach for me as well so I mostly use Ctrl+C. Now I've read somewhere that these two key combinations don't actually have exactly the same behaviour and that it is better to use Ctrl+[. I haven't come across any problems so far though so I'd like to know what exactly is the difference between the two?

[A]
According to Vim's documentation,
Ctrl
+
C
does not check for abbreviations and does not trigger the
```
InsertLeave
```
autocommand event while
Ctrl
+
[
does.
One option is to use the following to remap
Ctrl
+
C
```
```
inoremap <C-c> <Esc><Esc>
```
```


q:
Phantom References serve for post-mortem operations.
The Java specification states that a phantom referenced object will not be deallocated until the phantom-reference itself is cleaned.

My question is: What purpose does this feature (object not deallocated) serve?

(The only idea i came up with, is to allow native code to do post-mortem cleanup on the object, but it isn't much convincing).

[A]
Edit, since I've misunderstand the question first:
Quoted from here
http://www.memorymanagement.org/glossary/p.html
:
The Java specification says that the
  phantom reference is not cleared when
  the reference object is enqueued, but
  actually, there's no way in the
  language to tell whether that has been
  done or not. In some implementations,
  JNI weak global references are weaker
  than phantom references, and provide a
  way to access phantom reachable
  objects.
But I found no other references which would say the same.


q:
I've started refactoring some legacy code recently and came across two functions for drawing a coordinate grid, the problem is that these functions differ only in orthogonal variables they treat, something like that

void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1)
{
    for(int x = x0; x < x1; x += step)
    {
         MoveToEx(dc, x, y0, NULL);
         LineTo(dc, x, y1);
    }
}
void DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1)
{
    for(int y = y0; y < y1; y += step)
    {
         MoveToEx(dc, x0, y, NULL);
         LineTo(dc, x1, y);
    }
}

So if I decide to add some fancy stuff, like antialiasing or merely change drawing pencil or whatever I'll have to put the same code in both of them and it's code duplication and it's bad we all know why.

My question is how would you rewrite these two functions into a single one to avoid this problem?

[A]
Here is my own solution
```
```
class CoordGenerator
{
public:
    CoordGenerator(int _from, int _to, int _step)
        :from(_from), to(_to), step(_step), pos(_from){}
    virtual POINT GetPoint00() const = 0;
    virtual POINT GetPoint01() const = 0;
    bool Next()
        {
            if(pos > step) return false;
            pos += step;
        }
protected:
    int from;
    int to;
    int step;
    int pos;
};

class GenX: public CoordGenerator
{
public:
    GenX(int x0, int x1, int step, int _y0, int _y1)
        :CoordGenerator(x0, x1, step),y0(_y0), y1(_y1){}
    virtual POINT GetPoint00() const
        {
            const POINT p = {pos, y0};
            return p;
        }
    virtual POINT GetPoint01() const
        {
            const POINT p = {pos, y1};
            return p;
        }
private:
    int y0;
    int y1;
};

class GenY: public CoordGenerator
{
public:
    GenY(int y0, int y1, int step, int _x0, int _x1)
        :CoordGenerator(y0, y1, step),x0(_x0), x1(_x1){}
    virtual POINT GetPoint00() const
        {
            const POINT p = {x0, pos};
            return p;
        }
    virtual POINT GetPoint01() const
        {
            const POINT p = {x1, pos};
            return p;
        }
private:
    int x1;
    int x0;
};

void DrawScale(HDC dc, CoordGenerator* g)
{
    do
    {
        POINT p = g->GetPoint00();
        MoveToEx(dc, p.x, p.y, 0);
        p = g->GetPoint01();
        LineTo(dc, p.x, p.y);
    }while(g->Next());
}
```
```
But I it seems to me too complicated for such a tiny problem, so I'm looking forward to still see your solutions.


q:
public static Logger getLogger() {
    final Throwable t = new Throwable();
    final StackTraceElement methodCaller = t.getStackTrace()[1];
    final Logger logger = Logger.getLogger(methodCaller.getClassName());
    logger.setLevel(ResourceManager.LOGLEVEL);
    return logger;
}

This method would return a logger that knows the class it's logging for.
Any ideas against it?

Many years later: https://github.com/yanchenko/droidparts/blob/master/droidparts/src/org/droidparts/util/L.java

[A]
You could of course just use Log4J with the appropriate pattern layout:
For example, for the class name "org.apache.xyz.SomeClass", the pattern %C{1} will output "SomeClass".
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html


q: I want to find 2nd, 3rd, ... nth maximum value of a column.

[A]
You could sort the column into descending format and then just obtain the value from the nth row.
EDIT::
Updated as per comment request.
WARNING
completely untested!
```
```
SELECT DOB FROM (SELECT DOB FROM USERS ORDER BY DOB DESC) WHERE ROWID = 6
```
```
Something like the above should work for Oracle ... you might have to get the syntax right first!


q: Any ideas how to determine the number of active threads currently running in an ExecutorService?

[A]
Use a
ThreadPoolExecutor
implementation and call
getActiveCount()
on it:
```
```
int getActiveCount()
// Returns the approximate number of threads that are actively executing tasks.
```
```
The ExecutorService interface does not provide a method for that, it depends on the implementation.


q:
I've been doing some work with the JAX-RS reference implementation (Jersey).
I know of at least two other frameworks (Restlet & Apache CXF).

My question is: Has anyone done some comparison between those frameworks and if so, which framework would you recommend and why?

[A]
My colleague mentions why we are using RESTeasy for our current project in
RESTful web services in Java EE with RESTeasy (JAX-RS)
:
Its reference implementation, Jersey, was not chosen because we had trouble integrating it well with EJB3 and Seam 2.0.
We are using the RESTeasy implementation of JAX-RS, because we had no trouble integrating it with our EJBs and Seam. It also has sufficient documentation.
There is another implementation from Apache, but I haven’t tried it because it uses an older version of JAX-RS.
Finally there is yet another framework for RESTful web services for Java called Restlet but we did not favour it because at the time of this writing, it is using a custom architecture, even though proper JAX-RS support is in the works.


q:
I've been wondering, is there a performance difference between using named functions and anonymous functions in Javascript?

for (var i = 0; i < 1000; ++i) {
    myObjects[i].onMyEvent = function() {
        // do something
    };
}

vs

function myEventHandler() {
    // do something
}

for (var i = 0; i < 1000; ++i) {
    myObjects[i].onMyEvent = myEventHandler;
}

The first is tidier since it doesn't clutter up your code with rarely-used functions, but does it matter that you're re-declaring that function multiple times?

[A]
As a general design principle, you should avoid implimenting the same code multiple times. Instead you should lift common code out into a function and execute that (general, well tested, easy to modify) function from multiple places.
If (unlike what you infer from your question) you are declaring the internal function once and using that code once (and have nothing else identical in your program) then an anonomous function
probably
(thats a guess folks) gets treated the same way by the compiler as a normal named function.
Its a very useful feature in specific instances, but shouldn't be used in many situations.


q:
On a file path field, I want to capture the directory path like:

textbox1.Text = directory path

Anyone?

[A]
There is a FolderBrowserDialog class that you can use if you want the user to select a folder.
http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx
```
```
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result.Equals(get_DialogResult().OK)) {
    textbox1.Text = folderBrowserDialog1.get_SelectedPath();
}
```
```
If all you want is to get the direcotory from a full path, you can do this:
```
```
textbox1.Text = Path.GetDirectoryName(@"c:\windows\temp\myfile.txt");
```
```
This will set the Text-property to "c:\windows\temp\"


q:
I have an Access 2007 form that is searchable by a combobox.  When I add a new record, I need to update the combobox to include the newly added item.

I assume that something needs to be done in AfterInsert event of the form but I can't figure out what.

How can I rebind the combobox after inserting so that the new item appears in the list?

[A]
I assume your combobox is a control on a form, not a combobox control in a commandBar. This combobox has a property called rowsource, that can be either a value list (husband;wife;son;girl) or a SQL SELECT instruction (SELECT relationDescription FROM Table_relationType).
I assume also that your form recordset has something to do with your combobox recordset. What you'll have to do is, once your form recordset is
properly updated
(afterUpdate event I think), to reinitialise the rowsource property of the combobox control
if the recordsource is an SQL instruction:
```
```
myComboBoxControl.recordsource = _
    "SELECT relationDescription FROM Table_relationType"
```
```
or if it is a value list
```
```
myComboBoxControl.recordsource = myComboBoxControl.recordsource & ";nephew"
```
```
But over all I find your request very strange. Do you have a reflexive (parent-child) relationship on your table?


q:
As the local subversion czar i explain to everyone to keep only source code and non-huge text files in the repository, not huge binary data files.  Smaller binary files that are parts of tests, maybe.

Unfortunately i work with humans!  Someone is likely to someday accidentally commit a 800MB binary hulk. This slows down repository operations.

Last time i checked, you can't delete a file from the repository; only make it not part of the latest revision.  The repository keeps the monster for all eternity, in case anyone ever wants to recall the state of the repository for that date or revision number.

Is there a way to really delete that monster file  and end up with a decent sized repository?   I've tried the svnadmin dump/load thing but it was a pain.

[A]
To permanently delete monster files from a svn repository, there is no other solution than using svnadmin dump/load. (
SVN Book: dump command
)
To prevent huge files from being committed, a hook script can be used. You could have, for example, a script that ran "pre-commit" whenever someone tried to commit to the repository. The script might check filesize, or filetype, and reject the commit if it contained a file or files that were too large, or of a "forbidden" type.
More typical uses of hook scripts are to check (pre-commit) that a commit contains a log message, or (post-commit) to email details of the commit or to update a website with the newly committed files.
A hook script is a script that runs in response to response to repository events (
SVN Book: Create hooks
).


q:
I am trying to use Zend_Db_Select to write a select query that looks somewhat like this:

SELECT * FROM bar WHERE a = 1 AND (b = 2 OR b = 3)

However, when using a combination of where() and orWhere(), it seems impossible to use condition grouping like the above.

Are there any native ways in Zend Framework to achieve the above (without writing the actual query?)

[A]
From
the manual
(Example 11.61. Example of parenthesizing Boolean expressions)
```
```
// Build this query:
//   SELECT product_id, product_name, price
//   FROM "products"
//   WHERE (price < 100.00 OR price > 500.00)
//     AND (product_name = 'Apple')

$minimumPrice = 100;
$maximumPrice = 500;
$prod = 'Apple';

$select = $db->select()
             ->from('products',
                    array('product_id', 'product_name', 'price'))
             ->where("price < $minimumPrice OR price > $maximumPrice")
             ->where('product_name = ?', $prod);
```
```


q:
I'm writing a Rails application which will monitor data quality over some specific databases. In order to do that, I need to be able to execute direct SQL queries over these databases - which of course are not the same as the one used to drive the Rails application models. In short, this means I can't use the trick of going through the ActiveRecord base connection.

The databases I need to connect to are not known at design time (i.e.: I can't put their details in database.yaml). Rather, I have a model 'database_details' which the user will use to enter the details of the databases over which the application will execute queries at runtime.

So the connection to these databases really is dynamic and the details are resolved at runtime only.

[A]
You may be able to do this through
```
self.establish_connection
```
.


q:
I am seeing strange behaviour with the flash.media.Sound class in Flex 3.

var sound:Sound = new Sound();
try{
sound.load(new URLRequest("directory/file.mp3"))
} catch(e:IOError){
 ...
}

However this isn't helping. I'm getting a stream error, and it actually sees to be in the Sound constructor.

Error #2044: Unhandled IOErrorEvent:.
  text=Error #2032: Stream Error.   at... ]

I saw one example in the Flex docs where they add an event listener for IOErrorEvent, SURELY I don't have to do this, and can simply use try-catch? Can I set a null event listener?

[A]
You will need to add a listener since the URLRequest is not instantaneous. It will be
very
fast if you're loading from disk, but you will still need the Event-listener.
There's a good example of how to set this up (Complete with IOErrorEvent handling) in the
livedocs
.


q:
I am trying to write some JavaScript RegEx to replace user inputed tags with real html tags, so [b] will become <b> and so forth. the RegEx I am using looks like so

var exptags = /\[(b|u|i|s|center|code){1}]((.){1,}?)\[\/(\1){1}]/ig;

with the following JavaScript

s.replace(exptags,"<$1>$2</$1>");

this works fine for single nested tags, for example:

[b]hello[/b] [u]world[/u]

but if the tags are nested inside each other it will only match the outer tags, for example

[b]foo [u]to the[/u] bar[/b]

this will only match the b tags. how can I fix this? should i just loop until the starting string is the same as the outcome? I have a feeling that the ((.){1,}?) patten is wrong also?

Thanks

[A]
AFAIK you can't express recursion with regular expressions.
You can however do that with .NET's System.Text.RegularExpressions using balanced matching. See more here:
http://blogs.msdn.com/bclteam/archive/2005/03/15/396452.aspx
If you're using .NET you can probably implement what you need with a callback.
If not, you may have to roll your own little javascript parser.
Then again, if you can afford to hit the server you can use the full parser. :)
What do you need this for, anyway? If it is for anything other than a preview I highly recommend doing the processing server-side.


q:
As you can see, even after the program should have died it speaks from the grave. Is there a way to "deregister" the exitfunction in case of exceptions?

import atexit

def helloworld():
    print("Hello World!")

atexit.register(helloworld)

raise Exception("Good bye cruel world!")

outputs

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    raise Exception("Good bye cruel world!")
Exception: Good bye cruel world!
Hello World!

[A]
If you call
```
```
import os
os._exit(0)
```
```
the exit handlers will not be called, yours or those registered by other modules in the application.


q:
In the KornShell (ksh) on AIX UNIX Version 5.3 with the editor mode set to vi using:

set -o vi

What are the key-strokes at the shell command line to autocomplete a file or directory name?

[A]
ESC\ works fine on AIX4.2 at least.  One thing I noticed is that it only autocompletes to the unique part of the file name.
So if you have the files x.txt, x171go and x171stop, the following will happen:
```
```
Press keys:           Command line is:
x                     x
<ESC>\                x
1                     x1
<ESC>\                x171
g<ESC>\               x171go
```
```


q:
What free and commercial garbage collection libraries are available for C++, and what are the pros and cons of each?

I am interested in hard-won lessons from actual use in the field, not marketing or promotional blurb.

There is no need to elaborate on the usual trade offs associated with automatic garbage collection, but please do mention the algorithms used (reference counting, mark and sweep, incremental, etc.) and briefly summarise the consequences.

[A]
The Boehm garbage collector
is freely available, and supposedly rather good (no first hand experience myself)
Theoretical paper (in PDF) about
C++0x proposal for the Boehm garbage collector
It was originally said to make C++0x
, but will not make it after all
(due to time constraints I suppose).
Proprosal N2670
(minimal support for garbage collectors) did get approved in june 2008 though, so as compiler implementations pick up on this, and the standard gets finalised, the garbage collection world out there for C++ is sure to change...


q:
Possible Duplicate:

  How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?

I'd like to have multiple global hotkeys in my new app (to control the app from anywhere in windows), and all of the given sources/solutions I found on the web seem to provide with a sort of a limping solution (either solutions only for one g.hotkey, or solutions that while running create annoying mouse delays on the screen).

Does anyone here know of a resource that can help me achive this, that I can learn from?
Anything?

Thanks !  :)

[A]
http://www.codeproject.com/KB/cs/CSLLKeyboardHook.aspx
If you're not using .net 3.5.


q: What is the best, preferably free/open source tool for auto-generating Java unit-tests? I know, the unit-tests cannot really serve the same purpose as normal TDD Unit-Tests which document and drive the design of the system. However auto-generated unit-tests can be useful if you have a huge legacy codebase and want to know whether the changes you are required to make will have unwanted, obscure side-effects.

[A]
To be honest, I probably wouldn't do this.  Unit tests are isolated and you won't actually know if you have "unwanted, obscure side-effects" because everything is walled off from the other things that cause the side effects.  As a result, you need integration or system testing and
that
is not something you can automate.
Build a few high-level, end-to-end system tests which give you a degree of confidence and then use coverage testing to find out what you've missed,  The downside is that when bugs crop up, it will be harder to point to their exact cause, but the upside is that you'll be far more likely to see the bugs.
Once you find bugs, write unit tests just for them.  As you move forward, you can use TDD for the bits you want to refactor.
I know this probably wasn't the answer you want to hear, but I've been testing for many, many years and this is a solid approach (though I would hardly call it the only approach :)


q: Which built in (if any) tool can I use to determine the allocation unit size of a certain NTFS partition ?

[A]
Open an administrator command prompt, and do this command:
```
```
fsutil fsinfo ntfsinfo [your drive]
```
```
The Bytes Per Cluster is the equivalent of the allocation unit.


q:
I know the combination Ctrl+A to jump to the beginning of the current command, and Ctrl+E to jump to the end.

But is there any way to jump word by word, like Alt+←/→ in Cocoa applications does?

[A]
Here's how you can do it
By default, the Terminal has these shortcuts to move (left and right) word-by-word:
esc
+
B
(left)
esc
+
F
(right)
You can configure
alt
+
←
and
→
to generate those sequences for you:
Open Terminal preferences (
cmd
+
,
);
At Settings tab, select Keyboard and double-click
```
⌥ ←
```
if it's there, or add it if it's not.
Set the modifier as desired, and type the shortcut key in the box:
esc
+
B
, generating the text
```
\033b
```
(you can't type this text manually).
Repeat for word-right (
esc
+
F
becomes
```
\033f
```
)
Alternatively, you can refer to this blog post over at textmate:
http://blog.macromates.com/2006/word-movement-in-terminal/


q:
The question says it all basically.

I want in a

class MyClass

to listen to a routed event. Can it be done ?

[A]
If you can create an
inner
class of MyClass (call it MyInnerClass) that derives from FrameworkElement while retaining the capability to access an enclosing MyClass object, your problem will be solved. You can then implement a 'getListener' method within MyClass that returns the embedded MyInnerClass that you will use to actually listen to events.


q: How do people usually detect the MIME type of an uploaded file using ASP.NET?

[A]
in the aspx page:
```
```
<asp:FileUpload ID="FileUpload1" runat="server" />
```
```
in the codebehind (c#):
```
```
string contentType = FileUpload1.PostedFile.ContentType
```
```


q:
I re-image one of my machines regularly; and have a script that I run after the OS install completes to configure my machine; such that it works how I like.

I happen to have my data on another drive...and I'd like to add code to my script to change the location of the Documents directory from "C:\Users\bryansh\Documents" to "D:\Users\bryansh\Documents".

Does anybody have any insight, before I fire up regmon and really roll up my sleeves?


q:
struct foo { unsigned x:1; } f;
printf("%d\n", (int)sizeof(f.x = 1));

What is the expected output and why?  Taking the size of a bitfield lvalue directly isn't allowed. But by using the assignment operator, it seems we can still take the size of a bitfield type.

What is the "size of a bitfield in bytes"?  Is it the size of the storage unit holding the bitfield?  Is it the number of bits taken up by the bf rounded up to the nearest byte count?

Or is the construct undefined behavior because there is nothing in the standard that answers the above questions?  Multiple compilers on the same platform are giving me inconsistent results.

[A]
Wouldn't
```
```
(f.x = 1)
```
```
be an expression evaluating to true (technically in evaluates to result of the assignment, which is 1/true in this case), and thus,
```
```
sizeof( f.x = 1)
```
```
is asking for the size of true in terms of how many chars it would take to store it?
I should also add that the Wikipedia article on
sizeof
is nice.  In particular, they say "sizeof is a compile-time operator that returns the size, in multiples of the size of char, of the variable or parenthesized type-specifier that it precedes."
The article also explains that sizeof works on expressions.


q:
Is there a way to change the encoding used by the String(byte[]) constructor ?

In my own code I use String(byte[],String) to specify the encoding but I am using an external library that I cannot change.

String src = "with accents: é à";
byte[] bytes = src.getBytes("UTF-8");
System.out.println("UTF-8 decoded: "+new String(bytes,"UTF-8"));
System.out.println("Default decoded: "+new String(bytes));

The output for this is :

UTF-8 decoded: with accents: é à
Default decoded: with accents: Ã© Ã

I have tried changing the system property file.encoding but it does not work.

[A]
Quoted from
defaultCharset()
The default charset is determined
  during virtual-machine startup and
  typically depends upon the locale and
  charset of the underlying operating
  system.
In most OSes you can set the charset using a environment variable.


q: What do you think of Quagga compared to XORP as a dynamic software routing engine? What are the technical merits of each engine comparatively? Additionally, what do most people think of them from a programming view. Who has manipulated networks using these enginers? I was wondering from an OSPF, routing, BGP protocol user's perpspective.

[A]
What do you think of Quagga compared to XORP as a dynamic software routing engine?
It is one of many options, but not particularly of very much use to you based upon your questions/information that you posted here. Have you tried looking into some of the alternatives such as (nothing comes to  mind)?
What are the technical merits of each engine comparatively?
Small, fast, oddly placed, optimized, super-heroic and more filler for a resume.
Additionally, what do most people think of them from a programming view.
I can't speak for most people, but I for myself do not give it much credit or merit, or well... you know what I mean.
Who has manipulated networks using these enginers?
I could not find specific references, but I do remember reading that both Disney and the 'famous' YUV corporation of South Africa both played with this notion before. I believe Disney abandoned it with the fall of Michael Eisner.
I was wondering from an OSPF, routing, BGP protocol user's perpspective.
I am a BGP protocol user's prospective. Hopefully we hear from OSPF and routing user's perspectives shortly.
Good question.


q: What are the private IP address ranges?

[A]
You will find the answers to this in
RFC 1918
. Though, I have listed them below for you.
```
```
10.0.0.0        -   10.255.255.255  (10/8 prefix)
 172.16.0.0      -   172.31.255.255  (172.16/12 prefix)
 192.168.0.0     -   192.168.255.255 (192.168/16 prefix)
```
```
It is a common misconception that 169.254.0.0/16 is a private IP address block. This is not true. It is link local, basically it is meant to be only used within networks, but it isn't official RFC1918. Additional information about IPv4 addresses can be found in
RFC 3300
.
On the other hand IPv6 doesn't have an equivalent to RFC1918, but any sort of site-local work should be done in fc00::/7. This is further touched on in
RFC 4193
.


q:
Currently I am using NetTiers to generate my data access layer and service layer. I have been using NetTiers for over 2 years and have found it to be very useful. At some point I need to look at LINQ so my questions are...

Has anyone else gone from NetTiers to LINQ To SQL?

Was this switch over a good or bad thing?

Is there anything that I should be aware of?

Would you recommend this switch?

Basically I would welcome any thoughts
.

[A]
NetTiers is very good for generating a heavy and robust DAL, and we use it internally for core libraries and frameworks.
As I see it, LINQ (in all its incarnations, but specifically as I think you're asking to SQL) is fantastic for quick data access, and we generally use it for more agile cases.
Both technologies are quite inflexible to change without regeneration of the code or dbml layer.
That being said, used properly LINQ 2 SQL is quite a robust solution, and you might even start using it for future development due to it's ease of use, but I wouldn't throw away your current DAL for it - if it aint broke ...


q:
If you declare variables of type byte or short and attempt to perform arithmetic operations on these, you receive the error "Type mismatch: cannot convert int to short" (or correspondingly "Type mismatch: cannot convert int to byte").

byte a = 23;
byte b = 34;
byte c = a + b;

In this example, the compile error is on the third line.

[A]
Although the arithmetic operators are defined to operate on any numeric type, according the Java language specification (5.6.2 Binary Numeric Promotion), operands of type byte and short are automatically promoted to int before being handed to the operators.
To perform arithmetic operations on variables of type byte or short, you must enclose the expression in parentheses (inside of which operations will be carried out as type int), and then cast the result back to the desired type.
```
byte a = 23;
byte b = 34;
byte c = (byte) (a + b);
```
Here's a follow-on question to the real Java gurus: why? The types byte and short are perfectly fine numeric types. Why does Java not allow direct arithmetic operations on these types? (The answer is not "loss of precision", as there is no apparent reason to convert to int in the first place.)
Update: jrudolph suggests that this behavior is based on the operations available in the JVM, specifically, that only full- and double-word operators are implemented. Hence, to operator on bytes and shorts, they must be converted to int.


q: I've got a site that provides blog-friendly widgets via JavaScript. These work fine in most circumstances, including self-hosted Wordpress blogs. With blogs hosted at Wordpress.com, however, JavaScript isn't allowed in sidebar text modules. Has anyone seen a workaround for this limitation?

[A]
you could always petition wp to add your widget to their 'approved' list, but who knows how long that would take. you're talking about a way to circumvent the rules they have in place about posting arbitrary script. myspace javascript exploits in particular have increased awareness of the possibility of such workarounds, so you might have a tough time getting around the restrictions - however, here's a classic ones to try:
put the javascript in a weird place, like anywhere that executes a URL. for instance:
```
```
<div style="background:url('javascript:alert(this);');" />
```
```
sometimes the word 'javascript' gets cut out, but occasionally you can sneak it through as java\nscript, or something similar.
sometimes quotes get stripped out - try String.fromCharCode(34) to get around that. Also, in general, using eval("codepart1" + "codepart2") to get around restricted words or characters.
sneaking in javascript is a tricky business, mostly utilizing unorthodox (possibly un-documented) browser behavior in order to execute arbitrary javascript on a page. Welcome to hacking.