q:
I search an implementation of a network (or distributed) file system like NFS in Java. The goal is to extend it and do some research stuff with it. On the web I found some implementation e.g. DJ NFS, but the open question is how mature and fast they are.

Can anyone purpose a good starting point, has anyone experience with such things?

P.S. I know Hadoop DFS and I used it for some projects, but Hadoop is not a good fit for the things I want to do here.

--EDIT--
Hadoop is really focused on highly scalable, high throughput computing without the possibilities to overwrite parts of a file and so an. The goal is you could use the filesystem e.g. for user home directories.

--EDIT--
More Details: The idea is to modify such a implementation so that the files are not stored directly on a local filesystem, but to apply data de-duplication.

[A]
I can't say I've actually played with anything other than HDFS, but here are some links that might help you.
http://www.hirednetwork.com/?p=61
http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=1266109
http://wiki.apache.org/nutch/NutchDistributedFileSystem


q:
I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to /login.php. During the login request I want to retrieve the cookies from the response header and store them so I can use them in the request to download the webpage /data.php.

How would I do this in python (preferably 2.6)? If possible I only want to use builtin modules.

[A]
```
```
import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()
```
```
```
resp.read()
```
is the straight html of the page you want to open, and you can use
```
opener
```
to view any page using your session cookie.

s: huggingface

c: devops

d: intermediate


q:
Conditions: do not modify the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version.

Is there a simpler way than:

List<String> newList = new ArrayList<String>();
newList.addAll(listOne);
newList.addAll(listTwo);

[A]
Slightly simpler:
```
```
List<String> newList = new ArrayList<String>(listOne);
newList.addAll(listTwo);
```
```


q:
There are many ways of doing debugging, using a debugger is one, but the simple one for the humble, lazy, programmer is to just add a bunch of print statements to your code.

i.e.

 def foo(x):
     print 'Hey wow, we got to foo!', x

     ...

     print 'foo is returning:', bar
     return bar

Is there a proper name for this style of debugging?

[A]
Yes - it's known as
```
printf()
```
debugging
, named after the ubiquitous C function:
Used
  to describe debugging work done by
  inserting commands that output more or
  less carefully chosen status
  information at key points in the
  program flow, observing that
  information and deducing what's wrong
  based on that information.
--
printf() debugging@everything2
Native users of other languages no doubt refer to it by the default print / log / or trace command available for their coding platform of choice, but i've heard the "printf()" name used to refere to this technique in many languages other than C. Perhaps this is due to its history: while BASIC and FORTRAN had basic but serviceable
```
PRINT
```
commands, C generally required a bit more work to format various data types:
```
printf()
```
was (and often still is)
by far
the most convenient means to this end, providing many built-in formatting options. Its cousin,
```
fprintf()
```
, takes another parameter, the stream to write to: this allowed a careful "debugger" to direct diagnostic information to
```
stderr
```
(possibly itself redirected to a log file) while leaving the output of the program uncorrupted.
Although often looked down on by users of modern debugging software, printf() debugging continues to prove itself indispensable: the wildly popular FireBug tool for the Firefox web browser (and similar tools now available for other browsers) is built around a console window into which web page scripts can log errors or diagnostic messages containing formatted data.


q:
Imagine I have a chunk of initialisation code at the top of a stored procedure with a number of variable assignments:

SET @proc = 'sp_madeupname'
SET @magic_number = 42
SET @tomorrows_date = DATEADD(dd, 1, GETDATE())
...

Clearly doing all of the above as one SELECT would be faster:

SELECT
     @proc = 'sp_madeupname'
    ,@magic_number = 42
    ,@tomorrows_date = DATEADD(dd, 1, GETDATE())
...

But how much faster? Say if this stored procedure was executed as part of a loop, several thousand times, is it going to make any significant difference to the performance?

[A]
I've thought about it but never tested it.
In my experience, the optimizer is pretty good, so I would think it makes no difference, but I'd run some tests if you thought it was really useful.
I think doing multiple assignments can be useful from a maintenance point of view, if you want some things which should always be done together to not be broken up with a cut and paste or refactoring.
For the same reason, code which is relatively modular can benefit from separate initialization, since this is more easily cut and pasted to refactor during maintenance.


q: I am wondering if someone can put a bit of an authoritative reference summary of when the !important declaration in CSS does not work to override inline styles.

[A]
I'm pretty sure not all browsers recognise the !important declaration. But can't remember which ones do off the top of my head. Will check and get back to you.
[EDIT]
I can confirm IE6 and earlier do not recognise !important (unless the browser is in standards compliance mode - not the default).
You can use !important to override an inline rule. But also remember that inline rules can be tagged !important as well.


q:
Is it possible to have transport security without authentication? I'm well aware of it's flaws but atm I can't install a certificate a the client side.
It seems I can set WSHttpBinding.SecurityMode to Transport and the ClientCredentialType to HttpClientCredentialType.None, but when I try to call the service I get this exception:

An error occurred while making the HTTP request to https://[MyService]. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.

I don't think it's a mismatch of the security binding between the client and the server because I'm using a proxy generated by svcutil.

Why's it looking for a server certificate if I've set the ClientCredentialType to None?

[A]
What you have set up looks correct for what you want.
I think that the problem relates to the difference between the certificate needed to ensure transport level security (HTTPS) and any certificate needed for authentication.
To perform transport level security you need to configure a certificate for the IIS server to use for its encryption. This is in no way used to identify parties in the WCF communication, just to secure the communication. (the certificate used for this HTTPS transport is also used to identify the server but that isn't related to WCF identity)
Here is a link to a
blog post
explaining how to set up a certificate in IIS for this purpose. Not necessarily the best google has to offer, just the first I found that covered all the important points. MSDN should cover this in detail too.


q:
Given the following code (that doesn't work):

while True:
    # Snip: print out current state
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok.lower() == "y": break 2 # This doesn't work :(
        if ok.lower() == "n": break

    # Do more processing with menus and stuff

Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?

[A]
First, ordinary logic is helpful.
If, for some reason, the terminating conditions can't be worked out, exceptions are a fall-back plan.
```
```
class GetOutOfLoop( Exception ):
    pass

try:
    done= False
    while not done:
        isok= False
        while not (done or isok):
            ok = get_input("Is this ok? (y/n)")
            if ok in ("y", "Y") or ok in ("n", "N") :
                done= True # probably better
                raise GetOutOfLoop
        # other stuff
except GetOutOfLoop:
    pass
```
```
For this specific example, an exception may not be necessary.
On other other hand, we often have "Y", "N" and "Q" options in character-mode applications.  For the "Q" option, we want an immediate exit.  That's more exceptional.


q:
I'm exporting data programatically from Excel to SQL Server 2005 using SqlBulkCopy. It works great, the only problem I have is that it doesn't preserve the row sequence i have in Excel file. I don't have a column to order by, I just want the records to be inserted in the same order they appear in the Excel Spreadsheet.

I can't modify the Excel file, and have to work with what I've got. Sorting by any of the existing columns will break the sequence.

Please help.

P.S. Ended up inserting ID column to the spreadsheet, looks like there's no way to keep the order during export/import

[A]
If you can save the excel spreadsheet as a CSV it is very easy to generate a list of INSERT statements with any scripting language which will be executed in the exact same order as the spreadsheet.  Here's a quick example in Groovy but any scripting language will do it just as easily if not easier:
```
```
def file1 = new File('c:\\temp\\yourSpreadsheet.csv')
def file2 = new File('c:\\temp\\yourInsertScript.sql')

def reader = new FileReader(file1)
def writer = new FileWriter(file2)

reader.transformLine(writer) { line ->
    fields =  line.split(',')

    text = """INSERT INTO table1 (col1, col2, col3) VALUES ('${fields[0]}', '${fields[1]}', '${fields[2]}');"""

}
```
```
You can then execute your "yourInsertScript.sql" against your database and your order will be the same as your spreadsheet.


q:
During recent discussions at work, someone referred to a trampoline function.

I have read the description at Wikipedia.  It is enough to give a general idea of the functionality, but I would like something a bit more concrete.

Do you have a simple snippet of code that would illustrate a trampoline?

[A]
I'll give you an example that I used in an anti-cheat patch for an online game.
I needed to be able to scan all files that were being loaded by the game for modification. So the most robust way I found to do this was to use a trampoline for CreateFileA. So when the game was launched I would find the address for CreateFileA using GetProcAddress, then I would modify the first few bytes of the function and insert assembly code that would jump to my own "trampoline" function, where I would do some things, and then I would jump back to the next location in CreateFile after my jmp code. To be able to do it reliably is a little trickier than that, but the basic concept is just to hook one function, force it to redirect to another function, and then jump back to the original function.
Edit: Microsoft has a framework for this type of thing that you can look at. Called
Detours


q:
I have a query that ran fine on SQL2005 but moving the database to SQL2008 gives me the error from the title.

The code that is the problem is a call to CONTAINS, CONTAINSTABLE or FREETEXT with an empty parameter. However I'm trying to only call or join when there is a value like such

where (@search_term = '' or (FREETEXT(lst.search_text, @search_term)))

or

left join containstable (listing_search_text, search_text,  @search_term) ftb on l.listing_id = ftb.[key]
    and len(@search_term) > 0

However I cannot find any workaround for this to work on SQL2008. Any ideas?

I know I can do dynamic SQL or have a if statement with two different cases (select with FT join, select without FT join. Any better workaround which doesn't require doing this?

[A]
I found the answer to this today when converting my own database from SQL 2005 to SQL 2008.
Pass
```
""
```
for your search term and change the @search_term =
```
''
```
test to be
```
@search_term = '""'
```
SQL server will ignore the double quotes and not throw an error.
For example, the following would actually returns all records in the Users table:
```
```
declare  @SearchTerm nvarchar(250)

SET @SearchTerm = '""'

select UserId, U.Description, U.UserName
from dbo.Users U
WHERE ((@SearchTerm = '""') OR CONTAINS( (U.Description, U.UserName), @SearchTerm))
```
```
If you are using .Net, you might grab a copy of E. W. Bachtal's FullTextSearch class.  His site is very informative:
http://ewbi.blogs.com/develops/


q:
How would you go about retrieving the @@IDENTITY value for each row when the SQLDataAdapater.Update is executed on a table?

eg. Is it possible to modify/intercept the InsertCommand, generated by the SQLCommandBuilder, to say add an output parameter, and then retrieve its value in the da.RowUpdated event???


q:
I have an odd problem...I'm using a documentation generator which generates a lot of output like docs/foo.php.html. It's XHTML, and thus contains <?xml...> tags at the beginning of file. The problem is, Apache has somehow decided to run it through the PHP interpreter, even though ".php" appears in the middle of the filename, and not at the end. This, in turn, triggers a PHP error, because it sees "<?" as the command to start executing PHP code, and immediately gets confused by the "xml..." which follows it.

How do I configure Apache to ONLY execute .php files and not .php.html files? The string "php.html" does not appear explicitly anywhere in my Apache config files. There is a line "AddHandler php5-script .php", but I don't see how that would also include ".php.html" files.

[A]
You could disable PHP's shorttags -- this is the recommended way to mix PHP and XML.
http://us.php.net/ini.core
```
```
short_open_tag = 0
```
```


q: I know there are things like doing manual check to make sure the codes committed is fundamentally correct. But beside that? Reason i asking is because a big project there are so many commits everyday.

[A]
I find it primarily useful for tracking.  In general such automatic notifications get filtered off into a bucket in my mailer, along with the "smoketest passed, smoketest failed" type email...then when there is a failure, you can track it back to the set of checkins fairly straightforwardly.
Note that one can also intuit the maturity of a project by the shape of the curve of checkins--number of lines of code changed per day as a function of total size of the code base.  It actually does give a reasonable idea of when you're going to be "done"...
Hope this helps!


q:
I have never seen a way to do this nicely, i would be interested in seeing how others do it.  Currently i format it like this:

public Booking createVehicleBooking(Long officeId,
                                    Long start,
                                    Long end,
                                    String origin,
                                    String destination,
                                    String purpose,
                                    String requirements,
                                    Integer numberOfPassengers) throws ServiceException {
/*..Code..*/
}

[A]
```
```
public Booking createVehicleBooking(
    Long officeId,
    Long start,
    Long end,
    String origin,
    String destination,
    String purpose,
    String requirements,
    Integer numberOfPassengers)

throws ServiceException {
/*..Code..*/
}
```
```


q:
I'm looking for tools that implement the distributed agent/service model ... I guess we could also call this grid or cloud computing, but I'm not sure the term is exactly analagous.  A distributed agent model would be one where developers build agents that are dispatched to a framework and the framework executes the agent somewhere in the distributed environment.

Specifically, I'm looking for a framework that support dynamic distribution across the grid/cloud, but replaces the transient agent with a more persistent service.  The goal here is to minimize the amount of time and effort it requires to deploy a service into the grid/cloud container.

FWIW, I think Digipede gets pretty close to this, but I'm interested in what else is out there.  I'm under the impression that assembly distribution would have to be considered in order for the solution to be viable.

[A]
There's a project at Microsoft called Dryad. Here's a good podcast with more info:
http://www.dotnetrocks.com/default.aspx?showNum=378
It uses LINQ and is supposed to be easy to use. Microsoft has it doing some production stuff for Microsoft's AdCenter.
Here's the research page.
http://research.microsoft.com/research/sv/Dryad/
Dryad is quite expressive. It completely subsumes other computation frameworks, such as Google's map-reduce, or the relational algebra. Moreover, Dryad handles job creation and management, resource management, job monitoring and visualization, fault tolerance, re-execution, scheduling, and accounting.
P.S. I don't see a download, but if you contact them and you are serious you could probably get it.
Update: it's now available for download here:
http://research.microsoft.com/en-us/downloads/03960cab-bb92-4c5c-be23-ce51aee0792c/default.aspx


q:
Our company is considering upgrading our SQL server.

At this point, would it be better to upgrade to 2005 or 2008?

Here are some of my considerations:

Features

Licensing costs

Learning curve

Bear in mind our staff has already been using SQL server 2000 for many years.

[A]
2005 is already quite different from 2000, at least in best practices, as a number of things like error handling are greatly improved.  As far as learning curve is concerned, if you're going to throw the learning curveball at them anyway, they're probably better off learning the new technology rather than the one that is already a few years old.
Beyond that though, it's difficult to comment on new features without you providing any info on what kind of work your company does.  One thing I'm very excited about in SQL 2008 is the geospatial data type that I wish had come out a few months prior (perhaps, the initial planned release date) as they would have made our huge mapping application much easier...


q:
What is the MIME type of javascript?

More specifically, what is the right thing to put in the "type" attribute of a script tag? application/x-javascript and text/javascript seem to be the main contenders.

[A]
In a script tag I would use text/javascript.   This appears in the HTML 4.0 specification, anyway.
http://www.w3.org/TR/REC-html40/interact/scripts.html
[EDIT] Funny how the
RFC
that standardized on application/javascript is 2 years old, but text/javascript is still more common.  Is this yet another case of custom triumphing over standards?  It also appears in
HTML5
.


q:
Which would be a neat implemenation of a N-ary tree in C language?

Particulary, I want to implement an n-ary tree, not self-ballancing, with an unbound number of children in each node, in which each node holds an already defined struct, like this for example:

struct task {
  char command[MAX_LENGTH];
  int required_time;
};

[A]
As a first pass, you could simply create a
struct
(let's call it
TreeNode
) which holds a
task
, as well as a set of pointers to
TreeNode
s.  This set could either be an array (if
N
is fixed) or a linked list (if
N
is variable).  The linked list would require you to declare an additional
struct
(let's called it
ListNode
) with a
TreeNode
pointer to the actual child (part of the tree), and a pointer to the next
ListNode
in the list (
null
if at the end of the list).
It might look something like this:
```
```
struct task {
  char command[MAX_LENGTH];
  int required_time;
};

struct TreeNode;

struct ListNode {
  struct TreeNode * child;
  struct ListNode * next;
};

struct TreeNode {
  struct task myTask;
  struct ListNode myChildList;
};
```
```


q:
I understand that we can use SMS Sender in command line mode. But i been getting this error same as this article http://www.oreillynet.com/pub/a/wireless/2003/10/10/sms.html

The smssender.exe will use the last device that was successfully used to send messages in the Windows version of SMS Sender. But I tried it many times, and smssender.exe always complains that no last device was used.

Anyone have any idea about this?

[A]
Not a direct answer to your question, but might help..
Take a look at some of the sms gateway services out there.
I've used Kapow with a lot of success.
http://www.kapow.co.uk/
It's a UK company, but I'm sure you find one in your country.
Most services provide a nice easy to use web api and give you good reporting on delivery, etc. They usually don't come for free, but are comparable to your standard mobile rates for low volume and pretty cheap for higher volumes.


q:
I'm looking for a regex that will allow me to validate whether or not a string is the reference to a website address, or a specific page in that website.

So it would match:

http://google.com
ftp://google.com
http://google.com/
http://lots.of.subdomains.google.com

But not:

http://google.com/search.whatever
ftp://google.com/search.whatever
http://lots.of.subdomains.google.com/search.whatever

Any ideas? I can't quite figure out how to handle allowing the / at the end of the URL.


q:
is there an if statement when it comes to mysql query statements?

when i am updating a table record, i want to only update certain columns if they have a value to be updated.

for example, i want an update table function, and there is a table for volunteers and a table for people who just want email updates.

i want to use the same function (there will be a function that only deals w/ the upd queries) and is it possible to do this in theory...

if you are updating volunteer table, only update these columns, if mailing_list, then update these

i know this can by done using an if statement w/ two query statements, based on what table you're updating, but i am wondering is it possible to use only one query statement w/ the conditionals in it to update the appropriate columns in the table.

this may sound like something you would dream about, let me know.

thanks.

[A]
I think this should work:
```
```
UPDATE volunteer, people
SET volunteer.email = 'me@email.com',
    people.email = 'other@gmail.com',
    people.first_name = 'first',
WHERE people.id = 2 AND volunteer.id = 5;
```
```
I got this from the
update syntax
on the MySQL website.


q:
I'm trying to port an old library (that doesn't use namespaces as far as I can tell) to modern compilers. One of my targets can't tell the difference between System::TObject and ::TObject (without a namespace). System::TObject is native to the compiler.

I've tried a using directive, i.e. using ::TObject;

But that doesn't do it.

The obvious solution is to wrap all the original library in a namespace and then calling it by name- that should avoid the ambiguity. But is that the wisest solution? Is there any other solution? Adding a namespace would require changing a bunch of files and I don't know if it would have unwanted repercussions later.

[A]
If you have the source to the library, maybe include a header file at the top of each source where that header file has only:
```
```
#define TObject TMadeUpNameObject
```
```


q:
I need to store the user's password in my iphone app.

When posting an app to the app store, I have to tell Apple if there's encryption in the app for export purposes.

I don't want my app to be restricted to US only, but I also don't want to store or send passwords over the net in clear text.

So basically the question is, can I encrypt passwords in a way that will not get my app restricted?

[A]
First, if the user name and password are encrypted and decrypted on the phone, then the decryption key is obviously also on the phone and pretty much worthless. I wouldn't worry about storing user names and passwords encrypted on the phone.
For secure communication, you should use SSL which is probably in a library that is already on the phone. If you use a library that is part of the phone OS, I don't think that means your app "contains encryption".
Of course, I am not a lawyer. Who knows - the law might consider "pig latin" a valid encryption technology.


q:
I'm trying to convert some code that worked great in VB, but I can't figure out what objects to use in .Net.

    Dim oXMLHttp As XMLHTTP
    oXMLHttp = New XMLHTTP
    oXMLHttp.open "POST", "https://www.server.com/path", False
    oXMLHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    oXMLHttp.send requestString

Basically, I want to send an XML file to a server, then store the response that it returns.  Can anyone point me in the right direction on this?

[A]
See the following for a sample which does this:
http://www.codeproject.com/KB/dotnet/NET_Interact_j2EE.aspx
I have put the sample below. Sorry, I know it's big, but you never know how long links like this will stay valid.
NOTE: the first version of the question didn't say in C# .NET - it just said "in .NET". (perhaps it was tagged C# and I didn't see it) Converting from VB.NET to C# is pretty easy (though unnecessary).
'This class is representing the same functionality of xmlHTTP object in MSXML.XMLHTTP.
```
```
Imports System.Net
Imports System.Web.HttpUtility

Public Class XMLHTTP
'Makes an internet connection to specified URL
   Public Overridable Sub open(ByVal bstrMethod As String, _
     ByVal bstrUrl As String, Optional ByVal varAsync As _
     Object = False, Optional ByVal bstrUser _
     As Object = "", Optional ByVal bstrPassword As Object = "")
       Try
           strUrl = bstrUrl
           strMethod = bstrMethod

           'Checking if proxy configuration
           'is required...(blnIsProxy value
           'from config file)
           If blnIsProxy Then
           'Set the proxy object
               proxyObject = WebProxy.GetDefaultProxy()

               'Finding if proxy exists and if so set
               'the proxy configuration parameters...
               If Not (IsNothing(proxyObject.Address)) Then
                   uriAddress = proxyObject.Address
                   If Not (IsNothing(uriAddress)) Then
                       _ProxyName = uriAddress.Host
                       _ProxyPort = uriAddress.Port
                   End If
                   UpdateProxy()
               End If
               urlWebRequest.Proxy = proxyObject
           End If

           'Make the webRequest...
           urlWebRequest = System.Net.HttpWebRequest.Create(strUrl)
           urlWebRequest.Method = strMethod

           If (strMethod = "POST") Then
               setRequestHeader("Content-Type", _
                   "application/x-www-form-urlencoded")
           End If

           'Add the cookie values of jessionid of weblogic
           'and PH-Session value of webseal
           'for retaining the same session
           urlWebRequest.Headers.Add("Cookie", str_g_cookieval)

       Catch exp As Exception
           SetErrStatusText("Error opening method level url connection")
       End Try
   End Sub
   'Sends the request with post parameters...
   Public Overridable Sub Send(Optional ByVal objBody As Object = "")
       Try
           Dim rspResult As System.Net.HttpWebResponse
           Dim strmRequestStream As System.IO.Stream
           Dim strmReceiveStream As System.IO.Stream
           Dim encode As System.Text.Encoding
           Dim sr As System.IO.StreamReader
           Dim bytBytes() As Byte
           Dim UrlEncoded As New System.Text.StringBuilder
           Dim reserved() As Char = {ChrW(63), ChrW(61), ChrW(38)}
           urlWebRequest.Expect = Nothing
           If (strMethod = "POST") Then
               If objBody <> Nothing Then
                   Dim intICounter As Integer = 0
                   Dim intJCounter As Integer = 0
                   While intICounter < objBody.Length
                     intJCounter = _
                       objBody.IndexOfAny(reserved, intICounter)
                     If intJCounter = -1 Then
UrlEncoded.Append(System.Web.HttpUtility.UrlEncode(objBody.Substring(intICounter, _
                                                    objBody.Length - intICounter)))
                       Exit While
                     End If
UrlEncoded.Append(System.Web.HttpUtility.UrlEncode(objBody.Substring(intICounter, _
                                                        intJCounter - intICounter)))
                     UrlEncoded.Append(objBody.Substring(intJCounter, 1))
                     intICounter = intJCounter + 1
                   End While

                   bytBytes = _
                     System.Text.Encoding.UTF8.GetBytes(UrlEncoded.ToString())
                   urlWebRequest.ContentLength = bytBytes.Length
                   strmRequestStream = urlWebRequest.GetRequestStream
                   strmRequestStream.Write(bytBytes, 0, bytBytes.Length)
                   strmRequestStream.Close()
                Else
                    urlWebRequest.ContentLength = 0
               End If
           End If
           rspResult = urlWebRequest.GetResponse()
           strmReceiveStream = rspResult.GetResponseStream()
           encode = System.Text.Encoding.GetEncoding("utf-8")
           sr = New System.IO.StreamReader(strmReceiveStream, encode)

           Dim read(256) As Char
           Dim count As Integer = sr.Read(read, 0, 256)
           Do While count > 0
               Dim str As String = New String(read, 0, count)
               strResponseText = strResponseText & str
               count = sr.Read(read, 0, 256)
           Loop
       Catch exp As Exception
           SetErrStatusText("Error while sending parameters")
           WritetoLog(exp.ToString)
       End Try
   End Sub
   'Setting header values...
   Public Overridable Sub setRequestHeader(ByVal bstrHeader _
                         As String, ByVal bstrValue As String)
       Select Case bstrHeader
            Case "Referer"
                urlWebRequest.Referer = bstrValue
            Case "User-Agent"
                urlWebRequest.UserAgent = bstrValue
            Case "Content-Type"
                urlWebRequest.ContentType = bstrValue
            Case Else
                urlWebRequest.Headers(bstrHeader) = bstrValue
       End Select
   End Sub

   Private Function UpdateProxy()
       Try
           If Not (IsNothing(uriAddress)) Then
               If ((Not IsNothing(_ProxyName)) And _
                 (_ProxyName.Length > 0) And (_ProxyPort > 0)) Then
                   proxyObject = New WebProxy(_ProxyName, _ProxyPort)
                   Dim strByPass() As String = Split(strByPassList, "|")
                   If strByPass.Length > 0 Then
                       proxyObject.BypassList = strByPass
                   End If
                   proxyObject.BypassProxyOnLocal = True
                   If blnNetworkCredentials Then
                       If strDomain <> "" Then
                           proxyObject.Credentials = New _
                             NetworkCredential(strUserName, _
                             strPwd, strDomain)
                       Else
                            proxyObject.Credentials = New _
                              NetworkCredential(strUserName, _
                              strPwd)
                       End If
                   End If
               End If
           End If
       Catch exp As Exception
           SetErrStatusText("Error while updating proxy configurations")
           WritetoLog(exp.ToString)
       End Try
   End Function
   'Property for setting the Responsetext
   Public Overridable ReadOnly Property ResponseText() As String
       Get
           ResponseText = strResponseText
       End Get
   End Property

   Private urlWebRequest As System.Net.HttpWebRequest
   Private urlWebResponse As System.Net.HttpWebResponse
   Private strResponseText As String
   Private strUrl As String
   Private strMethod As String
   Private proxyObject As WebProxy
   Private intCount As Integer
   Private uriAddress As Uri
   Private _ProxyName As String
   Private _ProxyPort As Integer
End Class
```
```


q: Have a n-tire web application and search often times out after 30 secs.  How to detect the root cause of the problem?

[A]
A simple solution:
Encode the image as a
jpeg
and look for a substantial change in
filesize
.
I've implemented something similar with video thumbnails, and had a lot of success and scalability.


q:
I'm making a simple 2D game for the iPhone. It's based on CrashLanding. so it's basically a background texture and a few rectangular textures moving around.

I have this bizarre little graphics problem:  some of the small 2d items (can assume just rectangles) moving around get this little flashing black bar on top of them (the background texture is almost completely white so the little bar is noticable).

The textures I'm using are small (~1Kb) pngs.

Has anyone else run into this? Is this a common openGL issue?

BTW this happens on both the simulator and the actual device.

[A]
Do you have a thing like that little black bar in your textures?
I've encountered similar problems when I have done something wrong. Here's a small check-list:
Have you have mipmapped your texture or not, and check what parameters does it have.
glTexParameters. (WRAP_S, WRAP_T, MAG_FILTER, MIN_FILTER...)
texture's dimensions. (If there's non-power-of-two -textures allowed, it may cause graphic glitches, depending about how you load your textures)
Are you are drawing that flashing bar on top of your rectangles?
Whether there's something that's causing the black bar, in your texture.
Alignment of the animation frames.
Blending and alpha-blending.
If something in the list is vague for you, it's good exercise to read about them.
I also do a good guess: I believe you aren't wrapping your textures in any direction, and that the animation frames are a bit misaligned, so that your application has a bit wrong texture coordinates/height in the quad you are drawing.
I hope my advices make sense. I have only experience with the usual opengl, not the OpenGL ES that's graphics pipelines have been pruned to make it more compact, cleaner and more elegant.


q:
I want to put Apache 2.2.9 in front of a Weblogic 9.2 server on Windows XP. What does it take to do that ?

I probably need mod_proxy on the apache side ?

As far as Weblogic and apache are concerned, is there something similar to mod_jk ?

I would like this setup so that I can introduce some filtering later on. But for now, the goal is to allow other computers to access weblogic appserver so that Apache forwards all requests coming to it (at a certain URL) to Weblogic.

I have done this several times earlier BUT have forgotten how I did it.

Thanks for any pointers,

I guess http://e-docs.bea.com/wls/docs81/plugins/apache.html answers most of the basic fundas. Will update the forum if I have more inputs.

[A]
We used the WebLogic plugin to load balance and front our applicatiosn, using virtual hosts and locations.
For example:
ServerName www.domain.com
WebLogicCluster 10.20.30.41:7002,10.20.30.42:7002
    SetHandler weblogic-handler
This config will balance requests to
http://www.domain.com/PathToApplication
to 10.20.30.41:7002 and 10.20.30.42:7002.


q:
I've studied C programming in college some years ago and have developed some medium applications back then (nothing serious). Now I have to develop some more 'advanced' C applications (involving POSIX threads and RPC), but right now I'm a little rusty even with the basics.

Can anyone recommend me good online C reference manuals? This may help me get in tune faster.

[A]
C standard library reference (both C89 and C99)
C89 library reference guide
GNU C tutorial
(more than just a tutorial, quite a useful reference)
I got these all from a previous similar question on SO.  I would like to credit the original posters, but unfortunately cannot seem to find that question.


q: If I have no connection to internet, does that mean I can't start IDLE (which comes with python 3.0)?

[A]
IDLE displays a warning message about firewall programs because it connects to the interpreter over the loopback interface, but that interface is always "connected" and doesn't require you to be on the Internet.
If IDLE isn't working for you with Python 3.0, you might consult
Python issue3628
.


q:
I need to generate random numbers in the range 1 - 10000 continuously with out duplication.
Any recommendations?

Description: we are building a new version for our application, which maintains records in Sqlite DB. in the last version of our application, we did not had unique key for each record. But now with new upgraded version, we need to support the import facility from the last version's DB. So what we do is, we read each and every record from the old DB and generate a random number for the unique key and store it in new DB. Here we many need to import up to 10000 records continuously.

[A]
Well, eventually you'll either have to stop generating them, or you're going to star duplicating them.
On a computer your options are pretty limited to Pseudo Random Number Generators (PRNGs), and given your constraint that they never repeat then a PRNG is your best option - real random data will occasionally duplicate a number.
In your case, I'd consider using a large PRNG (32 bit or larger) to shuffle your 10,000 numbers, and then send the numbers out in the shuffled order.
Once they're used up you can shuffle again - since the PRNG is so large you'll be able to go through the 10k numbers many times before duplicating a sequence.
Give us more information about what your doing and we may come up with a better answer.
-Adam


q: I know it's a long shot, but is there some package or means to insert emoticons into a LaTeX document?

[A]
Unicode's "miscellaneous symbols" include 3 simple emoticons:
```
0x2639
```
-
```
0x263B
```
. You can possibly use
```
0x2686
```
-
```
0x2689
```
as well.
For more variation you are going to need to use images and include them somehow.
I am curious as to the circumstances which lead to this question :)


q:
I am trying to set my DOS environment variable in Ruby, and have it persist after the script exits. For example, if I want a ruby script set_abc_env.rb to set environment variable 'ABC' to 'blah', I expect to run the following:

C:> echo %ABC%
C:> set_abc_env.rb
C:> echo %ABC% blah

How do I do this?

[A]
You can access environment variables via Ruby ENV object:
```
```
i = ENV['ABC']; # nil
ENV['ABC'] = '123';
i = ENV['ABC']; # '123'
```
```
Bad news is, as MSDN
says
, a process can never directly change the environment variables of another process that is not a child of that process. So when script exits, you lose all changes it did.
Good news is what Microsoft Windows stores environment variables in the registry and it's possible to
propagate
environment variables to the system. This is a way to modify user environment variables:
```
```
require 'win32/registry.rb'

Win32::Registry::HKEY_CURRENT_USER.open('Environment', Win32::Registry::KEY_WRITE) do |reg|
  reg['ABC'] = '123'
end
```
```
The documentation also says you should log off and log back on or broadcast a WM_SETTINGCHANGE message to make changes seen to applications. This is how broadcasting can be done in Ruby:
```
```
require 'Win32API'

SendMessageTimeout = Win32API.new('user32', 'SendMessageTimeout', 'LLLPLLP', 'L')
HWND_BROADCAST = 0xffff
WM_SETTINGCHANGE = 0x001A
SMTO_ABORTIFHUNG = 2
result = 0
SendMessageTimeout.call(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 'Environment', SMTO_ABORTIFHUNG, 5000, result)
```
```


q:
I need to do a lot of searches of certain patterns in source files while the user is changing them, so I need to do regexp matching that is efficient in time and memory. The pattern repeats itself so should be compiled once, but I need to be able to retrieve subparts (rather than just confirm a match)

I'm considering using java.util.regexp or the Jakarta perl5util (if it still exists, been a few years since I used it), or perhaps the Eclipse search engine though I doubt that ti's smarter.

Is there any significant performance difference between the two?

[A]
I am not sure there is a huge performance gap in term of the different regexp java engines.
But there sure is a performance issue when constructing a regexp (and that is, if the data is large enough, as
noted by Jeff Atwood
)
The only thing you should avoid is
catastrophic backtracking
, better avoided when using
atomic grouping
.
So, by default I would use the java.utils.regexp engine, unless you have specific perl-compliant sources of regexp you need to reuse in your program.
Then I would carefully construct the regexp I intend to use.
But in term of choosing one engine or another... as it
has been
said
in
many
other questions
...:
"make it work, make it fast - in that order"
beware of "premature optimization".


q:
I have found no way of dumping the stack on all threads in .NET. Neither a signal to be send to the process nor programatic access to all the threads. I can only get access to the current thread via Thread.CurrentThread.

Any tricks ?

[A]
There is a variety of handy classes in the System.Diagnostics that can help you with debugging and gathering various tracking information, i.e. StackTrace.
There is a wonky Process class that can be used to get the number of executing threads but very few details. Use the following Snippet:
```
```
Using  System.Diagnostics;

var threads = Process.GetCurrentProcess().Threads;
```
```
Okay after looking a little bit more it appears the easiest way to capture all the current stacks is through a mini dump and a tool like
SOS
or if you are running vista
this
.
Good luck.


q:
I have a multi-table query, similar to this (simplified version)

SELECT columns, count(table2.rev_id) As rev_count, sum(table2.rev_rating) As sum_rev_rating
FROM table1
LEFT JOIN table2
ON table1.dom_id = table2.rev_domain_from
WHERE dom_lastreview != 0 AND rev_status = 1
GROUP BY dom_url
ORDER BY sum_rev_rating/rev_count DESC

The problem is in the ORDER BY clause. This causes a MySQL error to show, which is as follows:

Reference 'sum_ rev_ rating' not supported (reference to group function)

[A]
my mysql is rusty; you might try
```
```
SELECT columns, count(table2.rev_id) As rev_count,
    sum(table2.rev_rating) As sum_rev_rating,
    sum(table2.rev_rating)/count(table2.rev_id) as rev_ratio
FROM table1
    LEFT JOIN table2ON table1.dom_id = table2.rev_domain_from
WHERE dom_lastreview != 0
AND rev_status = 1
GROUP BY dom_url
ORDER BY rev_Ratio DESC
```
```
or
```
```
SELECT * from (
    SELECT columns, count(table2.rev_id) As rev_count,
        sum(table2.rev_rating) As sum_rev_rating
    FROM table1
        LEFT JOIN table2ON table1.dom_id = table2.rev_domain_from
    WHERE dom_lastreview != 0
    AND rev_status = 1
    GROUP BY dom_url
) X
ORDER BY X.sum_rev_rating/X.rev_count DESC
```
```
or
```
```
SELECT * from (
    SELECT columns, count(table2.rev_id) As rev_count,
        sum(table2.rev_rating) As sum_rev_rating,
        sum(table2.rev_rating)/count(table2.rev_id) as rev_ratio
    FROM table1
        LEFT JOIN table2ON table1.dom_id = table2.rev_domain_from
    WHERE dom_lastreview != 0
    AND rev_status = 1
    GROUP BY dom_url
) X
ORDER BY rev_Ratio DESC
```
```


q:
I am after documentation on using wildcard or regular expressions (not sure on the exact terminology) with a jQuery selector.

I have looked for this myself but have been unable to find information on the syntax and how to use it. Does anyone know where the documentation for the syntax is?

EDIT: The attribute filters allow you to select based on patterns of an attribute value.

[A]
James Padolsey created a
wonderful filter
that allows regex to be used for selection.
Say you have the following
```
div
```
:
```
```
<div class="asdf">
```
```
Padolsey's
```
:regex
```
filter can select it like so:
```
```
$("div:regex(class, .*sd.*)")
```
```
Also, check the
official documentation on selectors
.
UPDATE:
```
:
```
syntax Deprecation JQuery 3.0
Since
```
jQuery.expr[':']
```
used in Padolsey's implementation is already deprecated and will render a syntax error in the latest version of jQuery, here is his code adapted to jQuery 3+ syntax:
```
```
jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {
    return function (elem) {
        var matchParams = expression.split(','),
            validLabels = /^(data|css):/,
            attr = {
                method: matchParams[0].match(validLabels) ?
                    matchParams[0].split(':')[0] : 'attr',
                property: matchParams.shift().replace(validLabels, '')
            },
            regexFlags = 'ig',
            regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
        return regex.test(jQuery(elem)[attr.method](attr.property));
    }
});
```
```


q:
I just got a dedicated server from a hosting company, and for some reason, it didn't have IIS installed.
It did have .Net 2.0, though.

So I installed IIS, but now my ASP.net websites won't work.
I just get a 404, no event log entries, nothing...

I noticed in the redistributable package information that:
"To access the features of ASP.NET, IIS with the latest security updates must be installed prior to installing the .NET Framework"

I also can't uninstall .Net, it just won't let me...

Is there a way to reinstall .Net 2.0, or somehow do whatever it is it does to IIS to make it work?

Thanks!
Daniel

[A]
run from the command line
```
```
aspnet_regiis -i
```
```
You may have to navigate to the folder it was installed.
Mine and the default is
```
```
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
```
```


q: How can I find out the decorated name that will be asigned to each method name ? I'm trying to find out what the decorated name is , so that I may export it , in a DLL .

[A]
This question is pretty similar:
Exporting DLL C++ Class , question about .def file
. The quick summary is that you probably want to use
```
__declspec(dllexport)
```
to let the compiler do the work of exporting your methods for you.
Microsoft changes the way they do function name mangling (or "decorated names" as they call them) with every compiler version, so you would probably run into future maintenance troubles if you try to manually export the mangled names. If you google for "msvc decorated names" there are some links that might help, but no guarantees.


q:
This may not be strictly programming related but more OS-structure related.

Running Vista 32 bit on a brand new laptop with 3GB of memory, Running idle the system consumes about 40% of its memory. Other then the fact that this is outrageous on its own right, the OS should be able to fit all of the processes nicely into memory and not need to swap to disk EVER.

Yet looking at the task manager I see processes having page faults all the time. Not many but still. for instance explorer.exe has one every second approximately.

Why is that? Why does the OS feel the need to swap out pages although it has plenty of physical memory?

[A]
A page fault doesn't necessarily mean that something was paged to disk. A modern OS has many levels of state that a page might be in, for example Windows will probably distinguish between a page of memory that is being actively used, and a page of memory that hasn't been touched in a while and could be paged to disk if needed. (This makes the pager's job easier, because it only has to look at the second kind of page to find out which ones it can page.) Now, how does a page get from the second state back to the first one? The kernel sets a bit on that page indicating that if anything accesses it, then the page will be marked as "active" and moved back to the first state. This results in a page fault.
Other things that might cause a page fault are things like memory mapped files. An application requests that a file be mapped to memory, that is it just
appears
in memory whenever the app wants to read from it. Obviously it would be tremendously expensive to load the whole file into memory all at once, so the kernel just marks the memory space with the "please page fault if this is ever accessed" bit, and reads from the disk if the app ever touches that page.
The real situation is a lot more complex than the above, but that should give you a general idea of what might be going on.


q:
In Scala, is it possible to get the string representation of a type at runtime?  I am trying to do something along these lines:

def printTheNameOfThisType[T]() = {
  println(T.toString)
}

[A]
Note: this answer is out of date!
Please see answer using TypeTag for Scala 2.10 and above
May I recommend #Scala on freenode
```
```
10:48 <seet_> http://stackoverflow.com/questions/190368/getting-the-string-representation-of-a-type-at-runtime-in-scala <-- isnt this posible?
10:48 <seet_> possible
10:48 <lambdabot> Title: Getting the string representation of a type at runtime in Scala - Stack Overflow,
                  http://tinyurl.com/53242l
10:49 <mapreduce> Types aren't objects.
10:49 <mapreduce> or values
10:49 <mapreduce> println(classOf[T]) should give you something, but probably not what you want.
```
```
Description of classOf


q:
An interesting issue came up recently.  We came across some code that is using hashCode() as a salt source for MD5 encryption but this raises the question: will hashCode() return the same value for the same object on different VMs, different JDK versions and operating systems?  Even if its not guaranteed, has it changed at any point up til now?

EDIT: I really mean String.hashCode() rather than the more general Object.hashCode(), which of course can be overridden.

[A]
No. From
http://tecfa.unige.ch/guides/java/langspec-1.0/javalang.doc1.html
:
The general contract of hashCode is as
  follows:
Whenever it is invoked on the same object more than once during an
  execution of a Java application,
  hashCode must consistently return the
  same integer. The integer may be
  positive, negative, or zero. This
  integer does not, however, have to
  remain consistent from one Java
  application to another, or from one
  execution of an application to another
  execution of the same application.
  [...]


q:
I am trying to store more than 1 data item at a single index in my linked-list.  All of the examples in my textbook seem to illustrate adding only 1 piece of data per index.  I'm assuming it is possible to add more?

For example, using the Collections API to store an integer I would do the following:

LinkedList <Integer>linky = new LinkedList<Integer>();
int num1 = 2, num2 = 22, num3 = 25, num4 = 1337;
linky.add(num1);

How would I go about adding num2, num3, and num4 to the same first index in the list?  Thanks guys.

[A]
Use a structure.
For example:
```
```
private struct Node
{
    int Num1;
    int Num2;
    int Num3;
}
```
```
...
```
```
LinkedList<Node> list = new LnkedList<Node>();

Node n = new Node();
n.Num1 = 10;
n.Num2 = 100;
n.Num3 = 1000;
list.Add(n);
```
```
Note; I assume this is in C#; correct me if I'm wrong and I will fix the code ;)
If you have not gone over OOP yet in your book - then I would recommend giving it a try; it will help you solve problems like this.


q:
How do I manipulate images at the pixel level in C#?

I need to be able to read/modify each bitmap pixel RGB values separately.

A code sample would be appreciated.

[A]
If you want speed, then
LockBits
.
See here for a good walkthrough by Bob Powell
. If you just want to edit a few, then
GetPixel
/
SetPixel
should do what you want.


q:
How do you use the CSS content property to add HTML entities?

Using something like this just prints &nbsp; to the screen instead of the non-breaking space:

.breadcrumbs a:before {
  content: '&nbsp;';
}

[A]
Use the hex code for a non-breaking space. Something like this:
```
```
.breadcrumbs a:before {
  content: '>\00a0';
}
```
```


q: How can I get Emacs style key bindings in Visual Studio?   Is it available in Settings? Do I need a Plug-in?

[A]
A quick Live search for "visual studio emacs" gave
this page
.  I'm not sure how thorough it is though (having never used emacs myself).


q: Is there a PHP function to find out the name of the caller function in a given function?

[A]
```
debug_backtrace()
```
supplies details of parameters, function/method calls in the current call stack.


q:
My motivation for trying out git-svn is the effortless merging and branching. Then I noticed that man git-svn(1) says:

Running git-merge or git-pull is NOT recommended on a branch you plan
  to dcommit from. Subversion does not represent merges in any
  reasonable or useful fashion; so users using Subversion cannot see any
  merges you've made. Furthermore, if you merge or pull from a git
  branch that is a mirror of an SVN branch, dcommit may commit to the
  wrong branch.

Does this mean I cannot create a local branch from svn/trunk (or a branch), hack away, merge back into svn/trunk, then dcommit? I understand that svn users will see the same mess that merges in svn pre 1.5.x have always been, but are there any other drawbacks? That last sentence worries me, too. Do people routinely do these kinds of things?

[A]
Creating local branches is definitely possible with git-svn. As long as you're just using local branches for yourself, and not trying to use git to merge between upstream svn branches, you should be fine.
I have a "master" branch that I use to track the svn server. This is the only branch that I dcommit from. If I'm doing some work, I create a topic branch and work away on it. When I want to commit it, I do the following:
Commit everything to the topic branch
git svn rebase
(resolve any conflicts between your work and svn)
git checkout master
git svn rebase
(this makes the next step a fast-forward merge, see Aaron's comments below)
git merge topic_branch
resolve any merge conflicts
(there shouldn't be any at this point)
git svn dcommit
I also have another situation where I need to maintain some local changes (for debugging) that should never be pushed up to svn. For that, I have the above master branch but also a branch called "work" where I normally do work. Topic branches are branched off work. When I want to commit work there, I checkout master and use cherry-pick to pick the commits from the work branch that I want to commit to svn. This is because I want to avoid committing the three local change commits. Then, I dcommit from the master branch and rebase everything.
It is worthwhile running
```
git svn dcommit -n
```
first to make sure that you are about to commit exactly what you intend to commit. Unlike git, rewriting history in svn is hard!
I feel that there must be a better way to merge the change on a topic branch while skipping those local change commits than using cherry-pick, so if anybody has any ideas they would be welcome.


q:
Up until recently, I've been storing multiple values into different hashes with the same keys as follows:

%boss = (
    "Allan"  => "George",
    "Bob"    => "George",
    "George" => "lisa" );

%status = (
    "Allan"  => "Contractor",
    "Bob"    => "Part-time",
    "George" => "Full-time" );

and then I can reference $boss("Bob") and $status("Bob") but this gets unwieldy if there's a lot of properties each key can have and I have to worry about keeping the hashes in sync.

Is there a better way for storing multiple values in a hash?  I could store the values as

        "Bob" => "George:Part-time"

and then disassemble the strings with split, but there must be a more elegant way.

[A]
This is the standard way, as per
perldoc perldsc
.
```
```
~> more test.pl
%chums = ( "Allan" => {"Boss" => "George", "Status" => "Contractor"},
           "Bob" => {"Boss" => "Peter", "Status" => "Part-time"} );

print $chums{"Allan"}{"Boss"}."\n";
print $chums{"Bob"}{"Boss"}."\n";
print $chums{"Bob"}{"Status"}."\n";
$chums{"Bob"}{"Wife"} = "Pam";
print $chums{"Bob"}{"Wife"}."\n";

~> perl test.pl
George
Peter
Part-time
Pam
```
```


q:
I am trying to figure out how to add a custom control to the iPhone MoviePlayer.
For an example of what I am trying to do see the following image.

I am trying to add something like the controls on the right and left of the basic movie controls.

I had done this in the Open SDK by adding a subclass to the playerview, but now in the official SDK and Apple moving to MPMoviePlayerController I am not sure how to do it.

Also with my old 1.x firmware way it required me to capture touch events and hide/show the control myself. I am hoping there is a way that would do this with the standard controls, but if not, that is fine.

Thanks in advance.

[A]
This sample application
that Apple provides should help. From the description:
Demonstrates how to use the Media
  Player Framework to play a movie
  full-screen. The sample contains code
  to configure the movie background
  color, playback controls and scaling
  mode via the built-in Settings
  application. Also shows how to draw
  custom overlay controls on top of the
  movie during playback.


q:
I've been working on a project in Delphi 7 where I wanted to have forms inherit components from other forms. I was able to get this working, but came across the following issues (and I'm going to post the solutions to hopefully help others in the future):

In the .pas file of a form, I would change the form to inherit from some other form, but it wouldn't get the components from the ancestor form.

For certain descendant forms, I would get the following error message when opening the form at design time: "Error creating form: Ancestor for 'TAncestorForm' not found." I would have to first manually open the ancestor form, and then I could open the descendant form.

[A]
First, for those who don't know how to inherit a form visually, you create the ancestor form as usual. Then go to File > New > Other. Select the tab with the name of the current project, and choose the form you want to inherit from. If you want to inherit from a form that's not part of the current project, open that form, right click it, and choose Add to Repository. Then you will be able to go to File > New > Other and select that form from the appropriate tab.
Given that, I came across issues because some of the descendant forms were already created, so I couldn't follow the process above. Also, I made some changes to forms from the standard code Delphi creates. I was able to resolve all issues with visual form inheritance using the following guidelines:
The .pas file of the descendant form must have the form's class inherit from the correct ancestor class, e.g.:
```
type TMyForm = class(TAncestorForm)
```
The first line in the .dfm of the descendant form must have the word
```
inherited
```
instead of
```
object
```
, e.g.:
```
inherited MyForm: TMyForm
```
EDIT: After double checking, the following is NOT required:
The .pas file of the ancestor form must have the standard global variable that Delphi creates, e.g.:
```
var AncestorForm: TAncestorForm;
```
The
```
uses
```
section of the .dpr file of the project must have that same global variable as a comment after the unit's file name, e.g.:
```
unAncestor in 'unAncestor.pas' {AncestorForm}
```
Notes/Tips:
Both the ancestor form and the descendant form are allowed to be non-auto created if you want (Set in Project > Options > Forms > Auto-create forms).
To revert a property on a descendant form to the ancestor form's value, right click on the property in the Object Inspector, and choose Revert to inherited.
To revert all property values of a component to the ancestor's values, right click the component and choose Revert to inherited.


q:
I'm not sure how familiar people are with the hobbit monitoring system - http://hobbitmon.sourceforge.net/ - but I've got a tricky question.

I've got a custom test, which returns two NCV values. One value normally returns ~300 milliseconds, the other one returns 500 000 euro. Obviously, these two values don't graph very well together. :)

Question is, can hobbit display two graphs for this one test? If so, how do I do it?

Thanks.

[A]
When accessed individually, I suspect that having a query that returns IQueryable would work - however, I expect that when this is part of a larger Expression, the expression interpreter will complain (which seems like what you are describing).
However, I suspect that you might be able to break it down a bit. Try adding (to customer):
```
```
public static Expression<Func<Customer, bool>> HasActiveContract
    {
        get { return cust => cust.Contracts.Count() == 1; }
    }
```
```
Then you should be able to use:
```
```
var filtered = db.Customers.Where(Customer.HasActiveContract);
```
```
Obviously it is hard to run it (from here) to see what TSQL it comes up with, but I'd be surprised if that does roundtrips; I would expect that to do the COUNT() in the TSQL. As a topmost query, you should also be able to wrap this:
```
```
public IQueryable<Customer> CustomersWithActiveContract
    {
        get { return Customers.Where(Customer.HasActiveContract); }
    }
```
```
Does any of that work?


q:
When using threads I sometimes visualise them as weaving together 3 or more dimensional interconnections between Objects in a Spatial context.  This isn't a general use case scenario, but for what I do it is a useful way to think about it.

Are there any APIs which you use which aid threading?

Have you used threads in a manner which doesn't conceptualise as thread being a process?

[A]
Are there any APIs which you use which aid threading?
You mean appart from
```
java.util.concurrent
```
?
FunctionalJava
got some constructs which aid in concurrent programming, as described in a multipart tutorial that starts
here
.
Have you used threads in a manner which doesn't conceptualise as thread being a process?
Yes, to the extent that threads doesn't conceptualise at all. Take an asynchronous task-runner for instance. It uses threads under the covers but I don't see them and I don't care about them. They are fully managed by the task-runner.
Under the covers, it is all just threads, but when we stop caring about the individual thread and just think about them as a number of slots where you can somehow put code in and have it run for a period of time, then that is when we start to reach for a higher level of abstraction.
Agents/Actors is a common way to do this. An Actor is like a thread that has a lump of state, and then you can send it some code and say "do this to your state when you have time" or something along those lines.


q:
Ruby has a wealth of conditional constructs, including if/unless, while/until etc.

The while block from C:

while (condition) {
    ...
}

can be directly translated to Ruby:

while condition
    ...
end

However, I can't seem to find a built-in equivalent in Ruby for a C-like do ... while block in which the block contents are executed at least once:

do {
    ...
} while (condition);

Any suggestions?

[A]
...The best I could come up with is the
```
loop
```
construct with a
```
break
```
at the end:
```
```
loop do
    ...
    break unless condition
end
```
```


q:
I'm creating some text boxes on my form programmatically which I need to reference later using FindControl.

I've put the FindControl instruction in the page load method after the code which creates them but get an error:

Object reference not set to an instance of an object.

I assume this is because the textbox controls are not created until later in the lifecycle and therefore cannot be referenced from within Page_Load.

Can someone advise where in my code-behind I would need to place the FindControl instruction so that it can find these programmatically created text boxes?

[A]
If you create textboxes programmatically you can use directly that to manipulate them. No need for FindControl (which would also be slower)
```
```
TextBox txt = new TextBox();
...
txt.Text = "Text";
```
```
If you need access in different methods you can just make txt a private variable of the class.
If you really need to use FindControl - are the textboxes added in the page (added to the Controls list of the page) when you call the function?


q:
I have a Rails app that I need to deploy. Here are the facts:

The app was developed on Windows and requires Windows binary gems

The app is to be deployed onto an Open Solaris shared server (Joyent)

I do not have permissions to install gems on the server

For the non-binary gems, I can simply do a rake gems:unpack locally and then upload; this works just fine.

So my question is, how do I get the binary gems I need onto my production server?

[A]
The binary gems are the real problem. For all other gems you can use the
```
vendor/gems
```
directory (only possible with Rails 2.1+).


q:
Delphi 2009 has changed its string type to use 2 bytes to represent a character, which allows support for unicode char sets.  Now when you get sizeof(string) you get length(String) * sizeof(char) .  Sizeof(char) currently being 2.

What I am interested in is whether anyone knows of a way which on a character by character basis it is possible to find out if it would fit in a single byte, eg find out if a char is ascii or Unicode.

What I'm primarily interested in knowing, is before my string goes to a database (oracle, Documentum) how many bytes the string will use up.

We need to be able to enforce limits before hand and ideally (as we have a large installed base) without having to change the database. If a string field allows 12 bytes, in delphi 2009 a string of length 7 would always show as using 14 bytes even though once it got to the db it would only use 7 if ascii or 14 if double byte, or somewhere in between if a mixture.

[A]
You could check the value of the character:
```
```
if ord(c) < 128 then
    // is an ascii character
```
```


q: I wonder if there is any good guideline for system administrators to calculate the resources needed to host an ASP.NET website? I want to do some estimates on the processing power needed so I know what kind of VPS/Cloud I need to get.

[A]
Load testing will be your best solution.
Applications differ in how they scale depending on a large number of variables including types of problem solving, approach to solution and other factors.
100 concurrent users consuming 10% CPU does not mean 500 concurrent at 50%, it could be 20% or it could be 100%.
Your bottleneck could be processor or memory or network bandwidth.
Without actually placing the load on your application, any estimation will be merely a guess and will quite likely be proven incorrect.


q:
I am writing a drop-in replacement for a legacy application in Java.  One of the requirements is that the ini files that the older application used have to be read as-is into the new Java Application.  The format of this ini files is the common windows style, with header sections and key=value pairs, using # as the character for commenting.

I tried using the Properties class from Java, but of course that won't work if there is name clashes between different headers.

So the question is, what would be the easiest way to read in this INI file and access the keys?

[A]
The library I've used is
ini4j
.  It is lightweight and parses the ini files with ease.  Also it uses no esoteric dependencies to 10,000 other jar files, as one of the design goals was to use only the standard Java API
This is an example on how the library is used:
```
```
Ini ini = new Ini(new File(filename));
java.util.prefs.Preferences prefs = new IniPreferences(ini);
System.out.println("grumpy/homePage: " + prefs.node("grumpy").get("homePage", null));
```
```


q:
We are trying to build a High-Volume Orders Record System.
There are three primary tables:
1. Orders
2. OrderDetails
3. OrderShipment

The Shipment table contains n record per order and any record shipment entry can be changed before the Customer accepts th order, after which it is frozen. (A business requirement)

Although this may not happen in real world scenarios...
during our load tests, we are getting System.Data.Linq.ChangeConflictException exceptions.
Wrapping up the submit inside a transacion is not helping either.
Can't we force LINQ to get a lock on the row for the entire duration of the update operation?

Is there any other way to get over this?

[A]
If you are having genuine issues with concurrent updates on the same data, then you might consider performing the entire operation in a transaction - i.e. getting the data
and
committing it. As long as you treat the get/update/commit as a short-lived, atomic operation (i.e. you don't pause for user-input in the middle) it should be OK.
In particular, with a serializable isolation level, nobody can update data that you have a read lock on (i.e. anything you have queried). The only problem is that this might lead to deadlock scenarios if different queries are reading data in different orders. AFAIK, there is no way to get LINQ-to-SQL to issue the (UPDLOCK) hint, which is a shame.
Either a TransactionScope or a SqlTransaction would do, as long as they are set as serializable isolation (which is the default for TransactionScope).


q:
How can I read the colors of an image with python using google app engine?

Example: I like to build a function to determine the most striking colors of an image to set a harmonic background color for it.

[A]
The
Images API
does not (currently) contain pixel-level functions. To quote the overview document:
Note: In order to use the Images API in your local environment you must first download and install PIL, the Python Imaging Library. PIL is not available on App Engine; it is only used as a stub for the Images API in your local environment. Only the transforms provided in the images API are available on App Engine.
The community has been asking for full
PIL
support for some time, but it looks like we'll have to wait.


q:
I'm working with dRuby and basicly I'm calling a remote method that returns me an object.

In the clientside I have this code:

handle_error(response) if response.is_a?(Error)

where response is the DRbObject. (I've developed this code before using dRuby and I'm returning an Error object if something went wrong). The problem is that now

response.is_a?(Error)

comes back with "false" because the object is actually a DRbObject.
Any idea on how I can check the class of my application object?

Thanks!
Roberto

[A]
Although I'm not sure how DRb manages the remote objects, I'd expect it to modify #kind_of?   to keep the class hierarchy on the remote object, so you could do:
```
```
response.kind_of?(Error)
```
```
If this doesn't work you can always ask it if it responds to an specific method and go from there
```
```
response.respond_to?(some_method_on_your_errors)
```
```


q: How do you build and use dynamic sql in a MySQL stored procedure?

[A]
I don't believe MySQL supports dynamic sql.  You can do "prepared" statements which is similar, but different.
Here is an example:
```
```
mysql> PREPARE stmt FROM
    -> 'select count(*)
    -> from information_schema.schemata
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;
```
```
The prepared statements are often used to see an execution plan for a given query.  Since they are executed with the
execute
command and the
sql
can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.
Here is a good
link
about this:
Don't forget to deallocate the
```
stmt
```
using the last line!
Good Luck!


q:
I've so far dabbled in Flash doing 1-man shows for quite some time, but have never done any big projects with it, where actually source management and code-reuse was truly necessary. However I'm considering Flash for a new project, but this time around it's won't be a 1-man show, that's when it struck me that I had no experience of how one is supposed to do that with flash.

What are some good tips or resources that could help us figure out a good workflow?

[A]
Good communication
Don't work in .fla's. 100% of the code in .as files
UML (at least discussed)
Different tasks for everybody
Comments in commits to code repository
"Manage your code so that anybody can at any time take over your job"
Consider
the bus factor
With junior developers it's also good to go through basic stuff such as package structures etc, just so that everybody is on the same page.
I think it's also good if somebody is kind of like a technical manager of the project, overseeing what the developers are doing. It may also be one of the developers but i think it's important to have one person who knows what everybody else is doing.


q:
I want to create an NSOpenPanel that can select any kind of file, so I do this

NSOpenPanel*    panel = [NSOpenPanel openPanel];

if([panel runModalForTypes:nil] == NSOKButton) {
    // process files here
}

which lets me select all files except symbolic links.

They're simply not selectable and the obvious setResolvesAliases

does nothing.

What gives?

Update 1: I did some more testing and found that this strangeness

is present in Leopard (10.5.5) but not in Tiger (10.4.8).

Update 2: The code above can select mac aliases (persistent path

 data that lives in the resource fork) but not symlinks (files created with ln -s).

[A]
I cannot reproduce this. I just tried it and it works just fine. If symlink points to a directory, it shows the directory content when I select the symlink and if the symlink points to a file, I can select it as well.
Of course if the symlink points to a directory, you can only select it if choosing directories is allowed
```
```
NSOpenPanel * panel = [NSOpenPanel openPanel];
[panel setCanChooseDirectories:YES];
if ([panel runModalForTypes:nil] == NSOKButton) {
    NSLog(@"%@", [panel filenames]);
}
```
```


q:
For a new project with Flash I was looking for something along the lines of standard libraries for basic programming needs, along the lines of Python or Ruby standard libraries. But the only thing I found was a dead project on Sourceforge.

Thus is there no standard library for flash? Does everyone reinvent the wheel each time?

[A]
The basic libraries are
built into flash
. Then on top of that there is
flex
, which gives you an entire RIA framework. Then there are 3rd party frameworks for
3d
,
physics engines
, various design patterns (
MVC
,
IoC
etc) to name just a few.
So no, you do not not to reinvent the wheel every time.


q:
I am responsible for the User Interface of an application written completely in Visual C++  using MFC and some third-part controls. I would like to use C# (WinForms or even better WPF) to improve the application look&feel.

I would like some advices about how to do it. Links, articles, examples...

Right now the user interface is isolated in a single project and I don't want to compile the whole module with CLR. So how do I have to manage that from the architectural point of view?

I have already looked at the Internet for the subject and read MSDN information. I would like more detailed information...is it convinient? pros/cons? have you used this approach successfully in a "big" application?
I don't want to compile the whole ui project with CLR...can I just have all the .NET code in a isolated project and call it from the ui project? what's the best way to do it?

Thanks in advance.


q:
I'm hoping to find out what tools folks use to synchronize data between databases. I'm looking for a JDBC solution that can be used as a command-line tool.

There used to be a tool called Sync4J that used the SyncML framework but this seems to have fallen by the wayside.

[A]
I have heard that the Data Replication Service provided by Db4O is really good. It allows you to use Hibernate to back onto a RDBMS - I don't think it supports JDBC tho (
http://www.db4o.com/about/productinformation/drs/Default.aspx?AspxAutoDetectCookieSupport=1
)
There is an open source project called Daffodil, but I haven't investigated it at all. (
https://daffodilreplicator.dev.java.net/
)
The one I am currently considering using is called SymmetricDS (
http://symmetricds.sourceforge.net/
)
There are others, they each do it slightly differently. Some use triggers, some poll, some use intercepting JDBC drivers. You need to decide what technical limitations you are under to determine which one you really want to use.
Wikipedia provides a nice overview of different techniques (
http://en.wikipedia.org/wiki/Multi-master_replication
) and also provides a link to another alternative DBReplicator (
http://dbreplicator.org/
).


q:
See code:

var file1 = "50.xsl";
var file2 = "30.doc";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc

function getFileExtension(filename) {
    /*TODO*/
}

[A]
```
```
return filename.replace(/\.([a-zA-Z0-9]+)$/, "$1");
```
```
edit: Strangely (or maybe it's not) the
```
$1
```
in the second argument of the replace method doesn't seem to work... Sorry.


q:
I have a few combo-boxes and  double spin boxes on my Qt Dialog. Now I need a "ResetToDefault" item on a menu that comes up when you right click on the widget (spin box or combo box).

How do i get it. Is there some way I can have a custom menu that comes up on right click or Is there a way i can add items to the menu that comes on right click.

[A]
First, for Qt4, the simplest way is to create an action to reset the data, and add it the the widget using the
```
addAction
```
method (or use the designer). Then, set the
```
contextMenuPolicy
```
attribute to
```
Qt::ActionsContextMenu
```
. The context menu will appear and the action will be triggered.
Code example:
```
```
QAction *reset_act = new QAction("Reset to default");
mywidget->addAction(reset_act);
mywidget->setContextMenuPolicy(Qt::ActionsContextMenu);
// here connect the 'triggered' signal to some slot
```
```
For Qt3, you might have to intercept the context menu event, and thus inherit the QSpinBox and others. Or maybe you can intercept the context menu event from the main window, detect if it occurred above the widget supposed to have a context menu (using the
```
QWidget::childAt
```
method) and show it there. But you'll have to test.


q: When you tap a row in a UITableView, the row is highlighted and selected. Is it possible to disable this so tapping a row does nothing?

[A]
All you have to do is set the selection style on the
```
UITableViewCell
```
instance using either:
Objective-C:
```
```
cell.selectionStyle = UITableViewCellSelectionStyleNone;
```
```
or
```
```
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
```
```
Swift 2:
```
```
cell.selectionStyle = UITableViewCellSelectionStyle.None
```
```
Swift 3 and 4.x:
```
```
cell.selectionStyle = .none
```
```
Further, make sure you either don't implement
```
-tableView:didSelectRowAtIndexPath:
```
in your table view delegate or explicitly exclude the cells you want to have no action if you do implement it.
More info here
and
here


q:
I have a DataGridView which shows the content of a DataTable.

I want to set the backcolor of a row based on the value of a cell in this row.

Note that the cell in question is in a column which is not displayed in the DataGridView (Visible=False).

[A]
If you handle the RowDataBound event you can check the value of the data and modify the attributes of the cell or apply a different style in that event handler.
```
```
protected void Page_Load(object sender, EventArgs e)
{
    GridView g1 = new GridView();
    g1.RowDataBound += new GridViewRowEventHandler(g1_RowDataBound);
}

void g1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        // Check the Value
        if(e.Row.Cells[1].Text = someValue)
        {
            e.Row.Cells[1].CssClass = "colorCellRed";
        }

    }
}
```
```
That should give you what you are looking for.  Let me know if you need it in VB rather than C#.
Good Luck!


q:
When I type 'from' (in a LINQ query) after importing System.Linq namespace, it is understood as a keyword. How does this magic happen?

Is 'from' a extension method on some type?

[A]
"from" is a language keyword (just like "if" or "foreach").
You don't even need to import System.Linq to use "from", but you need to use 3.5 framework.


q:
I'm trying to dynamically hide certain DIV's when a print (or print preview) occurs from the browser.

I can easily differentiate statically by having two style sheets, one for normal and one for print media:

But I need to go one step further and hide some elements dynamically when the print style sheet becomes active during a print based upon certain criteria

One way to easily solve it would be to handle a DOM event for handling print / printview, then I could just use jQuery to change the display:none on the classes that need to be hidden, but I can't find a DOM print event!!

Anyone know what the solution is?

[A]
There's an
onbeforeprint
event in IE. It doesn't appear to be supported by other major browsers. (I tested Firefox 3.0.3 and Safari 3.1.2.)


q:
dir(re.compile(pattern))

does not return pattern as one of the lists's elements. Namely it returns:

['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']

According to the manual, it is supposed to contain

the object's attributes' names, the
  names of its class's attributes, and
  recursively of the attributes of its
  class's base classes.

It says also that

The list is not necessarily complete.

Is there a way to get the complete list? I always assumed that dir returns a complete list but apparently it does not...

Also: is there a way to list only attributes? Or only methods?

Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)

[A]
For the
complete
list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the
```
getattr
```
built-in function. As the user can reimplement
```
__getattr__
```
, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The
```
dir
```
function returns the keys in the
```
__dict__
```
attribute, i.e. all the attributes accessible if the
```
__getattr__
```
method is not reimplemented.
For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the
```
inspect
```
module determine the class methods, methods or functions.


q:
How do I set the initial width of a QDockWidget?

I have implemented the sizeHint function but what next?

[A]
If you want it to have the same width as the same last time the program was running, you should look into settings. The Qt 4.4 documentation has an example on how to use settings
here
.
This is how I have done it:
```
```
void Applicotion::readSettings() {
  QSettings settings("Company Name", "Application Name");
  settings.beginGroup("LibraryDock");
  libraryDock->setFloating(settings.value("docked").toBool());
  libraryDock->resize(settings.value("size", QSize(1, 1)).toSize());
  libraryDock->move(settings.value("pos", QPoint(200, 200)).toPoint());
  addDockWidget((Qt::DockWidgetArea)settings.value("dockarea", Qt::RightDockWidgetArea).toInt(), libraryDock);
  settings.endGroup();
}

void Applicotion::writeSettings() {
  QSettings settings("Company Name", "Application Name");
  settings.beginGroup("LibraryDock");
  settings.setValue("dockarea", dockWidgetArea(libraryDock));
  settings.setValue("docked", libraryDock->isFloating());
  settings.setValue("size", libraryDock->size());
  settings.setValue("pos", libraryDock->pos());
  settings.endGroup();
```
```
}


q:
In deploying to a new (Solaris 9) environment recently, one of the steps was to copy a set of files and directories to their new location and then to apply the group UID bit (using "chmod -R g+s") to all files in the directory tree giving a mode of -rwxr-s--- to everything. The result was that none of our shell scripts would execute unless they were individually opened and re-saved. I should add that we had earlier set g+s on the target parent folder prior to copying files; this had set the initial mode on all the new directories to drwxr-s--- but the files had a mode of -rwxr-x---

Having eventually discovered which step caused the problem, we were able to cut out that step and proceed.

I would like, however, to understand what the "s" bit means when applied to directories and files, in the hope that this will explain why we had the problem in the first place.

[A]
For executable files, this means that when the file is executed, it is executed as the group that owns the file, not the group of the user executing the file.
This is useful if you want users to be able to assume the permissions of a particular group just for running one command.
However, it is also a security risk as it is allowing users to elevate their permissions. You have to know that the scripts with this bit set aren't going to do anything that would let users abuse these extra permissions.


q:
Could someone please explain to me how the current python webframworks fit together?

The three I've heard of are CherryPy, TurboGears and Pylons. However I'm confused because TurboGears seems to use CherryPy as the 'Controller' (although isn't CherryPy a framework in in it's own right?), and TurbGears 2 is going to be built on top of Pylons (which I thought did the same thing?).

[A]
There are more to it ofcourse.
Here's a comprehensive list and details!
Web Frameworks for Python
Extract from above link:
Popular Full-Stack Frameworks
A web application may use a
  combination of a base HTTP application
  server, a storage mechanism such as a
  database, a template engine, a request
  dispatcher, an authentication module
  and an AJAX toolkit. These can be
  individual components or be provided
  together in a high-level framework.
These are the most popular high-level
  frameworks. Many of them include
  components listed on the WebComponents
  page.
Django
(1.0 Released 2008-09-03) a
  high-level Python Web framework that
  encourages rapid development and
  clean, pragmatic design
Pylons
(0.9.6.2 Released 2008-05-28) a
  lightweight Web framework emphasizing
  flexibility and rapid development. It
  combines the very best ideas from the
  worlds of Ruby, Python and Perl,
  providing a structured but extremely
  flexible Python Web framework. It's
  also one of the first projects to
  leverage the emerging WSGI standard,
  which allows extensive re-use and
  flexibility but only if you need it.
  Out of the box, Pylons aims to make
  Web development fast, flexible and
  easy. Pylons is built on top of Paste
  (see below).
TurboGears
(1.0.4.4 Released
  2008-03-07) the rapid Web development
  megaframework you've been looking for.
  Combines
CherryPy
, Kid, SQLObject and
MochiKit
. After reviewing the website
  check out:
QuickStart Manual
web2py
(currently version 1.43)
  Everything in one package with no
  dependencies. Development, deployment,
  debugging, testing, database
  administration and maintenance of
  applications can be done via the
  provided web interface. web2py has no
  configuration files, requires no
  installation, can run off a USB drive.
  web2py uses Python for the Model, the
  Views and the Controllers, has a
  built-in ticketing system to manage
  errors, an internationalization
  engine, works with MySQL, PostgreSQL,
  SQLite , Oracle, MSSQL and the Google
  App Engine via an ORM abstraction
  layer. web2py includes libraries to
  handle HTML/XML, RSS, ATOM, CSV, RTF,
  JSON, AJAX, XMLRPC, WIKI markup.
  Production ready, capable of
  upload/download of very large files,
  and always backward compatible.
Grok
(0.13 Released 2008-06-23) is
  built on the existing Zope 3
  libraries, but aims to provide an
  easier learning curve and a more agile
  development experience. It does this
  by placing an emphasis on convention
  over configuration and DRY (Don't
  Repeat Yourself).
Zope
(2.10.4 Released 2007-07-04,
  3.3.1 Released 2007-01-14, Zope 3.4.0c1 Released 2008-01-31) Being the grandaddy of Python web frameworks,
  Zope has grown into a family of
  frameworks over the years. Zope 1 was
  released in 1999. Zope 2 is both a web
  framework and a general purpose
  application server, today it is
  primarily used by
  ContentManagementSystems. Zope 3 is
  both a standalone framework and a
  collection of related libraries, which
  are also included with newer releases
  of Zope 2. All of the Zope frameworks
  include the ZODB, an object database
  for Python.


q: I'm getting ready to start a new project and I've been researching the entity framework. My question is what is the best strategy for validating the entities? Other projects I've worked on have used attributes for most of the validation, but obviously this is not possible in the entity framework. Is the only way to do this by handling the partial methods in the property setters? All advice is much appreciated.

[A]
I have not actually used the Entity framework before but a quick search indicates that you have several options.
1) Validate at another layer in your application
Always an option, I just thought I would throw it out there explicitly.
2) Hook into the OnChanged events of the Entity then perform validation
Likely brittle and would become confusing/slow after if you have many different properties things that can change for each entity.
3) Implement partial methods to validate property changes
According to
this
post and
this
walkthrough there are partial methods available for validation. This seems like your best option as it is not very intrusive and you can selectively implement the validation you want.
I hope that helps. Good luck.


q: I am currently using NUnit and testing a class library. Up until now, I have used a list of constants at the top of the test class to hold some static test variables. Is this the best way to do this, or is there a more fluent way to handle it?

[A]
By "static test variables" do you actually mean constants (whether genuine constant, immutable instances or just ones you don't change)? I use those frequently, and just put them at the top of the test class.
If there are several related test classes, it can be handy to separate out common values into a different class though. (It
could
act as your base class, but I'm not terribly fond of using inheritance just to get access to things more easily. Java static imports are handy there...)


q:
I have a table in SQL server that has the normal tree structure of Item_ID, Item_ParentID.
Suppose I want to iterate and get all CHILDREN of a particular Item_ID (at any level).

Recursion seems an intuitive candidate for this problem and I can write an SQL Server function to do this.

Will this affect performance if my table has many many records?
How do I avoid recursion and simply query the table? Please any suggestions?

[A]
Perhaps some more detail is in order.
If you have a master-detail relationship as you describe, then won't a simple JOIN get what you need?
As in:
```
```
SELECT
  SOME_FIELDS
FROM
  MASTER_TABLE MT
 ,CHILD_TABLE CT
WHERE CT.PARENT_ID = MT.ITEM_ID
```
```


q:
By default, copying from the command prompt will prompt you to overwrite files that already exist in the target location.

You can add "/Y" to say "Yes to all" replacements.

But how can you say "No to all" ?

In other words, I want to copy everything from one directory that does not already exist in the target.

The closest thing I see is the XCOPY argument to only copy things after a specific mod-datetime.

[A]
I expect
xxcopy
has an
option
for that.
Bingo:
http://www.xxcopy.com/xxcopy27.htm#tag_231
```
```
2.3   By comparison with the file in destination

    The switches in this group select files based on the
    comparison between the files in the source and those in
    the destination.  They are often used for periodic backup
    and directory synchronization purposes. These switches
    were originally created as variations of directory backup.
    They are also convenient for selecting files for deletion.

2.3.1  by Presence/Absence

    The /BB and /U switches are the two switches which select
    files by the pure presence or absence as the criteria.
    Other switches in the this group (Group 2.3) are also
    affected by the file in the destination, but for a
    particular characteristics for comparison's sake.

    /BB  Selects files that are present in source but not in destination.
    /U   Selects files that are present in both source and destination.
```
```
-Adam


q:
I'm experimenting with Latent Dirichlet Allocation for topic disambiguation and assignment, and I'm looking for advice.

Which program is the "best", where best is some combination of easiest to use, best prior estimation, fast

How do I incorporate my intuitions about topicality.  Let's say I think I know that some items in the corpus are really in the same category, like all articles by the same author.  Can I add that into the analysis?

Any unexpected pitfalls or tips I should know before embarking?

I'd prefer is there are R or Python front ends for whatever program, but I expect (and accept) that I'll be dealing with C.

[A]
In addition to the
usual
sources
, it seems like the most active area talking about this is on the
topics-models listserv
.  From my initial survey, the easiest package to understand is the
LDA Matlab package
.
This is not lightweight stuff at all, so I'm not surprised it's hard to find good resources on it.


q:
I have the following code fragment that starts a Google Earth process using a hardcoded path:

var process =
    new Process
        {
            StartInfo =
                {
                    //TODO: Get location of google earth executable from registry
                    FileName = @"C:\Program Files\Google\Google Earth\googleearth.exe",
                    Arguments = "\"" + kmlPath + "\""
                }
        };
process.Start();

I want to programmatically fetch the installation location of googleearth.exe from somewhere (most likely the registry).

[A]
From the example given you can gauge that I'm actually trying to pass a KML file to Google Earth. Because of this, the simplest way of resolving this problem is relying on the file association of KML with Google Earth and using the following as a replacement for the entire example:
```
```
Process.Start(kmlPath);
```
```
This was found by reviewing the answers to
this
question.


q:
We've recently completed phase 1 of a ASP.Net website in English and French. We went with using resource files to store language specific strings, but because the site used ASP.Net AJAX and javascript heavily we rigged up a solution to pass the right files through the ASP.Net pipeline where we could catch "tokens" and replace them with the appropriate text pulled from the resource files.

This is the second project I've been involved in that had these kinds of challenges, the first one stored the text strings in a database, and instead of ASP.Net AJAX, it used the AJAX tools that come with the Prototype library and put all Javascript into aspx files so that the tokens could be replaced on the way out.

What I'm wondering is, has anyone else encountered a similar scenario? What approach did you take? What lessons were learned? How did you deal with things like internationalized date formats?

[A]
In my main project (a RAD framework using PHP with gettext for translations) we're doing already alot of prepare operations on javascript files like merging and minifying them. Within this preperations we parse for gettext-markers and replace them with the language specific text.
The result get save as javascript file and normal included into the html.
```
```
<script scr="var/scripts/en_GB-76909c49e9222ec2bb2f45e0a3c8baef80deb665.js"></script>
```
```
The filename contains Locale and a hash value for caching.
Date and money values get always converted from system format to Locale format on output and visa versa for input.


q: How would you manually trigger additional team builds from a team build? For example, when we were in CC.Net other builds would trigger if certain builds were successful. The second  build could either be projects that use this component or additional, long running test libraries for the same component.

[A]
One way you could do it is you could an an AfterEndToEndIteration target to your TFSBuild.proj file that would runs the TfsBuild.exe command line to start you other builds.  I'm thinking something like this (though I haven't tested it)
```
```
<Target Name="AfterEndToEndIteration">

    <GetBuildProperties TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
                        BuildUri="$(BuildUri)"
                        Condition=" '$(IsDesktopBuild)' != 'true' ">
      <Output TaskParameter="Status" PropertyName="Status" />
    </GetBuildProperties>

    <Exec Condition=" '$(Status)'=='Succeeded' "
          Command="TfsBuild.exe start /server:$(TeamFoundationServerUrl) /buildDefinition:"Your Build Definition To Run"" />

  </Target>
```
```


q: I want to force the current execution line to a specific line in the same function, possibly skipping intermediate lines. All my old school debuggers had this feature, but I can't find it in eclipse. Is there a way to do it without changing code?

[A]
"Run to line" appears to need the program to be running and in a paused state to use.  The other option is to set a breakpoint for that line when running in debug-mode.
Double-click far-left vertical bar in the source pane on the same line to add a breakpoint; or,
Select the line and go to Run > Toggle Breakpoint.
At least, this is in Eclipse 3.3.2.


q:
If you launch Emacs using the -nw flag to force a console session (rather than an X session if you have X windows running), how do you get to the menu?

There are some items held in the menus that are infrequently-enough used on my part that I don't recall the escape or control sequence to do them.


q:
I am working through a book which gives examples of Ranges being converted to equivalent arrays using their "to_a" methods

When i run the code in irb I get the following warning

 warning: default `to_a' will be obsolete

What is the the correct alternative to using to_a?

are there alternate ways to populate an array with a Range?

[A]
This works for me in irb:
```
```
irb> (1..4).to_a
=> [1, 2, 3, 4]
```
```
I notice that:
```
```
irb> 1..4.to_a
(irb):1: warning: default `to_a' will be obsolete
ArgumentError: bad value for range
        from (irb):1
```
```
So perhaps you are missing the parentheses?
(I am running Ruby 1.8.6 patchlevel 114)