q:
How to get to know DNS name of the server where ASP.NET application is run?

I want to get string "www.somehost.com" if my application URL is http://www.somehost.com/somepath/application.aspx

Is there some property of Server, Contex, Session or Request objects for this?

Thanks!

[A]
The HTTP_HOST server variable can give you what you need.
```
```
Request.ServerVariables("HTTP_HOST")
```
```


q:
I need a Javascript application that, when run, prompts a password to be entered, and if the password is correct, the script causes the webpage to close. If the password is incorrect, the script prompts for the password to be entered again.

I'm planning on loading this script onto my cell phone, which doesn't have a password-protected keylock feature.

[A]
Ok, we can have two approuches.
We can all read javascript, so if the person actually open your code he will see the password.
By ajax, check the password in a specific page.
```
```
function passWrdAPI() {
    this.getHX = function() {
        var hx;
        try {
            hx = new XMLHttpRequest();
        }
        catch(e) {
            try {
                hx = new ActiveXObject("Microsoft.XMLHttp");
            }
            catch(ex) {
                hx = new ActiveXObject("Msxml2.XMLHttp");
            }
        }
        return hx;
    }

    this.password = "mypass";
    this.checkPwd = function(pass) {
        if (pass != this.password) {
            // Or close or redirect
            alert('Wrong!');

            window.close(); //or
            location.href = 'http://www.google.com';
        }
    }
    this.checkPwdPage(page, pass) {
        var hx = this.getHX();
        if (hx != null) {
            hx.open('GET',page + "?mypwd=" + pass);
            hx.onreadystatechange = function() {
                if (hx.readyState == 4) {
                    if (hx.responseText == 'false') {
                        // Or close or redirect
                        alert('Wrong!');

                        window.close(); //or
                        location.href = 'http://www.google.com';
                    }
                }
            }
            hx.send(null);
        }
        else {
            alert('error!');
        }
    }
}
```
```
Usage:
```
for the first approach:

var check = new passWrdAPI();
check.checkPwd(THEPASSENTERED);

 for the second:

var check = new passWrdAPI();
check.checkPwdPage(YOURPAGE, THEPASS);
```
I don't know if it will work on your cell phone =/
Sorry if I don't help.. bye bye!

s: huggingface

c: devops

d: intermediate


q:
I have a need to reference two different versions of the Sharepoint API dll.  I have a webservice that needs to run under both Sharepoint 2 and Sharepoint 3, but also needs to work with new features provided by the Sharepoint 3 API (Checkout and Content Approval)

What is the best way to acheive this - I'm currently leaning towards having two projects, with the code in a single file shared between the two with various sections of the code compiled in using conditional compilation.

Is there a better way ?

Thanks

Matt

[A]
You could give an "extern alias" a go.
This is one of those times when the VB late binding (option strict off) approach works well. Roll on C# 4.0 and
```
dynamic
```
.
You might try writing an interface for the bits you need (in a base library), and write 2 dlls: one referencing each version of the sharepoint dll. For both projects, implement the interface (throwing
```
NotSupportedException
```
for the bits you can't do), and load the appropriate dll at runtime? (factory approach)
Just try it with a single method before you get too absorbed... don't do the whole thing until you know it works for the simplest of simple methods.


q:
I started with jetlang and the basic samples are pretty clear.
What I didn't found is a good sample for using the PoolFiber. Anybody played around
with that already? I read also the retlang samples but it seems little bit different there.

Thanks for sharing your thoughts!

Okami

[A]
Using a PoolFiber and ThreadFiber are nearly the same. The only difference is that the thread pool needs to initialized and used for creating each PoolFiber.
```
```
// create java thread pool.
ExecutorService pool = Executors.newCachedThreadPool();
//initialize factory with backing pool
PoolFiberFactory fiberFactory = new PoolFiberFactory(pool);
Fiber fiber = fiberFactory.create();
fiber.start();
//use fiber for normal publishing and subscribing.
```
```


q: Is there a way to create a function/sub signature that accepts an arbitrary typed generic in vb.net.

[A]
Its like this:
```
```
Public Function DoThing(Of T)(ByVal value As T)
```
```


q:
I need to bind labels or items in a toolstrip to variables in Design Mode.
I don't use the buit-in resources not the settings, so the section Data is not useful. I am taking the values out from an XML that I map to a class.

I know there are many programs like:
http://www.jollans.com/tiki/tiki-index.php?page=MultilangVsNetQuickTourForms
but they work with compiled resx. I want to use not compiled XML.

I know that programatically i can do it, i create a method (for example, UpdateUI()), and there I assign the new values like this:
this.tsBtn.Text=Class.Texts.tsBtnText;

I would like something i could do from Design Mode or a more optimized way than the current one. Is there any Custom Control out there or Extension?

[A]
Try with inheriting basic win controls and override OnPaint method. Example bellow is a button that has his text set on paint depending on value contained in his Tag property (let suppose that you will use Tag property to set the key that will be used to read matching resource). Then you can find some way to read all cache resource strings from xml files (e.g. fictional MyGlobalResources class.
```
```
public class LocalizedButton : Button
{
    protected override void OnPaint(PaintEventArgs pevent)
    {
        base.OnPaint(pevent);
        this.Text = MyGlobalResources.GetItem(this.Tag.ToString());
    }
}
```
```


q:
I need to get authentication credentials from the users within a Windows script but the classic "first Google result" approach:

SET /P USR=Username:
SET /P PWD=Password:

is less than satisfying, so I was wondering if there's let's say an "equivalent" to HTML's input type="password"?

Any comment would be really appreciated, thanks much in advance!

[A]
I assume that you want no echo of the password on the screen.
If a pop-up window is ok for you, you could use e.g. VBScript to show an IE window displaying a password field. Here's an
example
.
As an alternative you could call your script from an HTA (HTML Application) file (see
Introduction to HTML Applications (HTAs)
.
Regards,
divo


q:
I'm having a difficult time figuring out how to add a .jar/library to a Netbeans project in such a way that I can get it committed to the repository.

The typical way to add a library (per the Netbeans documents I've already gone through) ends up with it just being local to me.  Anyone who checks out my project ends up missing my required library.

Inserting it manually and trying to work around Netbeans results in Netbeans hanging while trying to scan the project...

So, how can I tell Netbeans to pick up a jar as a library and include it in my project in such a way that Subversion will be able to handle it?

[A]
Not really an answer to your question but... generally you should not include these libraries in your subversion repository. There is usually no need to have them managed. What you might want is to set up a central repository similar to what happens with maven. If you use maven, you can create a local repository of libraries on a server accessible by the team. The dependencies on these libraries are entered in the pom.xml file and this is in the subversion repository. Now, as team members check out the code from subversion they all have access to the maven repository.
[I am looking for a reference to this right now. When I find it I'll edit this answer.]


q: Like the title says, how can I remove GAC assembly file using vbscript?

[A]
You can run this to uninstall it from GAC:
```
```
gacutil /u YourAssembly
```
```


q:
On Windows Mobile (but I guess it's the same on Windows) in a native C++ app, how would I go about setting a SYSTEMTIME structure correctly? Assuming I have

int year, month, dayOfMonth, hour, minute, second;

I obviously should set the wHour, wYear, etc members of the SYSTEMTIME structure, but what happens with wDayOfWeek in that case, I would rather have this set up correctly as well. I have looked but not found any functions in MSDN that would allow me to populate a SYSTEMTIME structure where the wDayOfWeek member would be calculated for me. Did I miss something or how would I go about that?

[A]
Hmm...
Maybe first construct a FILETIME and then call FileTimeToSystemTime?
Info on FILETIME
http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx
Or, first contruct a VARIANT of VT_TIME and then callVariantTimeToSystemTime.
http://msdn.microsoft.com/en-us/library/ms221440.aspx


q:
The following code is implemented in Page_Load event to show SaveFileDialog to the user

string targetFileName = Request.PhysicalApplicationPath + "Reports\\TempReports\\FolderMasters" + Utility.GetRandomNumber() + ".pdf";

FileInfo file = new FileInfo(targetFileName);
// Clear the content of the response.
Response.ClearContent();

Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/pdf";
Response.TransmitFile(file.FullName);
Response.End();

How can I get the user response to SaveFileDialog, as I need to know user response to this dialog?

Also, is there something wrong with these lines of code, as I had the following exception

"Unable to evaluate expression because the code is optimized or a native frame is on   top of the call stack."

[A]
I'm here again, as I got a solution for my second question.
For
```
Response.End
```
, call the
```
HttpContext.Current.ApplicationInstance.CompleteRequest
```
method instead of Response.End to bypass the code execution to the Application_EndRequest event.
Have look ...


q: What is the JSON (JavaScript Object Notation) format?

[A]
From Wikipedia:
JSON
(Javascript object notation)
The JSON format is often used for
  transmitting structured data over a
  network connection in a process called
  serialization. Its main application is
  in Ajax web application programming,
  where it serves as an alternative to
  the use of the XML format.


q:
I need to cut out and save/use part of a string in C#. I figure the best way to do this is by using Regex. My string looks like this:

"changed from 1 to 10".

I need a way to cut out the two numbers and use them elsewhere. What's a good way to do this?

[A]
In your regex put the fields you want to record in parentheses, and then use the
```
Match.Captures
```
property to extract the matched fields.
There's a C# example
here
.


q:
How can I get the value between quotes with an RegEx

for example I want to find all the parameters from the function test

<html>
   test("bla");
   print("foo");
   test("moo");
</html>

The result must be { "bla", "moo" }

[A]
edit: Removed old code and made a linq version...
```
```
var array = (from Match m in Regex.Matches(inText, "\"\\w+?\"")
                 select m.Groups[0].Value).ToArray();

    string json = string.Format("{{{0}}}", string.Join(",", array));
```
```


q: In Java, is there a way to control the TTL of the IP header for packets sent on a socket?

[A]
Apparently only on Multicast sockets, which have:
```
```
MulticastSocket.setTimeToLive(int ttl);
```
```


q:
I have an ASP.net page. When I am closing the webpage I need to clear the session variables.

How to to handle this I need to maintain the timeout to 20 minutes.
If he closes and login for any number of times in the 20 minutes timed out time

Is there any possiblity for clearing the ASP.net session id

[A]
[EDIT] As others have suggested, your session should time out eventually, but if you want to close the session before the timeout (for example to clean up large session objects) AND have javascript available to you...
You can do this with an
```
window.onbeforeunload
```
handler that posts back to a sign out page.
```
```
function CloseSession( )
{
    location.href = 'SignOut.aspx';
}
window.onbeforeunload = CloseSession;
```
```
You could also do it via AJAX.  The SignOut.aspx page (or whatever platform you are using) should abandon the user's session.


q:
I think this mostly applies to web applications, since you often see things like language and database vendor in regards to web applications, but not so much on desktop applications.

If a web application is created using language X, would that have any noticeable impact on who deploys the application? For example, would a company that uses .NET products ever consider using a Python application that meets their needs or would they tend to find a .NET product that they could use?

EDIT 1: Refined the question to refer to apps meant to be deployed, not just used.

[A]
It really depends on how much customisation and integration is required - and whether the app exposes any sort of sane API to it.
For example, you might want these types of customisation:
Custom authentication via a module; platform may well be important
Generate your own reports; database is likely to be important
Act against a web service which is part of the app; protocol (SOAP, REST, custom etc) is likely to be important, but not implementation language
In addition, there's the matter of support and maintenance - a Windows ISV is likely to be better at keeping IIS running than Apache, for instance, and the reverse. Likewise it helps if you've already got servers running the required operating system...


q:
How do I programmatically find out the width and height of the video in an mpeg-2 transport program stream file?

Edit: I am using C++, but am happy for examples in any language.
Edit: Corrected question - it was probably program streams I was asking about

[A]
Check out the source code to
libmpeg2
, a F/OSS MPEG2 decoder.  It appears that the width and height are set in the
```
mpeg2_header_sequence()
```
function in
```
header.c
```
.  I'm not sure how control flows to that particular function, though.  I'd suggest opening up an MPEG2 file in something using libmpeg2 (such as
MPlayer
) and attaching a debugger to see more closely exactly what it's doing.


q: Is it possible to set up somehow Microsoft SQL Server to run a stored procedure on regular basis?

[A] Yes, in MS SQL Server, you can create scheduled jobs. In SQL Management Studio, navigate to the server, then expand the SQL Server Agent item, and finally the Jobs folder to view, edit, add scheduled jobs.


q:
I mean, can you use couchDB for:

CRUD of items, users

bids and auctions resolutions

bidirectional califications

forum

items comparison

[A]
You could try to use CouchDB for an application - as to whether you would be successful is another question.
Something on the scale of eBay will have special requirements that are not representative of a typical application, If you are building a small auction site then perhaps CouchDB would suffice. A document-oriented database like CouchDB may not be so hot when you have to deal with transactional/records-based data like that associated with auctions.


q:
What exactly do *args and **kwargs mean?

According to the Python documentation, from what it seems, it passes in a tuple of arguments.

def foo(hello, *args):
    print(hello)

    for each in args:
        print(each)

if __name__ == '__main__':
    foo("LOVE", ["lol", "lololol"])

This prints out:

LOVE
['lol', 'lololol']

How do you effectively use them?

[A]
Putting
```
*args
```
and/or
```
**kwargs
```
as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.
For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:
```
```
def my_sum(*args):
    return sum(args)
```
```
It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.
You don’t actually have to call them
```
args
```
and
```
kwargs
```
, that’s just a convention. It’s the
```
*
```
and
```
**
```
that do the magic.
The official Python documentation has
a more in-depth look
.


q:
What number would you give someone who wants a concrete target number for API code coverage?

UPDATE: To clarify, statement/line code coverage. I realize concrete numbers don't make much sense, but this is for the situation where you tell people that concrete numbers don't make much sense and they still insist on getting a number from you no matter what. I specifically wrote API/SDK because some people might find lower code coverages more acceptable for application/GUI level software, as opposed to libraries, where more interfaces are exposed.


q:
I am building an application that is very similar to a shopping cart.  The user selects a product from a list, and then based on that product, a few properties need to be set and saved.

Example.

If the user selects a type of paint that allows custom color matches, then I must allow them to enter in a formula number that they received through a color match process. So I have an Order Detail item for a Product that is a type of Paint, and that sku has the attribute of "AllowsCustomColorMatch", but I need to store the Formula Number somewhere also.

I'm not sure how to handle this elegantly throughout my code.  Should I be creating subclasses or products?  Right now I'm saving the data the user enters in an OrderDetails object that has a reference to the Product it is associated with.

[A]
You can have a Product class with a collection of product properties
```
```
public class Product
    {
        private Dictionary<string, string> properties;

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        /// <value>The name.</value>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the price.
        /// </summary>
        /// <value>The price.</value>
        public double Price
        {
            get;
            set;
        }

        public Dictionary<string, string> Properties
        {
            get;
        }

        public Product()
        {
            properties = new Dictionary<string, string>();
        }

    }
```
```
In the datasource you can have a table that defines the properties to each type of product. Then when you render the page you know what properties to show and the name to give in the dictionary.


q:
I'm looking to find records in a table that match a specific number that the user enters.  So, the user may enter 12345, but this could be 123zz4-5 in the database.

I imagine something like this would work, if PHP functions worked in MySQL.

SELECT * FROM foo WHERE preg_replace("/[^0-9]/","",bar) = '12345'

What's the equivalent function or way to do this with just MySQL?

Speed is not important.

[A]
The simplest way I can think to do it is to use the MySQL REGEXP operator a la:
```
```
WHERE foo LIKE '1\D*2\D*3\D*4\D*5'
```
```
It's not especially pretty but MySQL doesn't have a
```
preg_replace
```
function so I think it's the best you're going to get.
Personally, if this only-numeric data is so important, I'd keep a separate field just to contain the stripped data. It'll make your lookups a lot faster than with the regular expression search.


q:
I am using LINQ-to-SQL for an application that queries a legacy database. I need to call a stored procedure, that selects a single integer value. Changing the stored procedure is not an option.

The designer creates a method with this signature:

private ISingleResult<sp_xal_seqnoResult> NextRowNumber([Parameter(DbType="Int")] System.Nullable<int> increment, [Parameter(DbType="Char(3)")] string dataset)

I would like the return type to be int. How do I do this using LINQ-to-SQL ?

[A]
This would be trivial with a scalar function (UDF) rather than an SP. However, it should work easily enough - although if the SP is complex (i.e. FMT_ONLY can't inspect it 100%) then you might need to "help" it...
Here's some dbml that I generated from a simplfied SP that returns an integer; you can edit the dbml via "open with... xml editor):
```
```
<Function Name="dbo.foo" Method="foo">
    <Parameter Name="inc" Type="System.Int32" DbType="Int" />
    <Parameter Name="dataset" Type="System.String" DbType="VarChar(20)" />
    <Return Type="System.Int32" />
</Function>
```
```
(note you obviously need to tweak the names and data-types).
And here is the generated C#:
```
```
[Function(Name="dbo.foo")]
public int foo([Parameter(DbType="Int")] System.Nullable<int> inc, [Parameter(DbType="VarChar(20)")] string dataset)
{
    IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), inc, dataset);
    return ((int)(result.ReturnValue));
}
```
```
If your current SP uses SELECT (instead of RETURN), then the DBML will need to reflect this. You can fix this by hiding the implementation details, and providing a public wrapper in a partial class; for example:
```
```
<Function Name="dbo.foo" Method="FooPrivate" AccessModifier="Private">
    <Parameter Name="inc" Type="System.Int32" DbType="Int" />
    <Parameter Name="dataset" Type="System.String" DbType="VarChar(20)" />
    <ElementType Name="fooResult" AccessModifier="Internal">
      <Column Name="value" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" />
    </ElementType>
</Function>
```
```
The above describes an SP that returns a single table with a single column; but I've made the SP "private" to the data-context, and the result-type "internal" to the assembly (hiding it):
```
```
[Function(Name="dbo.foo")]
private ISingleResult<fooResult> FooPrivate(
    [Parameter(DbType="Int")] System.Nullable<int> inc,
    [Parameter(DbType="VarChar(20)")] string dataset)
{
    IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), inc, dataset);
    return ((ISingleResult<fooResult>)(result.ReturnValue));
}
```
```
Now
in my own class file
I can add a new partial class (a new .cs file) in the correct namespace, that exposes the method more conveniently:
```
```
namespace MyNamespace {
    partial class MyDataContext
    {
        public int Foo(int? inc, string dataSet)
        {
            return FooPrivate(inc, dataSet).Single().value;
        }
    }
}
```
```
(the namespace and context names need to be the same as the actual data-context). This adds a public method that hides the grungy details from the caller.
Don't
edit the designer.cs file directly; your changes will be lost. Only edit either the dbml or partial classes.


q:
I have the SOAP request in an XML file. I want to post the request to the web service in .net
How to implement?

[A]
You need to post the data over HTTP. Use the
WebRequest class
to post the data. You will need to send other data with the post request to ensure you have a valid SOAP envelope. Read the
SOAP spec
for all of the details.


q: Using Lucene, one can retrieve the terms contained within in an index, i.e. the unique, stemmed words, excluding stop-words, that documents in the index contain. This is useful for generating autocomplete suggestions amongst other things. Is something similar possible with MS SQL Server full text indices?

[A]
You can use the new system view in SQL Server 2008 to get you the terms and count of occurrences, is this what you want?
```
```
sys.dm_fts_index_keywords_by_document
(
    DB_ID('database_name'),
    OBJECT_ID('table_name')
)
```
```
You need to supply the
```
db_id
```
and
```
object_id
```
of the fulltext table. This is the MSDN link for this:
sys.dm_fts_index_keywords_by_document
.


q:
I have a load of user-submitted content. It is HTML, and may contain URLs. Some of them will be <a>'s already (if the user is good) but sometimes users are lazy and just type www.something.com or at best http://www.something.com.

I can't find a decent regex to capture URLs but ignore ones that are immediately to the right of either a double quote or '>'. Anyone got one?

[A]
Jan Goyvaerts, creator of
RegexBuddy
, has
written a response
to Jeff Atwood's blog that addresses the issues Jeff had and provides a nice solution.
```
```
\b(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-Z0-9+&@#/%=~_|$?!:,.]*[A-Z0-9+&@#/%=~_|$]
```
```
In order to ignore matches that occur right next to a " or >, you could add
```
(?<![">])
```
to the start of the regex, so you get
```
```
(?<![">])\b(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-Z0-9+&@#/%=~_|$?!:,.]*[A-Z0-9+&@#/%=~_|$]
```
```
This will match full addresses (
http://..
.) and addresses that start with www. or ftp. - you're out of luck with addresses like ars.userfriendly.org...


q:
Say a class

Person
+Name: string
+Contacts: List<Person>

I want to be able to check if a person has a contact with a certain name without having to create a dummy Person instance.

person.Contacts.Contains<string>("aPersonName");

This should check all persons in the Contacts list if their Name.Equals("aPersonName");
I see that there is a Contains already available, but I don't know where I should implement it's logic.

[A]
It's probably easiest to use
Enumerable.Any
:
```
```
return person.Contacts.Any(person => person.Name=="aPersonName");
```
```
Alternatively, project and then contain:
```
```
return person.Select(person => person.Name).Contains("aPersonName");
```
```


q:
The example below throws an InvalidOperationException, "Collection was modified; enumeration operation may not execute." when executing the code.

var urls = new List<string>();
urls.Add("http://www.google.com");

foreach (string url in urls)
{
    // Get all links from the url
    List<string> newUrls = GetLinks(url);

    urls.AddRange(newUrls); // <-- This is really the problematic row, adding values to the collection I'm looping
}

How can I rewrite this in a better way? I'm guessing a recursive solution?

[A]
I would create two lists add into the second and then update the reference like this:
```
```
var urls = new List<string>();
var destUrls = new List<string>(urls);
urls.Add("http://www.google.com");
foreach (string url in urls)
{
    // Get all links from the url
    List<string> newUrls = GetLinks(url);
    destUrls.AddRange(newUrls);
}
urls = destUrls;
```
```


q:
Should I start a Python program with:

if__name__ == '__main__':
some code...

And if so, why? I saw it many times but don't have a clue about it.

[A]
If your program is usable as a library but you also have a main program (e.g. to test the library), that construct lets others import the file as a library and not run your main program. If your program is named foo.py and you do "import foo" from another python file,
```
__name__
```
evaluates to
```
'foo'
```
, but if you run "python foo.py" from the command line,
```
__name__
```
evaluates to
```
'__main__'
```
.
Note that you do need to insert a space between if and _, and indent the main program:
```
```
if __name__ == '__main__':
    main program here
```
```


q:
Modern browsers have multi-tab interface, but JavaScript function window.showModalDialog() creates a modal dialog that blocks all of the tabs.

I'd like to know if there is a way to create a modal dialog that blocks only the tab it's been created in?

[A]
You could use one of the more 'Ajax-like' modal dialogs, which are just absolute positioned divs, floating on top of everything else.
Those are modal to the 'document' and not the browser.
For instance take a look it
this jQuery plugin
P.S.
```
showModalDialog()
```
is an IE only call, so you might want to not use that altogether.


q: Is it possible to develop plugins for Microsoft Office Communicator?  If so, where does one start -- is there an SDK?

[A]
A good place to start would be the
SDK
. I'm not sure if you can create plugins for it, but since it has a API, you can definitely hook into it from external apps or webpages.


q:
I've looking to find a simple recommended "minimal" c++ makefile for linux which will use g++ to compile and link a single file and h file. Ideally the make file will not even have the physical file names in it and only have a .cpp to .o transform. What is the best way to generate such a makefile without diving into the horrors of autoconf?

The current dir contains, for example

t.cpp
t.h

and I want a makefile for that to be created. I tried autoconf but its assuming .h is gcc instead of g++. Yes, while not a beginner, I am relearning from years ago best approaches to project manipulation and hence am looking for automated ways to create and maintain makefiles for small projects.

[A]
If it is a single file, you can type
```
```
make t
```
```
And it will invoke
```
```
g++ t.cpp -o t
```
```
This doesn't even require a Makefile in the directory, although it will get confused if you have a t.cpp and a t.c and a t.java, etc etc.
Also a real Makefile:
```
```
SOURCES := t.cpp
# Objs are all the sources, with .cpp replaced by .o
OBJS := $(SOURCES:.cpp=.o)

all: t

# Compile the binary 't' by calling the compiler with cflags, lflags, and any libs (if defined) and the list of objects.
t: $(OBJS)
    $(CC) $(CFLAGS) -o t $(OBJS) $(LFLAGS) $(LIBS)

# Get a .o from a .cpp by calling compiler with cflags and includes (if defined)
.cpp.o:
    $(CC) $(CFLAGS) $(INCLUDES) -c $<
```
```


q:
What are the steps to get Team Foundation Server running unit tests when a given build runs?

What are the caveats / pitfalls / workarounds a dev or sysadmin should be aware of when setting up a TFS server to do this for the first time?

What are common troubleshooting steps for unit test problems during builds?

[A]
it depends on which version of TFS you are running, so I will assume it is 2008.
Firstly, you must have Team Edition for Testers installed on the computer that will act as your build agent, as stated in
How To: Create a Build Definition
There are a couple of ways to tell Team Build to run tests for your build.
Unit tests can be run from a defined Test List within the Solution being built.  This list is referenced by the build definition and all tests within the chosen list(s) are executed. More info
here
WildCard test exectution is also available by defining a wildcard mask (i.e. Test*.dll) that instructs Team Build to run any tests present in assemblies that match the mask.  This is done when defining the build definition as well.
Things to note:
If you intend to use the wildcard method and want to enable code coverage for your test configuration, you must add the following to your build definition file to enable it.
```
```
<RunConfigFile>$(SolutionRoot)\TestRunConfig.testrunconfig</RunConfigFile>
```
```
See my previous question on this for more info
here


q:
Vista has introduced a new API to display a text in the list view control when it doesn't have any items. As the MSDN library states, I should process the LVN_GETEMPTYMARKUP notification.

In the inherited ListView control the WndProc method is overriden:

protected override void WndProc(ref Message m) {
  try {
    if(m.Msg == 78 /* WM_NOTIFY */) {
      var nmhdr = (NMHDR)Marshal.PtrToStructure(m.LParam, typeof(NMHDR));
      if(nmhdr.code == -187 /* LVN_GETEMPTYMARKUP */) {
        var nmlvemptymarkup =
          (NMLVEMPTYMARKUP)Marshal.PtrToStructure(m.LParam, typeof(NMLVEMPTYMARKUP));
        nmlvemptymarkup.szMarkup = "The ListView is empty.";
        m.Result = (IntPtr)1;
      }
    }
  } finally {
    base.WndProc(ref m);
  }
}

However, it doesn't work (although it doesn't throw any exception). Actually I never get nmhdr.code equals to -187. Any ideas?

[A]
Have you tried calling
```
SetWindowTheme
```
on the control, as indicated in
this article
?


q: I have a Probablistic Neural Network classification experiment set up in MATLAB. I can get the classes for unseen data using the sim command. Is there any way I can get the probabilities for the classes that the classifier calculates? Also, is there any direct way to plot the Reciever Operating Characterstic curve and calculate the Area Under the ROC for my classifier?

[A] You may have better luck getting a response if you include a little more background and define your terms.  I recognize ROC as receiver operating characteristic curve, but PNN and AUC are just alphabet soup to me.  Don't make the mistake of assuming that someone outside of your very specific problem domain cannot help you.  You have to build a bit of a language bridge by explaining your jargon first, though.  This has the added advantage of making this particular question more useful to the stackoverflow community at large when it is eventually answered.


q:
Problem, there's no method:

bool ChangePassword(string newPassword);

You have to know the current password (which is probably hashed and forgotten).

[A]
This is an easy one that I wasted too much time on. Hopefully this post saves someone else the pain of slapping their forehead as hard as I did.
Solution, reset the password randomly and pass that into the change method.
```
```
MembershipUser u = Membership.GetUser();
u.ChangePassword(u.ResetPassword(), "myAwesomePassword");
```
```


q:
I'm looking for a way to select until a sum is reached.

My "documents" table has "tag_id" and "size" fields.

I want to select all of the documents with tag_id = 26 but I know I can only handle 600 units of size.  So, there's no point in selecting 100 documents and discarding 90 of them when I could have known that the first 10 already added up to > 600 units.

So, the goal is: don't bring back a ton of data to parse through when I'm going to discard most of it.

...but I'd also really like to avoid introducing working with cursors to this app.

I'm using MySQL.

[A]
You need some way to order which records get priority over others when adding up to your max units.  Otherwise, how do you know which set of records that totals up to 600 do you keep?
```
```
SELECT d.id, d.size, d.date_created
FROM documents d
INNER JOIN documents d2 ON d2.tag_id=d.tag_id AND d2.date_created >= d.date_created
WHERE d.tag_id=26
GROUP BY d.id, d.size, d.date_created
HAVING sum(d2.size) <= 600
ORDER BY d.date_created DESC
```
```
This is just a basic query to get you started, and there are a number of problems still to solve:
It stops at <= 600, so in most cases you won't fill up your size limit exactly. This  means you might want to tweak it to allow one more record.  For example, if the first record is > 600 the query will return nothing, and that could be a problem.
It won't do anything to check for additional smaller records later on that might still fit under the cap.
Records with identical date_created values could be sort of 'double counted' here and there.


q:
I am trying to setup Weblogic Server 10.3 (and Portal etc.) to use maven as a build tool. I am trying to find a decent tutorial or documentation how to do this. There are some tutorials for older versions like 9.0, but there is little info for version 10.

I am looking a way to build weblogic's ear file with maven. Are people actually doing this? Is using maven worth the trouble?

I would like to use maven in order to have easier integration with continuous integration tools like Hudson.

edit: There seems to be a way to export maven files directly http://edocs.bea.com/wlw/docs102/guide/ideuserguide/build/conMavenScript.html. But those files are simple wrappers for ant.

[A]
I am using maven to build an EAR which I deploy an WebLogic Server 10.3. The tricky parts were:
Finding all dependencies of the weblogic-maven-plugin
Putting all dependencies in the maven repo (I really recommend
Sonatype Nexus
)
Setting noExit to true (otherwise you will get problems in hudson!)
I use the following directory structure in the EAR project:
```
```
pom.xml
src/
   main/
        app/
            META-INF/
                     weblogic-application.xml
```
```
The following is taken from my pom.xml:
```
```
<build>
    <plugins>
        <plugin>
            <artifactId>maven-ear-plugin</artifactId>
            <configuration>
                <displayName>My Project</displayName>
                <earSourceDirectory>src/main/app</earSourceDirectory>
                <modules>
                    <webModule>
                        <groupId>com.somecompany</groupId>
                        <artifactId>webapp</artifactId>
                    </webModule>
                </modules>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>weblogic-maven-plugin</artifactId>
            <version>2.9.1</version>
            <executions>
                <execution>
                    <phase>deploy</phase>
                    <goals>
                        <goal>deploy</goal>
                        <goal>start</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <name>my-project</name>
                <adminServerHostName>${wls.adminServerHostName}</adminServerHostName>
                <adminServerPort>${wls.adminServerPort}</adminServerPort>
                <adminServerProtocol>t3</adminServerProtocol>
                <userId>${wls.userId}</userId>
                <password>${wls.password}</password>
                <upload>true</upload>
                <remote>true</remote>
                <verbose>false</verbose>
                <debug>false</debug>
                <targetNames>AdminServer</targetNames>
                <noExit>true</noExit>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>com.sun</groupId>
                    <artifactId>tools</artifactId>
                    <version>1.5</version>
                    <scope>system</scope>
                    <systemPath>${java.home}/../lib/tools.jar</systemPath>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>weblogic</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>webservices</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.utils.full</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.i18n</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.weblogic.rmi.client</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>javax.enterprise.deploy</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>webserviceclient</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.weblogic.security.wls</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.weblogic.security.identity</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.weblogic.security</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>wlclient</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.transaction</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.utils.classloaders</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>wljmsclient</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.management.core</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>wls-api</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.descriptor</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.logging</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.weblogic.socket.api</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.weblogic.security.digest</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.weblogic.workmanager</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.weblogic.lifecycle</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.utils.wrapper</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>wlsafclient</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.management.jmx</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>weblogic</groupId>
                    <artifactId>com.bea.core.descriptor.wl</artifactId>
                    <version>${weblogic.version}</version>
                    <scope>provided</scope>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>
```
```


q:
I was wondering if there was a simple way to use WMI to get you the current windows user name with domain. The Windows API call just gets you the short username, so you end up doing another call for the domain name. I have some code, but I get an automation error.
Any ideas? I think I'm on the right path, but I am a little new to WMI.

Function GetFullName() As String
    Dim computer As String
    computer = "."
    Dim objWMIService, colProcessList As Object
    Set objWMIService = GetObject("winmgmts:\\" & computer & "\root\cimv2")
    Set colProcessList = objWMIService.ExecQuery _
        ("SELECT TOP 1 * FROM Win32_Process WHERE Name = 'EXCEL.EXE'")
    Dim uname, udomain As String
    Dim objProcess As Object
    For Each objProcess In colProcessList
        objProcess.GetOwner uname, udomain
    Next
    GetFullName = UCase(udomain) & "\" & UCase(uname)
End Function

UPDATE: see comments on accepted answer

[A]
There is no TOP 1 clause in WQL. Leave it out and your query should work:
```
```
"SELECT * FROM Win32_Process WHERE Name = 'EXCEL.EXE'"
```
```


q:
How can you find the number of occurrences of a particular character in a string using sql?

Example: I want to find the number of times the letter ‘d’ appears in this string.

declare @string varchar(100)
select @string = 'sfdasadhfasjfdlsajflsadsadsdadsa'

[A]
Here you go:
```
```
declare @string varchar(100)
select @string = 'sfdasadhfasjfdlsajflsadsadsdadsa'
SELECT LEN(@string) - LEN(REPLACE(@string, 'd', '')) AS D_Count
```
```


q:
I'm trying to switch on and off the Rotate 180 degree setting for an HP Laserjet printer (4200/ 4350) using a duplexer unit.

The Business has a requirement to "print on both sides", for maximum control I'd like to be able to manipulate at print time (through print macros) whether or not duplex printing is enabled for each of the different types of a document the business works with.

I can control the tray assignments, print order and switch duplexing on and off.  However, cannot figure out how to control the rotation option (switch this on and off).

Any solutions available other than a blanket - enable this option on the print server for all documents/ users?


q:
When writing a custom itemRenderer, how do you reference the height and width of the grid cell that it will be rendered in?  In such a way that it will resize correctly when the grid is resized.

I am writing a dataGrid itemRenderer that draws a bar graph in the final column of a table.

I have tried referencing 'this', 'this.parent', and a few other things with no success.
My interim hack solution is to add this data to the datacollection, but this wont work when the grid changes size, so I will have to edit it every time.

[A]
All flex components including cell renderers are aware of their own widths and heights, so you should be able to just access this.width and this.height
If you're looking for events that tell you when a cell has resized you can listen to the
```
ResizeEvent.RESIZE
```
event or override
```
protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
```
on the component.


q:
So I've got a big text file which looks like the following:

<option value value='1' >A
<option value value='2' >B
<option value value='3' >C
<option value value='4' >D

It's several hundred lines long and I really don't want to do it manually. The expression that I'm trying to use is:

<option value='.{1,}' >

Which is working as intended when i run it through several online regular expression testers. I basically want to remove everything before A, B, C, etc. The issue is when I try to use that expression in Vim and Notepad++, it can't seem to find anything.

[A]
This will remove the
```
option
```
tag and just leave the letters in vim:
```
```
:%s/<option.*>//g
```
```


q:
So I've setup an Ubuntu server running the 8.04 release. I set it up to authenticate with our Active Directory using the likewise-open package using these instructions. Part of that setup was giving Domain Admin users who login to the machine sudo access.

Now I'd like to deny login rights for all domain logins except for those users that are in the "Domain Admins" group. Local users should still be able to login. Anyone have any idea how to accomplish this?

[A]
On windows, this is done through group policy. Samba currently doesn't have any support for managing *nix clients with group policy (Samba 4 maybe??).
You can try allowing full control of the computer object for "Domain Admins", and removing all of the permissions for "everyone", but I don't think that will prevent login. I'm just wondering if not having the "Allowed to Authenticate" permission may inadvertently block logins. I'm far from being an AD expert, so this is just a guess.
Likewise does have a product to handle this, but I think it's only in their enterprise package
.
[Edit] addendum
You can try using the netgroup syntax in /etc/password.
You can verify the full name of the group your in by running "id". If your groupname has "\" or " " you may need to escape them.
At the end of your /etc/password file add the line
```
```
+@AdminGroup::::::/bin/bash
+@Everyone::::::/sbin/nologin
```
```
This was designed for nis netgroups, but it's worth a shot.


q:
Lucky me, I have to work with Oracle. And packages.

I have a package that a lot of different developers are touching and it's scaring me. Is it possible to put a package inside of Version Control? Is there some kind of software out there that already does this? If not, is there some kind of export procedure? Can I just grab a file off of a file system?

[A]
How are they inputting it? The way we used to work at my last job is editing a text file, and loading it with SQL*Plus. You can just put that source file under version control.
The source must be between "
```
CREATE OR REPLACE PACKAGE MYPACKAGE AS
```
" and "
```
END;
```
" followed by a single slash on a line of its own ("/"); and ditto for "PACKAGE BODY" instead of "PACKAGE".
And yes, there's a way to pull the source out of Oracle. It's in a table, line by line, look up
ALL_SOURCE
and USER_SOURCE. You can pull it out with a query like
```
```
SELECT TEXT FROM ALL_SOURCE
WHERE TYPE='PACKAGE BODY'
  AND NAME='MYPACKAGE'
  AND OWNER='MYPACKAGEOWNER'
ORDER BY LINE
```
```
(untested as I no longer have access to Oracle) and ditto for the 'PACKAGE'.
I think it's best to load it again into Oracle using SQL*Plus; make sure to set "SCAN OFF".


q:
I have some static images in a folder on my IIS 6-based website that I want to be downloaded as little as possible (to preserve bandwidth). I've set the Content Expiration to expire after 30 days. Is there anything else I can do in IIS to try to maximize the caching by browsers, proxy, and gateway caches?

Such as adding a Cache-Control header? Anything else?


q:
Let's assume I have a model called "product."  Let's assume that product has three fields.  These fields are 'name' (type string), 'cost' (type integer), and 'is_visible' (type bool).

1) How can I do a search query using the Rails "find" method (if there is another method, that's fine) so that I can search for all products with a cost greater than 100 AND is_visible is true?

2) What if we wanted to change this to search to where name != '' OR cost == 0?

This isn't a problem to do an SQL, but I would like to think that Rails has a way to do AND/OR queries to the database without using SQL.

Thanks!

[A]
You would need to use the conditions option on the find method.  The conditions option can be either a Hash, Array, or String.  There are lots of options for conditions, so I recommend reading the
API help
for it.
For example if you want to (1):
```
```
Product.find(:all, :conditions => ['cost > ? and is_visible is true', 100])
```
```
Or (2)
```
```
Product.find(:all, :conditions => ["name != '' or cost =0])
```
```


q:
What is the difference between HAVING and WHERE in an SQL SELECT statement?

EDIT: I have marked Steven's answer as the correct one as it contained the key bit of information on the link:

When GROUP BY is not used, HAVING behaves like a WHERE clause

The situation I had seen the WHERE in did not have GROUP BY and is where my confusion started. Of course, until you know this you can't specify it in the question.

[A]
```
HAVING
```
is used when you are using an aggregate such as
```
GROUP BY
```
.
```
```
SELECT edc_country, COUNT(*)
FROM Ed_Centers
GROUP BY edc_country
HAVING COUNT(*) > 1
ORDER BY edc_country;
```
```


q: I know that when you add/change/remove methods in a COM interface you're supposed to change the interface/coclass GUID but what about type libraries.  When should you change the type library's GUID? Do you change it if a GUID inside the type library has changed? Or should you only change it when something that doesn't have its own GUID within the type library changes.

[A]
The basic principle is that COM interfaces and Type Libraries should be immutable (that is, they shouldn't ever change).  If you change one item inside a COM interface, then the new version needs to be a completely separate entity from the previous version.  The only way to do this is to change the GUID for every interface in the library and the GUID for the type library itself.  It's also a good idea (for your own personal sanity) to change the name of the type library.
Ideally you shouldn't ever change a COM interface.  Instead create a new derived COM interface and publish in a new type library.


q:
What is a proxy object in the Inversion of Control / Aspect-Oriented sense?

Any good articles on what a proxy object is ?

Why you would want to use one ?

And how to write one in C# ?

[A]
In general, a Proxy object is an object (instance of a class) that exposes the exact same public interface as a "real class" but simply forwards all calls made to it's members to the other real class.  Proxy objects are used for a variety of reasons...
One purpose is to "pretend" to be the real class so a client component (or object) can "believe" it's talking to the "real" object, but inside the proxy, other stuff, (like logging, transactional support, etc.) is being done at the same time... Secondly, a proxy can be very cheap in comparson to the real object,. and often is used so that the real objects can be conserved (turned off or released to a pool to be used by other clients) when the client is not using them... The proxy stays "alive" and the client thinks it still has a connection to the real object, but whenever it "calls" the object, it is actually calling the proxy, which goes and gets another real object just to handle the call, and then releases the real object when the call is done.
As to
Inversion of Control
(IOC).. That refers to a common pattern (also referred to as Dependency Injection),  where dependant objects inside of a class are "injected" into an instance of the class, from client code, to control which version of a dependant object the instance will use... IOC can be used to inject a "Proxy" object into a class where it thinks it is using the real object...  The phrase
Inversion of Control
refers to the fact that when using this pattern, the decision as to which actual implementation is called is no longer under the control of the class making the call, but to the client of that class, when it
injects
an instance of a dependant object into the class to be used for this call.
Generally the term IOC is used with what is called an
IOC Container
, which is a class specifically designed to be responsible for creating instances of dependant classes based on loosely coupled information about those classes (Types) which it gets from some source other than hard-wired dependencies (most often, from some kind of configuration file).   Generally, when you use an IOC container, you create an instance of it when the application starts, and then (by reading config data or whatever), you "register" each of the classes (types) that the IOC container will be responsible for, with a key value.  The key is often the abstract type or interface that all instances of this registration must implement).  Then, in the normal operations of your application, where you might otherwise have new'd up an instance of one of these types, you call the IOC Container, and ask it for an instance instead, using the abstract type/Interface as the key.  The IOC container then uses reflection or dynamic loading, (or whatever), to create an instance of whatever type has been "registered" with that key.   In this way, simply by changing configuration data, you can control the actual types used by the application, changing them in one environment or deployment location from those used in another.


q:
I have a CSS class called grid which I place on my tables. I want to Zebra strip my even rows so I use the following jQuery code

$(".grid tr:nth-child(even)").addClass("even");

This basically says "Apply the css class even to any tr tag which has a parent (at any level) with a class of grid." The problem with this is when I have nested tables, the child table's tr tags will also get the even style. Since I did not specify the child table with a class of grid, I don't want it to pick up the zebra stripe.

How can I specify to only apply the even class on tr tags which are a direct descendant of the tag which has the grid class?

[A]
You want to use a different selector, like the child selector:
```
```
$(".grid > tr:nth-child(even)").addClass("even");
```
```
This limits the selection to direct children your
```
.grid
```
only.


q: I have an object created in a host application and can access it remotely using remoting, is there any way I can test the connection to ensure it is still "alive"? Maybe an event I can use that fires if the remoting connection gets disconnected, or some property that can tell me the state of the remoting connection.  Is there something like this available?

[A]
I generally add another method to the remoting server MarshallByRef class,
 (I generally name it Ping(), as in:
```
```
public void Ping() {}
```
```
that does nothing, and returns nothing.. Then to "test" my connection, I call this method... If it throws a System.Net.Sockets.Exception,  I have lost the connection....


q:
Is there a way in Oracle to select the date on which daylight savings will switch over for my locale?

Something vaguely equivalent to this would be nice:

SELECT CHANGEOVER_DATE
FROM SOME_SYSTEM_TABLE
WHERE DATE_TYPE = 'DAYLIGHT_SAVINGS_CHANGEOVER'
  AND TO_CHAR(CHANGEOVER_DATE,'YYYY') = TO_CHAR(SYSDATE,'YYYY');  -- in the current year

Edit: I was hoping for a solution that would not require changes when Congress adjusts DST laws, as they did in 2007.  The posted solutions will work, though.

[A]
In the United States, Daylight Savings Time is defined as beginning on the second Sunday in March, and ending on the first Sunday in November, for the areas that observe DST, for years after 2007.
I don't think there's an easy way to get this information from Oracle, but based on the standard definition, you should be able to write a stored procedure that calculates the beginning and ending date using the
Doomsday Algorithm
.


q:
I have the following code, I'm trying to get a table with 4 columns across. If I run out of columns, create a new row and make 4 more coumns. rinse. lather. repeat.

<tbody>
<%
int i = 0;
foreach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia) {
  if (i%4 == 0 && i== 0)
  {
    %><tr><%
  }
  if (i%4 == 0 && i != 0)
  {
    %></tr><tr><%
  }
  %>
  <td><%= multimedia.ImgTag100 %></td>
  <%
  i++;
  } %>

It works, but it sucks. Is there something built in to the framework or an extension method I can use? I guess I could roll my own, but figured there had to be something out there.

[A]
You should replace the second if with else if.. Other than that, it's okay.
```
```
foreach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia)
{
  if (i%4 == 0 && i== 0)
  {
      %>
<%
  }
  else if (i%4 == 0 && i != 0)
  {
      %>

<%
  }
  %><%= multimedia.ImgTag100 %>	<%
  i++;
}%>
```
```


q:
I have a rather simple scenario where I have two tables in which I want to add data. They are managed with primary key/foreign key. I want to add new data into TABLE A and then retrieve the Id and insert into TABLE B.

I can certainly do it with a stored procedure, but I'm looking at trying to do it using Linq.

What is the best approach ?

I can certainly get the ID and do two separate inserts but that doesn't certainly seem to be a very good way of doing things.

db.Table.InsertOnSubmit(dbObject);
db.SubmitChanges();

Int32 id = dbOject.Id;

//Rest of the code

Any way to elegantly do this?

[A]
Do you have the relationship defined between the 2 tables in the object relational designed? If so, you can have linq take care of assigning the ID property of the second table automatically.
Example...
Table A – Order
OrderId
OrderDate
Table B – Order Item
OrderItemId
OrderId
ItemId
Code (Using LINQ-to-SQL):
```
```
Order order = new Order();
Order.OrderDate = DateTime.Now();
dataContext.InsertOnSubmit(order);

OrderItem item1 = new OrderItem();
Item1.ItemId = 123;
//Note: We set the Order property, which is an Order object
// We do not set the OrderId property
// LINQ will know to use the Id that is assigned from the order above
Item1.Order = order;
dataContext.InsertOnSubmit(item1);

dataContext.SubmitChanges();
```
```


q:
This seems like a very simple and a very common problem. The simplest example I can think of is this:

The form has five checkboxes with a "check all/check none" checkbox above them. When a user selects checking all checkboxes, I toggle the states of the "children" - obviously I don't want to fire the check events of all the children until I am done setting all of the checkboxes.

I can't find a form-wide suspend control event. If I'm simply missing it then great simple answer. Barring a simple solution that I am just missing, what is the best way (best practice? accepted solution?) to suspend form control events?

[A]
From your other question, I'm going to guess you're using VB .NET.  So, RemoveHandler is your best bet.  Normally in VB people set up event handlers using the Handles clause.  But you can also do it this way:
```
```
AddHandler chk1.CheckedChanged, AddressOf DoSomething
```
```
where DoSomething might look like this:
```
```
Private Sub DoSomething(ByVal sender As Object, ByVal e As EventArgs)
    ' whatever
End Sub
```
```
AddHandler wires up the event, so it'll fire.  To get it not to fire, use RemoveHandler:
```
```
RemoveHandler chk1.CheckedChanged, AddressOf DoSomething
```
```
Before updating the Checked property of your child checkboxes, call RemoveHandler on each of them; then when you're done, call AddHandler to put the event handlers back.  If all your checkboxes use the same handler, you can put them in a collection and loop through the collection to add or remove the handlers.


q:
Is it safe to use MS SQL's WITH (NOLOCK) option for select statements and insert statements if you never modify a row, but only insert or delete rows?

I..e you never do an UPDATE to any of the rows.

[A]
If you're asking whether or not you'll get data that may no longer be accurate, then it depends on your queries. For example, if you do something like:
```
```
SELECT
     my_id,
     my_date
FROM
     My_Table
WHERE
     my_date >= '2008-01-01'
```
```
at the same time that a row is being inserted with a date on or after 2008-01-01 then you may not get that new row. This can also affect queries which generate aggregates.
If you are just mimicking updates through a delete/insert then you also may get an "old" version of the data.


q: If a hacker has access to the hashes in my DB, he has access to the rest of the information in the DB anyways. So why would he bother trying to decrypt the passwords? Should I be storing the passwords on a different server to the rest of my data? That is the only scenario in which I can envision it being useful.

[A]
Sometimes a hacker doesn't get full access to your DB.  Sometimes they find a little SQL injection hole or other weakness that someone didn't code correctly, and so they can only do simple things at first like print out database cells one at a time.  If they can print out a real password all of  a sudden things get much worse.
Things happen: backup tapes are lost, accidentally thrown away, or stolen. A retired system wasn't wiped properly. A breach elsewhere leads to accidental exposure of a database. If a hacker gets access to a snapshot like this he can learn a lot about your system.  But if the passwords are still hashed he can't also use the system to do something malicious, like log in as a different user and start changing things.
I've heard that most hacks are an inside job.  Better to remove the ability even for people you trust to log in as others.
It's not about just you. Users tend to share passwords across systems. Maybe some day (God forbid) you have a breach that has nothing to do with passwords, but in the course of that breach your authentication tables will be one of the attacker's targets. If you store passwords in plain-text, you have also just compromised user accounts at many other services, and your very bad day just got quite a lot worse.
If you think this kind of thing doesn't happen, go talk to the guys at reddit.


q:
I use an sql server regularly and have recently been getting frustrated by the performance. It would be difficult for me to get direct access to find out the hardware so:

Is there a direct way in management studio to assess performance or find out the exact hardware.

Alternatively does someone have a set of test sql procedures I could try and ideally compare to other results to get an idea of it's performance.

So far I have setup a few quick queries on my local machines sql express server just as test these seem to run quicker than the sql server on the network which is meant to be high performance although no one knows when it was last upgraded I have a feeling it hasn't been for 6 or 7 years. Obviously these test don't account for the possibility of others querying at the same time or network transfers of results... Hopefully someone has a better solution.

[A]
You can't just ask your server guys? Seems like there's a fair bit of mistrust if you can't get hardware metrics. Count of CPUs, total memory, etc.
If there's that amount of mistrust, even if you found the answer from the database server, rectifying it would be impossible. If you can't get the current parameters, how could you get a change of hardware passed the server guys?
Start building rapport. The best line in the world to get someone on your side is, "I'm in trouble and I need your help..." You've elevated them and subjugated yourself, you've put them in a position to save you. You'd be amazed at how much you can get out of people that way.
As far as standard queries. You could look at
TPC
queries.


q:
I have a right outer join, that almost does what I want...

SELECT
users_usr.firstname_usr,
users_usr.lastname_usr,
credit_acc.given_credit_acc,
users_usr.created_usr,
users_usr.sitenum_usr,
users_usr.original_aff_usr,
users_usr.id_usr
FROM
credit_acc
right Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr

The problem is, I want to add a

where credit_acc.type_acc = 'init'

But this gets rid of all users who don't have a row in credit_acc... which is WHY I need a right outer join.

Is there a way to get this without having to do two queries and a union?

[A]
```
```
SELECT
users_usr.firstname_usr,
users_usr.lastname_usr,
credit_acc.given_credit_acc,
users_usr.created_usr,
users_usr.sitenum_usr,
users_usr.original_aff_usr,
users_usr.id_usr
FROM
credit_acc
right Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr
WHERE credit_acc.type_acc = 'init' OR credit_acc.type_acc is NULL
```
```
Or, as @Tomalak pointed out:
```
```
WHERE COALESCE(credit_acc.type_acc, 'init') = 'init'
```
```
which
may
be faster (see comments).


q:
Is it possible to do  a "C like" fork in java, using an new independent jvm process ?

How?

[A]
Funnily, I am just working on this: a Java process running other Java processes. I used the article
From Runtime.exec() to ProcessBuilder
as a solid base, and
When Runtime.exec() won't
as a good advice how to gobble the output streams.
PS.: For those wondering, I had to do that (instead of spawning new threads) because yet another Java process is checking the presence of these processes which are, normally, ran separately with shell commands.


q:
I want to discover at run-time ONLY the static Methods of a class, how can I do this?
Or, how to differentiate between static and non-static methods.

[A]
Use
```
Modifier.isStatic(method.getModifiers())
```
.
```
```
/**
 * Returns the public static methods of a class or interface,
 *   including those declared in super classes and interfaces.
 */
public static List<Method> getStaticMethods(Class<?> clazz) {
    List<Method> methods = new ArrayList<Method>();
    for (Method method : clazz.getMethods()) {
        if (Modifier.isStatic(method.getModifiers())) {
            methods.add(method);
        }
    }
    return Collections.unmodifiableList(methods);
}
```
```
Note: This method is actually dangerous from a security standpoint. Class.getMethods "bypass[es] SecurityManager checks depending on the immediate caller's class loader" (see section 6 of the Java secure coding guidelines).
Disclaimer: Not tested or even compiled.
Note
```
Modifier
```
should be used with care. Flags represented as ints are not type safe. A common mistake is to test a modifier flag on a type of reflection object that it does not apply to. It may be the case that a flag in the same position is set to denote some other information.


q:
In OpenGL I'm trying to rotate a camera around a point, with camera being distance r from the point and facing the point when it rotates.  In other words, I want the camera to move along the circumference  of a circle at a radius r from the center, with the camera facing the center at any point along the circumference.

Lets say that in 3d space the center of the circle is (3, 0, 3);

I've tried:

// move to center of circle
glTranslatef(-3, 0, -3)
// move a distance away from the circle
glTranslatef(0, 0, r);
// rotate along the y "up" axis
glRotatef(CameraAngle, 0, 1, 0);

where CameraAngle is the degrees being moved around the circle.

My end result is the camera is still rotating along the origin, not the center of the circle.  Can anyone help me fix this problem?  Thanks!

[A]
You need to either:
rotate the camera around the origin and then translate it (*)
or:
use
```
gluLookAt
```
to keep the camera pointing at the center of the circle
(*) rotation functions normally rotate about the origin.  To rotate around another point
```
P
```
you have to:
translate(-P)
rotate
translate(P)


q: How do I create tabbed navigation with the "Current" tab highlighted in the UI?

[A]
Before MVC I looked at the file path and figured out which tab was currrent. Now it's a lot easier, you can assign the current tab based on the current controller.
Check it out ...
Most of the work happens in the usercontrol.
```
```
public partial class AdminNavigation : ViewUserControl
{
    ///
    /// This hold a collection of controllers and their respective "tabs." Each Tab should have at least one controller in the collection.
    ///
    private readonly IDictionary<Type, string> dict = new Dictionary<Type, string>();

    public AdminNavigation()
    {
        dict.Add(typeof(BrandController), "catalog");
        dict.Add(typeof(CatalogController), "catalog");
        dict.Add(typeof(GroupController), "catalog");
        dict.Add(typeof(ItemController), "catalog");
        dict.Add(typeof(ConfigurationController), "configuration");
        dict.Add(typeof(CustomerController), "customer");
        dict.Add(typeof(DashboardController), "dashboard");
        dict.Add(typeof(OrderController), "order");
        dict.Add(typeof(WebsiteController), "website");
    }

    protected string SetClass(string linkToCheck)
    {
        Type controller = ViewContext.Controller.GetType();
        // We need to determine if the linkToCheck is equal to the current controller using dict as a Map
        string dictValue;
        dict.TryGetValue(controller, out dictValue);

        if (dictValue == linkToCheck)
        {
            return "current";
        }
        return "";
    }
}
```
```
Then in your .ascx part of the usercontol call into the SetClass method to check the link against the dict. Like so:
```
```
<li class="<%= SetClass("customer") %>"><%= Html.ActionLink<CustomerController>(c=>c.Index(),"Customers",new{@class="nav_customers"}) %>

```
```
All you need now is the CSS to highlight your current tab. There are a bunch of different ways to do this, but you can get started with some ideas here:
http://webdeveloper.econsultant.com/css-menus-navigation-tabs/
Oh, and don't forget to put the usercontrol on your page (or MasterPage) ...
```
```
<% Html.RenderPartial("AdminNavigation"); %>
```
```


q:
I'm using this simple regular expression to validate a hex string:

^[A-Fa-f0-9]{16}$

As you can see, I'm using a quantifier to validate that the string is 16 characters long. I was wondering if I can use another quantifier in the same regex to validate the string length to be either 16 or 18 (not 17).


q:
I'm using IIS 6 with EPiserver CMS which requires all requests to go through aspnet_isapi.dll.

I want to gzip all my static files (js, css mainly). Trying to setup compression in IIS didn't work.

Is there a setting in EPiServer that will allow me to achieve this?
Can .net framework compress files automatically?

[A]
You'll need to configure the html extension in the IIS metabase
as a dynamically compressed extension
. You are probably  treating it as a static page. If the .js and .css extensions are mapped to aspnet_isapi they are considered as dynamic pages.
The setting in
metabase.xml
should look like this:
```
```
HcScriptFileExtensions="asp
dll
exe
js
css"
```
```
Don't forget to remove the extensions from
```
HcFileExtensions
```
(for static files) if you inserted them there before.
Hope this helps.


q:
I am looking for any best practices or ideas on how you would create an interface with a DB from a .NET web application to upload data from Excel files
Should I use a mechanism that allows all the records to be loaded and flags the errors or should I use a mechanism that stops the load when an error occurs.

I've never had to deal with this type of requirement before so any help would be super!

Thanks

[A]
do you want to put the excel files in the DB as a blob? or do you want to parse the files and put the records in the files into the db?
I'm assuming it is the latter.
As a user I'd like to have the option to know what the errors are so I can fix them and try again. I think how I try again depends on how much data I'm uploading.
I'd try to do a hybrid solution .. if there are only a few errors show a screen to correct those errors so the user can move on quickly. If there are a ton of errors you should just can it and have the user try all over again.
As far as the DB. Either have a separate table that uploads go into until they are checked and get with your "real" data, or have a UploadUniqueId column so you can roll-back any upload without much fuss.
delete tableName where UploadUniqueId = 'GUID'


q:
I thought this code would work, but the regular expression doesn't ever match the \r\n. I have viewed the data I am reading in a hex editor and verified there really is a hex D and hex A pattern in the file.

I have also tried the regular expressions /\xD\xA/m and /\x0D\x0A/m but they also didn't match.

This is my code right now:

   lines2 = lines.gsub( /\r\n/m, "\n" )
   if ( lines == lines2 )
       print "still the same\n"
   else
       print "made the change\n"
   end

In addition to alternatives, it would be nice to know what I'm doing wrong (to facilitate some learning on my part).  :)


q:
I am using an ancient version of Oracle (8.something) and my ADO.NET application needs to do some fairly large transactions. Large enough to not fin in our small rollback segments. Now we have a large rollback segment as well but it is not used by default.

Oracle has a command to select the rollback segment to be used (SET TRANSACTION USE ROLLBACK SEGMENT MY_ROLLBACK_SEGMENT) but it needs to be the first command issued in the transaction. Unfortunately, it seems that ADO.NET issues some other commands at the beginning of a transaction since issuing this command right after .BeginTransaction() throws an error about SET TRANSACTION not being the first command.

I am sure I am not the only one who faced this issue. How do you solve it or how would you get around it?

Thanks

[A]
If this is a 'one-off' requirement then one solution is to put the other rollback segments offline while you run your transactions then put them online when you've finished;
```
```
ALTER ROLLBACK SEGMENT <name> OFFLINE;

ALTER ROLLBACK SEGMENT <name> ONLINE;
```
```
Otherwise make all the rollback segments the same size.


q:
Recently an application I wrote started not working on Internet Explorer. There has been no change to the underlying (ruby on rails) code.

In IE 6 or IE 7, I can make one request (HTTP Post) to the app, but when I try to make a 2nd  request, I get an "Operation Aborted" message. Everything works fine in firefox. The HTTP Request and Response headers are exactly the same. The response header for the correct and incorrect results both have the same content-length (about 104k). The correct response has the full content, but the incorrect response has the content cut off after bout 40k. (So about 65k of the response is just gone.)

The even trickier thing is that if I use the IP address instead of the domain name to make the request, everything works great.

This is an apache2 web server.

Any ideas?

[A]
You could try to debug the issue using
Fiddler
. It's free HTTP Proxy tool for Internet Explorer.
It lists every detail of the request and response. Maybe you can see the actual cause of that behaviour inspecting the whole HTTP traffic.
Hope this helps!
alt text http://i.msdn.microsoft.com/Bb250446.ie_introfiddler_fig04(en-us,VS.85).gif


q:
I'm working with an existing Java codebase which, while it can be invoked from an HTML page using an <APPLET> tag, does not actually subclass the Applet class. The same jars are also used in a non-browser context, so they did not subclass Applet.

Now I need to communicate some values from Java back to the Javascript of the invoking page. Normally one would do this using JSObject, but so far as I can one has to use JSObject.getWindow which only works for subclasses of Applet.

Is there either:

a way to use JSObject from something which isn't an Applet subclass?

some other mechanism to communicate back to the Javascript of the invoking page?

[A]
Call
```
JSObject.getWindow(this)
```
in the applet. Then pass the
```
JSObject
```
into the code that needs it in the usual fashion.


q:
I am creating a form in HTML that will be printed, with fields that need to be written in by the recipient. Basically what I want is a single line that stretches from the end of the field label to the side of the page. Here's how I'm doing it right now:

<table width="100%">
    <tr>
        <td width="1%">
            Label:
        </td>
        <td style="border-bottom-style:solid; border-bottom-width:1px;">
            &nbsp;
        </td>
    </tr>
</table>

This works, but there must be an easier way to do this without needing a whole table element. Any ideas?

[A]
How about using the span tag?
```
```
Text
```
```


q:
If you have to use String.Replace() to replace test 50 times, you essentially have to create a new string 50 times.  Does StringBuilder.Replace() do this more efficiently?  E.g., should I use a StringBuilder if I'm going to be replacing a lot of text, even while I won't be appending any data to it?

I'm using .NET, but I assume this would be the same as Java and possibly other languages.

[A]
Yes, it is.
```
String.Replace
```
always creates a new string –
```
StringBuilder.Replace
```
doesn't.


q: Is there an API to access Subversion from C#?

[A]
Check
SubversionSharp
, its basically a C# wrapper library that fully covers the client API of Subversion.


q:
I'm trying to come up with a reusable JS or jQuery function that would allow me to test if one object is a DOM descendant of another.

I've seen a model of testing for

$b.parents('nodename').length>0

Which is fantastic when you only need to check if an element is a child of any node by that name.

But what about a specific node? You can't test

$b.parents($a).length>0

Because jQuery parents takes a nodename expression as an argument to filter.

As a little background, I'm trying to test if a document click event's target is a child of a specific object. For instance, if the event.target is a child of $b, return true, otherwise, return false. But this function could have other implications later on.

Thanks!

[A]
Try this:
```
```
$('#foo').filter(function(){

   return $(this).parent().is('#foo-parent');

});
```
```
So here we are selecting all the foo elements and then filtering only the elements that have the foo-parent as their immediate parent.
If you are looking to find if the any of the ancestors of the current object comply to the rule, then I guess it should be:
```
```
$('#foo').filter(function(){

   return $(this).parents().is('#foo-parent');

});
```
```


q:
DataGridView, for example, lets you do this:

DataGridView dgv = ...;
DataGridViewCell cell = dgv[1,5];

but for the life of me I can't find the documentation on the index/square-bracket operator.  What do they call it?  Where is it implemented?  Can it throw?  How can I do the same thing in my own classes?

ETA: Thanks for all the quick answers.  Briefly: the relevant documentation is under the "Item" property; the way to overload is by declaring a property like public object this[int x, int y]{ get{...}; set{...} }; the indexer for DataGridView does not throw, at least according to the documentation.  It doesn't mention what happens if you supply invalid coordinates.

ETA Again: OK, even though the documentation makes no mention of it (naughty Microsoft!), it turns out that the indexer for DataGridView will in fact throw an ArgumentOutOfRangeException if you supply it with invalid coordinates.  Fair warning.

[A]
```
```
Operators                           Overloadability

+, -, *, /, %, &, |, <<, >>         All C# binary operators can be overloaded.

+, -, !,  ~, ++, --, true, false    All C# unary operators can be overloaded.

==, !=, <, >, <= , >=               All relational operators can be overloaded,
                                    but only as pairs.

&&, ||                              They can't be overloaded

() (Conversion operator)            They can't be overloaded

+=, -=, *=, /=, %=                  These compound assignment operators can be
                                    overloaded. But in C#, these operators are
                                    automatically overloaded when the respective
                                    binary operator is overloaded.

=, . , ?:, ->, new, is, as, sizeof  These operators can't be overloaded

    [ ]                             Can be overloaded but not always!
```
```
Source of the information
For bracket:
```
```
public Object this[int index]
{

}
```
```
##BUT
The array indexing operator
cannot be overloaded
; however, types can define indexers, properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indices, but indexer parameters can be declared to be of any type (unlike array indices, which must be integral).
From
MSDN


q: I am having severe performance issues when compiling a moderately large ASP.Net website in Visual Studio 2008 (targeting .Net 3.5). I know there are some tips & registry hacks for improving compilation performance in VS 2005, are there any for VS 2008? Specifically, it seems that VS 2008 is compiling the whole website every time F5 is hit, even when no files have changed in that project since the last compile, or perhaps there is some way to skip the validation stage?

[A]
I'm guessing this is an ASP.Net Website project and
not
an ASP.Net Web Application project. You'll get better compile performance from a Web Application project so you might consider converting it.
For a Website project, you can open the Website in Visual Studio, right click the web site project node in the Solution Explorer and click Properties. When the dialog box opens, click the Build item and set the item labeled "Before Running Startup Page" to "No Build" or "Build Page". This will prevent Visual Studio from compiling all the pages in your site and improve your local development experience at the cost of reduced compilation. Probably a worthy trade-off in your case.


q: I know that jQuery and prototype have a $.each() function for iterating over each element in an array. Does YUI offer any help with this?

[A]
What keeps you from simply
iterating
the array?
```
```
for(var i=0; i<ary.length; i++)
  // assuming that ary[] contains objects with a DoSometing() method
  ary[i].doSomething();
```
```


q:
I'd like to make an (MS)SQL query that returns something like this:

Col1 Col2                  Col3
---- --------------------- ------
AAA  18.92                 18.92
BBB  20.00                 40.00
AAA  30.84                 30.84
BBB  06.00                 12.00
AAA  30.84                 30.84
AAA  46.79                 46.79
AAA  86.40                 86.40

where Col3 is equal to Col2 when Col1 = AAA and Col3 is twice Col2 when Col1 = BBB.
Can someone point me in the rigth direction please?

[A]
You didn't mention what kind of database you're using.  Here's something that will work in SQL Server:
```
```
SELECT Col1, Col2,
    CASE WHEN Col1='AAA' THEN Col2 WHEN Col1='BBB' THEN Col2*2 ELSE NULL END AS Col3
FROM ...
```
```


q:
Ruby on Rails controllers will automatically convert parameters to an array if they have a specific format, like so:

http://foo.com?x[]=1&x[]=5&x[]=bar

This would get converted into the following array:

['1','5','bar']

Is there any way I can do this with an ActionScript 3 HTTPService object, by using the request parameter?  For example, It would be nice to do something like the following:

var s:HTTPService = new HTTPService();
s.request['x[]'] = 1;
s.request['x[]'] = 5;
s.request['x[]'] = 'bar';

However, that will simply overwrite each value, resulting in only the last value being sent.  Anyone have a better idea?  I know I could just append stuff to the query string, but I'd like to do it in the POST body.

[A]
I usually do something like this...
```
```
var s:HTTPService = new HTTPService();
s.url = "http://foo.com";
s.method = "post";
// add listeners...
s.addEventListenser(ResultEvent.RESULT,function(event:ResultEvent){

    mx.controls.Alert.show(event.result.toString());
});

// send the data...
s.send({
    a: 1,
    b: 5,
    c: "bar"
});
```
```
which would result in the HTTP Get / POST of:
http://foo.com?a=1&b=5&c=bar
You could also just create an associative array and pass it to the HTTPService send method, that would be something like:
```
```
var postdata:Object = {};

postdata["a"] = 1;
postdata["b"] = 5;
postdata["c"] = "bar";

// s is the HTTPService from above...
s.send(postdata);
```
```


q:
How can I match (PCRE) everything inbetween two tags?

I tried something like this:

<!--\s*LoginStart\s*-->(.*)<!--\s*LoginEnd\s*-->

But it didn't work out too well for me..

I'm kind of new to regular expressions, so I was hoping if someone would be kind enough to explain to me how I would accomplish this, if its even possible with regular expressions.

Thanks

[A]
PHP and regex?  Here's some suggestions:
```
```
'/<!--\s*LoginStart\s*-->(.*)<!--\s*LoginEnd\s*-->/Us'
```
```
Might be better - the
```
U
```
capitalized makes the regex non-greedy, which means it'll stop at the first
```
<!--
```
that may work.  But the important one is the
```
s
```
, which tells the regex to match a newline with the
```
.
```
character.
Depending on how certain you are on the capitalization, adding an
```
i
```
at the end will make the regex search case-insensitive.


q:
So, I've been tasked with making a kiosk for the office for showing statistics about our SCRUM progress, build server status, rentability and so forth. It should ideally run a slideshow with bunch of different pages, some of them showing text, some showing graphs and so on.

What is the best approach for this? I first thought of powerpoint, but It should be able to take the images from a webserver so I can automate the graph generation procedure. I would also like to take text from an external source when showing "Who broke the build" or some page like that.

I have no doubt that ready-made systems exist, but I don't really know where to look for them.

Is this easy/hard in powerpoint? Or are there an ubiquous app that everybody but me knows about?

[A]
I would recommend creating it as a series of web-pages, which uses Javascript or the meta refresh tag to cycle though the different pages. Simply full-screen the browser on a spare machine, and connect it to a projector/monitor/big TV.
This has lots of benefits:
it's
trivial
to display images from an external server (an
```
<img>
```
tag)
it will cost nothing to setup (it can run on basically any functioning machine), and runs in a browser
it is quick to do (you do not have to worry about cross-browser compatibility, or different screen resolutions as you know the exact machine you are developing for
it's expandable - while what you describe is probably possible within Powerpoint, but if you do it as a web-page, you can use Javascript (or a JS framework like jQuery), and it's very easy to serve the pages via a web-server, then you can use any server-side scripting language.
Basically, you would have a series of files, say
```
slide001.htm
```
,
```
slide002.htm
```
and
```
slide003.htm
```
. Slide 1 would redirect to slide002 after 30 seconds, slide002 to slide 003, and slide003 would redirect to slide001..
The specific things you mention: graph generation and "Who broke the build" text:
Not sure which CI tool you use, but many of them generate graphs anyway, so that would be required is having one "slide" with something like
```
<img src="http://hudson.abc/job/proj042/buildTimeGraph">
```
For the who-broke-the-build text, you would be easiest to run the slides as
```
.php
```
files served though a web-server, using
XAMMP
.
Then you would have a function that scrapes your CI server for whoever broke the last build, and in one of the slides, you would have
```
<?PHP echo(who_broke_build()); ?>
```
(Obviously if you know some other language/system better, use that!)
The final benefit I can think of is that, if you serve the files through a web-server, you can allow people display it locally, say as their browsers home-page.


q: Joel often talks about using MS Excel for lightweight project management, but I'm curious about actual implementations of this idea. I've seen some templates that seem to clone MS Project via macros, which would be overkill for a lightweight project. Anyone have any useful templates?

[A]
You have some pretty advance template with
Pipetalk Scheduler
alt text http://ep.yimg.com/ip/I/pipetalk_2055_216386
However, since it seems to be a
little too much
, I just transfered that to the
worst UI thread
;)


q:
I found one source which successfully overrode Time.strftime like this:

class Time
  alias :old_strftime :strftime
  def strftime
    #do something
    old_strftime
  end
end

The trouble is, strftime is an instance method.  I need to override Time.now - a class method - in such away that any caller gets my new method, while the new method still calls the original .now method.  I've looked at alias_method and have met with no success.

[A]
Class methods are just methods. I highly recommend against this, but you have two equivalent choices:
```
```
class Time
  class << self
    alias_method :old_time_now, :now

    def now
      my_now = old_time_now
      # new code
      my_now
    end
  end
end

class << Time
  alias_method :old_time_now, :now

  def now
    my_now = old_time_now
    # new code
    my_now
  end
end
```
```


q:
I need some help regarding algorithm for randomness. So Problem is.

There are 50 events going to happen in 8 hours duration. Events can happen at random times.
Now it means in each second there is a chance of event happening is 50/(8*60*60)= .001736.
How can I do this with random generation algorithm?

I can get random number

int r = rand();
double chance = r/RAND_MAX;
if(chance < 0.001736)
    then event happens
else
    no event

But most of times rand() returns 0 and 0<0.001736 and I am getting more events than required.

Any suggestions?

sorry I forget to mention
I calculated chance as
double chance = (static_cast )(r) / (static_cast)(RAND_MAX);

It removed double from static_cast

double chance = (double)r/(double)(RAND_MAX);

[A]
Both
```
r
```
and
```
RAND_MAX
```
are integers, so the expression
```
```
double chance = r / RAND_MAX;
```
```
is computed with integer arithmetic. Try:
```
```
double chance = 1.0 * r / RAND_MAX;
```
```
which will cause the division to be a floating point division.
However, a better solution would be to use a random function that returns a floating point value in the first place. If you use an integer random number generator, you will get some bias errors in your probability calculations.


q:
I have often wondered why it is that non-English speaking programmers are forced to use a different language when programming when it would seem to be so easy to offer an IDE that could replace keywords with localized versions. Why can't the Germans use a "während..macht" loop?

Do programmers in Japan, Germany, France, Spain, Botswana just make extensive use of macros/define statements to make life more tolerable or do they just get used to the functional significance of print, if, then, while, do, begin, end, var, double, function, etc?

Perhaps the increased use of frameworks (J2EE/.NET) makes this more complicated, but it still seems worthwhile. On the other hand, if Klingon became the de-facto programming language in the US I'd probably regret suggesting this.

[A]
In most programming languages, keywords are reserved, so they can't be used for variable names etc.
Now suppose the keywords changed every time you changed culture - code written in one culture couldn't be ported to another without changing identifiers. Ick. Furthermore, when anyone copied their code onto a question forum like this, we'd no longer be speaking the same language, as it were.
There are distinct advantages to only having one culture in the programming language itself...


q:
I am using a WCF service and a net.tcp endpoint with serviceAuthentication's principal PermissionMode set to UseWindowsGroups.

Currently in the implementation of the service i am using the PrincipalPermission attribute to set the role requirements for each method.

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrators")]
        [OperationBehavior(Impersonation = ImpersonationOption.Required)]
        public string method1()

I am trying to do pretty much the same exact thing, except have the configuration for the role set in the app.config. Is there any way to do this and still be using windows groups authentication?

Thanks

[A]
If I understood well you want to select the role at runtime. This can be done with a
permission
demand within the WCF operation. E.g.
```
```
public string method1()
{
    PrincipalPermission p = new PrincipalPermission(null, "Administrators");
    p.Demand();
    ...
```
```


q:
I have a netbook running Linux and a large collection of computer books and reference material as HTML. I'd like some compact way of storing these books which can be browed without unpacking them first. This would save space and reduce wear on my small SSD.

If there was some way to convince Firefox to browse files contained in ZIP file, this would be ideal. (I know iCab (Mac) had a web archive format that worked this way.)  Perhaps a Firefox plugin? A small web server that can serve directly from ZIP files? Some magic FUSE module? Does anyone have any ideas?

On my PDA (which the netbook is largely replacing) I used iSilo for this, but it's not available for Linux, its conversions are lossy and it costs money.

[A]
You can use
OpenOffice.org
to open the html pages, and then save them as OO documents. OO documents are essentially a zip files.
Another option is to use OO to save as pdf.
You can even do this from a command line using this
OO macro
.
Same with
AbiWord
- you can use it on
commandline to convert
.
In the AbiWord example there is shown how to convert all files in a directory to a desired format (pdf). Then you can use
pdftools
to merge all pages in one document.
Also, I do not know what windows manager your laptop has, but if it is KDE, konqueror (the file and web browser for KDE) opens web pages from inside a zip file w/o any problem.
Most probably Gnome's Nautilus can do this as well (I have no Gnome here to test).
Have you ever tried to open a zip file with whatever file manager you have, and then click on a web page inside it?