Question:
I am developing an .net application which heavely depends on plugins. The application itself contains an connection to a remote server.

Recently I digged into Application domains and see them as the ideal solution for isolating the plugin code from the rest of the application.

However there is one big disadvantage which makes me unable to implement the application domains for hosting the plugins. It seems there is no way to pass an object by reference to another application domain which is needed to pass an reference to the connection object.

I was hoping someone could give me a workaround so I can pass an reference to that object.

Note: Creating a proxy is out of the question, the connection layer already acts as a proxy since the classes are auto generated.

Note2: System.AddIn can not be used as it is not available on the compact framework.

Answer:
Have you tried deriving from
MarshalByRefObject
? It's a pain in that it screws up your inheritance hierarchy, but I think it's what you want.
From the docs:
MarshalByRefObject is the base class
  for objects that communicate across
  application domain boundaries by
  exchanging messages using a proxy.
  Objects that do not inherit from
  MarshalByRefObject are implicitly
  marshal by value. When a remote
  application references a marshal by
  value object, a copy of the object is
  passed across application domain
  boundaries.
MarshalByRefObject objects are
  accessed directly within the
  boundaries of the local application
  domain. The first time an application
  in a remote application domain
  accesses a MarshalByRefObject, a proxy
  is passed to the remote application.
  Subsequent calls on the proxy are
  marshaled back to the object residing
  in the local application domain.
Types must inherit from
  MarshalByRefObject when the type is
  used across application domain
  boundaries, and the state of the
  object must not be copied because the
  members of the object are not usable
  outside the application domain where
  they were created.
In my experience, it can be pretty limiting - you really need to do as little as possible across the AppDomain boundary, preferrably restricting yourself to operations which only require primitive types, strings, and arrays of both. This may well be due to my own inexperience in working with multiple AppDomains, but it's just a warning that it's a bit of a minefield.


Question:
We have a JavaEE server and servlets providing data to mobile clients (first JavaME, now soon iPhone). The servlet writes out data using the following code:

DataOutputStream dos = new DataOutputStream(out);

dos.writeInt(someInt);

dos.writeUTF(someString);

... and so on

This data is returned to the client as bytes in the HTTP response body, to reduce the number of bytes transferred.

In the iPhone app, the response payload is loaded into NSData object. Now, after spending hours and hours trying to figure out how to read the data out in the Objective-C application, I'm almost ready to give up, as I haven't found any good way to read the data into NSInteger and NSString (as corresponding to above protocol)

Would anyone have any pointers how to read stuff out from a binary protocol written by a java app? Any help is greatly appreciated!

Thanks!

Answer:
The main thing is to understand the binary data format itself. It doesn't matter what's written it, so long as you know what the bytes mean.
As such, the docs for
DataOutputStream
are your best bet. They specify everything (hopefully) about what the binary data will look like.
Next, I would try to basically come up with a class on the iPhone which will read the same format into appropriate data structure. I don't know Objective C at all, but I'm sure that it can't be too hard to read 4 bytes, know that the first byte is the most significant (etc) and do appropriate bit-twiddling to get the right kind of integer. (Basically read a byte, shift it left 8, read the next byte and add it into the result, shift the whole lot left 8 bits, etc.) There may well be more efficient ways of doing it, but get something that works first. When you've got unit tests around it all, you can move onto optimising it.


Question: Please let me know how can I remove default banner of web server from response - Apache http1.1 coyote

Answer:
If you're talking about the generated line at the bottom of apache generated pages, you have to update your httpd.conf with this command:
```
```
ServerSignature Off
```
```
See
http://httpd.apache.org/docs/2.2/mod/core.html#serversignature
Be careful, theses informations are also sent through HTTP headers. You can alter them via this
directive
About Coyote, AFAIK there is no key to hide these info.


Question:
I ask this question in anticipation as part of a project. I have experience of developing and consuming web services in the past and am au fait with those. However I have been told that as part of this next project I will need to use "secure" web services. Can you provide some insight into what additional development tasks there will be to implement these as opposed to standard dare i say it insecure web services?

Cheers

Answer:
If your going to be using WCF, check out these guide lines on
MSDN
Exising ASMX Web Service can be secured using
Web Services Enhancements (WSE) 3.0


Question:
Is it possible (and if yes, how) to bypass DNS when doing a HTTP request ?

I want to hit directly a front-end with an HTTP request, without getting through NLB but with the correct host header.
As I have the IP of my server, I just need to bypass the DNS.

I tried to use WebRequest, replacing the URL with the IP and setting the Host header, but this header is protected.

How can I do that ? Do I need to create the HTTP request myself ?

Note: editing host file is not an option

Answer:
At the time this question was asked this was not possible to do with the WebRequest class. However following a Microsoft Connect issue raised as a result of this question, Microsoft Added the Host property to the HttpWebRequest class in .Net version 4.0. As such if you are using .net 4.0 or later you can achieve what you want with this code.
```
```
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://127.0.0.1");
Request.Host = "www.example.com"
```
```
Prior to version 4 of .Net the only real option is to open a Socket and do the HTTP request yourself or find a 3rd Party component that has more functionality.


Question:
I try Request.Form.Set(k, v) but it's throwing exception

Collection is read-only

Answer:
The form is a representation of what the client sent in the request. What is it you want to do? Personally, I would try to separate the "read the form" code from the "do something with the values" code - that way, you can do any pre-processing early on (when reading from the form), and none of the later code needs to know about what was
actually
sent - it just takes the values given to it (i.e. it never talks to the request directly).
It also means you can test your logic without the need for a form, or even an http-request at all.
Actually, ASP.NET MVC will do a lot of this (the above paragraph) for you...
Note that you can update the .Items collection - but this is a bit more vague (i.e. it doesn't relate specifically to the form).


Question: I'm working with C and through a socket I will be receiving a message with one space in it, I need to split the string into parts at the space. How would I go about doing this?

Answer:
strtok_r
is your friend.
Don't use plain
```
strtok()
```
, as it's NOT thread-safe.
Even on platforms where it is thread-safe (because the state is held in Thread-Local Storage), there is still the problem that the use of internal state means you cannot parse tokens from several strings simultaneously.
for example, if you write a function which uses
```
strtok()
```
to separate string A, your function cannot be called within the loop of a second function which is using
```
strtok()
```
to split string B.


Question:
Are there any guidelines/best practices for deciding what type of data should be stored in the database?

For ex., is it ok to use database to store

Application logs

Configuration details (like server IP addresses etc.)

System information (e.g., names of shell scripts, scheduling information for batch jobs, batch jobs status etc.)

I have seen applications that use database for storing these. Is this acceptable? What are the pros and cons of such a design?

Answer:
To answer this question we have to understand what database storage provides that isn't available in say, flat file storage.
security - You can store stuff and be sure that updates, deletes and views would be controlled
audit - you can keep track of who made changes and when
distributed servers - if you have multiple application servers accessing a single database, you avoid storing the same data in multiple places
If these are desirables for your data, it's a good idea to store them in the database.


Question:
I am using Crystal Reports 10.  In the report I have two prompts.

How can I give this report to users such that they can enter the parameters on the web?

Thx in advance,
S.Gyazuddin

Answer:
Some ideas that may smooth the process :
Talk to the developers directly and ask if they have any specific requirements. Different platforms have different needs and requirements. Communication is important.
Get the basics of good HTML and CSS down. There are many references but you can try
A  List Apart
as a starting point.


Question:
What is the best way to convert from Pascal Case (upper Camel Case) to a sentence.

For example starting with

"AwaitingFeedback"

and converting that to

"Awaiting feedback"

C# preferable but I could convert it from Java or similar.

Answer:
Pseudo-code:
```
```
NewString = "";
Loop through every char of the string (skip the first one)
   If char is upper-case ('A'-'Z')
     NewString = NewString + ' ' + lowercase(char)
   Else
     NewString = NewString + char
```
```
Better ways can perhaps be done by using regex or by string replacement routines (replace 'X' with ' x')


Question: Can someone tell me what Strong typing and weak typing means and which one is better?

Answer:
Weak typing means that you don't specify what type a variable is, and strong typing means you give a strict type to each variable.
Each has its advantages, with weak typing (or dynamic typing, as it is often called), being more flexible and requiring less code from the programmer. Strong typing, on the other hand, requires more work from the developer, but in return it can alert you of many mistakes when compiling your code, before you run it. Dynamic typing may delay the discovery of these simple problems until the code is executed.
Depending on the task at hand, weak typing may be better than strong typing, or vice versa, but it is mostly a matter of taste. Weak typing is commonly used in scripting languages, while strong typing is used in most compiled languages.


Question:
This might be a silly question:

Does HTTP ever use the User Datagram Protocol?

For example:

If one is streaming MP3 or video  using HTTP,  does it internally use UDP for transport?

Answer:
Typically, no.
Streaming is seldom used over HTTP itself, and HTTP is seldom run over UDP. See, however,
RTP
.
For something as your example (in the comment), you're not showing a protocol for the resource. If that protocol were to be HTTP, then I wouldn't call the access "streaming"; even if it in some sense of the word is since it's sending a (possibly large) resource serially over a network. Typically, the resource will be saved to local disk before being played back, so the network transfer is not what's usually meant by "streaming".
As commenters have pointed out, though, it's certainly possible to really stream over HTTP, and that's done by some.


Question:
I am looking for a redistributable component to convert HTML to PDF.

I would - at the moment - like to avoid using a "PDF printer", as this requires a printer installation and some user "playing around" in the printers panel might break that feature.

The HTML is available in a Browser control or as external file. The HTML is normally fairly simple, but customers can create their own templates, so a "good range" of HTML should be supported.

Should be accessible for an automated process from C++ - DLL / COM / external executable with command line support are all fine.

Commercial is fine, but in the thousands is not an option right now.

So, which components do you know or can you recommend?

Answer:
You might want to have a look at
PDFReactor


Question:
Part of my application maps resources stored in a number of locations onto web URLs like this:

http://servername/files/path/to/my/resource/

The resources location is modelled after file paths and as a result there can be an unlimited level of nesting. Is it possible to construct an MVC route that matches this so that I get the path in its entirety passed into my controller? Either as a single string or possibly as an params style array of strings.

I guess this requires a match on the files keyword, followed by some sort of wildcard. Though I have no idea if MVC supports this.

Answer:
A route like
```
```
"Files/{*path}"
```
```
will get the path as a single string. The
```
*
```
designates it as a wildcard mapping and it will consume the whole URL after
```
"Files/"
```
.


Question:
Is there a way to mount a folder on the hard disk as a device in Finder. The intend here is to provide the user with an easy way to get to a folder that my application uses to store data. I don't want my user to go searching for data in Application Data. I would rather allow them to make this data available as a mounted volume or device in Finder. I would also like this volume or device to be read/write, so that if the user makes any changes to the data files, the changes will get reflected in the original folder.

Is there a way to do this in cocoa, carbon or applescript.

Answer:
Try looking into FUSE.  You can have all sorts of psuedo filesystems with that.
But I'd caution a little against what you are trying to do.  It may make more sense to just have a button that opens the folder in your application, rather than create a new device.  I personally would find it hard to continue to use an application that does such a thing.  It doesn't really fit with the rest of the available applications.
You could also use an alias to point to your Application Data directory.


Question:
I try to migrate a Windows SVN Server to Linux.

I have configured Apache to validate against AD for Useraccess so only AD Users can logon.

Now i have to set permissions for repositories with authz files.

When i set permission with AD username it works, but AD groups it doesn't.

The authz file looks like the following:

[test:/]
user1=rw   #That works

[test2:/]
@usergroup=rw  #No access for the groupmembers

When I create groups inside the authz file and asign AD users, that internal group works fine, but i can't administer groups in 2 locations, there just to much changes made every day.

Has anyone an idea, how to use AD groups inside authz files?

Answer:
You can't automatically use AD groups inside the authz files.
A possibile solution could be writing a script that query the AD for the groups and their member users and writes the correct authz file, defining also the groups themselves.
The final output shuold be something like:
```
```
[groups]
usergroup = user1, user2, user3

[test:/]
user1 = rw

[test2:/]
usergroup = rw
```
```


Question: How does the C/C++ compiler manipulate the escape character ["\"] in source code? How is compiler grammar written for processing that character? What does the compiler do after encountering that character?

Answer:
Most compilers are divided into parts: the compiler front-end is called a
lexical analyzer
or a scanner. This part of the compiler reads the actual characters and creates tokens. It has a state machine which decides, upon seeing an escape character, whether it is genuine (for example when it appears inside a string) or it modifies the next character. The token is output accordingly as the escape character or some other token (such as a tab or a newline) to the next part of the compiler (
the parser
). The state machine can group several characters into a token.


Question:
I have an app that needs to handle very large strings between a SQL Server database and .NET code. I have a LINQ query that generates the strings when saving them to the database, but when trying to create the strings from the database, the app crashes with an OutOfMemoryException because of the size of the strings.

Do I have to do something to make the LINQ generated code avoid that? Using some kind of compression might be an option, but would like to avoid that for performance reasons.

Answer:
What do you call "very large"? And what is the string? CLOB? BLOB? xml?
I suspect you should be using things like
```
ExecuteReader()
```
, which (via
```
IDataReader
```
) exposes methods for reading such columns in chunks:
```
```
using (var reader = cmd.ExecuteReader(
            CommandBehavior.SequentialAccess)) {
            char[] buffer = new char[8040]; // or some multiple (sql server page size)
            while (reader.Read()) {
                long dataOffset = 0, read;
                while((read = reader.GetChars(colIndex, dataOffset, buffer, 0, buffer.Length)) > 0) {
                    // process "read"-many chars from "buffer"
                    dataOffset += read;
                }
            }
        }
```
```
Obviously with xml you might want an
```
XmlReader
```
via
```
cmd.ExecuteXmlReader()
```
.
Updated re LINQ comment (now deleted):
To use
```
IDataReader
```
directly from LINQ-to-SQL, I expect the closest you can get is
```
ctx.GetCommand()
```
, passing it a query. You would then use
```
ExecuteReader
```
or
```
ExecuteXmlReader
```
as above. I don't know much about EF...
If you give an example of the type of query that is failing, there might be some tricks possible - for example, if you are filtering or selecting subsets of the xml, there are things you can do in SQL/XML - perhaps in a UDF called via LINQ-to-SQL.


Question:
If a user requests a large file from an Apache web server, but cancels the download before it completes, is this logged by Apache?

Can I tell from the log file which responses were not sent fully, and how many bytes were sent?

Answer:
Yes. If I remember correctly, it will show the amount of bytes transferred before the download was interrupted. You could then work out how many bytes should have been sent for that request and compare.
If you're using PHP (as the question was tagged a minute ago), you could probably do some sort of response buffer, where you chunk out the file in smaller bits. Start off by working out how many chunks you need to send, write a log (to db, or the syslog) to say you've started and once you hit the final chunk, another to say you've finished (or delete the first).


Question: In Sharepoint, is it possible to deny regular users the possibility of removing web parts and/or web part zones? If yes; how?

Answer:
The options to deny users from closing/moving a web part are in the 'Advanced' section of the web part's tool pane in sharepoint (Accessed via the 'Modify Shared Web Part' option in the web part's menu).
Alternatively you can modify the permission levels for the site (Site settings > Permissions > Settings > Permission Levels) and remove the 'Add/Remove personal web parts' and 'Update personal web parts' permissions from the levels your users run as.
Hope this helps.


Question:
I've got a DataTable containing a sitemap hierarchy with the following columns:

ItemId

ParentId

Name

Url

I need to generate a set of nested lists in HTML (left the anchor elements out for clarity):

<ul>
<li>Item 1</li>
<li>Item 2</li>
    <ul>
    <li>Sub Item 1</li>
    <li class="current">Sub Item 2</li>
    </ul>
<li>Item 3</li>
</ul>

The tree should only contain branches that lead to the 'current' node/page (so using the above example any child items that Item '1' or '3' have are not displayed. Can anyone help out with some pseudo code / code example that can traverse the tree from the leaf to root building the HTML as it goes? Thanks.

Answer:
I made something similar, it might not be that efficient but its easy to debug.
Find path to selected node.
Add rootnodes to list.
Find node in list which is in path.
Add all childern to this node.
Find next node in path.
Repeat 4-5 until at selected node, and if not at leaf add selected nodes childern as well.
Alternative:
1. Find selected node, print this and all siblings
2. Print parent and all siblings around the string from 1.
3. Repeat 2 until at root.


Question:
The developer environment db server is SqlServer 2005 (developer edition)

Is there any way to make sure my SQL Queries will run in SqlServer 2000?

This database is set to Compatibility level "SQL Server 2000 (80)" but some queries that run without problems in the development system can not run in the Test Server (SqlServer).

(The problems seems to be in subqueries)

Answer:
Compatibility levels are designed to work the opposite way - to allow an older version of T-SQL code to work without modifications on a newer version of SQL Server.  The changes typically involve T-SQL syntax and reserved words, and it's possible to use SQL Server 2005 features such as INCLUDED columns in indexes on a database in Compatibility Level 80.  However, you can't use 2005 T-SQL features such as CROSS APPLY.
Your best option is to develop/test all your code against a SQL Server 2000 instance.  Note that you can use 2005's Management Studio to connect to the SQL Server 2000 instance, so you don't have to go backwards with regards to tools.


Question: We need to see what methods/fields an object has in Javascript.

Answer:
If you are using firefox then the
firebug plug-in
console is an excellent way of examining objects
```
```
console.debug(myObject);
```
```
Alternatively you can loop through the properties (including methods) like this:
```
```
for (property in object) {
    // do what you want with property, object[property].value
}
```
```


Question:
I've found an interesting article about Lucene and geosearching:

http://sujitpal.blogspot.com/2008/02/spatial-search-with-lucene.html

Is there an equivilant .NET implementation out there that I have been unable to find or do I have to rework the Java-code in his example to fit in the .NET Framework?

Answer:
I came across this article, as well.  I do not see a .NET-specific in my Googling, so I am planning on probably porting this code when the need arises, as well.  Right now, I am just getting my feet wet with Lucene.NET and have not gotten to the point that I am comfortable enough with it to start extending it, yet.
The code in the article appears to be a derived example of the conceptual geo-distance functionality outlined in Lucene In Action.  Although the book is based on the Java product, it is a great read.  The samples port easily and it is full of information.


Question: How can I get a full list of Groups in my Active Directory?

Answer:
Microsoft .NET Framework provides a standard library for working with Active Directory:
System.DirectoryServices namespace
in the System.DirectoryServices.dll.
Microsoft recommends using two main classes from the System.DirectoryServices namespace:
DirectoryEntry
and
DirectorySearcher
. In most cases, it is enough to use DirectorySearcher class only.
You can find some examples in this
CodeProject article
.


Question:
A.Event1 := nil;
A.Event2 := nil;
try
  ...
finally
  A.Event1 := MyEvent1;
  A.Event2 := MyEvent2;
end;

Can something go wrong with it?

EDIT:

I've accepted Barry's answer because it answered exactly what I asked, but Vegar's answer is also correct depending on the scenario, sadly I can't accept both.

Answer:
It entirely depends on what happens in the bit of code marked '...'. If it e.g. starts up a background thread and tries to invoke Event1 or Event2 after execution has continued into the finally block, you may get unexpected results.
If the code is entirely single-threaded, then yes, neither Event1 nor Event2 should be triggered while the code is between the try and finally.
However, that does assume that Event1 and Event2 properties (all Delphi events are properties of a method pointer type) do not do unusual things in their setters. A pathologically malicious event setter could squirrel away a method pointer, and still be able to invoke it, even after you later call the setter with 'nil' as the value.
But that would be highly unusual behaviour.


Question:
I know how to disable WSDL-cache in PHP, but what about force a re-caching of the WSDL?

This is what i tried: I run my code with caching set to disabled, and the new methods showed up as espected. Then I activated caching, but of some reason my old non-working wsdl showed up again. So: how can I force my new WSDL to overwrite my old cache?

Answer:
I'd try
```
```
$limit = ini_get('soap.wsdl_cache_limit');
ini_set('soap.wsdl_cache_limit', 0);
ini_set('soap.wsdl_cache_limit', $limit);
```
```
Or possibly set
```
soap.wsdl_cache_ttl
```
to 0 and back


Question:
I have the following code in Visual Studio 2005.

    Dim OutFile As System.IO.StreamWriter
    Try
        OutFile = New System.IO.StreamWriter(Filename)
       // Do stuff with OutFile
    Catch Ex As Exception
       // Handle Exception
    Finally
       If OutFile IsNot Nothing Then OutFile.Close()
    End Try

But VS2005 brings up the warning for the line "If OutFile IsNot.." that

Variable 'OutFile' is used before it has been assigned a value. A null reference exception could result at runtime.

Is there some way of removing this warning by subtly altering the code or is there just a better way of doing what I'm trying to do?

Thanks

Rob

Answer:
```
```
Dim OutFile As System.IO.StreamWriter
OutFile = Nothing
Try
    OutFile = New System.IO.StreamWriter(Filename)
   // Do stuff with OutFile
Catch Ex As Exception
   // Handle Exception
Finally
   If OutFile IsNot Nothing Then OutFile.Close()
End Try
```
```
Similar to
C# error: Use of unassigned local variable


Question:
I have the following route defined

            routes.MapRoute(
            "ItemName",
            "{controller}/{action}/{projectName}/{name}",
            new { controller = "Home", action = "Index", name = "", projectName = "" }
            );

This route actually works, so if I type in the browser

/Milestone/Edit/Co-Driver/Feature complete

It correctly goes to the Milestone controller, the edit action and passes the values.

However, if I try and construct the link in the view with a url.action -

<%=Url.Action("Edit", "Milestone", new {name=m.name, projectName=m.Project.title})%>

I get the following url

Milestone/Edit?name=Feature complete&projectName=Co-Driver

It still works, but isn't very clean. Any ideas?

Answer:
You can try
```
```
Html.RouteLink("Edit","ItemName", new {name=m.name, projectName=m.Project.title});
```
```


Question: Has anyone encountered the following problem: I have IIS7 running on my computer. On that same computer, I open IE7 and the website works (http://localhost/web.site/Default.aspx). Put that same url in Firefox 3 and I get the welcome screen of IIS7, a big image with IIS7 in the middle and 'Welcome' in several different languages. Clicking on the image leads you to http://www.iis.net/.

Answer:
One browser accesses your server via 127.0.0.1, and another via your external IP.
Make sure virtualhost works with all network interfaces.


Question:
Question so easy that fitted in the title :)
Eclipse (pydev): Is it possible to assign a shortcut to send selection to the python console?

Answer:
One browser accesses your server via 127.0.0.1, and another via your external IP.
Make sure virtualhost works with all network interfaces.


Question:
I haven't played with CSS for too long a time and am without references at the moment. My question should be fairly easy but googling isn't bringing up a sufficient answer. So, adding to the collective knowledge...

|#header---------------------------------------------------------------|
|                               TITLE                                  |
|#sub-title------------------------------------------------------------|
|bread > crumb                    |                  username logout   |
|#sub-left                        |                          #sub-right|
|---------------------------------|------------------------------------|

That's what I'm wanting my layout to be. The heading anyways. I wanted sub-title to contain sub-left AND sub-right. What css rules do I use to ensure a div is bound by the attributes of another div. In this case, how do I ensure that sub-left and sub-right stay within sub-title?

Answer:
Something like this perhaps...
```
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

                 #head

                #sub-title

                    #sub-left

                    #sub-right

```
```


Question:
I'm currently developing a PHP application that's using an Access database as a backend. Not by choice you understand... the database is what the client used originally and using it is part of the requirements.

One of the problems with this database is that the column names have the most insane naming convention you could possibly imagine. Uppercase, lowercase, underscores, spaces and the plain insane. For example the column "gender" holds a date. And so does column "User2". There's a lot more but you get the idea.

Faced with this I decided to create an array to map the database columns to PHP variables so we can isolate the code from the madness. However my colleague believes that I'm over-complicating things and we should use the database's column names for the corresponding PHP variables so we don't need to go through the mapping array to find what goes where.

So my question is this... am I doing the right thing or am I complicating things?

Answer:
Absolutely you are on the right track.  If you don't abstract away the madness you will eventually succumb to the madness yourself.
Your colleague has a valid point though, so I suggest you also code an easy way to determine the data to column mapping in PHP.
This isn't about keeping it simple, it's about retrofitting a solid foundation to build upon.
The thing that would worry me is that this kind of random design often hides certain business rules, things like "...if the gender is a date then they must have purchased a widget at some point therefore they can't be allowed to fribbish the lubdub... " - crazy I know but more common than it should be.


Question:
When designing a file format for recording binary data, what attributes would you think the format should have? So far, I've come up with the following important points:

have some "magic bytes" at the beginning, to be able to recognize the files (in my specific case, this should also help to distinguish the files from "legacy" files)

have a file version number at the beginning, so that the file format can be changed later without breaking compatibility

specify the endianness and size of all data items; or: include some space to describe endianness/size of data (I would tend towards the former)

possibly reserve some space for further per-file attributes that might be necessary in the future?

What else would be useful to make the format more future-proof and minimize headache in the future?

Answer:
Take a look at the
PNG spec
. This format has some very good rationale behind it.
Also, decide what's important for your future format: compactness, compatibility, allowing to embed other formats (different compression algorithms) inside it. Another interesting example would be the
Google's protocol buffers
, where size of the transferred data is the king.
As for endianness, I'd suggest you to pick one option and stick with it, not allowing different byte orders. Otherwise, reading and writing libraries will only get more complex and slower.


Question:
Can anyone please help me to get all the domains in Active Directory. I have tried many times, but all the programs are listing only the current working domain.

How can I do this?

Answer: Using DirectorySearcher you can connect and read the structure of one Active Directory, including the structure (organization units, groups, users, computers, domain controllers). In order to connect to a different domain, you would need credentials of that other domain. We had problems in connecting to another domain from a machine that belongs to a different domain than the target one. I'm also curious if that's even possible.


Question:
This is more of an academic inquiry than a practical question.  Are there any language or framework features that can, or will in future, allow a heterogeneous typed dcitionary, e.g.

myDict.Add("Name", "Bill");
myDict.Add("Height", 1.2);

where myDict now contains not two object types as values, but one string and one double?  I could then retrieve my double with

double dbl = myDict["Height"];

and expect a double or an exception to be thrown?

Please note:  The Name and Height values are not necessarily of the same object.

Answer:
You can use Generic
```
Dictionary<object, object>
```
; object type for key and object type for value. C# could help.


Question:
I have this code

while($row = mysql_fetch_row($result))
{
echo '<tr>';
$pk = $row[0]['ARTICLE_NO'];

foreach($row as $key => $value)
{
echo '<td><a href="#" onclick="GetAuctionData(\''.$pk.'\')">' . $value . '</a></td>';
}

which gets pk. pk is then passed on to the axjax part with this:

function GetAuctionData(pk)
{
.....
var url="get_auction.php?"
url=url+"cmd=GetAuctionData&pk="+pk;

And finally used in a separate php file with:

$pk = $_GET["pk"];
$sql="SELECT * FROM Auctions WHERE ARTICLE_NO ='$pk'";

the second php file works fine when using it by itself and passing parameters. Likewise there are no errors anywhere. The problem seems to be with passing or generating $pk, as the links in the output file result in $pk being incremednted by 2, eg 4, 6, 8 etc

I can not understand why this is happening.

Answer:
I don't think this does what you expect:
```
```
$pk = $row[0]['ARTICLE_NO'];
```
```
Try with:
```
```
$pk = $row['ARTICLE_NO'];
```
```


Question:
I need to test a url that it does not end with .asp

So test, test.html and test.aspx should match, but test.asp should not match.

Normally you'd test if the url does end with .asp and negate the fact that it matched using the NOT operator in code:

if(!regex.IsMatch(url)) { // Do something }

In that case the regular expression would be \.asp$ but in this case I need the regular expression to result in a match.

Background: I need to use the regular expression as a route contraint in the ASP.NET MVC RouteCollection.MapRoute extension method. The route needs to match all controllers but it should fall through when the controller in the url ends with .asp

Answer:
Try this
```
```
^((?!\.asp$).)*$
```
```


Question:
Does anyone know of a definitive list of LINQ to SQL query limitations that are not trapped at compile time, along with (where possible) workarounds for the limitations?

The list we have so far is:

Calling methods such as .Date on DateTime

no workaround found

string.IsNullOrEmpty

simple, just use == "" instead

.Last()

we used .OrderByDescending(x => x.WhateverProperty).First()

Answer:
Basically, that list is huge... it is everything outside of the relatively
small set of things that
are
handled
. Unfortunately, the
Law Of Leaky Abstractions
kicks in, and each provider has different answers...
LINQ-to-Objects will do anything (pretty much), since it is delegates; LINQ-to-SQL and Entity Framework have
different
sets of support.
In general, I've had a fair amount of success using the
```
DateTime
```
properties etc - but in reality, you're going to have to ensure that your query expressions are covered by unit tests, so that if you ever change providers (or the provider gets updated) you know it all still works.
I guess one view is to think in terms of TSQL; there is no
```
BOTTOM n
```
, but there is a
```
TOP 1
```
(re the
```
OrderByDescending
```
); In terms of
```
string.IsNullOrEmpty
```
, you could be quite literal:
```
foo.Bar == null || foo.Bar == ""
```
; and with
```
DateTime.Date
```
you can probably do quite a bit with
```
DATEPART
```
/ the various components.
Another option with LINQ-to-SQL is to encapsulate the logic in a UDF - so you could write a UDF that takes a
```
datetime
```
and returns a
```
datetime
```
, and expose that via the dbml onto the data-context. You can then use that in your queries:
```
```
where ctx.Date(foo.SomeDate) == DateTime.Today
```
```
This approach, however, doesn't necessarily make good use of indexes.
Update:
The supported method translations etc are
here
.
The supported query operations etc are
here
.
For the full gory details, you can look at
```
System.Data.Linq.SqlClient.PostBindDotNetConverter+Visitor
```
in reflector - in particular the
```
Translate...
```
methods; some
```
string
```
functions are handled separately. So not a
huge
selection - but this is an implementation detail.


Question: Is it possible to make a big 50MB database native on the iPhone?  So that it can be searched very quickly in a smart way?  With SQlite?

Answer:
There's some talk to a
SQLite for iPhone SDK
in this article. It uses
FMDB
, which is a cocoa wrapper fro SQLite3


Question:
I'm wondering if it's possible to define a foreign key in a models.py file in Django that is a reference to a table in another app?

In other words, I have two apps, called cf and profiles, and in cf/models.py I have (amongst other things):

class Movie(models.Model):
    title = models.CharField(max_length=255)

and in profiles/models.py I want to have:

class MovieProperty(models.Model):
    movie = models.ForeignKey(Movie)

But I can't get it to work. I've tried:

    movie = models.ForeignKey(cf.Movie)

and I've tried importing cf.Movie at the beginning of models.py, but I always get errors, such as:

NameError: name 'User' is not defined

Am I breaking the rules by trying to tie two apps together in this way, or have I just got the syntax wrong?

Answer:
OK - I've figured it out. You can do it, you just have to use the right
```
import
```
syntax. The correct syntax is:
```
```
from prototype.cf.models import Movie
```
```
My mistake was not specifying the
```
.models
```
part of that line. D'oh!


Question:
It' possible to use Junitperf with junit4?
I've a simplet Junit4 test class with several tests and I want to do a TimedTest on single test of that class. How can I do that?

To be more clear my Junit4 class is something like:

public class TestCitta {

    @Test
    public void test1 {}

        @Test
    public void test2 {}
}

with junit3 i shold write something like:

public class TestCittaPerformance {

    public static final long toleranceInMillis = 100;

    public static Test suite() {

        long maxElapsedTimeInMillis = 1000 + toleranceInMillis;

        Test testCase = new TestCitta("test2");

        Test timedTest = new TimedTest(testCase, maxElapsedTimeInMillis);

        return timedTest;
    }

    public static void main(String args[]) {
        junit.textui.TestRunner.run(suite());
    }
}

with Junit4?

Answer:
I had the same problem but was not lucky trying to make it run in different build environments. So I used the @Rule feature available since JUnit 4 to inject performance test invocation and requirements checking using annotations. It turned out to become a small library which replaced JUnitPerf in this project and I published it under the name
contiperf
. If you are interested in this approach, you can find it at
https://github.com/lucaspouzac/contiperf
.


Question:
I have a project with several sources directories :

src/A
   /B
   /C

In each, the Makefile.am contains

AM_CXXFLAGS = -fPIC -Wall -Wextra

How can avoid repeating this in each source folder ?

I tried to modifiy src/Makefile.am and the configure.in, but without success. I thought I could use AC_PROG_CXX to set the compilation flags globally but can't find much documentation on how to use those macro (do you have any pointer to such a documentation ?).

Thanks in advance

Answer:
You can do several things:
(1) One solution is to include a common makefile fragment on all your
```
Makefile.am
```
s:
```
```
include $(top_srcdir)/common.mk
...
bin_PROGRAMS = foo
foo_SOURCES = ...
```
```
in that case you would write
```
```
AM_CXXFLAGS = -fpic -Wall -Wextra
```
```
to
```
common.mk
```
and in the future it will be easier to add more macros or rules to all
```
Makefile.am
```
s by just editing this file.
(2) Another solution would be to set these variables globally in your
```
configure.ac
```
(the name
```
configure.in
```
has been deprecated long ago), as in :
```
```
...
AC_SUBST([AM_CXXFLAGS], [-fpic -Wall -Wextra])
...
```
```
Then you don't even have to say anything in your
```
Makefile.am
```
s, they automatically inherit this global definition.  The drawback is that you can't opt-out easily (with the first solution it's easy to decide not to include
```
common.mk
```
) and the dependency is not really explicit to third-party people (when they read the
```
Makefile.am
```
they have no hint about where the flags may come from).
(3) A third solution would be to do as
orsogufo
suggested: overwriting the user variable CXXFLAGS in
```
configure.ac
```
.  I would advise against it, because it defeats one of the features of the GNU Build System: users are allowed to override this variable at
```
make
```
-time.   For instance you may want to type
```
```
make CXXFLAGS='-O0 -ggdb'
```
```
when debugging a piece of code, and this will overwrite any definition of
```
CXXFLAGS
```
(but
not those in
```
AM_CXXFLAGS
```
).  To be honest, most projects fails to support this correctly because they play tricks with
```
CXXFLAGS
```
.
Finally, I should mention that
```
-fpic
```
,
```
-Wall
```
, and
```
-Werror
```
are not portable options.
Depending on the scope of your project you may want to add configure check for these (
gnulib
recently acquired new macros to tests for warnings flags, and
libtool
can be used to build shared libraries).


Question:
This code

select.select([sys.stdin], [], [], 1.0)

does exactly what I want on Linux, but not in Windows.

I've used kbhit() in msvcrt before to see if data is available on stdin for reading, but in this case it always returns 0.  Additionally msvcrt.getch() returns '\xff' whereas sys.stdin.read(1) returns '\x01'.  It seems as if the msvcrt functions are not behaving properly.

Unfortunately I can't use TCP sockets as I'm not in control of the application talking my Python program.

Answer:
In some rare situations, you might care what stdin is connected to.  Mostly, you don't care -- you just read stdin.
In
```
someprocess | python myprogram.py
```
, stdin is connected to a pipe; in this case, the stdout of the previous process.  You simply read from
```
sys.stdin
```
and you're reading from the other process.  [Note that in Windows, however, there's still (potentially) a "CON" device with a keyboard.  It just won't be
```
sys.stdin
```
.]
In
```
python myprogram.py <someFile
```
, stdin is connected to a file.  You simply read from
```
sys.stdin
```
and you're reading from the file.
In
```
python myprogram.py
```
, stdin is left connected to the console (
```
/dev/ttyxx
```
in *nix).  You simple read from
```
sys.stdin
```
and you're reading from the keyboard.
Note the common theme in the above three cases.  You simply read from
```
sys.stdin
```
and your program's environment defines everything for you.  You don't check "to see if data is available on stdin for reading".  It's already available.
Sometimes, you want a keyboard interrupt (or other shenanigans).  Python, BTW, has a keyboard interrupt as a first-class feature of the I/O elements.  Control-C raises an interrupt during I/O (it won't break into a tight loop, but it will signal a program that prints periodically.)
Sometimes you need to find out what kind of file
```
stdin
```
is connected to.
Something like
```
os.isatty( sys.stdin.fileno() )
```
If
```
sys.stdin
```
is a TTY, you're program was left connected to the windows "CON" (the keyboard).  If
```
sys.stdin
```
is not a TTY, it's connected to a file or a pipe.
Example
```
```
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\slott>python
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import sys
>>> os.isatty( sys.stdin.fileno() )
True
>>>
```
```
The value of
```
True
```
tells me Python is running without a file or pipe attached.
```
sys.stdin
```
is the keyboard.  Using windows
```
kbhit
```
is needless.
A value of
```
False
```
tells me Python is running with a file or pipe attached.
```
sys.stdin
```
is NOT the keyboard.  Checking
```
kbhit
```
might be meaningful.  Also, I could open the
```
CON:
```
device and read the keyboard directly, separate from
```
sys.stdin
```
.
I'm not sure why you need "to see if data is available on stdin for reading".  It might help to update your question with additional details of what you're trying to accomplish.


Question:
I am wondering how I should properly get rid of branches that no longer have any purpose. Right now even if i delete them and commit they are still listed as branches in the properties windows for a particular branching root (directory). If I select merge I don't get an option to merge to the deleted branch which obviously is as expected but therefore I am puzzled about the branch still showing up in the properties window.

Any explanation on this behavior would be greatly appreciated.

Answer:
The deleted branch is only marked as deleted at a moment in time and it's possible to still get to the code if you sync to a changeset or time before that delete operation.
If you do not want to have the file in the branch in the database at all you can use the
```
tf destroy
```
command line:
http://msdn.microsoft.com/en-us/library/bb386005.aspx
As your branch is already deleted you'll need to use
```
tf dir /deleted
```
to find the deletion number of that branch in order to destroy the files.


Question:
How do you combine two jQuery search results? eg:

var $allFoos = $('.foo'),
    $allBars = $('.bar')
    $allFoosAndBars = $allFoos + $allBars;

Obviously, I just made up that last line, but I hope it makes it sorta clear what I mean. To be clear, the example is greatly simplified, and it could be any arbitrary sets i'm talking about, so $('.foo, .bar') is not what I'm after.

Answer:
You can use
add()
;
```
```
var $foos = $('.foo');

var $foosAndBars = $foos.add('.bar');
```
```
or
```
```
var $allFoosAndBars = $allFoos.add($allBars);
```
```


Question:
I need to edit /etc/sudoers from a script to add/remove stuff from white lists.

Assuming I have a command that would work on a normal file, how could I apply it to /etc/sudoers?

Can I copy and modify it, then have visudo replace the original with the modified copy? By providing my own script in $EDITOR?

Or can I just use the same locks and cp?

The question is more about potential issues than about just finding something that works.

Answer:
You should make your edits to a temporary file, then use visudo -c -f sudoers.temp to confirm that the changes are valid and then copy it over the top of /etc/sudoers
```
```
#!/bin/sh
if [ -f "/etc/sudoers.tmp" ]; then
    exit 1
fi
touch /etc/sudoers.tmp
edit_sudoers /tmp/sudoers.new
visudo -c -f /tmp/sudoers.new
if [ "$?" -eq "0" ]; then
    cp /tmp/sudoers.new /etc/sudoers
fi
rm /etc/sudoers.tmp
```
```


Question: We're usually 1-4 developers / art directors / copywriters on each project at my firm, what methodology would you recommend use to use? Agile? XP? Scrum? Something else? (I know they are all variations of essentially the same concept, yes)

Answer:
I don't think there's a general answer for it, the question is too broad, and you can't just "adopt a methodology" as if it were a product that you take out of the box, it's something that you evolve over time...but in any case I highly recommend you getting a copy of this book:
Head First Software Development
Then you adapt the ideas you like into your project. Don't worry about names and buzzwords, they will be all "passé" next year anyway.
Keep it simple
at first, adopt the ideas that make more sense and give the most bang for buck, and don't try to solve problems that don't exist yet. It will be a very good start.


Question:
Quick question: Would it be a good or a bad idea to implement my domain-driven design style repositories as singletons? Why?

Or should I maybe use a dependency injector container to manage my repositories and decide if they are singletons or not?

I'm still reading DDD Quickly, and would like to see some good repository examples.

Answer:
Use your dependency injection container to decide how and where repositories are created.
By using
```
```
UserRepository.Instance.Find(userId);
```
```
you're creating a barrier to testing.
If your repositories are passed into services using Constructor Injection, then you can also easily replace them with mocks.


Question:
After creating a translucent window (based on example code by Matt Gemmell) I want to get keyboard events in this window.  It seems that there are only keyboard events when my application is the active application while I want keyboard events even when my application isn't active but the window is visible.

Basically I want behavior like that provided by the Quicksilver application (by blacktree).

Does anybody have any hints on how to do this?

Answer:
There are two options:
Use
```
GetEventMonitorTarget()
```
with a tacked-on Carbon run loop to grab keyboard events. Sample code is available on
this page
at CocoaDev.
Register an event trap with
```
CGEventTapCreate
```
. Sample code can be found in
this thread
from the Apple developer mailing list.
Edit:
Note that these methods only work if you check off “Enable access for assistive devices” in the Universal Access preference pane.


Question:
I'm trying to find out how much memory my objects take to see how many of them are ending up on the Large Object Heap (which is anything over 85,000 bytes).

Is it as simple as adding 4 for an int, 8 for a long, 4 (or 8 if you're on 64 bit) for any reference types etc for each object, or are there overheads for methods, properties, etc.?

Answer:
Don't forget that the size of an actual object doesn't include the size of any objects it references.
The only things which are likely to end up on the large object heap are arrays and strings - other objects tends to be relatively small in themselves. Even an object with (say) 10 reference type variables (4 bytes each on x86) and 10 GUIDs (16 bytes each) is only going to take up about 208 bytes (there's a bit of overhead for the type reference and sync block).
Likewise when thinking about the size of an array, don't forget that if the element type is a reference type, then it's only the size of the
references
that count for the array itself. In other words, even if you've got an array with 20,000 elements, the size of the array object itself will only be just over 80K (on x86) even if it references a lot more data.


Question:
I want to know how to set a Publishing page content through the code (MOSS 2007).

This is how I've created the page:

PublishingPage page = publishingWeb.GetPublishingPages().Add("MyPage.aspx", pageLayout);
SPFile pageFile = page.ListItem.File;
page.Title = "My Page";
page.Update();

But my attempts of setting it's content didn't work.

Answer:
I don't know if it's
ok
to answer my own question, but after reflecting Sharepoint's codebehind I was able to find a way to set the page's content:
```
```
string content = "Welcome to My Page";
page.ListItem[FieldId.PublishingPageContent] = content;
```
```


Question: I know each iPhone has a electronic identifier other than the phone # or ESN - how do I call it and what does it return?

Answer:
The UIDevice class contains the information you need.
```
[[UIDevice currentDevice] uniqueIdentifier]
```


Question:
I'm looking at building a Rails application which will have some pretty
large tables with upwards of 500 million rows.  To keep things snappy
I'm currently looking into how a large table can be split to more
manageable chunks.   I see that as of MySQL 5.1 there is a partitioning
option and that's a possible option but I don't like the way the column
that determines the partitioning has to be part of the primary key on
the table.

What I'd really like to do is split the table that a AR model writes to
based upon the values written but as far as I am aware there is no way
to do this - does anyone have any suggestions as to how I might
implement this or any alternative strategies?

Thanks

Arfon

Answer:
Partition columns in MySQL are not limited to primary keys. In fact, a partition column does not have to be a key at all (though one will be created for it transparently). You can partition by RANGE, HASH, KEY and LIST (which is similar to RANGE only that it is a set of discrete values). Read the MySQL manual for
an overview
of partioning types.
There are alternative solutions such as
HScale
- a middleware plug-in that transparently partitions tables based on certain criteria.
HiveDB
is an open-source framework for horizontal partioning for MySQL.
In addition to sharding and partioning you should employ some sort of clustering. The simplest setup is a replication based setup that helps you spread the load over several physical servers. You should also consider more advanced clustering solutions such as MySQL cluster (probably not an option due to the size of your database) and clustering middleware such as
Sequioa
.
I actually asked a relevant question regarding
scaling with MySQL
here on stack-overflow some time ago, which I ended up answering myself several days later after collecting a lot of information on the subject. Might be relevant for you as well.


Question:
Can anyone point me out, how can I parse/evaluate HQL and get map where key is table alias and value - full qualified class name.

E.g. for HQL

SELECT a.id from Foo a INNER JOIN a.test b

I wish to have pairs:

a, package1.Foo

b. package2.TestClassName

It's relatively easy to do for result set

HQLQueryPlan hqlPlan = ((SessionFactoryImpl)sf).getQueryPlanCache().getHQLQueryPlan( getQueryString(), false, ((SessionImpl)session).getEnabledFilters() );
String[] aliases = hqlPlan.getReturnMetadata().getReturnAliases();
Type[] types = hqlPlan.getReturnMetadata().getReturnTypes();

See details here.

Answer:
Hardly a good way of doing it, but it seems you can get the AST through some internal interfaces and traverse this:
```
```
QueryTranslator[] translators = hqlPlan.getTranslators();
AST ast = (AST)((QueryTranslatorImpl)translators[0]).getSqlAST();
    new NodeTraverser(new NodeTraverser.VisitationStrategy() {
    public void visit(AST node) {
        if(node.getType() == SqlTokenTypes.FROM_FRAGMENT || node.getType() == SqlTokenTypes.JOIN_FRAGMENT) {
            FromElement id = (FromElement)node;
            System.out.println(node+": "+id.getClassAlias()+" - "+id.getClassName());
        }
    }
}).traverseDepthFirst(ast);
```
```
So this seems to retrieve the alias-mappings from the compiled query, but I would be very careful using this solution: it typecasts objects to subclasses not usually visible to a hibernate-client and interprets the AST based on guessing the semantics of the different nodes.  This might not work on all HQL-statements, and might not work, or have different behaviour, on a future hibernate-version.


Question:
What are the pros and cons of adopting Open Source software for an organisation? Is there anybody out there who has done this and how well has it been working out with some examples of the softwares they adopted and how it has been in use?

Usually contributions come because people do it as a hobby, then how can we make sure that there will be continued support for it? IMHO, in case of proprietary software there is an incentive for the organisation (money), and they will keep hiring people to keep it under development as long as the software is profitable. Correct me if I am wrong. What are the arguments I might expect from a Manager who might oppose the suggestion to use Open Source softwares?

Answer:
The term "Open Source" only describes a licensing model.  Strictly speaking, the only pro that you are guaranteed to have are the freedoms given by the license, and there are no cons that you are guaranteed to have.
There are many Open Source products that are also commercial, created, maintained, and supported by a company for a profit.  There are also many Open Source products that are maintained by volunteers but also supported commercially.  For example, if you buy Red Hat Enterprise Linux, then Red Hat will support you on all of the products that come with it, even the ones that are maintained by volunteers.
As for how to be sure that there will be continued support, you can't.  Not with Open Source, not with proprietary software, not with anything.  With Open Source, if the community is large enough, you can be reasonably confident that the community will continue to maintain it (maybe under a new name) even if the current maintainers abandon it, and you have the option of maintaining it yourself or hiring someone else to do it.  Maintaining it yourself may not be an attractive option, but it can be a life saver in a pinch.
With proprietary software, if the author decides to stop maintaining it, you are just plain out of luck.  Consider, for example, the thousands of users of Visual Basic 6.


Question:
I wonder if with a simple Map<String,Object> implementation for plain records is enough.

I want to do it similar to Ror. When you add a field to the table in the database automatically you have access to the field in the Dto.

I don't want to add a field and then have to add the same field to the DTO declaration. It isn't DRY.

Answer:
What I think you're looking for a is very lightweight Object Relational Mapping tool?
If you want to roll your own, then there is a tiny example one as part of
this article
on developerWorks.
You may want to look at any number of others but Hibernate, JPA and JDO are probably the most popular.
Prevayler
type systems may be what you're looking for. Of course, none of this may not be what you're after. Could you be a little more specific?


Question:
Imagine I have the following:

inFile = "/adda/adas/sdas/hello.txt"

# that instruction give me hello.txt
Name = inFile.name.split("/") [-1]

# that one give me the name I want - just hello
Name1 = Name.split(".") [0]

Is there any chance to simplify that doing the same job in just one expression?

Answer:
```
```
>>> inFile = "/adda/adas/sdas/hello.txt"
>>> inFile.split('/')[-1]
'hello.txt'
>>> inFile.split('/')[-1].split('.')[0]
'hello'
```
```


Question:
We are deciding the naming convention for tables, columns, procedures, etc. at our development team at work. The singular-plural table naming has already been decided, we are using singular. We are discussing whether to use a prefix for each table name or not. I would like to read suggestions about using a prefix or not, and why.

Does it provide any security at all (at least one more obstacle for a possible intruder)? I think it's generally more comfortable to name them with a prefix, in case we are using a table's name in the code, so to not confuse them with variables, attributes, etc. But I would like to read opinions from more experienced developers.

Answer:
I prefer prefixing tables and other database objects with a short name of the application or solution.
This helps in two potential situations which spring to mind:
You are less likely to get naming conflicts if you opt to use any third-party framework components which require tables in your application database (e.g. asp net membership provider).
If you are developing solutions for customers, they may be limited to a single database (especially if they are paying for external hosting), requiring them to store the database objects for multiple applications in a single database.


Question:
trying to mount an smb share on OS X so that the 'www' user can read files from there.

the SMB share is accessible via an Active Directory account. I can mount the share through the Finder (cmd-k ...)

my basic approach is

# 1) create mountpoint
sudo mkdir /Volumes/www_mdisk

# 2) permissions for mountpoint
sudo chown www:www /Volumes/www_mdisk; sudo chmod 777 /Volumes/www_mdisk

# 3) make a link from apache docroot to mountpoint (http.conf FollowSymlinks is on)
cd /Library/WebServer/Documents; ln -s /Volumes/www_mdisk mdisk

# 4) mount the SMB share using the Active Directory user 'ad_user'
sudo mount_smbfs -O www/www '//DOMAIN;ad_user@smbshare_host/sharepath'

step 4 fails though. I have read the manpages, tried many different combinations (with or without -O switch), but can't get it to work

can you help me get it right?
thanks!

Answer:
ok, I can do this now on Mac OS X 10.4
```
```
# 4) mount the SMB share using the Active Directory user 'ad_user'
sudo mount_smbfs -O www/www -u 70 -g 70 '//DOMAIN;ad_user@smbshare_host/sharepath' www_mdisk

# 5) make sure http.conf has 'Options Indexes' enabled for Docroot
duh.
```
```
So everything works now on 10.4, following the steps above.
problem is, step 4) doesn't work on Mac OS X 10.5. mount_smbfs has lost the '-O' option...
Anybody knows how to do this on 10.5?


Question:
We are looking at various options in porting our persistence layer from Oracle to another database and one that we are looking at is MS SQL. However we use Oracle sequences throughout the code and because of this it seems moving will be a headache. I understand about @identity but that would be a massive overhaul of the persistence code.

Is it possible in SQL Server to create a function which could handle a sequence?

Answer:
That depends on your current use of sequences in Oracle. Typically a sequence is read in the Insert trigger.
From your question I guess that it is the persistence layer that generates the sequence before inserting into the database (including the new pk)
In MSSQL, you can combine SQL statements with ';', so to retrieve the identity column of the newly created record, use INSERT INTO ... ; SELECT SCOPE_IDENTITY()
Thus the command to insert a record return a recordset with a single row and a single column containing the value of the identity column.
You can of course turn this approach around, and create Sequence tables (similar to the dual table in Oracle), in something like this:
```
```
INSERT INTO SequenceTable (dummy) VALUES ('X');
SELECT @ID = SCOPE_IDENTITY();
INSERT INTO RealTable (ID, datacolumns) VALUES (@ID, @data1, @data2, ...)
```
```


Question:
Ever since the publication of Enterprise Integration Patterns people have been using the notation introduced in that book for documenting asynchronous heterogenous messaging systems.

But our shop is more or less standardized around a proprietary documentation tool that does exclusively UML. Is one of the standard UML diagrams appropriate for documenting asynchronous messaging systems, including transformers, routers et al.? If yes, which one? If not, what would be a killer argument against the tweaking of UML for this purpose?

Answer:
UML provides a mechanism for extension through
profiles
A profile allows you to specify stereotypes, tagged values, and constraints.
Every stereotype can have an optional stereotype icon.
Perhaps there is an EIP profile for UML you could download?
If not, you can build your own profile if your UML tool supports this, and use the icons available as Visio shapes from
Gregor Hohpe's website
Hope this helps.


Question:
I have developed a framework that is used by several teams in our organisation. Those "modules", developed on top of this framework, can behave quite differently but they are all pretty resources consuming even though some are more than others. They all receive data in input, analyse and/or transform it, and send it further.

We planned to buy new hardware and my boss asked me to define and implement a benchmark based on the modules in order to compare the different offers we have got.

My idea is to simply start sequentially each module with a well chosen bunch of data as input.

Do you have any advice? Any remarks on this simple procedure?

Answer:
The most meaningful benchmark is to measure how your code performs under everyday usage.  That will obviously provide you with the most realistic numbers.
Choose several real-life data sets and put them through the same processes your org uses every day.  For extra credit, talk with the people that use your framework and ask them to provide some "best-case", "normal", and "worst-case" data.  Anonymize the data if there are privacy concerns, but try not to change anything that could affect performance.
Remember that you are benchmarking and comparing two sets of hardware, not your framework.  Treat all of the software as a black box and simply measure the hardware performance.
Lastly, consider saving the data sets and using them to similarly evaluate any later changes you make to the software.


Question:
I'm compiling a vc8 C++ project in a WinXp VmWare session.  It's a hell of a lot slower than gcc3.2 in a RedHat VmWare session, so I'm looking at Task Manager.  It's saying a very large percentage of my compile process is spent in the kernel.  That doesn't sounds right to me.

Is there an equivalent of strace for Win32? At least something which will give me an overview of which kernel functions are being called.  There might be something that stands out as being the culprit.

Answer:
Not exactly strace, but there is a way of getting visibility into the kernel call stack, and by sampling it at times of high CPU usage, you can usually estimate what's using up all the time.
Install
Process Explorer
and make sure you configure it with symbol server support. You can do this by:
Installing
WinDebug
to get an updated dbghelp.dll
Set Process Explorer to use this version of dbghelp.dll by setting the path in the Options | Configure Symbols menu of Process Explorer.
Also in the same dialog, set the symbols path such that it includes the MS symbol server and a local cache.
Here's an example value for the symbol path:
```
```
SRV*C:\symbolcache*http://msdl.microsoft.com/download/symbols
```
```
(You can set _NT_SYMBOL_PATH environment variable to the same value to have the debugging tools use the same symbol server and cache path.) This path will cause dbghelp.dll to download symbols to local disk when asked for symbols for a module that doesn't have symbols locally.
After having set up Process Explorer like this, you can then get a process's properties, go to the threads tab, and double-click on the busiest thread. This will cause Process Explorer to temporarily hook into the process and scan the thread's stack, and then go and look up the symbols for the various return addresses on the stack. The return addresses's symbols, and the module names (for non-MS third-party drivers) should give you a strong clue as to where your CPU time is being spent.


Question: I am developing a website using CodeIgniter and PHP.  Some of my friends suggest I start using Subversion to take care of my organization.  Could someone give me a basic explanation of what SVN is without the jargon and also if it is practical for a framework where 5 files are needed to run a single page?

Answer:
SVN is a
version control
system - which means that it stores various previous versions of a given file, and allows many people to work on the same file, and in the end put all the changes together. It also helps you go back to a previous version if necessary.
You should use that in your project if there are a lot of people working on the project. But even if you are the only one working, it will be easier to manage the project if it is on version control.


Question: What's the best way to throw an exception in objective-c/cocoa?

Answer:
I use
```
[NSException raise:format:]
```
as follows:
```
```
[NSException raise:@"Invalid foo value" format:@"foo of %d is invalid", foo];
```
```


Question:
If I have several Section elements in an XML document, what XQuery do I use to get a list of all the name values?

<Section name="New Clients" filePath="XNEWCUST.TXT" skipSection="False">

Answer:
```
```
/Section/@name
```
```


Question:
I have html code that looks roughly like this:

<div id="id1">
  <div id="id2">
    <p>some html</p>
    <span>maybe some more</span>
  </div>
  <div id="id3">
    <p>different text here</p>
    <input type="text">
    <span>maybe even a form item</span>
  </div>
</div>

Obviously there's more to it than that, but that's the basic idea. What I need to do is switch the location of #id2 and #id3, so the result is:

<div id="id1">
  <div id="id3">...</div>
  <div id="id2">...</div>
</div>

Does anyone know of a function (I'm sure I'm not the first person to require this functionality) that can read and write the two nodes (and all their children) so as to swap their location in the DOM?

Answer:
In this case,
```
document.getElementById('id1').appendChild(document.getElementById('id2'));
```
should do the trick.
More generally you can use
```
insertBefore()
```
.


Question:
How can I give a general rule that includes all the expressions below?
E.g one expression, another one for sub and one for mult.
I need to use recursion but i got confused...

simplify :: Expr->Expr

simplify (Mult (Const 0)(Var"x"))
 = Const 0
simplify (Mult (Var "x") (Const 0))
 = Const 0
simplify (Plus (Const 0) (Var "x"))
= Var "x"
simplify (Plus (Var "x") (Const 0))
 = Var "x"
simplify (Mult (Const 1) (Var"x"))
= Var "x"
simplify (Mult(Var"x") (Const 1))
 = Var "x"
simplify (Minus (Var"x") (Const 0))
 = Var "x"
simplify (Plus (Const x) (Const y))
= Const (x + y)
simplify (Minus (Const x) (Const y))
= Const (x - y)
simplify (Mult (Const x) (Const y))
 = Const (x * y)
simplify x = x

Answer:
The recursion comes in when you need to deal with nested expressions.  For instance, how do you simply (Plus (Plus 2 3) (Plus 4 5))?
One approach is to break it into two functions.  Move the one level logic (which you show above) into its own function.  The main simplify function might have a rule similar to the following for Plus:
```
```
simplify (Plus x y) = simplify_one_level (Plus (simplify x) (simplify y))
```
```


Question:
This is a multi-site problem.  I have a lot of sites with .htaccess files with multiple line similar to:

rewriterule ^(page-one|page-two|page-three)/?$ /index.php?page=$1 [L]

This means that both www.domain.com/page-one and www.domain.com/page-one/ will both load www.domain.com/index.php?page=page-one

However I'm always told that it is good SEO practice to make sure you use only one URL per page so what I'd like to do make www.domain.com/page-one to redirect to www.domain.com/page-one/ via the .htaccess file.

Please note the answer I'm NOT looking for is to remove the ?$ from the end of the line as that will just cause www.domain.com/page-one to become a 404 link.

Answer:
Untested
, but can't you just do this?
```
```
RewriteRule ^(.*[^/])$ $1/
RewriteRule ^(page-one|page-two|page-three)?$ /index.php?page=$1 [L]
```
```


Question: I was wondering if it is possible to tweak the way garbage collector works on JavaMe in order to improve performance somehow(may reducing the number of passages)? I´ve seen some articles about it, but mostly directed Java SE and most of them says GC is highly dependant on the maker. How much would that be.

Answer:
I don't see any possible way to tweak the garbage collection behavior in J2ME.
If you have problems with pauses induced by garbage collections, you have to do two things:
Reduce the garbage that your program produces, by re-using objects, and avoid costly things like string concatenations (use StringBuffer instead)
Use System.gc() to force garbage collection when a little freeze doesn't matter (for example, during the "loading" screen of a game), to reduce the odds that the collector process is triggered when it's annoying.


Question:
I have an existing htaccess that works fine:

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule (.*) /default.php
DirectoryIndex index.php /default.php

I wish to modify this so that all urls that start with /test/ go to /test/default.php.

Example: http://www.x.com/hello.php -- > http://www.x.com/default.php
Example: http://www.x.com/test/hello.php -- > http://www.x.com/test/default.php

Answer:
Basically, just put
```
/test/
```
in front of your expression. Also, the parentheses are unnecessary here:
```
```
RewriteRule ^/test/ /test/default.php
```
```


Question:
Possible Duplicate:

  Symbolic simplification in Haskell (using recursion?)

The simplifications I have in mind are

0*e = e*0 = 0
1*e = e*1 = 0+e = e+0 = e-0 = e

and simplifying constant subexpressions, e.g. Plus (Const 1) (Const 2) would become Const 3. I would not expect variables (or variables and constants) to be concatenated: Var "st" is a distinct variable from Var "s".

For example simplify(Plus (Var "x") (Const 0))= Var "x"

Answer:
Well, can't you apply pattern matching to the individual cases?
```
```
simplify (Plus (Const 0) (Expr x)) = simplify (Expr x)
simplify (Plus (Expr x) (Const 0)) = simplify (Expr x)
simplify (Mult (Const 0) _) = Const 0
simplify (Mult _ (Const 0)) = Const 0
– … and so on
```
```
EDIT: Yes, of course … recursion added.


Question: I've been looking into adopting Carbon Emacs for use on my Mac, and the only stumbling block I've run into is the annoying scroll beep when you try to scroll past the end of the document. I've looked online but I can't seem to find what I should add to my .emacs that will stop it from beeping when scrolling. I don't want to silence it completely, just when scrolling. Any ideas?

Answer:
You will have to customize the
```
ring-bell-function
```
.
This page may provide hints:
http://www.emacswiki.org/emacs/AlarmBell


Question:
How can I display something over all other application. I want to to display something over all form of my program and all other programs open on my desktop (not mine).

*Top Most doesn't work I have tested and my browser can go OVER my application :S

Here is an image of when I use TopMost to TRUE. You can see my browser is over it...

http://www.freeimagehosting.net/uploads/5a98165605.png

Answer:
You can use the form instance and set the property
TopMost
to True.
If you want to be over all Windows, there are another way with
Win32 Api
calls.
Here is what you could do:
In your form class add :
```
```
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
```
```
In the form load you can add :
```
```
SetForegroundWindow(this.Handle);
```
```
This should do the trick.
Update
TopMost
should do the job BUT: Top most OR/AND the Win32 Api call will only work not inside Visual Studio (well for Vista and with VS2008 I tested it... I can't tell for other). Try running the program with the .Exe from the /bin directory, it will works.


Question:
I have installed Delphi Prism and XNA Game Studio 3.0. I have managed to translate to Delphi Prism XNA Tutorial 1 "Displaying a 3D Model on the Screen" (http://msdn.microsoft.com/en-us/library/bb197293.aspx).
Project compiles fine, but I cannot load a model. It looks like there is a new "contentproj" type in XNA that is not in Delphi Prism...
Any idea how to get it to work?

Answer:
I haven't done any XNA stuff yet, but here is my best guess :-)
So, the Content Project type is a sub-project for a standard XNA project that just compiles the game content (textures, sound etc) as a nested compile process, correct?
So I would assume that there must be some reference to the sub-project in either the project file or the solution file, perhaps the best way would be to create a simple XMA proj in C# or VB and look at the generated meta-files (csproj, contentproj etc)
Edit:
Oh, I'm suggesting here that you manually create the contentproj file and insert the reference, once you know what they look like, I assume that VS will then allow you to add, delete your content etc
That then just leaves the question of how is the XNA content pipeline compile process is fired, if it doesn't "just happen" that might be a question for marc hoffman et al
Hope this helps a little, its just a guess.
Good to see you in StackOverFlow by the way.
Rgds Tim Jarvis.


Question:
I would like to return a string with all of the contents of a CSS rule, like the format you'd see in an inline style. I'd like to be able to do this without knowing what is contained in a particular rule, so I can't just pull them out by style name (like .style.width etc.)

The CSS:

.test {
    width:80px;
    height:50px;
    background-color:#808080;
}

The code so far:

function getStyle(className) {
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
    for(var x=0;x<classes.length;x++) {
        if(classes[x].selectorText==className) {
            //this is where I can collect the style information, but how?
        }
    }
}
getStyle('.test')

Answer:
//works in IE, not sure about other browsers...
```
```
alert(classes[x].style.cssText);
```
```


Question:
Earlier versions of the Notes client would automatically turn a sent URL into a clickable link for the recipient (regardless of mail client) but with 6.5 (and presumably later) this no longer happens; that is, the URL is sent as plain text. The Notes UI allows it to be done via the Create->Hotspot->Link Hotspot menu but this gets tedious.

I'm looking for a way to create a Link Hotspot in LotusScript. My research to date leads me to believe that this isn't possible but there may be a hack of some kind.

Answer:
The automatic conversion of urls into clickable links is a user preference.
In 6.5 it is set via File/Preferences/User Preferences/Basics.  In 8 it is set via File/Prefences/Basic Notes Client Config.
I don't think you can create a url link hotspot explicitly using lotusscript.  You can create a doc link, but there is no obvious way to turn it into a url link.
You could try an approach where the form is set to render passthrough html on the client and then construct the relevant html for a link.
Update in response to comment.
The scenario is that we want to to control what a user receiving mail sees.  We have a few cases we should think about.
The recipient is using Notes and received the mail directly via notes to notes routing.
The recipient is out on the internet using any client and allows email in a rich format.
The recipient is out on the internet using any client and only allows email in plain text.
In the first case the user will see links if they turn on the option for that.  You could also create pass-through html in the rich text and that will render on the Notes client assuming the form option is set in the design.  If it's straight email and you don't really need any other rich Notes features you could also construct a  MIME message.
In the next two cases you just want to send properly formatted MIME messages.  In the first of those cases the user will accept rich formatting and therefore you can construct the message as simple html and include links that way.  In the second case the user will not, and you have to make do with plain text.  Luckily most mail clients will automatically turn urls received in plain text messages into links for you.  This may be an option as in the Notes client.
It is best practice when sending rich mail content to also include a MIME section for plain text.  That way you don't need to care what version the user prefers.


Question:
I am working on a calculator that allows you to perform calculations past the decimal point in octal, hexadecimal, binary, and of course decimal. I am having trouble though finding a way to convert floating point decimal numbers to floating point hexadecimal, octal, binary and vice versa.

The plan is to do all the math in decimal and then convert the result into the appropriate number system. Any help, ideas or examples would be appreciated.

Thanks!

Answer:
Hmm... this was a homework assignment in
my
university's CS "weed-out" course.
The operations for binary are described in
Schaum's Outline Series: Essential Computer Mathematics
by Seymour Lipschutz.  For some reason it is still on my bookshelf 23 years later.
As a hint, convert octal and hex to binary, perform the operations, convert back to binary.
Or you can perform decimal operations and perform the conversions to octal/hex/binary afterward.  The process is essentially the same for all positional number systems arithmetic.


Question:
Im trying to generate views in unit tests but i can't get around the missing VirtualPathProvider. Most viewengines use the VirtualPathProviderViewEngine base class that gets the provider from the current HostingEnvironment.

protected VirtualPathProvider VirtualPathProvider {
    get {
        if (_vpp == null) {
            _vpp = HostingEnvironment.VirtualPathProvider;
        }
        return _vpp;
    }
    set {
        _vpp = value;
    }
}

In unit tests there is no HostingEnvironment, even if i create one there is no current VirtualPathProvider.

How can i workaround this problem? Do i have to create a custom FakeWebFormViewEngine?

Answer:
I tried to do this as well.  Unfortunately, it is not just the VirtualPathProvider (VPP) that is the problem.  The VPP is used to map the view or partial view to a physical path to determine the existance of the file.  Unfortunately, the ViewContext ends up with the virtualpath, not the physical path, so when the view is rendered the Builder uses properties of the HostingEvnironment which does not exist.
If you are using a version of Visual Studio with Testing, then you could use a Web Unit Test.  This will allow you to use the browser to call the URL and then parse the response to check for values.


Question:
Given:

my @mylist1;
push(@mylist1,"A");
push(@mylist1,"B");
push(@mylist1,"C");

my @mylist2;
push(@mylist2,"A");
push(@mylist2,"D");
push(@mylist2,"E");

What's the quickest way in Perl to insert in mylist2 all elements that are in mylist1 and not already in mylist2 (ABCDE).

Answer:
```
```
my %k;
map { $k{$_} = 1 } @mylist1;
map { $k{$_} = 1 } @mylist2;
@mylist2 = keys %k;
```
```
Alternatively:
```
```
my %k;
map { $k{$_} = 1 } @mylist2;
push(@mylist2, grep { !exists $k{$_} } @mylist1);
```
```
Actually - these might be wrong because they don't account for whether duplicates might exist in either of the original lists.
You didn't say in your question whether the lists are supposed to represent sets (which can't contain duplicates) or just plain lists.  That you effectively want
```
@mylist2 = @mylist1 U @mylist2
```
suggests that you are treating them as sets.
EDIT: changed increment to assign - saves a read of the hash value


Question:
I have the following problem:

  # line is a line from a file that contains ["baa","beee","0"]
  line = TcsLine.split(",")
  NumPFCs = eval(line[2])
  if NumPFCs==0:
     print line

I want to print all the lines from the file if the second position of the list has a value == 0.

I print the lines but after that the following happens:
Traceback (most recent call last):

['baaa', 'beee', '0', '\n']

BUT after I have the next ERROR

ilation.py", line 141, in ?
    getZeroPFcs()
ilation.py", line 110, in getZeroPFcs
    NumPFCs = eval(line[2])
  File "<string>", line 0

Can you please help me?
thanks

What0s

Answer:
Your question is kind of hard to read, but using eval there is definitely not a good idea.  Either just do a direct string comparison:
```
```
line=TcsLine.split(",")
if line[2] == "0":
    print line
```
```
or use int
```
```
line=TcsLine.split(",")
if int(line[2]) == 0:
    print line
```
```
Either way, your bad data will fail you.
I'd also recomment reading
PEP 8
.


Question:
For the moment my batch file look like this:

myprogram.exe param1

The program starts but the DOS Window remains open. How can I close it?

Answer:
You can use the exit keyword. Here is an example from one of my batch files:
```
```
start myProgram.exe param1
exit
```
```


Question:
I am trying to set one bindable variable to be bound to another.  Essentially I want to create an alias.  I would give up, but this seems like something that would be good to know.

essentially, I want changes in model.configView to be reflected in view, so that things bound to view.... behave the same as things bound to model.configView... in this example
[Bindable]
var view = model.configView;

...
<mx:Label text="{view.lblThisLabel.name}" />

at the moment it does not, and I am getting errors that say "unable to bind to property 'lblThisLabel' on class 'Object' (class is not an IEventDispatcher)"

Answer:
Not quite enough code here to really say what's going on, however you have made
```
view
```
bindable and that does not automatically mean that all of
```
view
```
's children are bindable.  You'll have to go into
```
view
```
and make
```
lblThisLabel
```
bindable too.
Also it is hard for the rest of us to know how it works in your head.  Perhaps you should describe that too.


Question: I have a trigger in which I want to have a variable that holds an INT I get from a SELECT, so I can use it in two IF statements instead of calling the SELECT twice. How do you declare/use variables in MySQL triggers?

Answer:
```
```
`CREATE TRIGGER `category_before_ins_tr` BEFORE INSERT ON `category`
  FOR EACH ROW
BEGIN
    **SET @tableId= (SELECT id FROM dummy LIMIT 1);**

END;`;
```
```


Question:
In C++ often do something like this:

typedef map<int, vector<int> > MyIndexType;

Where I then use it like this:

MyIndexType myIndex;
for( ... some loop ...)
{
  myIndex[someId].push_back(someVal);
}

If there was no entry in the map the code will insert a new empty vector and then append to it.

In Python it would look like this:

myIndex = {}

for (someId,someVal) in collection:
   try:
      myIndex[someId].append(someVal)
   except KeyError:
      myIndex[someId] = [someVal]

The try except is a bit ugly here. Is there a way to tell the dictionary an object type to insert when a KeyError is encountered at dictionary declaration time?

Answer:
Something like this perhaps:
```
```
myIndex = {}
for (someId,someVal) in collection:
    myIndex.setdefault(someId, []).append(someVal)
```
```


Question:
Some examples I found that apparently worked with older versions of mvc suggest that there was a length parameter of sorts:

<%=Html.TextBox("test", 50)%>

But that may have been mistakenly setting the value.

How do this work in the current release? Passing in the style doesn't appear to have any effect.

Answer:
Something like this should work:
```
```
<%=Html.TextBox("test", new { style="width:50px" })%>
```
```
Or better:
```
```
<%=Html.TextBox("test")%>

<style type="text/css">
    input[type="text"] { width:50px; }
</style>
```
```


Question:
Is it faster to do the following:

 if ($var != 'test1' && $var != 'test2' && $var != 'test3' && $var != 'test4') { ... }

Or:

 if (!in_array($var, array('test1', 'test2', 'test3', 'test4') { ... }

Is there a number of values at which point it's faster to do one or the other?

(In this case, the array used in the second option doesn't alreay exist.)

Answer:
i'd strongly suggest just using
```
in_array()
```
, any speed difference would be negligible, but the readability of testing each variable separately is horrible.
just for fun here's a test i ran:
```
```
$array = array('test1', 'test2', 'test3', 'test4');
$var = 'test';
$iterations = 1000000;

$start = microtime(true);
for($i = 0; $i < $iterations; ++$i) {
    if ($var != 'test1' && $var != 'test2' && $var != 'test3' && $var != 'test4') {}
}
$end = microtime(true);

print "Time1: ". ($end - $start)."
";

$start2 = microtime(true);
for($i = 0; $i < $iterations; ++$i) {
    if (!in_array($var, $array) ) {}
}
$end2 = microtime(true);

print "Time2: ".($end2 - $start2)."
";

// Time1: 1.12536692619
// Time2: 1.57462596893
```
```
slightly trivial note to watch for, if
```
$var
```
is not set, method 1 takes much longer (depending on how many conditions you test)
Update for newer PHP versions:
Martijn: I'ved extended the array to
five
elements, and look for
```
test3
```
, as sort of an average case.
PHP5.6
```
```
Time1: 0.20484399795532
Time2: 0.29854393005371
```
```
PHP7.1
```
```
Time1: 0.064045906066895
Time2: 0.056781053543091
```
```
PHP7.4
```
```
Time1: 0.048759937286377
Time2: 0.049691915512085
```
```
PHP8.0
```
```
Time1: 0.045055150985718
Time2: 0.049431085586548
```
```
Conclusion: The original test wasnt the best test, and also: In php7+ is has become a matter of preference.


Question:
When implementing an +initialize or +load method in one of your Objective-C classes, should you always start with this kind of guard?:

@implementation MyClass

+ (void)initialize {
    if (self == [MyClass class]) {
        ...
    }
}

...
@end

Seems like code in +load and +initialize usually only wants to be executed once. So this would help avoid dupe execution when subclasses load/initialize.

I guess I'm just wanting some reinforcement from some ObjC wizards that this is necessary/common practice...

What's the common wisdom on this? would you recommend always doing this?

Is your advice the same for both +load and +initialize, or is there a difference in they way they should be handled?

thanks.

Answer:
Yes, you should do this in your intialize and load methods if you are initializing globals that should only be initialized once.
That said, there are a number of cases where you may avoid it...
You shouldn't wrap with this conditional if the work needs to be performed on every inheritant of every class:
For example, adding all inherited class names for each class to a set.
edited addition:
or you're establishing KVO dependencies (as mentioned by eJames)
There are also situations where you just needn't bother:
If the actions you perform are idempotent (don't change values if repeated)
The class is "sealed" (has no descendants by design)
The "idempotent" part is relevant. An initializer should just be setting the initial state (which should be the same each time). In a good initializer, repetition shouldn't matter. Although I suppose that if you forget to wrap the method in the conditional when it
does
matter, this might be annoying.
edited addition:
A different approach, that properly reflects any initialize-only-once requirements would be to test if your properties to initialize are initialized already. i.e.
```
```
id myGlobalObject = nil;

+(void)initialize
{
    if (myGlobalObject == nil)
    {
        myGlobalObject = [[MyGlobalClass alloc] init];
    }
}
```
```


Question:
I have clustered applications that requires one of the nodes to be designated as the master. The cluster nodes are tracked in a table with nodeID, isMaster, lastTimestamp columns.

Each node in the cluster will try to become a master every X seconds. Node can only become a master if either

there is no other master nodes

the lastTimestamp on current master node is older by 2*X

When one of the above conditions is satisfied

the current master node's isMaster should be cleared

the new master node's isMaster should be set

the new master node's lastTimestamp should be set to 'now' timestamp.

What is the single (portable) SQL statement to achieve the above without the possibility of two or more nodes becoming the master?

Answer:
The normal way of avoiding the "delete then move fails problem" is:
Write to file.new
Move file.current to file.old
Move file.new to file.current
Delete file.new
Then when you come to read, use file.new if file.current is missing, deleting file.old if you see it.
Checking for whether or not the file is available: try opening it for write, but appending to the end. Of course, you'll need to close the handle before you then move it, and in-between someone else could open it - but it would at least be a
reasonable
optimisation.
Not sure about copying summaries etc, I'm afraid.


Question:
How do I access the user R13 and R14 which are saved when supervisor mode is entered? I am using an ARM7TDMI.

I.E. I do not want to access supervisor R14 which now contains the return address to user mode, instead want the value of user mode's link register. This is part of a debugger I am writing.

Are there special aliases for these registers?

Thanks

Answer:
I'll describe the answer for your specific question but the same approach applies to other modes as well.
You'll need to change the processor mode by changing the mode bits in the CPSR to system mode.  This will give you access to user mode's SP/LR (R13 & R14).  Remember that system mode is privileged, but its R13 and R14 are the same as user mode's R13 and R14.
Once you're in system mode, read R13 and R14 and put them where you want.  Then just switch the mode bits back to your previous mode (I believe that was supervisor mode in your example) and you're good to go.
Note that we did not switch from supervisor to user mode.
If you switched from supervisor to user,
you couldn't get back to supervisor mode
.  (Otherwise there would be no protection from user code escalating privilege).  That's why we used system mode -- system mode is privileged, but the registers are the same as user mode.
You can switch between any of the privileged modes at will by manipulating the mode bits in the CPSR.  I think they're the lower 5 bits?  I'm on the road & don't have the info at my fingertips.  Otherwise I would have provided you with the assembly code for what I've described above.  Actually, if you want to put some hair on your chest, take what I've given you above, implement it, test it, and post it back here.  :-D
(One thing I should add for the "general case" (yours is very specific) -- you can examine the SPSR to see "where you came from" -- and use that to determine which mode you need to switch to.)
By the way, I just did this recently for one of my customers.... small world, I guess.


Question:
I'm currently using std::ofstream as follows:

std::ofstream outFile;
outFile.open(output_file);

Then I attempt to pass a std::stringstream object to outFile as follows:

GetHolesResults(..., std::ofstream &outFile){
  float x = 1234;
  std::stringstream ss;
  ss << x << std::endl;
  outFile << ss;
}

Now my outFile contains nothing but garbage: "0012E708" repeated all over.

In GetHolesResults I can write

outFile << "Foo" << std:endl;

and it will output correctly in outFile.

Any suggestion on what I'm doing wrong?

Answer:
You can do this, which doesn't need to create the string. It makes the output stream read out the contents of the stream on the right side (usable with any streams).
```
```
outFile << ss.rdbuf();
```
```


Question:
I'm developing class to represent special kind of matrix:

type
  DifRecord = record
    Field: String;
    Number: Byte;
    Value: smallint;
  end;

type
  TData = array of array of MainModule.DataRecord;

type
  TDifference = array of DifRecord;

type
  TFogelMatrix = class
  private
    M: Byte;
    N: Byte;
    Data: ^TData;
    DifVector: ^TDifference;
    procedure init();
  public
    constructor Create(Rows, Cols: Byte);
    destructor Destroy;
  end;

Now in constructor I need to reserve memory for Data and DifVector class members. I use pointers to array of records, as you see. So, the main question is, how can I correctly reserve memory? I suppose I can not use something like that:

new(Data);

new(DifVector);

cause I`m loosing the main idea - to reserve memory space, as much as I want to, at run-time. Thanks for comments.

Answer:
Since you're using dynamic arrays,
```
array of
```
, then you should use SetLength to specify the length of the array, which can be done dynamically.
ie. like this:
```
```
SetLength(Data, 100);
```
```
This will not reserve 100 bytes, but will reserve enough space to hold 100 elements of whatever type the array holds.
Change your declarations for the arrays to simple arrays:
```
```
Data: TData;
DifVector: TDifference;
```
```
and use it with SetLength, it should do the trick.


Question:
One of my API calls can result in updates to a large number of objects (Django models). I'm running into performance issues with this since I'm updating each item individually, saving, and moving on to the next:

for item in Something.objects.filter(x='y'):
    item.a="something"
    item.save()

Sometimes my filter criterion looks like "where x in ('a','b','c',...)".

It seems the official answer to this is "won't fix". I'm wondering what strategies people are using to improve performance in these scenarios.

Answer:
You need to use transactions or create the sql statement by hand. You could also try using SQLAlchemy which supports a few great ORM features like Unit of Work (or application transaction).
Django transactions:
http://docs.djangoproject.com/en/dev/topics/db/transactions/?from=olddocs
SQLAlchemy:
http://www.sqlalchemy.org/


Question:
I have something like this:

<node TEXT="   txt A   "/>
<node TEXT="

       txt X

"/>
<node>
   <html>
      <p>
        txt Y
      </p>
   </html>
</node>
<node TEXT="txt B"/>

and i want to use XSLT to get this:

txt A
txt X
txt Y
txt B

I want to strip all useless whitespaces and linebreaks of @TEXT's and CDATA's. The only XML-input that is giving structure to the output are the <node>-tags.

Answer:
You probably want
```
```
<xsl:strip-space elements="node"/>
```
```
explained
here
. And this
article
has a lot more details.


Question: I'm looking for a good online resource of software patterns. Preferably something with a comprehensive selection and concise well written explanations, not just a collection of links. .Net examples would be nice, but not essential.

Answer:
Enterprise Solutions Patterns using Microsoft .NET
Design Patterns for ASP.NET Programmers
Data and Object Factory, Inc -- Patterns
DesignPatternsFor.Net


Question:
I added the following to my web.config to redirect the user to the login page if they aren't authenticated, but going to the URL does cause a redirect?

 <location path="user/add">
    <system.web>
      <authorization>
        <deny users="?" />
      </authorization>
    </system.web>
  </location>

I have setup forms authen. like this:

<authentication mode="Forms">
      <forms loginUrl="/user/login"
             protection="All"
             timeout="30"
             name="MyCookie"
             requireSSL="false"
             slidingExpiration="true"
             defaultUrl="default.aspx"
             />

    </authentication>

Using .net and mvc.

Answer:
For one of my applications I have the following in the same node as
```
<authentication>
```
:
```
```
<authorization>
    <deny users="?"/>
</authorization>
```
```
But this covers the entire application...