q:
I have an Excel application in which I want to present the user with a list of the Data Source Names (ie: DSN's), whereby s/he can choose what data source to use.

Hopefully once I've got the list, I can easily access the DSN properties to connect to the appropriate database.

Please note, I do not want to use a DSN-less connection.

[A]
The DSN entries are stored in the registry in the following keys.
```
HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\ODBC Data Sources
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources
```
This contains the list of all defined DSN. This acts as an global index and the specific details for each DSN are stored in a key with the DSN name under:
```
HKEY_CURRENT_USER\Software\ODBC\ODBC.INI
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI
```
Create some entries in both User DSN and System DSN tabs from Data Sources (ODBC) control panel applet and check how these values are stored in the registry.
The following example enumerate the DSN defined for the user trough Control Panel > Administrative Tools > Data Sources (ODBC) [User Dsn Tab].
http://support.microsoft.com/kb/178755
```
```
Option Explicit

  Private Declare Function RegOpenKeyEx Lib "advapi32.dll" _
      Alias "RegOpenKeyExA" _
      (ByVal hKey As Long, _
      ByVal lpSubKey As String, _
      ByVal ulOptions As Long, _
      ByVal samDesired As Long, phkResult As Long) As Long

  Private Declare Function RegEnumValue Lib "advapi32.dll" _
      Alias "RegEnumValueA" _
      (ByVal hKey As Long, _
      ByVal dwIndex As Long, _
      ByVal lpValueName As String, _
      lpcbValueName As Long, _
      ByVal lpReserved As Long, _
      lpType As Long, _
      lpData As Any, _
      lpcbData As Long) As Long

  Private Declare Function RegCloseKey Lib "advapi32.dll" _
      (ByVal hKey As Long) As Long

  Const HKEY_CLASSES_ROOT = &H80000000
  Const HKEY_CURRENT_USER = &H80000001
  Const HKEY_LOCAL_MACHINE = &H80000002
  Const HKEY_USERS = &H80000003

  Const ERROR_SUCCESS = 0&

  Const SYNCHRONIZE = &H100000
  Const STANDARD_RIGHTS_READ = &H20000
  Const STANDARD_RIGHTS_WRITE = &H20000
  Const STANDARD_RIGHTS_EXECUTE = &H20000
  Const STANDARD_RIGHTS_REQUIRED = &HF0000
  Const STANDARD_RIGHTS_ALL = &H1F0000
  Const KEY_QUERY_VALUE = &H1
  Const KEY_SET_VALUE = &H2
  Const KEY_CREATE_SUB_KEY = &H4
  Const KEY_ENUMERATE_SUB_KEYS = &H8
  Const KEY_NOTIFY = &H10
  Const KEY_CREATE_LINK = &H20
  Const KEY_READ = ((STANDARD_RIGHTS_READ Or _
                    KEY_QUERY_VALUE Or _
                    KEY_ENUMERATE_SUB_KEYS Or _
                    KEY_NOTIFY) And _
                    (Not SYNCHRONIZE))

  Const REG_DWORD = 4
  Const REG_BINARY = 3
  Const REG_SZ = 1

  Private Sub Command1_Click()
     Dim lngKeyHandle As Long
     Dim lngResult As Long
     Dim lngCurIdx As Long
     Dim strValue As String
     Dim lngValueLen As Long
     Dim lngData As Long
     Dim lngDataLen As Long
     Dim strResult As String

     lngResult = RegOpenKeyEx(HKEY_CURRENT_USER, _
             "SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources", _
              0&, _
              KEY_READ, _
              lngKeyHandle)

     If lngResult <> ERROR_SUCCESS Then
         MsgBox "Cannot open key"
         Exit Sub
     End If

     lngCurIdx = 0
     Do
        lngValueLen = 2000
        strValue = String(lngValueLen, 0)
        lngDataLen = 2000

        lngResult = RegEnumValue(lngKeyHandle, _
                                 lngCurIdx, _
                                 ByVal strValue, _
                                 lngValueLen, _
                                 0&, _
                                 REG_DWORD, _
                                 ByVal lngData, _
                                 lngDataLen)
        lngCurIdx = lngCurIdx + 1

        If lngResult = ERROR_SUCCESS Then
           strResult = strResult & lngCurIdx & ": " & Left(strValue, lngValueLen) & vbCrLf
        End If
     Loop While lngResult = ERROR_SUCCESS
     Call RegCloseKey(lngKeyHandle)

     Call MsgBox(strResult, vbInformation)
  End Sub
```
```


q:
I'm after a regex that will validate a full complex UK postcode only within an input string. All of the uncommon postcode forms must be covered as well as the usual. For instance:

Matches

CW3 9SS

SE5 0EG

SE50EG

se5 0eg

WC2H 7LT

No Match

aWC2H 7LT

WC2H 7LTa

WC2H

How do I solve this problem?

[A]
```
```
^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$
```
```
Regular expression to match valid UK
  postcodes. In the UK postal system not
  all letters are used in all positions
  (the same with vehicle registration
  plates) and there are various rules to
  govern this. This regex takes into
  account those rules. Details of the
  rules: First half of postcode Valid
  formats [A-Z][A-Z][0-9][A-Z]
  [A-Z][A-Z][0-9][0-9] [A-Z][0-9][0-9]
  [A-Z][A-Z][0-9] [A-Z][A-Z][A-Z]
  [A-Z][0-9][A-Z] [A-Z][0-9] Exceptions
  Position - First. Contraint - QVX not
  used Position - Second. Contraint -
  IJZ not used except in GIR 0AA
  Position - Third. Constraint -
  AEHMNPRTVXY only used Position -
  Forth. Contraint - ABEHMNPRVWXY Second
  half of postcode Valid formats
  [0-9][A-Z][A-Z] Exceptions Position -
  Second and Third. Contraint - CIKMOV
  not used
http://regexlib.com/REDetails.aspx?regexp_id=260

s: huggingface

c: devops

d: intermediate


q:
I need a simple table with a user name and password field in MySQL. Since user names must be unique, it makes sense to me to make them the primary key.

Is it better to use CHAR() or VARCHAR() as a primary key?

[A]
may as well just use a user ID index, it's much faster for joins vs char/varchar. the two seconds it takes to add that now could save you a lot of time later if you accidently have to expand the functionality of your schema.
some pitfalls to think about:
say we add a few tables at a future date, what if someone wants to change a username?
say the app is more successful then we think, and we have to look at optimization, do you really want to redo your schema at this point to reduce the overhead of a varchar'ed index?


q:
Using C# in Visual Studio 2008 and stepping through a function in the debugger I get to the end of a function and am on the final curly brace } and about to return. Is there a way to find out what value the function is about to return?

This is necessary if the return value is calculated such as:

return (x.Func() > y.Func());

[A]
You can put
```
```
(x.Func() > y.Func())
```
```
in a watch window to evaluate it, and see the result.  Unless the statement is
```
```
return ValueChangesAfterEveryCall();
```
```
you should be fine.


q:
I would like to upgrade my web projects on an IIS 5 server from .NET 2.0 to .NET 3.5.  These web applications live on a server with other web applications that will not be upgraded to .NET 3.5.  The server administrator is reluctant to install .NET 3.5 because he is afraid it will break the applications on that machine that are running 2.0 and 1.1.

As far as I know this WON'T be a problem since .NET 3.5 is an addition to 2.0 more than it is a new Framework.  I would like the communities help gathering evidence to show him that their concerns are moot and it won't hurt the other applications.

Thanks in advance.

[A] It won't have any problem and you will be able to run your 2.0 and 3.5 application using the same server. This is because the code base for both of the frameworks is the same.


q:
Does anyone happen to know if there is a token I can add to my csv for a certain field so Excel doesn't try to convert it to a date?

I'm trying to write a .csv file from my application and one of the values happens to look enough like a date that Excel is automatically converting it from text to a date.  I've tried putting all of my text fields (including the one that looks like a date) within double quotes, but that has no effect.

[A]
If you put an inverted comma at the start of the field, it will be interpreted as text.
Example:
```
25/12/2008
```
becomes
```
'25/12/2008
```
You are also able to select the field type when importing.


q:
This is an excerpt of code from a class I am working with in Java (below). Obviously the code is defining a static variable named EPSILON with the data type double. What I don't understand is the "1E-14" part. What kind of number is that? What does it mean?

final double EPSILON = 1E-14;


q:
Anyone knows of a good error log beautifier? (should be able to handle apache error logs).

Should be open source / free, preferably with a web interface

[A]
I use
http://www.librelogiciel.com/software/ScanErrLog/action_Presentation
It runs through the error log producing a summary webpage, or some other formats.  While it's best run from a regular cron-job (and it will keep a record of what it's parsed before to save effort), it can also be run as a CGI (though the demo appears to be broken).


q:
I'm hand-maintaining an HTML document, and I'm looking for a way to automatically insert a link around text in a table. Let me illustrate:

<table><tr><td class="case">123456</td></tr></table>

I would like to automatically make every text in a TD with class "case" a link to that case in our bug tracking system (which, incidentally, is FogBugz).

So I'd like that "123456" to be changed to a link of this form:

<a href="http://bugs.example.com/fogbugz/default.php?123456">123456</a>

Is that possible? I've played with the :before and :after pseudo-elements, but there doesn't seem to be a way to repeat the case number.

[A]
Not in a manner that will work across browsers. You could, however, do that with some relatively trivial Javascript..
```
```
function makeCasesClickable(){
    var cells = document.getElementsByTagName('td')
    for (var i = 0, cell; cell = cells[i]; i++){
        if (cell.className != 'case') continue
        var caseId = cell.innerHTML
        cell.innerHTML = ''
        var link = document.createElement('a')
        link.href = 'http://bugs.example.com/fogbugz/default.php?' + caseId
        link.appendChild(document.createTextNode(caseId))
        cell.appendChild(link)
    }
}
```
```
You can apply it with something like
```
onload = makeCasesClickable
```
, or simply include it right at the end of the page.


q:
The following code:

template <typename S, typename T>
struct foo {
   void bar();
};

template <typename T>
void foo <int, T>::bar() {
}

gives me the error

invalid use of incomplete type 'struct foo<int, T>'
declaration of 'struct foo<int, T>'

(I'm using gcc.) Is my syntax for partial specialization wrong? Note that if I remove the second argument:

template <typename S>
struct foo {
   void bar();
};

template <>
void foo <int>::bar() {
}

then it compiles correctly.

[A]
You can't partially specialize a function. If you wish to do so on a member function, you must partially specialize the entire template (yes, it's irritating). On a large templated class, to partially specialize a function, you would need a workaround. Perhaps a templated member struct (e.g.
```
template <typename U = T> struct Nested
```
) would work. Or else you can try deriving from another template that partially specializes (works if you use the
```
this->member
```
notation, otherwise you will encounter compiler errors).


q:
What's wrong with Linq to SQL?

Or - what about Linq to SQL would make it unsuitable for a project, either new or existing? I want to hear about why you would not choose Linq to SQL for a particular project - including what project parameters make it unsuitable.

[A]
Well, I have developed some applications using LINQ to SQL. One of the main problems that I find is having to layer your application. In LINQ to SQL the entity classes are tied very closely with the data access code. Also, there are some issues with DataContext which means that you can use a DataContext object to retrieve an item but you cannot transfer the item (object) to another DataContext (at least not easily).
LINQ to SQL will be useful if you don't care about layering your application properly and also if all you wanted is to create an application in a rapid manner also know as RAPID Application Development.


q:
I work with a lot of offsite developers and contractors. I ask them daily to send me a quick 5 minute status of their work for the day. I have to sometimes consolidate the status of individuals into teams and sometimes consolidate the status of a week, for end-of-period reporting to my clients.

I want to learn:

Items accomplished and how much time was spent on each

Problems encountered and how much time was spent on each

Items that will be worked on next, their estimates (in man hours) and their target dates

Questions they have on the work

I'm looking for a format that will provide this information while:

Being quick for the developers to complete (5-10 minutes, without thinking too much)

Easy for me to read and browse quickly

Is uniform for each developer

What would you suggest?

[A]
Just give them a template laid out in a format that you expect to see the data returned in.  You may also consider increasing the time they are going to devote to this and removing the "not thinking too much" clause if you are requiring estimates for future work. I wouldn't trust an estimate that someone came up with in 5 mins. without thinking.
If you are currently using any project management software, it should be trivial for the developers to record and review (or even just remember) what they have done compile it for you.  Ideally they would be recording issues or questions throughout the day and not trying to come up with them just to fill in the report.
It seems like your "I want to learn" list is an excellent starting point to generate a template from. Only you will know what the perfect format for you is.


q:
I read in this article  that a company has created a software capable of using multiple GPU-based video cards in parallel to process hundreds of billions fixed-point calculations per second.

The program seems to run in Windows. Is it possible from Windows to assign a thread to a GPU? Do they create their own driver and then interact with it? Any idea of how they do it?

[A]
I imagine that they are using a language like
CUDA
to program the critical sections of code on the GPUs to accelerate their computation.
The main function for the program (and its threads) would still run on the host CPU, but data are shipped off the the GPUs for processing of advanced algorithms.  CUDA is an extension to C syntax, so it makes it easier to programmer than having to learn the older shader languages like
Cg
for programming general purpose calculations on a GPU.


q: Does SubSonic.SqlQuery have a between/and for date ranges?  If not, what would be the best way to get a range.

[A]
Try something like this:
```
```
SqlQuery query = new SqlQuery().From("Table")
                               .WhereExpression("Column")
                               .IsBetweenAnd("1/1/2008", "12/31/2008");
DataSet dataSet = query.ExecuteDataSet();  // Or whatever output you need
```
```


q:
In mysql, how do I get the primary key used for an insert operation, when it is autoincrementing.

Basically, i want the new autoincremented value to be returned when the statement completes.

Thanks!

[A]
MySQL's
LAST_INSERT_ID()


q:
I want to display dates in the format: short day of week, short month, day of month without leading zero but including "th", "st", "nd", or "rd" suffix.

For example, the day this question was asked would display "Thu Oct 2nd".

I'm using Ruby 1.8.7, and Time.strftime just doesn't seem to do this.  I'd prefer a standard library if one exists.

[A]
You can use active_support's ordinalize helper method on numbers.
```
```
>> 3.ordinalize
=> "3rd"
>> 2.ordinalize
=> "2nd"
>> 1.ordinalize
=> "1st"
```
```


q:
I'm failing to understand exactly what the IF statement is doing, from what I can see it is checking if the variable x is equal to the int 0. If this is true the ABSOLUTE value of the variable y is returned... this is when I lose the plot, why would the return statement then go on to include <= ESPILON? Surely this means less than or equal to the value of epsilon? if so how is that working? If it doesn't mean that then what does it mean?

(JAVA CODE)

final double EPSILON = 1E-14;
if (x == 0)
    return Math.abs(y) <= EPSILON;

[A]
It returns true if the absolute value of y is <= EPSILON, and false otherwise. The <= is evaluated before the return statement. This code is equivalent:
```
```
if(x == 0)
{
   boolean ret = Math.abs(y) <= EPSILON;
   return ret;
}
```
```
The code isn't simply read from left to right. A simpler example is
```
```
int x = 3 + 4 * 5;
```
```
After evaluating this, x is 23, not 35. The evaluation is 3 + (4*5), not (3+4)*5, because the * has a higher precedence than the +. The return statement in the original example has a very low precedence. All operators like +, -, <, >= are evaluated before it.


q:
I have some c(++) code that uses sprintf to convert a uint_64 to a string.  This needs to be portable to both linux and Solaris.

On linux we use %ju, but there does not appear to be any equivalent on Solaris.  The closest I can find is %lu, but this produces incorrect output.  Some sample code:

#include <stdio.h>
#include <sys/types.h>

#ifdef SunOS
typedef uint64_t u_int64_t;
#endif

int main(int argc, char **argv) {
    u_int64_t val = 123456789123L;

#ifdef SunOS
    printf("%lu\n", val);
#else
    printf("%ju\n", val);
#endif
}

On linux, the output is as expected; on Solaris 9 (don't ask), it's "28"

What can I use?

[A]
You can use
```
%llu
```
for long long. However, this is not very portable either, because
```
long long
```
isn't guaranteed to be 64 bits. :-)


q:
How can I check the umask of a program which is currently running?

[update: another process, not the current process.]

[A]
If you're the current process, you can write a file to /tmp and check its setting.  A better solution is to call umask(3) passing zero - the function returns the setting prior to the call - and then reset it back by passing that value back into umask.
The umask for another process doesn't seem to be exposed.


q:
Although I played with it before, I'm finally starting to use Dvorak (Simplified) regularly. I've been in a steady relationship with Vim for several years now, and I'm trying to figure out the best way to remap the key bindings to suit my newfound Dvorak skills.

How do you remap Vim's key bindings to best work with Dvorak?

Explanations encouraged!

[A]
I use one of the more
common recommended keybindings
:
```
```
Dvorak it!
no d h
no h j
no t k
no n l
no s :
no S :
no j d
no l n
no L N
Added benefits
no - $
no _ ^
no N <C-w><C-w>
no T <C-w><C-r>
no H 8<Down>
no T 8<Up>
no D <C-w><C-r>
```
```
Movement keys stay in the same location.  Other changes:
Delete 'd' -> Junk 'j'
Next 'n' -> Look 'l'
Previous 'N' -> Look Back 'L'
There were also some changes for familiarity, 's'/'S' can be used to access command mode (the old location of the :, which still works).
Added Benefits
End of line '$' -also- '-'
Beginning of line '^' -also- '_'
Move up 8 'T'
Move down 8 'H'
Next window
```
<C-w><C-w>
```
-also- 'N'
Swap windows
```
<C-w><C-r>
```
-also- 'D'
-Adam


q:
If I load the nextimg URL manually in the browser, it gives a new picture every time I reload. But this bit of code shows the same image every iteration of draw().

How can I force myimg not to be cached?

<html>
  <head>
    <script type="text/javascript">
      function draw(){
        var canvas = document.getElementById('canv');
        var ctx = canvas.getContext('2d');
        var rx;
        var ry;
        var i;

        myimg = new Image();
        myimg.src = 'http://ohm:8080/cgi-bin/nextimg'

        rx=Math.floor(Math.random()*100)*10
        ry=Math.floor(Math.random()*100)*10
        ctx.drawImage(myimg,rx,ry);
        window.setTimeout('draw()',0);
      }
    </script>
  </head>
  <body onload="draw();">
    <canvas id="canv" width="1024" height="1024"></canvas>
  </body>
</html>

[A]
The easiest way is to sling an ever-changing querystring onto the end:
```
```
var url = 'http://.../?' + escape(new Date())
```
```
Some people prefer using
```
Math.random()
```
for that instead of
```
escape(new Date())
```
. But the correct way is probably to alter the headers the web server sends to disallow caching.


q:
From the MSDN article on STAThread:

Indicates that the COM threading model for an application is single-threaded apartment (STA).

(For reference, that's the entire article.)

Single-threaded apartment... OK, that went over my head. Also, I read somewhere that unless your application uses COM interop, this attribute actually does nothing at all. So what exactly does it do, and how does it affect multithreaded applications? Should multithreaded applications (which includes anything from anyone using Timers to asynchronous method calls, not just threadpools and the like) use MTAThread, even if it's 'just to be safe'? What does STAThread and MTAThread actually do?

[A]
What that does it it ensures that
```
CoInitialize
```
is called specifying COINIT_APARTMENTTHREADED as the parameter. If you do not use any COM components or ActiveX controls it will have no effect on you at all. If you do then it's kind of crucial.
Controls that are apartment threaded are effectively single threaded, calls made to them can only be processed in the apartment that they were created in.
Some more detail from MSDN:
Objects created in a single-threaded
  apartment (STA) receive method calls
  only from their apartment's thread, so
  calls are serialized and arrive only
  at message-queue boundaries (when the
  Win32 function PeekMessage or
  SendMessage is called).
Objects created on a COM thread in a
  multithread apartment (MTA) must be
  able to receive method calls from
  other threads at any time. You would
  typically implement some form of
  concurrency control in a multithreaded
  object's code using Win32
  synchronization primitives such as
  critical sections, semaphores, or
  mutexes to help protect the object's
  data.
When an object that is configured to
  run in the neutral threaded apartment
  (NTA) is called by a thread that is in
  either an STA or the MTA, that thread
  transfers to the NTA. If this thread
  subsequently calls CoInitializeEx, the
  call fails and returns
  RPC_E_CHANGED_MODE.


q:
I'm trying to produce just the day number in a WPF text block, without leading zeroes and without extra space padding (which throws off the layout). The first produces the day number with a space, the second produces the entire date. According to the docs, 'd' should produce the day (1-31).

string.Format("{0:d }", DateTime.Today);
string.Format("{0:d}", DateTime.Today);

UPDATE:Adding % is indeed the trick. Appropriate docs here.

[A]
See
here
d, %d
The day of the month. Single-digit days do not have a leading zero. The application specifies "%d" if the format pattern is not combined with other format patterns.
Otherwise d is interpreted as:
d - 'ShortDatePattern'
PS. For messing around with format strings, using
LinqPad
is invaluable.


q:
I am having fickle of problem in Oracle 9i

select 1"FirstColumn" from dual;

Oracle throwing error while executing above query. ORA-03001: unimplemented feature in my Production server.

The Same query is working fine in my Validation server. Both servers are with Oracle 9i

Any one have Idea what's wrong...? Is this something configurable item in Oracle server.

[A] What is the full Oracle version on both servers?  9i is a marketing label-- are you comparing a 9.0.1.x database to a 9.2.0.x database?


q:
I'm looking for a way to validate the SQL schema on a production DB after updating an application version. If the application does not match the DB schema version, there should be a way to warn the user and list the changes needed.

Is there a tool or a framework (to use programatically) with built-in features to do that?
Or is there some simple algorithm to run this comparison?

Update: Red gate lists "from $395". Anything free? Or more foolproof than just keeping the version number?

[A]
Make a table and store your version number in there. Just make sure you update it as necessary.
```
```
CREATE TABLE version (
    version VARCHAR(255) NOT NULL
)
INSERT INTO version VALUES ('v1.0');
```
```
You can then check the version number stored in the database matches the application code during your app's setup or wherever is convenient.


q:
I need help on this following aspx code

aspx Code:

<asp:Label ID ="lblName" runat ="server" Text ="Name"></asp:Label>
<asp:TextBox ID ="txtName" runat ="server"></asp:TextBox>

Consider this is my aspx page content. I am going to populate the values for the TextBox only after the postback from server. But the label is also posting to the server (runat="server") even though it's not necessary. Should I write my code like this to save time from server with less load.

Corrected Code:

<label id ="lblNames">Name</label>
<asp:TextBox ID ="txtName" runat ="server"></asp:TextBox>

Only my server control will send to the server for postback and not my HTML control which has a static value.

Please suggest whether this is the correct way of coding.

[A]
If you take the
```
runat='server'
```
out of the
```
<label>
```
element then it won't be parsed as a server control. If you're not going to do anything with
```
lblNames
```
from the server then it is perfectly okay to leave it out.


q:
I have a "span" element inside a "table" "td" element.  The span tag has a Title.

I want to get the title of that span tag and pull it out to make it the "mouseover" tip for the "td" element.

For example:

I want to turn this:

<td>
    <a href="#"><span id="test" title="Acres for each province">Acres</span></a>
</td>

Into this:

<td onmouseover="tip(Acres for each province)">
    <a href="#"><span id="test">Acres</span></a>
</td>

EDIT: I don't think you guys understand.  I am trying to put the onmouseover function into the "td" tag.  I am NOT trying to put it into the "span" tag.

[A]
something like:
```
```
$("span#test").mouseover( function () {
   tip($(this).attr("title"));
}
```
```


q: I have seen member functions programed both inside of the class they belong to and outside of the class with a function prototype inside of the class.  I have only ever programmed using the first method, but was wondering if it is better practice to use the other or just personal preference?

[A]
Assuming you mean C++, it is always better to define functions
outside
of the class, because if you put it inside the class, compiler may try to inline it, which is not always desirable:
Increase in code size (every object file that includes this header might end up with a copy of the function in their code).
Breaking binary compatibility when function definition changes.
Even with inline functions, it is
usually
better to put definitions outside the class to improve readability of class public interface, unless the function is a trivial accessor or some other one-liner.


q:
How can I detect mouse clicks regardless of the window the mouse is in?

Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out.

I found this on microsoft's site:
http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx

But I don't see how I can detect or pick up the notifications listed.

Tried using pygame's pygame.mouse.get_pos() function as follows:

import pygame
pygame.init()
while True:
    print pygame.mouse.get_pos()

This just returns 0,0.
I'm not familiar with pygame, is something missing?

In anycase I'd prefer a method without the need to install a 3rd party module.
(other than pywin32 http://sourceforge.net/projects/pywin32/ )

[A]
The windows way of doing it is to handle the
```
WM_LBUTTONDBLCLK
```
message.
For this to be sent, your window class needs to be created with the
```
CS_DBLCLKS
```
class style.
I'm afraid I don't know how to apply this in Python, but hopefully it might give you some hints.


q:
So i have a piece of assembly that needs to call a function with the fastcall calling convention on windows, but gcc doesn't (afaict) support it.  GCC does provide the regparm attribute but that expects the first 3 parameters to be passed in eax, edx and ecx, whereas fastcall expects the first two parameters to be passed in ecx and edx.

I'm merely trying to avoid effectively duplicating a few code paths, so this isn't exactly critical, but it would be great if it were avoidable.

[A]
If you're calling the function from asm then surely you have complete control over how you call the function. What's stopping you from just loading up the registers and issuing a
```
CALL
```
?


q: I would like to ask if it is possible to show Generalization relationship in UML for a Domain Model although I understand I can do that in a Class Diagram? I did not see much examples of Domain Model displaying Generalization Relationship except in Class Diagram. If not possible, what is the best way to display that an Entity in a Domain Model is either a Entity A or Entity B or Entity C or Entity D etc ?

[A]
You need to clarify why you're distinguishing between a domain model and a class diagram.
On the one hand, your domain model could simply be a class diagram of everything that could map to your database, and consume it. Hence a generalization relationship could simply depict implementation inheritance or interface inheritance.
On the other hand, your domain model could simply express how you expect your classes to work. In which case, it could be any of the standard UML diagrams: class, sequence, collaboration, component, activity, etc.
ADD: are you talking about finding different ways to categorize your persistent entities like a tagging system? Or you could make it possible to have a persistent entity have many nodes in a category tree?


q:
I have Windows Vista MCML app, and I need to figure out the current name of the file playing.

The Media Center SDK alludes to using MediaMetadata["Title"] to get this information, unfortunately this does not work with playlists (.wpl) files as there is no method for getting the position in the playlist.

[A]
Have you tried:
```
```
MediaContext.GetProperty(TrackTitle)
```
```
I've also seen samples that in the markup for the media display layout file they specify an element such as:
```
```
<music-title duration = "2000" x="69" y="29" width="187" height="20"/>
```
```
Good Luck!


q:
I have a list of times in a database column (representing visits to a website).

I need to group them in intervals and then get a 'cumulative frequency' table of those dates.

For instance I might have:

9:01
9:04
9:11
9:13
9:22
9:24
9:28

and i want to convert that into

9:05 - 2
9:15 - 4
9:25 - 6
9:30 - 7

How can I do that? Can i even easily achieve this in SQL? I can quite easily do it in C#

[A]
Create a table
```
periods
```
describing the periods you wish to divide the day up into.
```
```
SELECT periods.name, count(time)
  FROM periods, times
 WHERE period.start <= times.time
   AND                 times.time < period.end
 GROUP BY periods.name
```
```


q:
I have a Flex app that does a a fair amount of network traffic, it uses ExternalInterface to make some javascript calls (for SCORM), it loads XML files, images, video, audio and it has a series of modules that it could be loading at some point...

So the problem is - we now have a requirement where the user needs to run this content locally on a machine that is not connected to the internet (which means they can't connect to Adobe's site to change their security settings.)  As you can imagine, when the user doubles clicks on the html page to launch this thing, they are greeted with a security warning that the swf is trying to communicate with another domain other than the one it's in.  We can't wrap it in an exe or an AIR app so I unless there is some way to tweak some obscure security settings we may be hosed.  Any idea's?

[A]
Did you try to specify the authorized domain with:
```
```
System.security.allowDomain("www.yourdomain.com");
```
```


q:
I was wondering if there was a way to get at the raw HTTP request data in PHP running on apache that doesn't involve using any additional extensions. I've seen the HTTP functions in the manual, but I don't have the option of installing an extension in my environment.

While I can access the information from $_SERVER, I would like to see the raw request exactly as it was sent to the server. PHP munges the header names to suit its own array key style, for eg. Some-Test-Header becomes HTTP_X_SOME_TEST_HEADER. This is not what I need.

[A]
Do you mean the information contained in
```
$_SERVER
```
?
```
```
print_r($_SERVER);
```
```
Edit:
Would this do then?
```
```
foreach(getallheaders() as $key=>$value)  {
    print $key.': '.$value."<br />";
}
```
```


q: Whenever I use the signal/slot editor dialog box, I have to choose from the existing list of slots. So the question is how do I create a custom named slot?

[A]
Unfortunately this is not possible in Qt4.
In Qt3 you could create custom slots which where then implemented in the ui.h file. However, Qt4 does not use this file so custom slots are not supported.
There is some discussion of this issue over on
QtForum


q: How can I display a calendar control (date picker) in Oracle forms 9/10?


q:
I need to add a tooltip/alt to a "td" element inside of my tables with jquery.

Can someone help me out?

I tried:

var tTip ="Hello world";
$(this).attr("onmouseover", tip(tTip));

where I have verified that I am using the "td" as "this".

**Edit:**I am able to capture the "td" element through using the "alert" command and it worked.  So for some reason the "tip" function doesn't work.  Anyone know why this would be?

[A]
```
```
$(this).mouseover(function() {
    tip(tTip);
});
```
```
a better way might be to put
```
title
```
attributes in your HTML. That way, if someone has javascript turned off, they'll still get a tool tip (albeit not as pretty/flexible as you can do with jQuery).
```
```

            Cell 1
            Cell 2

```
```
and then use this code:
```
```
$('#myTable td[title]')
    .hover(function() {
        showTooltip($(this));
    }, function() {
        hideTooltip();
    })
;

function showTooltip($el) {
    // insert code here to position your tooltip element (which i'll call $tip)
    $tip.html($el.attr('title'));
}
function hideTooltip() {
    $tip.hide();
}
```
```


q: How to use data mining feature of SQL Server 2008 with ASP.Net

[A]
Take a look at
SqlServerDataMining.com
, a site run by Microsoft's SQL Server Data Mining team.


q:
I need a function to return a suffix for days when displaying text like the "th" in "Wednesday June 5th, 2008".

It only need work for the numbers 1 through 31 (no error checking required) and English.

[A]
The following function works for C:
```
```
char *makeDaySuffix (unsigned int day) {
    //if ((day < 1) || (day > 31)) return "";
    switch (day) {
        case 1: case 21: case 31: return "st";
        case 2: case 22:          return "nd";
        case 3: case 23:          return "rd";
    }
    return "th";
}
```
```
As requested, it only works for the numbers 1 through 31 inclusive. If you want (possibly, but not necessarily) raw speed, you could try:
```
```
char *makeDaySuffix (unsigned int day) {
    static const char * const suffix[] = {
        "st","nd","rd","th","th","th","th","th","th","th",
        "th","th","th","th","th","th","th","th","th","th"
        "st","nd","rd","th","th","th","th","th","th","th"
        "st"
    };
    //if ((day < 1) || (day > 31)) return "";
    return suffix[day-1];
}
```
```
You'll note that I have bounds checking in there though commented out. If there's even the
slightest
possibility that an unexpected value will be passed in, you'll probably want to uncomment those lines.
Just keep in mind that, with the compilers of today, naive assumptions about what is faster in a high-level language may not be correct:
measure, don't guess.


q:
Could you please explain what the practical usage is for the internal keyword in C#?

I know that the internal modifier limits access to the current assembly, but when and in which circumstance should I use it?

[A]
When you have classes or methods which don't fit cleanly into the Object-Oriented Paradigm, which do dangerous stuff, which need to be called from other classes and methods under your control, and which you don't want to let anyone else use.
```
```
public class DangerousClass {
    public void SafeMethod() { }
    internal void UpdateGlobalStateInSomeBizarreWay() { }
}
```
```


q:
The end() function in jQuery reverts the element set back to what it was before the last destructive change, so I can see how it's supposed to be used, but I've seen some code examples, eg: on alistapart (which were probably from older versions of jQuery - the article is from 2006) which finished every statement off with .end(). eg:

$( 'form.cmxform' ).hide().end();

Does this have any effect?

Is it something I should also be doing?

What does the above code even return?

[A]
That
```
end()
```
doesn't do anything. There's no point to coding like that. It will return
```
$('#myBox')
```
-- the example is pretty poor. More interesting is something like this:
```
```
$('#myBox').show ().children ('.myClass').hide ().end ().blink ();
```
```
Which will show
```
myBox
```
, hide the specified children, and then blink the box. There are more interesting examples here:
http://simonwillison.net/2007/Aug/15/jquery/
such as:
```
```
$('form#login')
    // hide all the labels inside the form with the 'optional' class
    .find('label.optional').hide().end()
    // add a red border to any password fields in the form
    .find('input:password').css('border', '1px solid red').end()
    // add a submit handler to the form
    .submit(function(){
        return confirm('Are you sure you want to submit?');
    });
```
```


q:
It seems pretty common to want to let your javascript know a particular dom node corresponds to a record in the database.  So, how do you do it?

One way I've seen that's pretty common is to use a class for the type and an id for the id:

<div class="thing" id="5">
<script> myThing = select(".thing#5") </script>

There's a slight html standards issue with this though -- if you have more than one type of record on the page, you may end up duplicating IDs.  But that doesn't do anything bad, does it?

An alternative is to use data attributes:

<div data-thing-id="5">
<script> myThing = select("[data-thing-id=5]") </script>

This gets around the duplicate IDs problem, but it does mean you have to deal with attributes instead of IDs, which is sometimes more difficult.  What do you guys think?

[A]
```
```
<div class="thing" id="myapp-thing-5"/>

// Get thing on the page for a particular ID
var myThing = select("#myapp-thing-5");

// Get ID for the first thing on the page
var thing_id = /myapp-thing-(\d+)/.exec ($('.thing')[0].id)[1];
```
```


q:
I have a question about locking. This doesn't have to be only about record locking, but anyway.

Let's say I'm writing a web accessible CMS. I am struggling with some ideas.

I could, on the moment when a user opens an article for editing, flag the article as being 'in use'. so far so good.

but when do I remove the flag? when the user saves the article? but what if the user doesn't feel like typing anymore and decides to close his browser and go to bed?

a time-out mechanism comes to mind, but how long does it take to write an article? 10 minutes too short, 30 minutes too long..

Maybe I am over-complicating this. I'd like to hear your thoughts on this subject.

[A]
My vote is for
optimistic locking
wherever possible.
In one place, where I have implemented actual locks, I had an admin page to remove locks. There was also a service running on the server to unlock any locks which did not have a corresponding active session..


q:
I'm looking for very simple obfuscation (like encrypt and decrypt but not necessarily secure) functionality for some data. It's not mission critical. I need something to keep honest people honest, but something a little stronger than ROT13 or Base64.

I'd prefer something that is already included in the .NET framework 2.0, so I don't have to worry about any external dependencies.

I really don't want to have to mess around with public/private keys, etc. I don't know much about encryption, but I do know enough to know that anything I wrote would be less than worthless... In fact, I'd probably screw up the math and make it trivial to crack.

[A]
The namespace
```
System.Security.Cryptography
```
contains the
```
TripleDESCryptoServiceProvider
```
and
```
RijndaelManaged
```
classes
Don't forget to add a reference to the
```
System.Security
```
assembly.


q:
I want to do some benchmarking of a C# process, but I don't want to use time as my vector - I want to count the number of IL instructions that get executed in a particular method call. Is this possible?

Edit I don't mean static analysis of a method body - I'm referring to the actual number of instructions that are executed - so if, for example, the method body includes a loop, the count would be increased by however many instructions make up the loop * the number of times the loop is iterated.

[A]
Well, it won't be easy.   I
think
you could instrument your assembly post-compile with performance counter code that executed after blocks of IL.  For example, if you had a section of a method that loaded an int onto the stack then executed a static method using that int under optimized code, you could record a count of 2 for the int load and call.
Even using existing IL/managed assembly reading/writing projects, this would be a pretty daunting task to pull off.
Of course, some instructions that your counter recorded might get optimized away during just-in-time compiling to x86/ia64/x64, but that is a risk you'd have to take to try to profile based on an abstract lanaguage like IL.


q:
What are opinions on the design of a "performance assertion checking" system?

The idea is that a developer makes some assertions about his/her code and use these to test the evolution of the performance of the code. What is the experience with such a system?

My current block is "What's a better way to translate these assertions, written in a specified language (that are to be checked against specified logs or runtime instrumentation) into, say, CLR, or assembly or bytecode that could be executed?"

Currently I have written a parser that parses the specification and holds it in a data structure.

[A]
Do we embed performance checks in our application?  No.  The reason is that the performance checks themselves take time and our application is very sensitive to performance.
Instead, we make our performance checks a test.  And for that we use NUnit.  For our nightly builds, we run the test, we generate a log with detailed timing data as well as a pass/fail indication given our requirements.  Since we keep our logs around for some time -- forever for beta and production releases -- we can track performance over time as well.


q:
How do you go about doing a daily build and striving for a zero-defect environment? Does it mean I never get to go home until I've killed all the bugs in my new code? Or does it mean I just don't check my code back in until I've fully tested it, which leaves the code effectively branched for a much longer time?

I'm working with a handful of programmers for the first time (as opposed to working on my own, or with just one other coder), so I'm just wrestling with decisions like this for the first time. Should we adopt a software development process?

[A]
Simple: Never check in code with
(known)
bugs in it. This doesn't mean you check in once per day. Check in when you have a meaningful change implemented so the other developers can get access to it.
We always integrate locally, run our tests against the code, and when all passes, we check in.  I check in about 20-30 times a day when working.  The build server picks up changes and it runs builds against the system. Continous Integration (CI) is a good thing. :D
Continuous Integration - Automate Your Builds
Start out with building successfully and keep it that way as much as possible. It is essential in a team environment. Just remember that builds will break. It's expected that they break every once in awhile. It is a sign that you just inadvertently checked in something bad, and you stop what you are doing to make the build green again. A build server that never has broken builds is a warning sign!
I also agree with chadmyers' answer: Whatever you decide, it needs to be automatic and automated. The best thing about automating tools to do this kind of stuff for you is that you no longer have to think about it or remember to do it. Or like Chad said, you don't stop doing it.
I could recommend make a recommendation for CI tools but have a look here:
What tools do you use for Automated Builds / Automated Deployments? Why?
Once you have CI, you can get higher quality if you can inject some humor (and shame) by introducing a broken build token!
http://ferventcoder.com/archive/2008/08/20/continuous-integration-enhancement--the-broken-build-token.aspx
Use a Good Tool for Automated Builds
Most people in .NET land use NAnt or MSBuild scripts to have automated builds that they can later hook up to their CI server. If you are just starting out, my suggestion would be to use
UppercuT
, it is an insanely easy to use build framework that uses NAnt. Here is a second link with deeper explanations:
UppercuT
.
Branches vs Trunk for Active Development
You would not have to branch unless you leave trunk open only for releases (which means that everyone else is working in the same branch as you). But I would have CI on both the trunk and the active development branch.
Software Development Process
Also to answer the question on a software development process, the answer is a resounding yes. But don't rush into anything unless a drastic change is required. Pick a process you want to migrate towards and slowly start adopting processes. And evaluate, evaluate, evaluate. If the particular process is not working for your group, figure out if you are doing something wrong or if you just need to eliminate it.  And then do. Whatever process you end up with needs to work for you or it won't work.


q:
Many of the questions asked here are relevant to research I'm doing. These questions and answers are widely dispersed and not always easy to find, doing manual browsing, and sometimes an insightful answer or comment occurs in unrelated topics as well.

I want to automate finding these relevant Q's & A's, based on sets of keywords, then use the information as pointers towards further in-depth research.

What tools, preferably open-source, are available that I can use for this type of site-mining? I am not a web guru & for me to try to develop them will take a long time and also impact on time I could have spent on my R&D.

[A]
Human interaction tools might be useful in such case (no development cost, probably a more consistent outcome, and evolving requirements).
Couple comes to mind:
Mechanical Turk
.
Time Svr
(more expensive) -
experiment/review
.


q:
Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like obj.attr ? Or perhaps write get accessors ?
What are the accepted naming styles for such things ?

Edit:
Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.

If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.

[A]
I think most just access them directly, no need for get/set methods.
```
```
>>> class myclass:
...     x = 'hello'
...
>>>
>>> class_inst = myclass()
>>> class_inst.x
'hello'
>>> class_inst.x = 'world'
>>> class_inst.x
'world'
```
```
BTW, you can use the dir() function to see what attributes/methods are attached to your instance:
```
```
>>> dir(class_inst)
['__doc__', '__module__', 'x']
```
```
Two leading underbars, "__" are used to make a attribute or function private.
For other conventions refer to PEP 08:
http://www.python.org/dev/peps/pep-0008/


q: Is there a way to step through a .bat script? The thing is, I have a build script , which calls a lot of other scripts, and I would like to see what is the order in which they are called, so that I may know where exactly I have to go about and add my modifications.

[A]
The only way I can think of is spinkle the code with
```
echo
```
s and
```
pause
```
s.


q: I have a windows mobile 5.0 app, written in C++ MFC, with lots of dialogs.  One of the devices I'm currently targetting does not have a tab key, so I would like to use another key to move between controls.  This is fine for buttons but not edit controls or combo boxes.  I have looked at a similar question but the answer does not really suit.  I've tried overriding the CDialog::OnKeyDown to no avail, and would rather not have to override the keystroke functionality for every control in every dialog.  My thoughts so far are to write new classes replacing CEdit and CComboBox, but as always am just checking if there is an easier way, such as temporarily re-programming another key.

[A]
I don't know MFC
that good
, but maybe you could pull it off by subclassing window procedures of all those controls with a single class, which would only handle cases of pressing cursor keys and pass the rest of events to the original procedures.
You would have to provide your own mechanism of moving to an appropriate control, depending on which cursor key was pressed but it may be worth the usability gains.
If that worked, you could enumerate all dialog controls and subclass them automatically.
Windows Mobile 6 allows switching between dialog controls using cursors by default - it's a new, more "smartphoney" way of moving around the UI and it's incredibly convenient.


q: What is meant by ‘value semantics’, and what is meant by ‘implicit pointer semantics’?

[A]
Java is using implicit pointer semantics for Object types and value semantics for primitives.
Value semantics means that you deal directly with values and that you pass copies around.
The point here is that when you have a value, you can trust it won't change behind your back.
With pointer semantics, you don't have a value, you have an 'address'.
Someone else could alter what is there, you can't know.
Pointer Semantics in C++ :
```
```
void foo(Bar * b) ...
... b->bar() ...
```
```
You need an * to ask for pointer semantics and -> to call methods on the pointee.
Implicit Pointer Semantics in Java :
```
```
void foo(Bar b) ...
... b.bar() ...
```
```
Since you don't have the choice of using value semantics, the * isn't needed nor the distinction between -> and ., hence the implicit.


q: So most Java resources when speaking of packages mention a com.yourcompany.project setup. However, I do not work for a company, and don't have a website. Are there any naming conventions that are common? An email address, perhaps?

[A]
Use a top-level domain like 'bernard' or something else unique.   The important part is that the domain is unique so that you avoid clashes, and not that it starts with a real Internet top-level domain like org or com.   E.g.
```
```
import java.util.*;
import bernard.myProject.*;
import org.apache.commons.lang.*;
```
```


q:
I have the following preprocessor divective:

#ifndef NDEBUG
#define TRACE printf
#else
#define TRACE(...)
#endif

and example of usage is:

TRACE("TRACE: some parameter = %i\n", param);

In C all works perfectly well when I build both debug and release versions, but in C++ compiler emits the following:

warning: invalid character in macro parameter name

error: badly punctuated parameter list in `#define'

and points these warning and error to the 'TRACE(...)' directive.

How to write this in C++ correctly?

[A]
You could do:
```
```
inline void TRACE(...) {}
```
```


q: What's the best available online resource.

[A]
I have only played with the Mobile Framework briefly but a good start would be
Windows Mobile Developer Center
Also it is worth looking at some example open source projects on
CodePlex
.
Microsoft on every training event is encouraging people to use it, and from my experience you can find some interesting projects there at least in standard .Net. I suppose the same applies to Mobile


q:
I'm interested: What is C#'s analog of std::pair in C++? I found System.Web.UI.Pair class, but I'd prefer something template-based.

Thank you!

[A]
Tuples
are available since .NET4.0
and support generics:
```
```
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
```
```
In previous versions you can use
```
System.Collections.Generic.KeyValuePair<K, V>
```
or a solution like the following:
```
```
public class Pair<T, U> {
    public Pair() {
    }

    public Pair(T first, U second) {
        this.First = first;
        this.Second = second;
    }

    public T First { get; set; }
    public U Second { get; set; }
};
```
```
And use it like this:
```
```
Pair<String, int> pair = new Pair<String, int>("test", 2);
Console.WriteLine(pair.First);
Console.WriteLine(pair.Second);
```
```
This outputs:
```
```
test
2
```
```
Or even this chained pairs:
```
```
Pair<Pair<String, int>, bool> pair = new Pair<Pair<String, int>, bool>();
pair.First = new Pair<String, int>();
pair.First.First = "test";
pair.First.Second = 12;
pair.Second = true;

Console.WriteLine(pair.First.First);
Console.WriteLine(pair.First.Second);
Console.WriteLine(pair.Second);
```
```
That outputs:
```
```
test
12
true
```
```


q:
Starting new .NET projects always involves a bit of work. You have to create the solution, add projects for different tiers (Domain, DAL, Web, Test), set up references, solution structure, copy javascript files, css templates and master pages etc etc.

What I'd like is an easy way of cloning any given solution.

If you use copy/paste, the problem is that you need to then go through renaming namespaces, assembly names, solution names, GUIDs etc.

Is there a way of automating this?

Something like this would be great:

solutionclone.exe --solution=c:\code\abc\template.sln --to=c:\code\xyz --newname=MySolution

I'm aware that Visual Studio has project templates, but I've not seen solution templates.

[A]
As you already found out: Copy the .sln File and make sure the paths/guids match.
Because the .sln are
```
text/plain
```
just use your favourite scripting language to script a cloner.
Maybe this is a good time to learn Python/Ruby/Perl/
Windows Script Host
MSDN Solution (.sln) File Definition


q:
If I want to call Bar() instead of Foo(), does Bar() return me a copy (additional overhead) of what Foo() returns, or it returns the same object which Foo() places on the temporary stack?

vector<int> Foo(){
    vector<int> result;
    result.push_back(1);
    return result;
}
vector<int> Bar(){
    return Foo();
}

[A]
Normally it returns a copy of the returned
```
vector<int>
```
. However this highly depends on the optimization done by the compiler. See the following discussion.
Debug Build
```
```
vector<int> Foo(){
004118D0  push        ebp
004118D1  mov         ebp,esp
004118D3  push        0FFFFFFFFh
004118D5  push        offset __ehhandler$?Foo@@YA?AV?$vector@HV?$allocator@H@std@@@std@@XZ (419207h)
004118DA  mov         eax,dword ptr fs:[00000000h]
004118E0  push        eax
004118E1  sub         esp,0F4h
004118E7  push        ebx
004118E8  push        esi
004118E9  push        edi
004118EA  lea         edi,[ebp-100h]
004118F0  mov         ecx,3Dh
004118F5  mov         eax,0CCCCCCCCh
004118FA  rep stos    dword ptr es:[edi]
004118FC  mov         eax,dword ptr [___security_cookie (41E098h)]
00411901  xor         eax,ebp
00411903  push        eax
00411904  lea         eax,[ebp-0Ch]
00411907  mov         dword ptr fs:[00000000h],eax
0041190D  mov         dword ptr [ebp-0F0h],0
    vector<int> result;
00411917  lea         ecx,[ebp-24h]
0041191A  call        std::vector<int,std::allocator<int> >::vector<int,std::allocator<int> > (411050h)
0041191F  mov         dword ptr [ebp-4],1
    result.push_back(1);
00411926  mov         dword ptr [ebp-0FCh],1
00411930  lea         eax,[ebp-0FCh]
00411936  push        eax
00411937  lea         ecx,[ebp-24h]
0041193A  call        std::vector<int,std::allocator<int> >::push_back (41144Ch)
    return result;
0041193F  lea         eax,[ebp-24h]
00411942  push        eax
00411943  mov         ecx,dword ptr [ebp+8]
00411946  call        std::vector<int,std::allocator<int> >::vector<int,std::allocator<int> > (41104Bh)
0041194B  mov         ecx,dword ptr [ebp-0F0h]
00411951  or          ecx,1
00411954  mov         dword ptr [ebp-0F0h],ecx
0041195A  mov         byte ptr [ebp-4],0
0041195E  lea         ecx,[ebp-24h]
00411961  call        std::vector<int,std::allocator<int> >::~vector<int,std::allocator<int> > (411415h)
00411966  mov         eax,dword ptr [ebp+8]
}
```
```
Here we can see that for
```
vector<int> result;
```
a new object is created on the stack at
```
[ebp-24h]
```
```
```
00411917  lea         ecx,[ebp-24h]
0041191A  call        std::vector<int,std::allocator<int> >::vector<int,std::allocator<int> > (411050h)
```
```
When we get to
```
return result;
```
a new copy is created in storage allocated by the caller at
```
[ebp+8]
```
```
```
00411943  mov         ecx,dword ptr [ebp+8]
00411946  call        std::vector<int,std::allocator<int> >::vector<int,std::allocator<int> > (41104Bh)
```
```
And the destructor is called for the local parameter
```
vector<int> result
```
at
```
[ebp-24h]
```
```
```
0041195E  lea         ecx,[ebp-24h]
00411961  call        std::vector<int,std::allocator<int> >::~vector<int,std::allocator<int> > (411415h)
```
```
Release Build
```
```
vector<int> Foo(){
00401110  push        0FFFFFFFFh
00401112  push        offset __ehhandler$?Foo@@YA?AV?$vector@HV?$allocator@H@std@@@std@@XZ (401F89h)
00401117  mov         eax,dword ptr fs:[00000000h]
0040111D  push        eax
0040111E  sub         esp,14h
00401121  push        esi
00401122  mov         eax,dword ptr [___security_cookie (403018h)]
00401127  xor         eax,esp
00401129  push        eax
0040112A  lea         eax,[esp+1Ch]
0040112E  mov         dword ptr fs:[00000000h],eax
00401134  mov         esi,dword ptr [esp+2Ch]
00401138  xor         eax,eax
0040113A  mov         dword ptr [esp+8],eax
    vector<int> result;
0040113E  mov         dword ptr [esi+4],eax
00401141  mov         dword ptr [esi+8],eax
00401144  mov         dword ptr [esi+0Ch],eax
    result.push_back(1);
    return result;
00401147  push        eax
00401148  mov         dword ptr [esp+28h],eax
0040114C  mov         ecx,1
00401151  push        esi
00401152  lea         eax,[esp+14h]
00401156  mov         dword ptr [esp+10h],ecx
0040115A  mov         dword ptr [esp+14h],ecx
0040115E  push        eax
0040115F  lea         ecx,[esp+1Ch]
00401163  push        ecx
00401164  mov         eax,esi
00401166  call        std::vector<int,std::allocator<int> >::insert (401200h)
0040116B  mov         eax,esi
}
0040116D  mov         ecx,dword ptr [esp+1Ch]
00401171  mov         dword ptr fs:[0],ecx
00401178  pop         ecx
00401179  pop         esi
0040117A  add         esp,20h
0040117D  ret
```
```
The line
```
vector<int> result
```
does not call the vector allocator because it is done at call site in
```
Bar
```
. The optimization makes no copy of the result from Foo.


q:
How can I scale the content of an iframe (in my example it is an HTML page, and is not a popup) in a page of my web site?

For example, I want to display the content that appears in the iframe at 80% of the original size.

[A]
I do not think HTML has such functionality. The only thing I can imagine would do the trick is to do some server-side processing. Perhaps you could get an image snapshot of the webpage you want to serve, scale it on the server and serve it to the client. This would be a non-interactive page however. (maybe an imagemap could have the link, but still.)
Another idea would be to have a server-side component that would alter the HTML. SOrt of like the firefox 2.0 zoom feature. this of course is not perfect zooming, but is better than nothing.
Other than that, I am out of ideas.


q:
I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash?

Ideally I'd want to capture all output (not just errors) and log it to a file. Any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual (i.e. the logging process ought to be transparent).

I'm sure someone must have done something along these lines before, but I've not managed to turn up anything that looks useful via google.

[A]
There are various ways. You can put a try..catch block in the wxApplication::OnInit, however, that would not always work with Gtk.
A nice alternative would be to override the Application::HandleEvent in your wxApplication derived class, and write a code like this:
```
```
void Application::HandleEvent(wxEvtHandler* handler, wxEventFunction func, wxEvent& event) const
{
    try
    {
        wxAppConsole::HandleEvent(handler, func, event);
    }
    catch (const std::exception& e)
    {
        wxMessageBox(std2wx(e.what()), _("Unhandled Error"),
            wxOK | wxICON_ERROR, wxGetTopLevelParent(wxGetActiveWindow()));
    }
}
```
```
It's a C++ example, but you can surely translate to Python easily.


q:
I'll regularly get an extract from a DB/2 database with dates and timestaps formatted like this:

2002-01-15-00.00.00.000000
2008-01-05-12.36.05.190000
9999-12-31-24.00.00.000000

Is there an easier way to convert this into the Excel date format than decomposing with substrings?

DB2date = DateValue(Left(a, 4) + "/" + Mid(a, 6, 2) + "/" + Mid(a, 9, 2))

thanks for your help!

[A]
I'm sure you could cook something up with Regex's if you really cared to. It wouldn't be any 'better' though, probably worse.
If you'll forgive a bit of C# (I havn't touched VB in years, so I don't know the function calls anymore) you could also do:
```
```
DB2string = "2002-01-15-00.00.00.000000";
DB2date = DateValue(DB2string.SubString(0, 10).Replace('-', '/'));
```
```
But again, you're not really gaining anything. Can you give an example of where your current code would break?


q:
I might be an exception here but I have never worked on a team with more than three developers and / or five people. Still we could manage to get the job done (somehow).

Is there a software development process which fits this "extreme" scenario? And, if you work as a standalone programmer is there something you can adapt to your daily life to make it more predicatable, coherent, documented and still get the job done?

[A]
The
agile methodologies
are a good starting point because, imho, they are better suited for small groups.
As for keeping your personal working pace I'd recommend a method based on TODO lists and some tool like
Task2Gather
. You might want to look at
GTD
, too.
Things I would never give up even for a team of me:
source version control
backups
TODO
unit testing/
TDD
code documentation
refactoring/code reviews


q:
Tcl/Tk is a simple way to script small GUIs.

Can anyone give a nice example with a button and a text widget. When the button is pressed should a shell command be executed and the output piped to the text widget.

If you have other nice and clean examples for useful tasks, please add them too.

[A]
I can give a start...please suggest improvements. I.e I'd like it to scroll as the command is outputting
```
```
#!/usr/bin/wish

proc push_button {} {
    put_text
    .main see end
}

proc put_text {} {
  set f [ open "| date" r]
  while {[gets $f x] >= 0} {
    .main insert end "$x\n"
  }
  catch {close $f}
}

button .but -text "Push Me" -command "push_button"
text .main -relief sunken -bd 2 -yscrollcommand ".scroll set"
scrollbar .scroll -command ".main yview"

pack .but
pack .main -side left -fill y
pack .scroll -side right -fill y
```
```


q:
I am trying to remotely run a DTSX package from a bat file with this command:

DTEXEC /DTS "\File System\MY_PACKAGE_NAME" /SERVER MY_SERVER_NAME /MAXCONCURRENT " -1 " /CHECKPOINTING OFF  /REPORTING V

This is working fine locally but failing remotely (I do have admin rights on the machine I am pointing to and I have SQL permissions as well) I am getting a timeout error (Login timeout expired).

[A]
After a bit of research it looks like it is impossible to run DTEXEC remotely (it needs to be run locally - remote execution is not supported).
To overcome this limitation the following method seems to be broadly implemented:
set up a SQL job to run the DTSX package
set up a Stored Procedure to run the job
use isql command line in a BAT file (remotely executed) to run the stored procedure on the relevant SQL instance (with SQL credentials and not machine credentials)


q: Is it possible to use oracle instant client for application that use oraoledb driver for connecting to oracle 9i DB.

[A]
I don't believe so.  The
Instant Client FAQ
states
What can Instant Client be used for?
  Instant Client can be used to run your OCI, OCCI, Pro
C, JDBC, and ODBC applications without installing a full Oracle Client. In addition, Instant Client supports SQL
Plus. As of Instant Client 10.2, it is also possible to develop applications for OCI and OCCI using the Instant Client SDK download.
OLE DB is conspicuously absent from that list.  Now, potentially, you could use the Microsoft OLE DB to ODBC provider along with the Instant Client and ODBC, but adding additional layers to software is never very fun.


q:
Is it possible to create a SQL query which will return one column which contains the dates from a given date range (e.g. all dates from last year till today). E.g.

dat
----
2007-10-01
2007-10-02
2007-10-03
2007-10-04
...

I am wondering if this is possible as an alternative to creating a table which holds all those dates precalculated.

Updated: I need a solution for MYSQL. I am not interested in any other DBs in this case.

[A]
AFAIK you cannot do that with a single SQL query. However the following block of code will do the job.
Currently in Transact-SQL (for SQL Server). I do not know how this translates to MySQL.
```
```
DECLARE @start datetime
DECLARE @end datetime
DECLARE @results TABLE
(
   val datetime not null
)
set @start = '2008-10-01'
set @end = getdate()
while @start < @end
begin
    insert into @results values(@start)
    SELECT @start = DATEADD (d, 1, @start)
end
select val from @results
```
```
This outputs:
```
```
2008-10-01 00:00:00.000
2008-10-02 00:00:00.000
2008-10-03 00:00:00.000
```
```


q:
what is the best way of displaying/using the revision number in a java webapp?

we just use ant to build our .war archive, no buildserver or such. i'd hope there was some kind if $ref that i could write in a resource file, but this is only updated when the file in question is committed. i need it globally.

what would you recommend? post-commit triggers that update certain files?
custom ant scripts? is there a more non-hacky way of doing this?
or it it better to have my own version number independent of svn.

edit: great suggestions! thanks a lot for the answers!

[A]
See
this thread
.
My favourite from that thread is just dumping
```
$Id:$
```
in your code where you want the revision ID. SVN will populate that with the real data when you do an export.


q:
I noticed last night that the WCF extensions for Visual Studio 2005 aren't available on their site any longer.  I've read that they want people to use Visual Studio 2008 for WCF/WF/WPF.

Have they made an official statement regarding this?

edit:

I already have the CTP3 for VS2005.  I want to know what Microsoft's official stance is.  Yes, I've read the threads and the blogs.  If a blog post is all that is needed to make it official then so be it.

[A]
There was never anything but CTP released for MS Visual Studio 2008
According to
this
thread MS wants you to move to Visual Studio 2008.
This
blog
post confirms that.
You could still download the
CTP3 for Visual Studio 2005
from a third-party server


q:
Since content of web applications is dynamically generated it would appear that AdSense is not going to produce relevant ads.

Is there a way to increase relevancy of the AdSense ads for the web application?

Is it possible to achieve Gmail-like ad functionality at all for third-party applications?

Is there a better ad provider for web apps than Google?

[A]
No, it's not really suitable. As you know, AdSense is based on page content and that's rarely going to target the correct ads unless your site is very focused on one advertising niche.
If you run a huge web-app that gets many millions of pageviews, then you might be able to get something worked out with Google privately. Otherwise, you're left to see what the best of the rest has to offer.
Chitika
does have the power to let you specify what niches you want to display adverts from... But their rates and even their quality of adverts aren't up there with Googles. Have a look around. There are thousands of advertising providers and I'm sure you'll find one that fits your model.
... But it's not Google at the moment.


q:
I have some simple shell scripting tasks that I want to do

For example: Selecting a file in the working directory from a list of the files matching some regular expression.

I know that I can do this sort of thing using standard bash and grep but I would be nice to be able to hack quick scripts that will work in windows and linux without me having to memorize a heap of command line programs and flags etc.

I tried to get this going but ended up getting confused about where I should be getting information such as a reference to the current directory

So the question is what parts of the Ruby libraries do I need to know to write ruby shell scripts?

[A]
"How do I write ruby" is a little beyond the scope of SO.
But to turn these ruby scripts into executable scripts, put this as the first line of your ruby script:
```
```
#!/path/to/ruby
```
```
Then make the file executable:
```
```
chmod a+x myscript.rb
```
```
and away you go.


q:
The ASP.NET application that I am currently responsible for at my day job has hit its limit in terms of its ability to scale inside a single server. Obviously we are working toward moving session out of process and the test and hopefully deploy date draws near. I would like to draw on the experiencies of people using the built in load balancing in Windows vs. an appliance solution such as one by Baracudda, Coyote Point, F5 etc. Did you start with one and move to the other and why ?

thoughts and advice appreciated in advance...

[A]
some thoughts
WLBS is often "good enough" to get you started with NLB.  However like any great engineer - you need to "measure to know"
its not just about scale-up its about soft or hard redundancy too.  We often NLB between VMs just to give us soft redundancy.
NLB applies just as much to back-edge as well as front-edge networks
stepping up to hardware acceleration brings you a new degree of ops costs.  New training specialized support, escalation etc.
look for hardware acceleration to give you a lot more than NLB e.g. DDoS protection, SSL, Compression, Caching, Content Switching, Connection Aggregation, Buffering.
educate both Devs & Ops SE's about hardware acceleration benefits,a great design can merge the line between network operations and application development.
hardware buffering on it's own made our ASP.NET around 30% quicker just by reducing our GC time.
content switching can enable you to transparently merge or migrate disparate systems.  We merged MSDN & MSDN2 platforms into a single url space using this technique.
session stickyness is a dual edged sword - use sparingly - again no substitute for good engineering - measure and test
everything
We use both WLBS and NLB within our network - cost often drives the conversation.  Treat both as tools in the toolbox, learn their nuances, cost models etc.


q:
I wonder what's the best deployment directory for Rails apps? Some developers use directories such as /u/apps/#{appname}. Are there any advantages when using /u/apps/#{appname} instead of /var/www/#{appname} or other OS default directories?

Obviously I want to pick the directory with the best security properties and the least friction for setting up the server environment.

How do you deploy your Rails apps? Why are you using a specific directory? Do you think it really matters anyway?

[A]
I tend to create a dedicated user for each rails app I run and install, and add that user to the
```
www-data
```
group. So, I tend to have
```
/home/mephisto/www
```
,
```
/home/warehouse/www
```
and so on.
I do this purely for organization, and I don't think it matters much.


q:
I was wondering if it would be possible to retrieve the complete list of security roles defined in a web.xml file in the java code? And if so how to do it?

I am aware of the 'isUserInRole' method but I also want to handle cases where a role is requested but not defined (or spelled differently) in the web.xml file.

[A]
As far as I know, there's no way do do this within the Servlet API.  However, you can parse web.xml directly and extract the values yourself.  I used dom4j below, but you can use whatever XML processing stuff you like:
```
```
protected List<String> getSecurityRoles() {
    List<String> roles = new ArrayList<String>();
    ServletContext sc = this.getServletContext();
    InputStream is = sc.getResourceAsStream("/WEB-INF/web.xml");

    try {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(is);

        Element webApp = doc.getRootElement();

        // Type safety warning:  dom4j doesn't use generics
        List<Element> roleElements = webApp.elements("security-role");
        for (Element roleEl : roleElements) {
            roles.add(roleEl.element("role-name").getText());
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    return roles;
}
```
```


q: I have a web application that generates a long report and I need to print it. If I just print the page it will break at the end of the physical page. How can I calculate where to make a break in the web page so that the page breaks line up with the physical pages when they print?

[A]
Paged media
Print Reference
page-break-after
(
MDN
)
page-break-before
(
MDN
)
page-break-inside
(
MDN
)


q:
I find it annoying that I can't clear a list. In this example:

a = []
a.append(1)
a.append(2)

a = []

The second time I initialize a to a blank list, it creates a new instance of a list, which is in a different place in memory, so I can't use it to reference the first, not to mention it's inefficient.

The only way I can see of retaining the same pointer is doing something like the following:

for i in range(len(a)):
    a.pop()

This seems pretty long-winded though, is there a better way of solving this?

[A]
You are looking for:
```
```
del L[:]
```
```


q:
I have never quite understood how/why I would use Maven modules (reactor builds).

We have tens of libraries that we share (as dependencies) among our products, and between libraries as well.  If we were to switch to making them Maven modules, how would we set it up, both in SVN and in our working copies?

Do Maven modules really need to be subfolders? Do they need to be subfolders in the SVN repo too?

Assuming you just need subfolders in the working copy, I suppose svn:externals would work to make, say, a "util" library be a module of multiple projects at the same time.  But I've read many bad things about using svn:externals because there is nothing to stop you from modifying the code in the external, but its not tracked.

Any suggestions?  Am I missing the boat on modules?

[A]
No ... a modular project should only be used when the child project is integrated into the parent to create a larger artifact, so an example might be an Enterprise project, where your modules contain the EJB (server and client), the WAR, and then those are combined into an EAR file.  This modularity is only for convenience and can be skipped if preferred.
In the case of reusable libraries, make them independent projects and deploy them to a shared repository.  Then they must be referenced as dependencies in the project using them.


q:
In a C++ file, I have a code like this:

#if ACTIVATE
#   pragma message( "Activated" )
#else
#   pragma message( "Not Activated")
#endif

I want to set this ACTIVE define to 1 with the msbuild command line.

It tried this but it doesn't work:

msbuild /p:DefineConstants="ACTIVATE=1"

Any idea?

[A]
I think you want:
```
```
/p:DefineConstants=ACTIVATE
```
```


q: I have a .bat and inside the .bat i would like to execute a special code if there's some modification inside the svn repository (for example, compile).

[A]
Are you wanting this to be reactive? Or, on-demand?
For reactive, see
hooks
. The script will have to be named according to it's purpose:
pre-commit.bat
,
post-commit.bat
. The scripts are called as:
[script] [repos-path] [revision-number]
For, on-demand:
Working Copy
svn log
svn st
svn diff
svn proplist
Repository
svnlook author
svnlook changed
svnlook date
svnlook diff
svnlook history
Example:
```
```
svn st "C:\path\to\working\directory\" >> C:\path\to\working\project.log
```
```
Every time you run the BAT, it'll add the
st
output to
project.log
. Adjust as needed.


q:
How do I set the code page to UTF-8 in a C Windows program?

I have a third party library that uses fopen to open files. I can use wcstombs to convert my Unicode filenames to the current code page, however if the user has a filename with a character outside the code page then this breaks.

Ideally I would just call _setmbcp(65001) to set the code page to UTF-8, however the MSDN documentation for _setmbcp states that UTF-8 is not supported.

How can I get around this?

[A]
All Windows APIs think in UTF-16, so you're better off writing a wrapper around your library that converts at the boundaries.
Oddly enough, Windows thinks UTF-8 is a codepage for the purposes of conversion, so you use the same APIs as you would to convert between codepages:
```
```
std::wstring Utf8ToUtf16(const char* u8string)
{
    int wcharcount = strlen(u8string);
    wchar_t *tempWstr = new wchar_t[wcharcount];
    MultiByteToWideChar(CP_UTF8, 0, u8string, -1, tempWstr, wcharcount);
    wstring w(tempWstr);
    delete [] tempWstr;
    return w;
}
```
```
And something of similar form to convert back.


q: How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?

[A]
```
```
import socket
socket.gethostbyname(socket.gethostname())
```
```
This won't work always (returns
```
127.0.0.1
```
on machines having the hostname in
```
/etc/hosts
```
as
```
127.0.0.1
```
), a paliative would be what gimel shows, use
```
socket.getfqdn()
```
instead. Of course your machine needs a resolvable hostname.


q: Is there any way so that i can echo password when asked for in unix shell without use of external binaries ? Something like simple function triggered when password prompt is displayed


q:
Sorry for the long question title.

I guess I'm on to a loser on this one but on the off chance.

Is it possible to make the calculation of a calculated field in a table the result of an aggregate function applied to a field in another table.

i.e.

You have a table called 'mug', this has a child called 'color' (which makes my UK head hurt but the vendor is from the US, what you going to do?) and this, in turn, has a child called 'size'. Each table has a field called sold.

The size.sold increments by 1 for every mug of a particular colour and size sold.

You want color.sold to be an aggregate of SUM size.sold WHERE size.colorid = color.colorid

You want mug.sold to be an aggregate of SUM color.sold WHERE color.mugid = mug.mugid

Is there anyway to make mug.sold and color.sold just work themselves out or am I going to have to go mucking about with triggers?

[A]
No, it is not possible to do this.  A computed column can only be derived from the values of other fields on the same row.  To calculate an aggregate off another table you need to create a view.
If your application needs to show the statistics ask the following questions:
Is it really necessary to show this in real time?  If so, why?  If it is really necesary to do this, then you would have to use triggers to update a table.
This
links to a short wikipedia article on denormalisation.  Triggers will affect write performance on table updates and relies on the triggers being active.
If it is only necessary for reporting purposes, you could do the calculation in a view or a report.
If it is necessary to support frequent ad-hoc reports you may be into the realms of a data mart and overnight ETL process.


q:
Does NetworkStream.DataAvailable know whether the sender's send buffer is empty? Or does it simply indicate whether the receiver's read buffer has data? My assumption is the latter...

Specifically, for some socket work involving an ongoing conversation, I currently use a length-prefix so the the receiver knows exactly how much data is in the current batch; however, I've been sent a .patch suggesting I use NetworkStream.DataAvailable instead. My concern is that this will just tell me what the receiver has got - not what the sender originally sent - but I'm not a sockets expert.

Am I wrong? Or is length-prefix the way to go?

(note I can't simply Read() until the stream is closed, since multiple batches are sent on the same connection, and it is vital that I treat each batch as separate; if I read too much in one batch (even if it gets buffered and discarded) then the conversation will break).

[A]
One side of a connection is not going to know whether the other side's send buffer is empty.
```
DataAvailable
```
only indicates whether there is incoming data to be read. You could use that prior to
```
Read()
```
, but it alone doesn't give you the information you want. It doesn't tell you the beginning and ending of each batch.
I've coded back-and-forth conversation before, and I used length-prefixes in the data. What I did was write helper functions that read an exact number of bytes (chunks at a time) and no more.
The only alternative to length-of-batch values in the stream is some way of examining the incoming data and recognizing the beginnings and endings of batches.


q: How can I find the public facing IP for my net work in Python?

[A]
This will fetch your remote IP address
```
```
import urllib
ip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()
```
```
If you don't want to rely on someone else, then just upload something like this PHP script:
```
```
<?php echo $_SERVER['REMOTE_ADDR']; ?>
```
```
and change the URL in the Python or if you prefer ASP:
```
```
<%
Dim UserIPAddress
UserIPAddress = Request.ServerVariables("REMOTE_ADDR")
%>
```
```
Note: I don't know ASP, but I figured it might be useful to have here so I googled.


q: I'm trying to handle this possible exploit and wondering what is the best way to do it? should i use apache's common-validator and create a list of known allowed symbols and use that?

[A]
From the
wikipedia article
:
The generic solution is to URL-encode strings before inclusion into HTTP headers such as Location or Set-Cookie.
Typical examples of sanitization include casting to integer, or aggressive regular expression replacement. It is worth noting that although this is not a PHP specific problem, the PHP interpreter contains protection against this attack since version 4.4.2 and 5.1.2.
Edit
im tied into using jsp's with java actions!
There don't appear to be any JSP-based protections for this attack vector - many descriptions on the web assume asp or php, but
this link
describes a fairly platform-neutral way to approach the problem (jsp used as an incidental example in it).
Basically your first step is to indentify the potentially hazardous characters (CRs, LFs, etc) and then to remove them. I'm afraid this about as robust a solution as you can hope for!
Solution
Validate input. Remove CRs and LFs (and all other hazardous characters) before embedding data into any HTTP response headers, particularly when setting cookies and redirecting. It is possible to use third party products to defend against CR/LF injection, and to test for existence of such security holes before application deployment.


q:
In java, when using SimpleDateFormat with the pattern:

yyyy-MM-dd'T'HH:mm:ss.SSSZ

the date is outputted as:

"2002-02-01T18:18:42.703-0700"

In xquery, when using the xs:dateTime function, it gives the error:

"Invalid lexical value [err:FORG0001]"

with the above date. In order for xquery to parse properly, the date needs to look like:

"2002-02-01T18:18:42.703-07:00" - node the ':' 3rd position from end of string

which is based on the ISO 8601, whereas Java date is based on the RFC 822 standard.

I would like to be able to easily specify the timezone in Java so that it will output the way that xquery wants.

Thanks!

[A]
Try this:
```
```
static public String formatISO8601(Calendar cal) {
MessageFormat format = new MessageFormat("{0,time}{1,number,+00;-00}:{2,number,00}");

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(cal.getTimeZone());
format.setFormat(0, df);

long zoneOff = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET) / 60000L;
int zoneHrs = (int) (zoneOff / 60L);
int zoneMins = (int) (zoneOff % 60L);
if (zoneMins < 0)
    zoneMins = -zoneMins;

return (format.format(new Object[] { cal.getTime(), new Integer(zoneHrs), new Integer(zoneMins) }));
}
```
```


q:
I need to either find a file in which the version is encoded or a way of polling it across the web so it reveals its version. The server is running at a host who will not provide me command line access, although I can browse the install location via FTP.

I have tried HEAD and do not get a version number reported.

If I try a missing page to get a 404 it is intercepted, and a stock page is returned which has no server information on it. I guess that points to the server being hardened.

Still no closer...

I put a PHP file up as suggested, but I can't browse to it and can't quite figure out the URL path that would load it. In any case I am getting plenty of access denied messages and the same stock 404 page. I am taking some comfort from knowing that the server is quite robustly protected.

[A]
The method
Connect to port 80 on the host and send it
```
```
HEAD / HTTP/1.0
```
```
This needs to be followed by carriage-return + line-feed twice
You'll get back something like this
```
```
HTTP/1.1 200 OK
Date: Fri, 03 Oct 2008 12:39:43 GMT
Server: Apache/2.2.9 (Ubuntu) DAV/2 SVN/1.5.0 PHP/5.2.6-1ubuntu4 with Suhosin-Patch mod_perl/2.0.4 Perl/v5.10.0
Last-Modified: Thu, 02 Aug 2007 20:50:09 GMT
ETag: "438118-197-436bd96872240"
Accept-Ranges: bytes
Content-Length: 407
Connection: close
Content-Type: text/html; charset=UTF-8
```
```
You can then extract the apache version from the Server: header
Typical tools you can use
You could use the HEAD utility which comes with a full install of Perl's
LWP
library, e.g.
```
```
HEAD http://your.webserver.com/
```
```
Or, use the
curl
utility, e.g.
```
```
curl --head http://your.webserver.com/
```
```
You could also use a browser extension which lets you view server headers, such as
Live HTTP Headers
or
Firebug
for Firefox, or
Fiddler
for IE
Stuck with Windows?
Finally. if you're on Windows, and have nothing else at your disposal, open a command prompt (Start Menu->Run, type "cmd" and press return), and then type this
```
```
telnet your.webserver.com 80
```
```
Then type (carefully, your characters won't be echoed back)
```
```
HEAD / HTTP/1.0
```
```
Press return twice and you'll see the server headers.
Other methods
As mentioned by cfeduke and Veynom, the server may be set to return limited information in the Server: header. Try and upload a PHP script to your host with this in it
```
```
<?php phpinfo() ?>
```
```
Request the page with a web browser and you should see the Apache version reported there.
You could also try and use
PHPShell
to have a poke around, try a command like
```
```
/usr/sbin/apache2 -V
```
```


q:
I am currently plowing my way through IBM's tutorial on CakePHP

At one point I run into this snippet of code:

<?php
class Dealer extends AppModel {
    var $name = 'Dealer';
    var $hasMany = array (
        'Product' => array(
            'className' => 'Product',
            'conditions'=>, // is this allowed?
            'order'=>, // same thing here
            'foreignKey'=>'dealer_id'
        )
    );
}
?>

When I run it I get the following error-message: "Parse error: syntax error, unexpected ',' in /Applications/MAMP/htdocs/cakephp/app/models/product.php on line 7"

I'm a n00b at PHP so my question is: is it allowed to make an array with keys without assigned values? Has anybody played around with this tut and know what is up?

[A]
It is legal, though as far as I'm aware, you have to explicitly say it's 'empty' by assigning null to it,
```
```
$hasMany = array ('Product' => array(
'className' => 'Product',
'conditions'=> null, // is this allowed?
'order'=> null, // same thing here
'foreignKey'=>'dealer_id'));
```
```
The example you've given sounds very wrong, and probably shouldn't work, as it isn't.


q:
I want to insert 'n' spaces (or any string) at the beginning of a string in C++. Is there a direct way to do this using either std::strings or char* strings?

E.g., in Python you could simply do

>>> "." * 5 + "lolcat"
'.....lolcat'

[A]
In the particular case of repeating a single character, you can use
```
std::string(size_type count, CharT ch)
```
:
```
```
std::string(5, '.') + "lolcat"
```
```
This can't be used to repeat multi-character strings.


q:
Currently, I'm in the process of hiring a web developer who will be working on a site that processes credit cards. While he won't have the credentials to log into the payment gateway's UI he will have access to the API login and transaction key since it's embedded in the application's code.

I'd like to be aware of all the "what if" scenarios pertaining to the type of damage one could do with that information. Obviously, he can process credit cards but the money goes into the site owner's bank account so I'm not sure how much damage that could cause. Can anyone think of any other possible scenarios?

UPDATE: The payment gateway being used is Authorize.net.

[A]
If the developer gets access to the raw credit card numbers that can become a bigger problem as your site can be associated with fraudulent activity, assuming the developer is a bad apple.  (They could redirect account numbers, CCV, expiration date to another site, though this should be spottable through network tools and a comprehensive code review.)
Does the API perform the "$1.00" charge (or "$X.XX") to verify that a credit card can be charged a certain amount (and thus returning the result to the caller, such as "yes" or "no")?  If so, it could be used to automate the validation of credit card account numbers traded on the Internet and abuse of such a system could lead back to you.


q:
In the following example should I expect that values.size() will be called every time around the loop? In which case it might make sense to introduce a temporary vectorSize variable. Or should a modern compiler be able to optimize the calls away by recognising that the vector size cannot change.

double sumVector(const std::vector<double>& values) {
    double sum = 0.0;
    for (size_t ii = 0; ii < values.size(); ++ii) {
        sum += values.at(ii);
    }
}

Note that I don't care if there are more efficient methods to sum the contents of a vector, this question is just about the use of size() in a for construct.

[A]
It all depends on what the vector's size implementation is, how aggressive the compiler is and if it listen/uses to inline directives.
I would be more defensive and introduce the temporary as you don't have any guarantees about how efficient your compiler will be.
Of course, if this routine is called once or twice and the vector is small, it really doesn't matter.
If it will be called thousands of times, then I would use the temporary.
Some might call this premature optimization, but I would tend to disagree with that assessment.
While you are trying to optimize the code, you are not investing time or obfuscating the code in the name of performance.
I have a hard time considering what is a refactoring to be an optimization.  But in the end, this is along the lines of "you say tomato, I say tomato"...


q: I am using MailLogger to send a message about a failed/successful release. I would like to make the mail body simple and easy to read. How can I suppress output for some particular tasks?


q:
I would like to know what kind of toolkits, languages, libraries exist for agent-based modeling and what are the pros/cons of them?

Some examples of what I am thinking of are
Swarm, Repast, and MASS.

[A]
I got introduced to
Dramatis
at OSCON 2008, it is an Agent based framework for Ruby and Python.  The author (Steven Parkes) has some references in his blog and is working at running a language agnostic
Actors discussion list
.
This page
at erights.org has a great set of references to, what I think are, the core papers that introduce and explore the Actors message passing model.


q: I know I can cycle through my tabs using cmd+{ or cmd+}, but is it possible to select a specific tab (i.e. cmd+3 for the third tab in iTerm) in Leopards' Terminal.app?

[A]
Yes it is, you use Command-1, Command-2 etc.
Have a look under the
Window
menu, and you'll see the windows listed with their shortcut equivalent. (The 'clover-leaf' is the symbol for the Command key - also known as the Apple key.)
My apologies - missed the fact you were referring to Tabs first time around. I don't believe there is any other keyboard shortcut to switch between Tabs beyond Cmd-{ and }. Perhaps if that's important, don't group them in the first place? Leave them as separate windows?


q: I have noticed that some apps like Safari and Mail show a loading indicator in the status bar (the bar at the very top of the phone) when they are accessing the network. Is there a way to do the same thing in SDK apps, or is this an Apple only thing?

[A]
It's in UIApplication:
For Objective C:
Start:
```
```
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
```
```
End:
```
```
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
```
```
For swift :
Start
```
```
UIApplication.shared.isNetworkActivityIndicatorVisible = true
```
```
End
```
```
UIApplication.shared.isNetworkActivityIndicatorVisible = false
```
```


q:
I've got a byte() array returned as result of directx sound capture, but for other parts of my program I want to treat the results as single(). Is trundling down the array item by item the fastest way of doing it or is there a clever way to do it ?

The code that gets it is

CType(Me._applicationBuffer.Read(Me._nextCaptureOffset, GetType(Byte), LockFlag.None, LockSize), Byte())

which creates the byte array, can Ctype handle single ? (note, I can't figure out a way to  do it!)

[A]
Try
```
```
float f = BitConverter.ToSingle(bytearray, 0);
```
```
In VB (I think):
```
```
Dim single s;
s = BitConverter.ToSingle(bytearray, 0);
```
```


q:
Does anyone know the full list of C# compiler number literal modifiers?

By default declaring '0' makes it an Int32 and '0.0' makes it a 'Double'. I can use the literal modifier 'f' at the end to ensure something is treated as a 'Single' instead. For example like this...

var x = 0;    // x is Int32
var y = 0f;   // y is Single

What are the other modifiers I can use? Is there one for forcing to Double, Decimal, UInt32? I tried googling for this but could not find anything. Maybe my terminology is wrong and so that explains why I am coming up blank. Any help much appreciated.

[A]
```
```
var y = 0f; // y is single
var z = 0d; // z is double
var r = 0m; // r is decimal
var i = 0U; // i is unsigned int
var j = 0L; // j is long (note capital L for clarity)
var k = 0UL; // k is unsigned long (note capital L for clarity)
```
```
From the
C# specification
2.4.4.2 Integer literals and 2.4.4.3 Real literals. Take note that L and UL are preferred as opposed to their lowercase variants for clarity as recommended by
Jon Skeet
.


q:
Suppose I have a base class B, and a derived class D.  I wish to have a method foo() within my base class that returns a new object of whatever type the instance is.  So, for example, if I call B.foo() it returns an object of type B, while if I call D.foo() it returns an object of type D; meanwhile, the implementation resides solely in the base class B.

Is this possible?

[A]
As long as each class has a default constructor:
```
```
public B instance() throws Exception {
        return getClass().newInstance();
    }
```
```


q:
I wonder, why the hell... did the VS team consider that NOT finding a project reference as a non crucial thing?

The referenced component 'X' could not be found. should be considered an error... and nothing else.

Is there a way (without turning 'Treat all warnings as errors' on) to get this warning as an error in VS2008?

[A]
That warning comes from the project system, not the compiler.  The project system doesn't know whether or not the reference will actually be needed when the code is compiled.  I've run into several cases (all involving multiple platforms and conditional compilation) where this features allows you to maintain a single project file when you might otherwise have to split into one file per configuration.
There is an option to "treat warnings as errors" -- you should be able to find it in the project configuration screen.


q:
I'm working on an integration testing project in .NET. The testing framework executable starts a service and then needs to wait for the service to complete an operation.

What is the best approach for the exe to wait on the service to complete its task (the service itself will not exit upon task completion)?

Both processes have access to the same database, so my first thought was a simple table that records the service's status. Once it's signaled that it's done, the exe can stop waiting and complete its task. Other approaches?

Let me reiterate that the service, once it has completed its task, will remain in a running/in-memory state, so waiting for it to exit won't work. ;-)

Also, this is purely for integration testing purposes, and will never go into production, so "simple" is the operative word.

[A]
You could use IPC Channels:
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6143016.html
Or maybe two way remoting:
http://www.codeproject.com/KB/IP/TwoWayRemoting.aspx
The database route would be
simple
, but not necessarily the best.