q:
I'm trying to consolidate some build information by using a common makefile. My problem is that I want to use that makefile from different subdirectory levels, which makes the working directory value (pwd) unpredictable. For example:

# Makefile.common
TOP := $(shell pwd)
COMPONENT_DIR := $(TOP)/component
COMPONENT_INC := $(COMPONENT_DIR)/include
COMPONENT_LIB := $(COMPONENT_DIR)/libcomponent.a

If I include Makefile.common from a subdirectory, like so, the $(TOP) directory is incorrect and everything else follows suit:

# other_component/Makefile
include ../Makefile.common
# $(COMPONENT_LIB) is incorrectly other_component/component

What's the best way to get Makefile.common to use its own directory path instead of the more fickle pwd?

[A]
Have you tried doing:
```
```
# Makefile.common
TOP ?= $(shell pwd)
COMPONENT_DIR := $(TOP)/component
COMPONENT_INC := $(COMPONENT_DIR)/include
COMPONENT_LIB := $(COMPONENT_DIR)/libcomponent.a

# other_component/Makefile
TOP ?= ..
include ../Makefile.common
```
```
Using the ?= construct will keep TOP from being redefined if it is already set.  You can set it to the appropriate value based on where you are in the tree when you invoke make.  I confess it's been awhile since I've used GNU make so this may not work or may need some tweaks.


q:
Is there a particular scenario where a WriteOnly property makes more sense then a method? The method approach feels much more natural to me.

What is the right approach?

Using Properties:

Public WriteOnly Property MyProperty As String
   Set(ByVal value as String)
      m_myField = value
   End Set
End Property

public string MyProperty
{
   set{ m_myField = value;}
}

Using Methods:

Public Sub SetMyProperty(ByVal value as String)
   m_myField = value
End Sub

public void SetMyProperty(string value)
{
   m_myField = value;
}

EDIT
Just to clarify I am referring to "WriteOnly" properties.

[A]
I think a property indicates something that can be read-only or read/write. The behaviour of a write-only property is not obvious so I avoid creating them.
As an example, setting a list of values in a drop-down on a view and accessing the selected item:
```
```
public interface IWidgetSelector
{
  void SetAvailableWidgets(string[] widgets);

  string SelectedWidget { get; set; }
}
```
```
Makes more sense than:
```
```
public interface IWidgetSelector
{
  string[] AvailableWidgets { set; }

  string SelectedWidget { get; set; }
}
```
```

s: huggingface

c: devops

d: intermediate


q:
Given my new understanding of the power of "includes" with PHP, it is my guess that ALL of my pages on my site will be .php extension.

Would this be considered strange?

I used to think that most pages would be .htm or .html, but in looking around the net, I am noticing that there really isn't any "standard".

I don't really think I have a choice, if I want to call my menus from a php file. It is just going to be that way, far as I can see... so just bouncing off you all to get a feel for what "real programmers" feel about such issues.

[A]
It doesn't matter what your URLs end with,
```
.php
```
is fine, and fairly common.  The only thing people care about these days when it comes to URLs is making them pretty for Search Engine Optimisation, but that's a whole new question.


q:
I'm at step 8 of the authentication overview found here: http://wiki.developers.facebook.com/index.php/How_Connect_Authentication_Works

In particular, the user has logged into facebook via Facebook Connect and their web session has been created.  How do I use the facebook developer toolkit v2.0 (from clarity) to retrieve information about the user.  For example, I'd like to get the user's first name and last name.

Examples in the documentation are geared towards facebook applications, which this is not.

Update

Facebook recently released the Graph API. Unless you are maintaining an application that is using Facebook Connect, you should check out the latest API:   http://developers.facebook.com/docs/

[A]
Facebook Connect actually isn't too difficult, there's just a lack of documentation.
Put the necessary javascript from here:
http://tinyurl.com/5527og
Validate the cookies match the signature provided by facebook to prevent hacking, see:
http://tinyurl.com/57ry3s
for an explanation on how to get started
Create an api object (Facebook.API.FacebookAPI)
On the api object, set the application key and secret Facebook provides you when you create your app.
Set
```
api.SessionKey
```
and
```
api.UserId
```
from the cookies created for you from facebook connect.
Once that is done, you can start making calls to facebook:
```
```
Facebook.Entity.User user = api.GetUserInfo();   //will get you started with the authenticated person
```
```


q: When I create utility classes I typically create a class that has a private constructor and exposes all of it's methods and properties as static. What's the best approach for this? What's the difference between the way I do or creating a static class?

[A]
Static classes are automatically sealed, so people can't inherit and override their behavior.
That is the only real difference (unless there is something special in the IL)
So if you use a static class, you save yourself the trouble of making the constructor private, and declaring the class sealed.
I would add, that defining a class as static, is "self-documenting" code. Users of your library will know that this class should not be instantiated, and only has static values.


q: I want to generate a list in C#. I am missing python's list comprehensions. Is there a C# way to create collections on the fly like list comprehensions or generator expressions do in python?

[A]
If you are using C# 3.0 (VS2008) then LINQ to Objects can do very similar things:
```
```
List<Foo> fooList = new List<Foo>();
IEnumerable<Foo> extract = from foo in fooList where foo.Bar > 10 select Foo.Name.ToUpper();
```
```


q:
I have this html...

<select id="View" name="View">
   <option value="1">With issue covers</option>
   <option value="0">No issue covers</option>
 </select>

It won't let me insert code like this...

<select id="View" name="View">
   <option value="1" <% ..logic code..%> >With issue covers</option>
   <option value="0" <% ..logic code..%> >No issue covers</option>
 </select>

So whats the best way to set one to selected?

Update:
Without using the HTML Helpers.

[A]
The "best" approach is probably to
use
the helpers:
```
```
var selectList = new SelectList(data, "ValueProp", "TextProp", data[1].ValueProp);
... Html.DropDownList("foo", selectList)
```
```
Where "data" could be an array of anonymous types, such as:
```
```
var data = new[] {
  new {Key=1, Text="With issue covers"},
  new {Key=0, Text="No issue covers"}
};
// todo: pick the selected index or value based on your logic
var selectList = new SelectList(data, "Key", "Text", data[1].Key);
Writer.Write(Html.DropDownList("foo", selectList));
```
```
Another approach might be to select the correct item client-side through script, but obviously that only works with script enabled.
Note it was missing comma and semicolon in data declaration, stopped it from working


q:
Let's say that I have a record in the database and that both admin and normal users can do updates.

Can anyone suggest a good approach/architecture on how to version control every change in this table so it's possible to roll back a record to a previous revision?

[A]
I think you are looking for versioning the content of database records (as StackOverflow does when someone edits a question/answer). A good starting point might be looking at some database model that uses
revision
tracking.
The best example that comes to mind is MediaWiki, the Wikipedia engine. Compare the database diagram
here
, particularly the
revision table
.
Depending on what technologies you're using, you'll have to find some good diff/merge algorithms.
Check
this question
if it's for .NET.


q:
Searched stackoverflow for this and found no answer

Coming from Ruby On Rails and Rspec, I need a tool like rspec (easier transition). Installed it through PEAR and tried to run it but it's not working (yet)

Just wanna ask around if anyone's using it have the same problem, since it's not running at all

tried running it with an example from the manual - http://dev.phpspec.org/manual/en/before.writing.code.specify.its.required.behaviour.html

phpspec NewFileSystemLoggerSpec

returns nothing

even running

phpspec some_dummy_value

returns nothing

[A]
I also couldn't get it to run, but you can also use BDD with PHPUnit. Check the
documentation
:


q:
I have a site with over 100 pages. We need to go live with products that are soon available, however, many site pages will not be prepared at the time of release.

In order to move forward, I would like to reference a "coming soon" page with links to pages that are current and available.

Is there an easy way to forward a URL to a Coming Soon page?
Is this valid, or is there a better way?

Found this at:
http://www.web-source.net/html_redirect.htm

"Place the following HTML redirect code between the  and  tags of your HTML code.

   meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourdomain.com/index.html"

Does this negatively affect you if the search engines crawl through your site?

Thank you!

[A]
Perhaps a better or "more correct way" would be to do the redirection at the header level. Using PHP, you would call
```
```
<?php
header("Location: http://www.yourdomain.com/index.html");
```
```
There's also ways to do this in Apache (assuming you are using it) and
```
.htaccess
```
-files. See
http://www.webweaver.nu/html-tips/web-redirection.shtml
for more info about that.


q:
Please, I am new to webparts and I need help!!

I have a custom web part that I created. I added MS Ajax to it using an UpdatePanel which works fine. I add all my controls to the CreateChildControls method. As soon as I add a UpdateProgress control my page breaks with the following error:

Script controls may not be registered before PreRender

I do not use the OnPreRender event as what other posts suggest. Please, if anyone can give me advice it will be very much appreciated.

Thanks

[A]
You might have forgotten to call the base method of an overrided event, which is not necessarily the OnPreRender event.
Check if the OnInit or OnLoad events are calling their base.On[...] method, e.g.:
```
```
protected override void OnLoad(EventArgs eventArgs)
{
    base.OnLoad(eventArgs);

    // your code...
}
```
```


q:
There is a SqlServer2000 Database we have to update during weekend.

It's size is almost 10G.

The updates range from Schema changes, primary keys updates to some Million Records updated, corrected or Inserted.

The weekend is hardly enough for the job.

We set up a dedicated server for the job,
turned the Database SINGLE_USER
made any optimizations we could think of: drop/recreate indexes, relations etc.

Can you propose anything to speedup the process?

SQL SERVER 2000 is not negatiable (not my decision). Updates are run through custom made program and not BULK INSERT.

EDIT:

Schema updates are done by Query analyzer TSQL scripts (one script per Version update)

Data updates are done by C# .net 3.5 app.

Data come from a bunch of Text files (with many problems) and written to local DB.

The computer is not connected to any Network.

[A]
What exactly does this "custom made program" look like? i.e. how is it talking to the data? Minimising the amount of network IO (from a db server to an app) would be a good start... typically this might mean doing a lot of work in TSQL, but even just running the app on the db server might help a bit...
If the app is re-writing large chunks of data, it might still be able to use bulk insert to submit the new table data. Either via command-line (bcp etc), or through code (
```
SqlBulkCopy
```
in .NET). This will typically be quicker than individual inserts etc.
But it really depends on this "custom made program".


q:
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.

[A]
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.


q:
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!

[A]
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.


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

[A]
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.


q:
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

[A]
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


q:
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

[A]
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.


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

Collection is read-only

[A]
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).


q: 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?

[A]
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.


q:
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?

[A]
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.


q:
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

[A]
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.


q:
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.

[A]
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')


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

[A]
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.


q:
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?

[A]
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.


q:
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?

[A]
You might want to have a look at
PDFReactor


q:
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.

[A]
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/"
```
.


q:
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.

[A]
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.


q:
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?

[A]
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
```
```


q: 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?

[A]
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.


q:
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.

[A]
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.


q:
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?

[A]
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).


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

[A]
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.


q:
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.

[A]
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.


q:
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)

[A]
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.


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

[A]
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
}
```
```


q:
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?

[A]
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.


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

[A]
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
.


q:
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.

[A]
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.


q:
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?

[A]
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


q:
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

[A]
```
```
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


q:
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?

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


q: 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/.

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


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


q:
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?

[A]
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

```
```


q:
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?

[A]
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.


q:
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?

[A]
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.


q:
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?

[A] 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.


q:
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.

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


q:
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.

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


q:
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


q:
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()

[A]
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.


q: 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?

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


q:
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?

[A]
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!


q:
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?

[A]
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
.


q:
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

[A]
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).


q:
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.

[A]
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.


q:
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.

[A]
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.


q:
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.

[A]
You can use
add()
;
```
```
var $foos = $('.foo');

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


q:
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.

[A]
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
```
```


q: 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)

[A]
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.


q:
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.

[A]
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.


q:
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?

[A]
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.


q:
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.?

[A]
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.


q:
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.

[A]
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;
```
```


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

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


q:
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

[A]
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.


q:
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.

[A]
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.


q:
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?

[A]
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.


q:
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.

[A]
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?


q:
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?

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


q:
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.

[A]
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.


q:
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!

[A]
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?


q:
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?

[A]
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, ...)
```
```


q:
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?

[A]
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.


q:
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?

[A]
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.


q:
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.

[A]
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.


q: 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?

[A]
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.


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

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


q:
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">


q:
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?

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


q:
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

[A]
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))
```
```


q:
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.

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


q: 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.

[A]
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.


q:
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

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


q:
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"

[A]
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.


q: 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?

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


q:
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

[A]
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.


q:
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?

[A]
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.


q:
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')

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


q:
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.

[A]
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.


q:
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!

[A]
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.


q:
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?

[A]
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.


q:
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).

[A]
```
```
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


q:
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

[A]
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
.


q:
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?

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


q:
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)"

[A]
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.


q: 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?

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

END;`;
```
```


q:
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?

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


q:
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.

[A]
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>
```
```