q:
I'm storing an object (TTF_Font) in a shared_ptr that is provided to me from a third-party API. I cannot use new or delete on the object, so the shared_ptr is also provided a "freeing" functor.

// Functor
struct CloseFont
{
    void operator()(TTF_Font* font) const
    {
        if(font != NULL) {
            TTF_CloseFont(font);
        }
    }
};

boost::shared_ptr<TTF_Font> screenFont;

screenFont = boost::shared_ptr<TTF_Font>( TTF_OpenFont("slkscr.ttf", 8), CloseFont() );

If, later, I need to explicitly free this object is it correct to do this:

screenFont.reset();

And then let screenFont (the actual shared_ptr object) be destroyed naturally?

[A]
shared_ptr<>::reset() will drop the refcount by one.  If that results in the count dropping to zero, the resource pointed to by the shared_ptr<> will be freed.
So I think the answer for you is, yes that will work.  Or you can simply let the screenFont variable be destructed due to dropping out of scope or whatever, if that's what's about to happen.
To be clear, the normal usage of shared_ptr<> is that you let it be destructed naturally, and it will deal with the refcount and freeing the resource when it drops to zero naturally.  reset() is only required if you need to release that particular instance of the shared resource before the shared_ptr<> would be naturally destructed.


q:
GWT gets locale from either the  locale property or the locale query string.  If neither is specified, it uses the "default" (ie en_US) locale.

Why doesn't it get it from the browser settings?

It seems the only solution to this is to replace your static html launch page with something like a JSP that reads the browser locales and sets the  locale or redirects using the query string. There has to be a better solution than this or simply hard-coding a locale, surely?

[A]
If you put a list of available languages into your *.gwt.xml file it will by default switch to the first language listed.
```
```
<!-- Slovenian in Slovenia -->
<extend-property name="locale" values="sl"/>

<!-- English language, independent of country -->
<extend-property name="locale" values="en"/>
```
```

s: huggingface

c: devops

d: intermediate


q:
I recently read somewhere that writing a regexp to match an email address, taking into account all the variations and possibilities of the standard is extremely hard and is significantly more complicated than what one would initially assume.

Why is that?

Are there any known and proven regexps that actually do this fully?

What are some good alternatives to using regexps for matching email addresses?

[A]
For the
formal
e-mail spec, yes, it is technically impossible via Regex due to the recursion of things like comments (especially if you don't remove comments to whitespace first), and the various different formats (an e-mail address isn't always someone@somewhere.tld). You can get close (with some massive and incomprehensible Regex patterns), but a far better way of checking an e-mail is to do the very familiar handshake:
they tell you their e-mail
you e-mail them a confimation link with a Guid
when they click on the link you know that:
the e-mail is correct
it exists
they own it
Far better than blindly accepting an e-mail address.


q: See title: what does it mean for a C++ function to be inline?

[A]
The function body is literally inserted inside the caller function. Thus, if you have multiple calls to this function, you get multiple copies of the code. The benefit is you get faster execution.
Usually very short function are inlined, when the copy of the function body would be not much bigger than the usual prologue/epilogue code generated for the normal function call.
You can read more at MSDN article about inline -
http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx


q: Is it possible to enumerate all the current errors being displayed through an "Error Provider" without having to access the controls?

[A] There is a summary validator that will give you all of the errors, but it's pretty ugly, and I'm not sure if you can use it without displaying it on the page.  Technically, if you are doing things the "right way", all of you error handling should be handled in your midddle teir and then bubbled to the screen that way, so you already have access to all the errors in a collection or dictionary.


q:
How do I write an Excel workbook to a MemoryStream without first saving it to the file system?

All options within the Microsoft.Office.Interop.Excel.WorkBook save options take a filename.

[A]
I have done extensive work with the PIA and with storing Excel files in a document repository and streaming it out to the browser, and I have not been able to find a solution to using the PIA without first writing the contents to the file system first.
I think that you are going to have to swallow the bullet and deal with the file system as an intermediary.  The good news is that you can just give the file a unique name like a guid or use some other tempfilename method (not sure if one exists in .net) and just delete the contents when you are done.


q:
How can I use JUnit idiomatically to test that some code throws an exception?

While I can certainly do something like this:

@Test
public void testFooThrowsIndexOutOfBoundsException() {
  boolean thrown = false;

  try {
    foo.doStuff();
  } catch (IndexOutOfBoundsException e) {
    thrown = true;
  }

  assertTrue(thrown);
}

I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.

[A]
How about this: catch a very general exception, make sure it makes it out of the catch block, then assert that the class of the exception is what you expect it to be.  This assert will fail if a) the exception is of the wrong type (eg. if you got a Null Pointer instead) and b) the exception wasn't ever thrown.
```
```
public void testFooThrowsIndexOutOfBoundsException() {
  Throwable e = null;

  try {
    foo.doStuff();
  } catch (Throwable ex) {
    e = ex;
  }

  assertTrue(e instanceof IndexOutOfBoundsException);
}
```
```


q:
I'm trying to insert some import lines into a python source file, but i would ideally like to place them right after the initial docstring. Let's say I load the file into the lines variable like this:

lines = open('filename.py').readlines()

How to find the line number, where the docstring ends?

[A]
If you're using the standard docstring format, you can do something like this:
```
```
count = 0
for line in lines:
    if line.startswith ('"""'):
        count += 1
        if count < 3:
            # Before or during end of the docstring
            continue
    # Line is after docstring
```
```
Might need some adaptation for files with no docstrings, but if your files are formatted consistently it should be easy enough.


q: CLR profiler does not seem to work with the Silverlight CLR. Does another memory profiler exist?

[A]
Doesn't seem to be one available yet. However, as
recommended in this forum thread
, you can convert your Silverlight app to a WPF application and profile that:
There is no tool as of now but as a workaround you can easily create a desktop (WPF) version of your Silverlight client from the same code base and few tweaks (refer Scot's blog for an example on this -
http://weblogs.asp.net/scottgu/pages/silverlight-tutorial-part-8-creating-a-digg-desktop-application-using-wpf.aspx
) .  Once you are done with this you can run any performance profiler that works with WPF.
Not an optimal solution, but it sounds like the best option for now...
Update:
Just saw a
blog post
about XPerf which is a cpu sampler for Silverlight. Not exactly a memory profiler but a good tool for testing the performance of Silverlight apps...


q:
Alright, I have been doing the following (variable names have been changed):

FileInputStream fis = null;
try
{
    fis = new FileInputStream(file);

    ... process ...

}
catch (IOException e)
{
    ... handle error ...
}
finally
{
    if (fis != null)
        fis.close();
}

Recently, I started using FindBugs, which suggests that I am not properly closing streams.  I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException.  What are people supposed to do here?  The Java libraries throw too many checked exceptions.

[A]
Something like the following should do it, up to you whether you throw or swallow the IOException on attempting to close the stream.
```
```
FileInputStream fis = null;
try
{
    fis = new FileInputStream(file);

    ... process ...

}
catch (IOException e)
{
    ... blah blah blah ...
}
finally
{
    try
    {
        if (fis != null)
            fis.close();
    }
    catch (IOException e)
    {
    }
}
```
```


q:
I am debugging some code in the Selenium-rc proxy server. It seems the culprit is the HttpURLConnection object, whose interface for getting at the HTTP headers does not cope with duplicate header names, such as:

Set-Cookie: foo=foo; Path=/
Set-Cookie: bar=bar; Path=/

The way of getting at the headers through the HttpURLConnection (using getHeaderField(int n) and getHeaderFieldKey(int n)) seems to be causing my second cookie to be lost. My question is

Is it true that HttpURLConnection itself can't cope with it, and

If so, is there a workaround to it?

[A]
Without actually having tried it (can't remember to have handled that topic myself), there's also getHeaderFields, inherited from
UrlConnection
. Does this do what you need?


q:
I need to import largish (24MB) text files into a MySQL table. Each line looks like this:

1 1 0.008  0  0  0  0  0

There are one or more spaces after each field, and the last field is tailed by about 36 spaces before the newline.

How do I import such a file into MySQL? From the documentation it seems that LOAD DATA expects all fields to be terminated by exactly the same string. I have tried

LOAD DATA INFILE 'filename' INTO TABLE mytable FIELDS TERMINATED BY ' ';

but MySQL will interpret a sequence of more than one space as delimiting an empty field.

Any ideas?

[A]
If you're on unix/linux then you can put it through sed.
open a terminal and type:
```
```
sed 's/ \+/ /g' thefile > thefile.new
```
```
this replaces all sequences of multiple spaces with one space.


q:
How do you setup an asp.net sql membership role/membership provider on a production machine? I'm trying to setup BlogEngine.NET and all the documentation says to use the ASP.NET Website Administration tool from Visual Studio but that isn't available on a production machine. Am I the first BlogEngine user to use it on a non-development box?

The SQL server is completely blocked off from everything but the production box, I do have SQL Management Studio on there though.

EDIT: I mean, how do you add new users/roles, not how do you create the tables. I've already ran aspnet_regsql to create the schema.

EDIT2: MyWSAT doesn't work because it requires an initial user in the database as well. I need an application that will allow me to create new users in the membership database without any authentication, just a connection string.

[A]
You'll have to have .NET 2.0 installed on the machine, all the VS tool is is a GUI wrapper for a command line tool which is part of the framework.
Check C:\Windows\Microsoft.NET\Framework\v2.0.50727 for the app aspnet_regsql.exe
/? for command line switches, /W for a wizard mode


q:
I started using Sandcastle some time ago to generate a Documentation Website for one of our projects. It's working quite well but we've always only written documentation for classes, methods, properties (...) in our project and had completely separate documentation for the overall project and project parts/modules/namespaces. It would be nice if I could merge that documentation together and add respective documentation to the generated helper files but I can't figure out how to do it.

Just adding comments to the namespace declaration doesn't seem to work (C#):

/// <summary>
/// My short namespace description
/// </summary>
namespace MyNamespace { ... }

Does anyone know how to do this? I know it's possible somehow and it would be really nice to have... :)

[A]
If you use
Sandcastle Help File Builder
there is a dialog to enter the Namespace summaries. (Apparently also support for defining a specific class, but I wouldn't prefer it..)
From the feature list:
Definition of project summary and
  namespace summary comments that will
  appear in the help file. You can also
  easily indicate which namespaces to
  include or exclude from the help file.
  Support is also included for
  specifying namespace comments via a
  NamespaceDoc class within each
  namespace.


q:
I've seen a few examples on how to do build deployment, however I have something unique that I'd like to do:

Deploy the build to a folder that has the build number (eg. Project\Builds\8423)

Alter the version number in the .NET AssmblyInfo.cs to match the build number

Has anyone done this before with .NET projects using NAnt + CruiseControl.net?

[A]
i haven't done it with nant, but we have written a custom application in C# that reads the  assembly and increments the release number.
we call it from an exec block in the ccnet config.
creating a folder and copying files would be trivial to add to that application
our thinking was we use C# all day, so it would be quicker to fix/alter the build program written in C#, then if we had to learn the intracies of nant scripts on top of that
obviously if you use nant all the time, there would be no reason not to build a custom nant plugin to do the job


q:
I'm just wondering if there can be a case where the hostname can be successfully resolved but the returned hostEntry.AddressList is empty.

Currently I'm doing something like this:

IPHostEntry hostEntry = Dns.GetHostEntry("some.hostname.tld");
if (hostEntry.AddressList.Count() < 1)
{
  // can that ever happen?
  throw new ArgumentException("hostName has no assigned IP-Address");
}
TcpClient client = new TcpClient(hostEntry.AddressList[0], 1234);

My assumption is that Dns.GetHostEntry either throws an exception if the hostname is not found or otherwise the AddressList is nonempty, but I'm not sure about that.

[A]
You have three possible situations here:
The hostname exists (DNS has an A Record) and resolves to an IP Address
Condition is never hit
The hostname exists (DNS knows about the domain) however no A records exists.
This is an extremely unlikely scenario, and I think this can never happen in the first place.
The hostname doesn't exist
Exception is thrown, you never get there.
So no, I don't think that can ever happen.


q:
We are using fmt:setBundle to load a resource bundle from a database (we extended the ResourceBundle class to do that).
When we modify a value in database, we have to reload the web server to display the new value on the web app.

Is there any simple way to use the new value without restarting the web server ?

(We do not want to always look up the value from database but we would like to invalidate the cache, for example by calling a special 'admin' URL)

EDIT : We are using JDK 1.4, so I would prefer a solution on that version. :)

[A]
If you're using JDK 1.6 you can use the callback methods
```
getTimeToLive()
```
and
```
needsReload()
```
in
ResourceBundle.Control
to control if the bundle cache needs to be loaded with new values from the database.


q:
I have a requirement to be able to provide a flex component in English and several asian languages.  I have looked at the flex documentation and it seems that I have to build several swf's, which feels wrong.

Does anyone know of a straightforward and practical way of bundling string resources in different languages and handling the fonts?

[A]
We use Flex for the client part of our application and support I18N via
```
ResourceBundle
```
s.


q:
I would like to know what of the many XSLT engines out there works well with Perl.

I will use Apache (2.0) and Perl, and I want to obtain PDFs and XHTMLs.

I'm new to this kind of projects so any comment or suggestion will be welcome.

Thanks.

Doing a simple search on Google I found a lot and I suppose that there are to many more.

http://www.mod-xslt2.com/

http://xml.apache.org/xalan-j/

http://saxon.sourceforge.net/

http://www.dopscripts.com/xslt_parser.html

Any comment on your experiences will be welcome.

[A]
Can't really say which is the best solution because I didn't have a chance to try them all.
But I can recommend you to try Perl module
LibXSLT
.
It's an interface to the gnome libxslt library. I used it on one of my recent project was satisfied with it.


q:
I am very new to creating webservers - and I have had several goes at trying to understand them and write a quick webserver, but it's never quite 'clicked'.  At the moment I am under the impression that REST would be most suitable for my purposes (I will explain later).

Can anyone either show me a basic code example in Java (using Tomcat Apache) or a tutorial resource to show how a webserver:

Can be used for security - i.e. pass in some kind of value to identify the client - from their the webserver will either deny or grant access to the client dependant on some criteria - maybe a lookup list.

Once the client is successfully accepted they will be allowed to pass in some more values to the webserver that will be used to write a row in a database table.

Many thanks.

PS - I would have thought there might have been soemthing that comes with Eclipse Ganymede? If someone can confirm?

[A]
The best way to write restful resources in Java is via the JAX-RS standard. So I'd recommend you download
Jersey which is the JAX-RS reference implementation
and check out its examples; its got lots of them. Take an example for a spin then try hacking it to do what you like.
BTW JAX-RS can be run inside any Servlet engine - you just build a WAR and deploy it (there are examples in the Jersery samples) - though Jersey also comes with a small lightweight web server you can use too which is a little easier to use - again there are examples in the distro of this.


q:
How do I initialize an automatic download of a file in Internet Explorer?

For example, in the download page, I want the download link to appear and a message: "If you download doesn't start automatically .... etc". The download should begin shortly after the page loads.

In Firefox this is easy, you just need to include a meta tag in the header, <meta http-equiv="Refresh" content="n;url"> where n is the number of seconds and url is the download URL. This does not work in Internet Explorer. How do I make this work in Internet Explorer browsers?

[A]
I recently solved it by placing the following script on the page.
```
```
setTimeout(function () { window.location = 'my download url'; }, 5000)
```
```
I agree that a meta-refresh would be nicer but if it doesn't work what do you do...


q:
I have an error occuring frequently from our community server installation whenever the googlesitemap.ashx is traversed on a specific sectionID. I suspect that a username has been amended but the posts havn't recached to reflect this.

Is there a way a can check the data integruity by performing a select statement on the database, alternatively is there a way to force the database to recache?


q:
In my environment here I use Java to serialize the result set to XML.
It happens basically like this:

//foreach column of each row
xmlHandler.startElement(uri, lname, "column", attributes);
String chars = rs.getString(i);
xmlHandler.characters(chars.toCharArray(), 0, chars.length());
xmlHandler.endElement(uri, lname, "column");

The XML looks like this in Firefox:

<row num="69004">
    <column num="1">10069</column>
    <column num="2">sd&#26;</column>
    <column num="3">FCVolume                      </column>
</row>

But when I parse the XML I get the a

org.xml.sax.SAXParseException: Character reference "&#26" is an
  invalid XML character.

My question now is: Which charactes do I have to replace or how do I have to encode my characters, that they will be valid XML?

[A]
Extensible Markup Language (XML) 1.0
says:
The ampersand character (&) and the
  left angle bracket (<) must not appear
  in their literal form, except when
  used as markup delimiters, or within a
  comment, a processing instruction, or
  a CDATA section. If they are needed
  elsewhere, they must be escaped using
  either numeric character references or
  the strings "&" and "<"
  respectively. The right angle bracket
  (>) may be represented using the
  string ">", and must, for
  compatibility, be escaped using either
  ">" or a character reference when
  it appears in the string "]]>" in
  content, when that string is not
  marking the end of a CDATA section.
You can skip the encoding if you use CDATA:
```
```
<column num="1"><![CDATA[10069]]></column>
<column num="2"><![CDATA[sd&]]></column>
```
```


q:
In Eclipse 3.3.2, I would like to replace a character (say ',') by a new line in a file.
What should I write in the "Replace with" box in order to do so ?

EDIT : Many answers seems to be for Eclipse 3.4. Is there a solution for Eclipse 3.3.X ?

[A]
Check box 'Regular Expressions' and use '\R' in the 'Replace with' box
It's a new feature introduced with Eclipse 3.4, See
What's New in 3.4


q: If I hit a page which calls session_start(), how long would I have to wait before I get a new session ID when I refresh the page?

[A]
Check out php.ini the value set for session.gc_maxlifetime is the ID lifetime in seconds.
I believe the default is 1440 seconds (24 mins)
http://www.php.net/manual/en/session.configuration.php
Edit:
As some comments point out, the above is not entirely accurate.  A wonderful explanation of why, and how to implement session lifetimes is available here:
How do I expire a PHP session after 30 minutes?


q:
I am trying to configure Reporting Services 2005SP2 on a machine with SQL 2008 on another hosting the ReportServer DB.

When I create the ReportServerDB the DB is created as version C.0.9.45:

When, afterwards, I try to initialise Reporting Services, I get an error about an incorrect version number. Reporting Services created a ReportServer DB version C.0.9.45 but now expects a version C.0.8.54.

Changing compatibility settings of the DB doesn’t have an effect. And changing the version number sproc in the DB to return what Reporting Services wants to hear only delays the crash until initialisation has started.

Any ideas?

[A] You must have created the reportServerDB using the SQL 2008 configuration tool. If you want to use the 2005 version of the server you need to create the configuration database using the configuration tool that came with SQL 2005. The 2005 SP2 tool will create a database with version C.0.8.54


q:
I am using Eclipse for quite some time and I still haven't found how to configure the Problems View to display only the Errors and Warnings of interest. Is there an easy way to filter out warnings from a specific resource or from a specific path? For example, when I generate javadoc I get tons of irrelevant html warnings. Also, is there a way to change the maximum number of appearing warnings/errors?

I am aware of the filters concept, but I am looking for some real life examples. What kind of filters or practices do other people use?

Edit: I found the advice to filter on "On selected element and its children" to be the best one. I have one other issue however. If I have "a lot" of warnings or errors, only the first 100 appear. In the rare case I want to see all of them, how do I do it?

[A]
In the top right hand corner of the problems pane is a filter button (it looks like three arrows pointing to the right), clicking that will let you configure the view.  You can filter by element, such as the class you're editing or working set, the type of problem (e.g. java problems, buildfile problems etc..) and by severity.  It's actually very configurable.
See
http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.user/concepts/cprbview.htm
for details and screenshots.


q: What i mean exactly is that build.xml that actually included those plugins like findbugs etc. Or nicely done build.xml

[A] You could use maven 2, because it has built-in plugin support.And all the stuff like: PMD, Findbugs, Checkstyle etc , could be integrated automatically . If you have some existing code it could be called from maven you could use maven-antrun-plugin.


q:
This is a followup question of How to encode characters from Oracle to Xml?

In my environment here I use Java to serialize the result set to xml. I have no access to the output stream itself, only to a org.xml.sax.ContentHandler.

When I try to output characters in a CDATA Section:

It happens basically like this:

xmlHandler.startElement(uri, lname, "column", attributes);
String chars = "<![CDATA["+rs.getString(i)+"]]>";
xmlHandler.characters(chars.toCharArray(), 0, chars.length());
xmlHandler.endElement(uri, lname, "column");

I get this:

<column>&lt;![CDATA[33665]]&gt;</column>

But I want this:

<column><![CDATA[33665]]></column>

So how can I output a CDATA section with a Sax ContentHandler?

[A]
It is getting escaped because the handler.characters function is designed to escape and the
```
<![CDATA[
```
part isn't considered part of the value.
You need to use the newly exposed methods in
```
DefaultHandler2
```
or use the
```
TransformerHandler
```
approach where you can set the output key
```
CDATA_SECTION_ELEMENTS
```
, which takes a whitespace delimited list of tag names that should output sub text sections enclosed in CDATA.
```
```
StreamResult streamResult = new StreamResult(out);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler hd = tf.newTransformerHandler();
Transformer serializer = hd.getTransformer();
serializer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "column");
hd.setResult(streamResult);
hd.startDocument();
hd.startElement("","","column",atts);
hd.characters(asdf,0, asdf.length());
hd.endElement("","","column");
hd.endDocument();
```
```


q:
I've written a simple SessionItem management class to handle all those pesky null checks and insert a default value if none exists.  Here is my GetItem method:

public static T GetItem<T>(string key, Func<T> defaultValue)
{
    if (HttpContext.Current.Session[key] == null)
    {
        HttpContext.Current.Session[key] = defaultValue.Invoke();
    }
    return (T)HttpContext.Current.Session[key];
}

Now, how do I actually use this, passing in the Func<T> as an inline method parameter?

[A]
Why don't you pass the default value directly? What use is the functor?
By the way,
```
defaultValue.Invoke()
```
is quite verbose. It's also possible to just write
```
defaultValue()
```
.


q: In C++ the storage class specifier static allocates memory from the data area. What does "data area" mean?

[A]
I'm not familiar with the term “data area” but memory is often divided into “code section” and “data section”. Code resides in the former, data in the latter. I presume this is what's meant here.
Classically, there's no distinction between the two. However, many modern operating systems can prohibit the execution of code int he data segment (provided the CPU supports this distinction). This sometimes goes by the catch phrase of “NX flag”, as in “no execution” and can effectively prevent some cases of malicious code injection.
/EDIT: Notice that the C++ standard doesn't mention a “data area”.


q:
In a question answer I find the following coding tip:-

2) simple lambdas with one parameter:

x => x.ToString() //simplify so many calls

As someone who has not yet used 3.0 I don't really understand this tip but it looks interesting so I would appreciate an expantion on how this simplifies calls with a few examples.

I've researched lambdas so I think I know what they do, however I may not fully understand so a little unpacking might also be in order.

[A]
This basically expands to:
```
```
private string Lambda(object x) {
  return x.ToString();
}
```
```


q: I need to consume a wcf service dynamically when all i know is its URL. I do not have the option of creating a service reference or web reference as my client side code picks up the URL from a config file. What classes and methods can i use from the System.ServiceModel namespace for doing so.

[A]
If you know the contract then you can do something like:
```
```
using (WebChannelFactory<IService> wcf = new WebChannelFactory<IService>(new Uri("http://localhost:8000/Web")))
```
```
More
here


q:
We're in the process of developing a measurement device that will be running
CE 6.0 with CF 3.5 on x86 embedded hardware, a PC is used to control the
device and is connected with it using ethernet.

We would like to communicate using interfaces (using DCOM (we know it is not
supported by default on CE6), .NET Remoting or Web services) instead of
using some sort of (custom) protocol. Calling methods defined in an
interface is so much easier and elegant then parsing raw data.

What would be the best solution in this case?

[A]
I've had some experience setting up comms between CE devices and a PC, and have used custom interfaces using winsock (thwacking some bytes back and forwards) and have tried SOAP. In Windows CE 5.0, the Microsoft provided SOAP server took our device down somehow every couple of hours or so. I spent many weeks trying to work out what was wrong, thinking it was something I'd done wrong. So, I prefer to stick to winsock now because at least I've got a chance of knowing what's going on and can fix it.
Also, CE devices aren't always the quickest performers depending on what hardware you've got. Web-services take up some overhead and time converting data to XML, and this may be a performance hit you are or are not able to afford.


q: Can anyone recommend good simulation software for mobile devices?  I am most interested in Nokia smart phones.

[A]
Are you looking for Emulator for Nokia phones? You can find those
here
..
Otherwise explain clearly what kind of simulation software you are looking for!


q:
I'm writing a shell for a project of mine, which by design parses commands that looks like this:

COMMAND_NAME ARG1="Long Value" ARG2=123 ARG3=me@me.com

My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements.

Any ideas how can this be solved? Any existing library for this?

[A]
Without fairly intensive surgery on optparse or getopt, I don't believe you can sensibly make them parse your format. You can easily parse your own format, though, or translate it into something optparse could handle:
```
```
parser = optparse.OptionParser()
parser.add_option("--ARG1", dest="arg1", help="....")
parser.add_option(...)
...
newargs = sys.argv[:1]
for idx, arg in enumerate(sys.argv[1:])
    parts = arg.split('=', 1)
    if len(parts) < 2:
        # End of options, don't translate the rest.
        newargs.extend(sys.argv[idx+1:])
        break
    argname, argvalue = parts
    newargs.extend(["--%s" % argname, argvalue])

parser.parse_args(newargs)
```
```


q:
I have been using C# for a while now, and going back to C++ is a headache. I am trying to get some of my practices from C# with me to C++, but I am finding some resistance and I would be glad to accept your help.

I would like to expose an iterator for a class like this:

template <class T>
class MyContainer
{
public:
    // Here is the problem:
    // typedef for MyIterator without exposing std::vector publicly?

    MyIterator Begin() { return mHiddenContainerImpl.begin(); }
    MyIterator End() { return mHiddenContainerImpl.end(); }

private:
    std::vector<T> mHiddenContainerImpl;
};

Am I trying at something that isn't a problem? Should I just typedef std::vector< T >::iterator? I am hoping on just depending on the iterator, not the implementing container...

[A]
This should do what you want:
```
```
typedef typename std::vector<T>::iterator MyIterator;
```
```
From
Accelerated C++
:
Whenever you have a type, such as
```
vector<T>
```
, that depends on a template parameter, and you want to use a member of that type, such as
```
size_type
```
, that is itself a type, you must precede the entire name by
```
typename
```
to let the implementation know to treat the name as a type.


q:
I'm planning to write a web service aka api for my application which was developed with .Net and SQLServer. .Net provides a simple way to create webservices by creating asmx files. But i need to know how best it can be designed or what are the best practices in creating a web service in .net or some pointers to good articles as this is my first experience in web services programming. Eventhough SF has many references to best practices in API (which are very good) i dont find much information oriented for .net webservices.

Update: After dariom's reply i would like to mention that i'm doing it in .net 2.0

[A]
It's not easy to remember all the best practices out there, but here is my advice:
Avoid using data types which aren't easily serializable or aren't compatible with the WS standards (and thus you won't be able to consume the service using different languages). Most notably are RecordSets and other MS-only reference types.
Notice there's a difference between static web service (a static method which has [webmethod]) and non-static (memeber function). This might affect your performance and resource usage.
There's a difference between designing a .NET webservice that runs inside your intranet, and a webservice designed for the internet. The second should be simpler in that the XML data that goes on the wire should be much smaller.
I guess the webservice is going to deployed on an IIS server. Notice there's a difference in authentication when running inside the intranet and on the internet. You might need to use impersonation for the service to be able to do specific tasks.
I guess there's much much more, better look for some documentation discussing that.


q:
I recently started learning Emacs. I went through the tutorial, read some introductory articles, so far so good.

Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project; and python.el, which is part of Emacs 22.

I read all information I could find but most of it seems fairly outdated and I'm still confused.

The questions:

What is their difference?

Which mode should I install and use?

Are there other Emacs add-ons that are essential for Python development?

Relevant links:

EmacsEditor @ wiki.python.org

PythonMode @ emacswiki.org

[A]
If you are using GNU Emacs 21 or before, or XEmacs, use python-mode.el. The GNU Emacs 22 python.el won't work on them. On GNU Emacs 22, python.el does work, and ties in better with GNU Emacs's own symbol parsing and completion, ElDoc, etc. I use XEmacs myself, so I don't use it, and I have heard people complain that it didn't work very nicely in the past, but there are updates available that fix some of the issues (for instance, on the emacswiki page you link), and you would hope some were integrated upstream by now. If I were the GNU Emacs kind, I would use python.el until I found specific reasons not to.
The python-mode.el's single biggest problem as far as I've seen is that it doesn't quite understand triple-quoted strings. It treats them as single-quoted, meaning that a single quote inside a triple-quoted string will throw off the syntax highlighting: it'll think the string has ended there. You may also need to change your auto-mode-alist to turn on python-mode for .py files; I don't remember if that's still the case but my init.el has been setting auto-mode-alist for many years now.
As for other addons, nothing I would consider 'essential'. XEmacs's func-menu is sometimes useful, it gives you a little function/class browser menu for the current file. I don't remember if GNU Emacs has anything similar. I have a rst-mode for reStructuredText editing, as that's used in some projects. Tying into whatever VC you use, if any, may be useful to you, but there is builtin support for most and easily downloaded .el files for the others.


q: I have an script that falls over if any of the procedures it is trying to create already exists. How can I check/drop if this procedure is already created?

[A]
I would guess something along the lines of:
```
```
IF EXISTS
(
    SELECT *
    FROM SYSPROCS
    WHERE SPECIFIC_SCHEMA = ???
      AND SPECIFIC_NAME = ???
      AND ROUTINE_SCHEMA = ???
      AND ROUTINE_NAME = ???
)
    DROP PROCEDURE ???
```
```
I don't know if you actually need the SPECIFIC_* information or not and I don't know how to handle cases where you have two procedures with the same name but different call signatures, but hopefully this gets you on the right track.


q:
I'm attempting to check for the existence of a node using the following .NET code:

xmlDocument.SelectSingleNode(
        String.Format("//ErrorTable/ProjectName/text()='{0}'", projectName));

This always raises:

XPathException: Expression must evaluate to a node-set.

Why am I getting this error and how can I resolve it? Thank you.

[A]
Try:
```
```
Node node = xmlDocument.SelectSingleNode(String.Format("//ErrorTable/ProjectName = '{0}'", projectName));

if (node != null) {
    // and so on
}
```
```
Edit: silly error


q: I have a list of tuples eg. [{1,40},{2,45},{3,54}....{7,23}] where 1...7 are days of the week (calculated by finding calendar:day_of_the_week()). So now I want to change the list to [{Mon,40},{Tue,45},{Wed,54}...{Sun,23}]. Is there an easier way to do it than lists:keyreplace?

[A]
Simple. Use map and a handy tool from the httpd module.
```
```
lists:map(fun({A,B}) -> {httpd_util:day(A),B} end, [{1,40},{2,45},{3,54},{7,23}]).
```
```


q:
When you're adding javaDoc comments to your code and you're outlining the structure of an XML document that you're passing back, what's the best way to represent attributes? Is there a best practice for this?

My general structure for my javaDoc comments is like this:

/**
 * ...
 *
 * @return XML document in the form:
 *
 * <pre>
 * &lt;ROOT_ELEMENT&gt;
 *    &lt;AN_ELEMENT&gt;
 *    &lt;MULTIPLE_ELEMENTS&gt;*
 * &lt;/ROOT_ELEMENT&gt;
 * </pre>
 */

[A]
Not sure I clearly  understand your question.
My preferred solution would be to embed the schema XSD or DTC in the description of the return parameter. Your solution seems to lead to personal idioms on how to represent things like multiple elements or others. Using a standard like XSD or DTD allows you to have a well know and recognized language on how to describe the structure of a XML document.
Regarding the JavaDoc representation if you are using Eclipse you can specify under Save Actions to format your document. This way you can write normally with > and < and see it converted to the escaped HTML codes.


q:
I made a view to abstract columns of different tables and pre-filter and pre-sort them. There is one column whose content I don't care about but I need to know whether the content is null or not. So my view should pass an alias as "true" in case the value of this specified column isn't null and "false" in case the value is null.

How can I select such a boolean with T-SQL?

[A]
You have to use a
CASE
statement for this:
```
```
SELECT CASE WHEN columnName IS NULL THEN 'false' ELSE 'true' END FROM tableName;
```
```


q:
As far as i know it is not possible to do the following in C# 2.0

public class Father
{
    public virtual Father SomePropertyName
    {
        get
        {
            return this;
        }
    }
}

public class Child : Father
{
    public override Child SomePropertyName
    {
        get
        {
            return this;
        }
    }
}

I workaround the problem by creating the property in the derived class as "new", but of course that is not polymorphic.

public new Child SomePropertyName

Is there any solution in 2.0?
What about any features in 3.5 that address this matter?

[A]
No. C# does not support this idea (it's called "return type covariance").
You can however do this:
```
```
public class FatherProp
{
}

public class ChildProp: FatherProp
{
}

public class Father
{
    public virtual FatherProp SomePropertyName
    {
        get
        {
            return new FatherProp();
        }
    }
}

public class Child : Father
{
    public override FatherProp SomePropertyName
    {
        get
        {
            // override to return a derived type instead
            return new ChildProp();
        }
    }
}
```
```
i.e. use the contract defined by the base class, but return a derived type. I have made a more detailed sample to make this point clearer - returning "this" again wouldn't change anything.
It is possible (but messy) to test the returned object for it's actual type (i.e. "if someObject is ChildProp"), but it is better to call a virtual method on it that does the right thing for its type.
The base class virtual method (in this case, virtual property) not only has an implementation, but also defines a contract: that a child class can supply a different implementation of SomePropertyName if it meets this contract (i.e. SomePropertyName returns an object of type "FatherProp"). Returning an object of type "ChildProp" derived from "FatherProp" meets this contract. But you can't change the contract in "Child" - this contract applies to all classes descended from "Father".
If you take a step back and look at your broader design, there are other language constructs in the C# toolkit that you may also want to think about instead - Generics, or interfaces.


q:
I'd like to limit the size of the file that can be uploaded to an application. To achieve this, I'd like to abort the upload process from the server side when the size of the file being uploaded exceeds a limit.

Is there a way to abort an upload process from the server side without waiting the HTTP request to finish?

[A]
You might try doing this in the doPost() method of your servlet
```
```
multi = new MultipartRequest(request, dirName, FILE_SIZE_LIMIT);

if(submitButton.equals(multi.getParameter("Submit")))
{
    out.println("Files:");
    Enumeration files = multi.getFileNames();
    while (files.hasMoreElements()) {
    String name = (String)files.nextElement();
    String filename = multi.getFilesystemName(name);
    String type = multi.getContentType(name);
    File f = multi.getFile(name);
    if (f.length() > FILE_SIZE_LIMIT)
    {
        //show error message or
        //return;
        return;
    }
}
```
```
This way you don't have to wait to completely process your HttpRequest and can return or show an error message back to the client side. HTH


q: Anybody knows how to do this? I got all the information of the email (body, subject, from , to, cc, bcc) and need to generate an .eml file out of it.

[A]
EML files are just plain text files. The headers are separated from the body by a blank line. Headers look like this:
```
```
From: "DR CLEMENT OKON" <drclement@nigerianspam.com>
To: "You" <you@yourdomain.com>
Subject: REQUEST FOR URGENT BUSINESS RELATIONSHIP
Date: Tue, 30 Sep 2008 09:42:47 -0400
```
```
For more info, the official spec is
RFC 2822
. It's actually not as hard to read as some RFCs.
Edit: When I said "plain text" I should have thought for a second. I really meant plain ASCII - and not the 8-bit "extended ASCII" either - just up to character 127. If you want more than seven bits, you need some kind of encoding and things get complicated.


q: I would like to send HTML email with graphic elements included. I have no idea to attach garaphics to this email.

[A]
I'm not going to bore you with a mediocre explanation here so instead let me link to this great tutorial over at Sitepoint which explained it to me in plain English! -
advanced-email-php


q:
With the best will in the world, whatever software you (and me) write will have some kind of defect in it.

What can I do, as a developer, to make things easier for the support department (first line, through to third line, and development) to diagnose, workaround and fix problems that the user encounters.

Notes

I'm expecting answers which are predominantly technical in nature, but I expect other answers to exist.

"Don't release bugs in your software" is a good answer, but I know that already.

[A]
Technical features:
In the error dialogue for a desktop app, include a clickable button that opens up and email, and attaches the stacktrace, and log, including system properties.
On an error screen in a webapp, report a timestamp including nano-seconds and error code, pid, etc so server logs can be searched.
Allow log levels to be dynamically changed at runtime. Having to restart your server to do this is a pain.
Log as much detail about the environment in which you're executing as possible (probably on startup).
Non-technical:
Provide a known issues section in your documentation. If this is a web page, then this correspond to a triaged bug list from your bug tracker.
Depending on your audience, expose some kind of interface to your issue tracking.
Again, depending on audience, provide some forum for the users to help each other.
Usability solves problems before they are a problem. Sensible, non-scary error messages often allow a user to find the solution to their own problem.
Process:
watch your logs. For a server side product, regular reviews of logs will be a good early warning sign for impending trouble. Make sure support knows when you think there is trouble ahead.
allow time to write tools for the support department. These may start off as debugging tools for devs, become a window onto the internal state of the app for support, and even become power tools for future releases.
allow some time for devs to spend with the support team; listening to customers on a support call, go out on site, etc. Make sure that the devs are not allowed to promise anything. Debrief the dev after doing this - there maybe feature ideas there.
where appropriate provide user training. An impedence mismatch can cause the user to perceive problems with the software, rather than the user's mental model of the software.


q: Which Computer-aided Software Engineering tools do you use and why? In what ways do they increase your productivity or help you design your programs? Or, in case you do not use CASE tools, what are your reasons for this?

[A]
I have used Rational Rose and a few other similar packages in the past. Mostly I have used them for the UML diagram elements and have not gone into the more detailed functionality such as code generation etc.
I mostly use them for aiding the design process and clarifying my own ideas. Often I find that, in trying to come up with a design for a componant, I end up needing to write down / draw what I want to happen so I can get a clear overview in my mind of what needs to happen and why. I have found that in a lot of cases, what I end up trying to draw is essentially the same as a predefined kind of diagram in UML, such as a Use Case Diagram etc. and by then adopting that style, it becomes easier to get my ideas on paper as I have some framework to work within.
So, I use CASE tools principally for thier UML / designing tools at a highish, semi-abstract level.


q:
In the past and with most my current projects I tend to use a for loop like this:

var elements = document.getElementsByTagName('div');
for (var i=0; i<elements.length; i++) {
    doSomething(elements[i]);
}

I've heard that using a "reverse while" loop is quicker but I have no real way to confirm this:

var elements = document.getElementsByTagName('div'),
    length = elements.length;

while(length--) {
    doSomething(elements[length]);
}

What is considered as best practice when it comes to looping though elements in JavaScript, or any array for that matter?

[A]
At the risk of getting yelled at, i would get a javascript helper library like
jquery
or
prototype
they encapsulate the logic in nice methods - both have an .each method/iterator to do it - and they both strive to make it cross-browser compatible
EDIT: This answer was posted in 2008. Today much better constructs exist. This particular case could be solved with a
```
.forEach
```
.


q:
We have a project consisting of multiple subprojects. With each subproject we potentially have some hibernate mapping files but in the end only one actual hibernate session. Those subprojects could be combined in several ways, some depend on each other. My problem is that actually I want to have a SessionFactoryBean which would be able to collect those mappings/mappinglocations from the applicationContext(s) and configure itself.

Has somebody written something like this, or do I have to do it myself (I envision something a bit like the urlresolver or viewresolver functionality from SpringMVC)?

[A]
```
LocalSessionFactoryBean
```
has a configLocations property.  You inject the list of config locations, and it will gather tham together for a single session factory configuration.


q:
Following Izb's question about Best binary XML format for JavaME, I'm looking for an implementation for either binary XML-like formats or just plain XML. My metrics for such implementation, by most important first, are:

Supported phones. A basic JTWI phone should be able to run it.

It should be either verified or open source, so I could have it verified.

Small memory footprint.

Fast.

Easy to use on server side.

[A]
The W3C defined a binary encoding for XML, it's called Fast InfoSet, but it's optimised for high-volume web services, rather than embedded devices, and I don't think there are any light and fast implementations suitable for you.
If you want to stick with plain XML, and you need a DOM implementation, then go with XOM (
http://xom.nu
). It's easily the DOM with the smallest footprint, and it's very fast.
But if you really need to reduce your footprint, then you need to use a non-DOM API like SAX or STAX, but that's considerably more work.


q:
We are using a PHP scripting for tunnelling file downloads, since we don't want to expose the absolute path of downloadable file:

header("Content-Type: $ctype");
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=\"$fileName\"");
readfile($file);

Unfortunately we noticed that downloads passed through this script can't be resumed by the end user.

Is there any way to support resumable downloads with such a PHP-based solution?

[A]
Yes. Support byteranges. See
RFC 2616 section 14.35
.
It basically means that you should read the
```
Range
```
header, and start serving the file from the specified offset.
This means that you can't use readfile(), since that serves the whole file. Instead, use
fopen()
first, then
fseek()
to the correct position, and then use
fpassthru()
to serve the file.


q:
I happened to debate with a friend during college days whether advanced mathematics is necessary for any veteran programmer. He used to argue fiercely against that. He said that programmers need only basic mathematical knowledge from high school or fresh year college math, no more no less, and that almost all of programming tasks can be achieved without even need for advanced math. He argued, however, that algorithms are fundamental & must-have asset for programmers.

My stance was that all computer science advances depended almost solely on mathematics advances, and therefore a thorough knowledge in mathematics would help programmers greatly when they're working with real-world challenging problems.

I still cannot settle on which side of the arguments is correct. Could you tell us your stance, from your own experience?

[A]
computer science != programming
OK, seriously, I know good and bad programmers who were English and Psychology majors and some that were Computer Science majors.  Some very famous guys that I admire as developers didn't have a CS background.  Larry Wall(Perl), for example, was a linguist.
On the other hand, it helps to know something about the domain you are working on because then you can at least see if your data makes sense and help your customer/users drill down to what they really want.
And yes, there's the issue of computational complexity and efficient data structures and program correctness.  That's stuff you learn in Computer Science and that's useful to know in almost any domain, but it's neither necessary nor sufficient.


q:
I want to find out, with an SQL query, whether an index is UNIQUE or not. I'm using SQLite 3.

I have tried two approaches:

SELECT * FROM sqlite_master WHERE name = 'sqlite_autoindex_user_1'

This returns information about the index ("type", "name", "tbl_name", "rootpage" and "sql"). Note that the sql column is empty when the index is automatically created by SQLite.

PRAGMA index_info(sqlite_autoindex_user_1);

This returns the columns in the index ("seqno", "cid" and "name").

Any other suggestions?

Edit: The above example is for an auto-generated index, but my question is about indexes in general. For example, I can create an index with "CREATE UNIQUE INDEX index1 ON visit (user, date)". It seems no SQL command will show if my new index is UNIQUE or not.

[A]
you can programmatically build a select statement to see if any tuples point to more than one row. If you get back three columns, foo, bar and baz, create the following query
```
```
select count(*) from t
group by foo, bar, baz
having count(*) > 1
```
```
If that returns any rows, your index is not unique, since more than one row maps to the given tuple. If sqlite3 supports derived tables (I've yet to have the need, so I don't know off-hand), you can make this even more succinct:
```
```
select count(*) from (
    select count(*) from t
    group by foo, bar, baz
    having count(*) > 1
)
```
```
This will return a single row result set, denoting the number of duplicate tuple sets. If positive, your index is not unique.


q:
I have a dictionary of 200,000 items (the keys are strings and the values are integers).

What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?

 a={ 'keyC':1, 'keyB':2, 'keyA':1 }
b = a.items()
b.sort( key=lambda a:a[0])
b.sort( key=lambda a:a[1], reverse=True )
print b
>>>[('keyB', 2), ('keyA', 1), ('keyC', 1)]

[A]
You can't sort dictionaries.  You have to sort the list of items.
Previous versions were wrong.  When you have a numeric value, it's easy to sort in reverse order.   These will do that.  But this isn't general.  This only works because the value is numeric.
```
```
a = { 'key':1, 'another':2, 'key2':1 }

b= a.items()
b.sort( key=lambda a:(-a[1],a[0]) )
print b
```
```
Here's an alternative, using an explicit function instead of a lambda and the cmp instead of the key option.
```
```
def valueKeyCmp( a, b ):
    return cmp( (-a[1], a[0]), (-b[1], b[0] ) )

b.sort( cmp= valueKeyCmp )
print b
```
```
The more general solution is actually two separate sorts
```
```
b.sort( key=lambda a:a[1], reverse=True )
b.sort( key=lambda a:a[0] )
print b
```
```


q:
How can this line in Java be translated to Ruby:

    String className = "java.util.Vector";

    ...

    Object o = Class.forName(className).newInstance();

Thanks!

[A]
```
```
Object::const_get('String').new()
```
```


q:
I have to work on an old 1.3 JVM and I'm asked to create a secure connection to another server. Unfortunately the HttpsURLConnection only appears sinc JVM 1.4.

Is there another way to create a secure connection? Is there a library that I could you to add this fonctionnality?

[A]
You need to install the Java Secure Socket Extension (JSSE), which used to be required because Sun wouldn't ship it with the JDK because of comedy export restrictions. I had a look on Sun's web site, but the JDK 1.3 instructions are preving elusive.  Bear in mind that JDK 1.3 is now end-of-lifed by Sun, so they may not have any information any more.
http://hc.apache.org/httpclient-3.x/sslguide.html


q:
I'm discovering a simple solution for singular-plural keywords searches. I heard about stemming but I don't want to use all its features, only plural/singular transformation. The language is Dutch. Have looked at http://www.snowball.tartarus.org before. Does anyone know the simple solution for singular|plural relevant searches?
Thanks in advance.

[A]
Use a dictionary, a list of stopwords (those you don't want to singularize) plus the rules for the language. If you don't know Dutch then I cannot help you, but show you how it'd be done in Spanish, for instance:
Plurals end with s, if it doesn't then it's done
If it ends with s,
check if it's a verb or conjugation ending with s if it is one, then it's done (verbs could be added to the stopwords list)
if it's not a verb, remove s
if the word exists in the dictionary, done
if it doesn't remove the previous letter, and check it in the dictionary.
if it's still not there it's an exception you'll need to check manually to code in the exceptions (I cannot right now think of any, but they always exist :)
Of course this will not translate directly to Dutch.
In general stemmers are already done and provide most of what you need, why don't you want them?


q:
I've got a XmlNodeList which I need to have it in a format that I can then re-use within a XSLT stylesheet by calling it from a C# extension method.

Can anyone help? I have read that it might have something to do with using a XPathNavigator but I'm still a bit stuck.

[A]
I had to solve this issue myself a couple of years ago. The only way I managed it was to create an XML fragment containing the nodes in the node list and then passing in the children of the fragment.
```
```
XsltArgumentList arguments = new XsltArgumentList();
XmlNodeList nodelist;
XmlDocument nodesFrament = new XmlDocument();
XmlNode root = nodesFragment.CreateElement("root");
foreach (XmlNode node in nodeList)
{
    root.AppendChild(node);
}
nodesFragment.AppendChild(root);

arguments.AddParam("argumentname", string.Empty, nodesFragment.CreateNavigator().SelectChildren(XPathNodeType.All));
```
```
Then you need to make sure you have the corresponding argument in your XSLT, of course.
Note that you probably don't need the additional XmlDocument. You could just call CreateNavigator() on the root XmlNode instance and use your existing XmlDocument for creating the element (I wrote this code some time ago and I've learned more since then - but I know the code above works, I haven't tried any alternatives).


q: I understand access modifiers at the class level and below, but why would an entire assembly be private? I assume by default, assemblies are public?

[A]
Well, in the context of assemblies, private means the assembly cannot be referenced by another application outside the directory it's contained in. Therefore, private to the application it's being used for.
As for your question about the default being public....someone correct me if I'm wrong, but there is no public. It would be shared. A shared assembly can obviously be referenced by multiple applications and must reside in the GAC. All the rules of the GAC would then apply.


q:
Background

I have a massive db for a SharePoint site collection.  It is 130GB and growing at 10gb per month.  100GB of the 130GB is in one site collection. 30GB is the version table.  There is only one site collection - this is by design.

Question

Am I able to partition a database (SharePoint) using SQL 2005s data partitioning features (creating multiple data files)?
Is it possible to partition a database that is already created?
Has anyone partitioned a SharePoint DB? Will I encounter any issues?

[A]
You would have to create a partition set and rebuild the table on that partition set.  SQL2005 can only partition on a single column, so you would have to have a column in the DB that
Behaves fairly predictably so you don't get a large skew in the amount of data in each partition
IIRC the column has to be a numeric or datetime value
In practice it's easiest if it's monotonically increasing - you can create a series of partitions (automatically or manually) and the system will fill them up as it gets to the range definitions.
A date (perhaps the date the document was entered) would be ideal.  However, you may or may not have a useful column on the large table.  M.S. tech support would be the best source of advice for this.
The partitioning
should
be transparent to the application (again, you need a column with appropriate behaviour to use as a partition key).
Unless you are lucky enough to have a partition key column that is also used as a search predicate in the most common queries you may not get much query performance benefit from the partitioning.  An example of a column that works well is a date column on a data warehouse.  However, your Sharepoint application may not make extensive use of this sort fo query.


q:
I'm using VisualSVN Server to host an SVN repo, and for some automation work, I'd like to be able to get specific versions via the http[s] layer.

I can get the HEAD version simply via an http[s] request to the server (httpd?) - but is there any ability to specify the revision, perhaps as a query-string? I can't seem to find it...

I don't want to do a checkout unless I can help it, as there are a lot of files in the specific folder, and I don't want them all - just one or two.

[A]
Subversion does not publicly document the Uris it uses internally to access that information. (And where it is documented, it is explicitly stated that this can change in future versions)
To access this information on the web you could use a web viewer (E.g.
websvn,
viewvc
).
If you want to access it from your own program you could also use a client binding like SharpSvn.
```
```
using (SvnClient client = new SvnClient())
using (FileStream fs = File.Create("c:\\temp\\file.txt"))
{
    // Perform svn cat http://svn.collab.net/svn/repos/trunk/COMMITTERS -r 23456
    //                    > file.txt

    SvnCatArgs a = new SvnCatArgs();
    a.Revision = 23456;
    client.Cat(new Uri("http://svn.collab.net/svn/repos/trunk/COMMITTERS"), a, fs);
}
```
```
[Update 2008-12-31: One of the next few versions of Subversion will start documenting public urls you can use for retrieving old versions.]


q:
Getting sporadic errors from users of a CMS; Ajax requests sometimes result in a "501 Method not implemented" response from the server. Not all the time; usually works.

Application has been stable for months. Users seem to be getting it with Firefox 3. I've seen a couple references via Google to such problems being related to having "charset=UTF-8" in the Content-type header, but these may be spurious

Has anyone seen this error or have any ideas about what the cause could be?

Thanks

Ian

[A] You may want to check the logs of the server to see what's causing the issue. For example, it might be that these requests are garbled, say, because of a flaw in the HTTP 1.1 persistent connection implementation.


q:
I'm trying to change the background color of a single subplot in a MATLAB figure.

It's clearly feasible since the UI allows it, but I cannot find the function to automate it.

I've looked into whitebg, but it changes the color scheme of the whole figure, not just the current subplot.

(I'm using MATLAB Version 6.1 by the way)

[A]
I've not used Matlab in several years, but I think it might well be the whitebg method called after the subplot declaration, similar to the way in which you would set a title.
```
```
subplot(3, 2, 4), hist(rand(50)), whitebg('y');
```
```


q: How do I use the ofstream to write text to the end of a file without erasing its content inside?

[A]
You can pass the flag
```
ios::app
```
when opening the file:
```
```
ofstream ofs("filename", ios::app);
```
```


q: Which Ajax framework/toolkit can you recommend for building the GUI of web applications that are using struts?

[A]
Struts already come with
Dojo
framework. You can set your application theme to ajax and you will be able to use it.
Give a look at struts.ui.theme property at struts.properties file!
A good article for you to read is
this one at  JavaWorld


q:
I want to use VBScript to catch errors and log them (ie on error "log something") then resume the next line of the script.

For example,

On Error Resume Next
'Do Step 1
'Do Step 2
'Do Step 3

When an error occurs on step 1, I want it to log that error (or perform other custom functions with it) then resume at step 2. Is this possible? and how can I implement it?

EDIT: Can I do something like this?

On Error Resume myErrCatch
'Do step 1
'Do step 2
'Do step 3

myErrCatch:
'log error
Resume Next

[A]
VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.
```
```
On Error Resume Next

DoStep1

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStep1: " & Err.Description
  Err.Clear
End If

DoStep2

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStop2:" & Err.Description
  Err.Clear
End If

'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0
```
```
The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.


q:
For a university project I programmed a Internet Explorer Browser Helper Object to process  web document information while browsing. It were running successful on Windows XP with IE6 and IE7.

Now I have the issue that under Windows Vista the same BHO needs administrator rights to run. Browser and BHO running if you start the IE as administrator but if you start as normal user it crashes.

The BHO is of course registered on the system and activated in the browser.

What can I do that a user with non-admin rights can run the registered and activated BHO? Or is maybe something else the reason and I totally miss it?

Thank you very much for your help!

[A]
Not sure if your problem is related to custom actions in your installer but the following two links should help you.
Building a BHO with the UAC in mind -
http://simonguest.com/blogs/smguest/archive/2006/11/19/Building-Browser-Helper-Objects-using-Managed-Code.aspx
(a little over half way down)
Using the NoImpersonate script -
http://blogs.msdn.com/astebner/archive/2007/05/28/2958062.aspx


q:
I have a program which needs to behave slightly differently on Tiger than on Leopard. Does anybody know of a system call which will allow me to accurately determine which version of Mac OS X I am running. I have found a number of macro definitions to determine the OS of the build machine, but nothing really good to determine the OS of the running machine.

Thanks,
Joe

[A]
In terminal:
```
```
system_profiler SPSoftwareDataType
```
```
Gives:
```
```
Software:

    System Software Overview:

      System Version: Mac OS X 10.5.5 (9F33)
      Kernel Version: Darwin 9.5.0
      Boot Volume: Main
      Boot Mode: Normal
      Computer Name: phoenix
      User Name: Douglas F Shearer (dougal)
      Time since boot: 2 days 16:55
```
```
Or:
```
```
sw_vers
```
```
Gives:
```
```
ProductName:    Mac OS X
ProductVersion: 10.5.5
BuildVersion:   9F33
```
```


q:
I'm trying to format a column in a <table/> using a <col/> element. I can set background-color, width, etc., but can't set the font-weight. Why doesn't it work?

<table>
    <col style="font-weight:bold; background-color:#CCC;">
    <col>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>3</td>
        <td>4</td>
    </tr>
</table>

[A]
A
```
col
```
tag must be inside of a
```
colgroup
```
tag, This may be something to do with the problem.


q:
I am looking for a way in LINQ to match the follow SQL Query.

Select max(uid) as uid, Serial_Number from Table Group BY Serial_Number

Really looking for some help on this one.  The above query gets the max uid of each Serial Number because of the Group By Syntax.

[A]
```
```
using (DataContext dc = new DataContext())
        {
            var q = from t in dc.TableTests
                    group t by t.SerialNumber
                        into g
                        select new
                        {
                            SerialNumber = g.Key,
                            uid = (from t2 in g select t2.uid).Max()
                        };
        }
```
```


q:
This is sort of SQL newbie question, I think, but here goes.

I have a SQL Query (SQL Server 2005) that I've put together based on an example user-defined function:

SELECT
    CASEID,
    GetNoteText(CASEID)
FROM
(
    SELECT
        CASEID
    FROM
        ATTACHMENTS
    GROUP BY
        CASEID
) i
GO

the UDF works great (it concatenates data from multiple rows in a related table, if that matters at all) but I'm confused about the "i" after the FROM clause.  The query works fine with the i but fails without it.  What is the significance of the "i"?

EDIT: As Joel noted below, it's not a keyword

[A]
When you use a subquery in the FROM clause, you need to give the query a name.  Since the name doesn't really matter to you, something simple like 'i' or 'a' is often chosen.  But you could put any name there you wanted- there's no significance to 'i' all by itself, and it's certainly not a keyword.
If you have a really complex query, you may need to join your sub query with other queries or tables. In that case the name becomes more important and you should choose something more meaningful.


q:
What is the benefit of using the servletContext as opposed the request in order to obtain a requestDispatcher?

servletContext.getRequestDispatcher(dispatchPath)

and using

argRequest.getRequestDispatcher(dispatchPath)

[A]
It's there in the javadocs in black and white
http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getRequestDispatcher(java.lang.String)
The difference between this method and
  ServletContext.getRequestDispatcher(java.lang.String)
  is that this method can take a
  relative path.


q:
I am looking to replace the life cycle tools currently used by my development teams.
Tools that I'm looking for:

Version Control

Defect/Issue Tracking

Requirements Tracking

Test Case Management

(potentially) Project Management: Project Status, hours entry

I have a new beefy server (Windows 2008 Server) to run all tools on.  I'm looking at COTS and Open Source options, but haven't decided so far.

Other factors:

Distributed team (different physical sites)

Some Windows Development, some Linux Development

Software, Firmware, Technical Writing need to be able to use it

Recommendations on a good suite that will work together?

If Open Source, best approach to run on the Windows 2008 Server?

[A]
Svn/Trac plus a few plugins will probably get you most of the way there for free.
If you use the version supplied by visualsvn (they bundle both trac and subversion) its a nice easy setup too.
http://www.visualsvn.com/server/
http://trac.edgewall.org/
http://trac-hacks.org/


q: I'm having a test hang in our rails app can't figure out which one (since it hangs and doesn't get to the failure report).  I found this blog post http://bmorearty.wordpress.com/2008/06/18/find-tests-more-easily-in-your-testlog/ which adds a setup hook to print the test name but when I try to do the same thing it gives me an error saying wrong number of arguments for setup (1 for 0).  Any help at all would be appreciated.

[A]
What test framework are you using?  Test/Unit?
I would take a look at RSpec which would provide a little more context for your tests.  You can also get a nice HTML report that looks like this:
RSpec Result http://myskitch.com/robbyrussell/rspec_results-20070801-233809.jpg
Had you had any failing tests, the specific test would be red and it would expand to the specific lines where the test failed to provide you more visibility on why the test failed and where you should look to address the issue.


q: Can ZK easily be integrated in a struts web application?

[A]
maybe you can find it interesting:
http://www.zkoss.org/smalltalks/zk-sample/zk-sample.html
moreover, you can browse a bit the zk forum you can find on
http://www.zkoss.org/
itself, it is more than easy to find some discussion about that.
hope it can help
luca


q:
The subject says it all, almost. How do I automatically fix jsp pages so that relative URLs are mapped to the context path instead of the server root? That is, given for example

<link rel="stylesheet" type="text/css" href="/css/style.css" />

how do I set-up things in a way that maps the css to my-server/my-context/css/style.css instead of my-server/css/style.css? Is there an automatic way of doing that, other than changing all lines like the above to

<link rel="stylesheet" type="text/css"
      href="<%= request.getContextPath() %>/css/style.css" />

[A]
Look into the
```
<BASE HREF="">
```
tag. This is an HTML tag which will mean all links on the page should start with your base URL.
For example, if you specified
```
<BASE HREF="http://www.example.com/prefix">
```
and then had
```
<a href="/link/1.html">
```
then the link should actually take you to /prefix/link/1.html. This should also work on
```
<LINK>
```
(stylesheet) tags.


q:
I've got a situation where I need to use LINQ's ExecuteCommand method to run an insert.

Something like (simplified for purposes of this question):

object[] oParams = { Guid.NewGuid(), rec.WebMethodID };

TransLogDataContext.ExecuteCommand (
"INSERT INTO dbo.Transaction_Log (ID, WebMethodID) VALUES ({0}, {1})",
oParams);

The question is if this is SQL injection proof in the same way parameterized queries are?

[A]
Did some research, and I found this:
In my simple testing, it looks like
  the parameters passed in the
  ExecuteQuery and ExecuteCommand
  methods are automatically SQL encoded
  based on the value being supplied.  So
  if you pass in a string with a '
  character, it will automatically SQL
  escape it to ''.  I believe a similar
  policy is used for other data types
  like DateTimes, Decimals, etc.
http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx
(You have scroll way down to find it)
This seems a little odd to me - most other .Net tools know better than to "SQL escape" anything; they use real query parameters instead.


q:
I was able to implement a thread-safe Dictionary in C# by deriving from IDictionary and defining a private SyncRoot object:

public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue>
{
    private readonly object syncRoot = new object();
    private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>();

    public object SyncRoot
    {
        get { return syncRoot; }
    }

    public void Add(TKey key, TValue value)
    {
        lock (syncRoot)
        {
            d.Add(key, value);
        }
    }

    // more IDictionary members...
}

I then lock on this SyncRoot object throughout my consumers (multiple threads):

Example:

lock (m_MySharedDictionary.SyncRoot)
{
    m_MySharedDictionary.Add(...);
}

I was able to make it work, but this resulted in some ugly code.  My question is, is there a better, more elegant way of implementing a thread-safe Dictionary?

[A]
You don't need to lock the SyncRoot property in your consumer objects.  The lock you have within the methods of the dictionary is sufficient.
To Elaborate:
What ends up happening is that your dictionary is locked for a longer period of time than is necessary.
What happens in your case is the following:
Say thread A acquires the lock on SyncRoot
before
the call to m_mySharedDictionary.Add.  Thread B then attempts to acquire the lock but is blocked.  In fact, all other threads are blocked.  Thread A is allowed to call into the Add method.  At the lock statement within the Add method, thread A is allowed to obtain the lock again because it already owns it.  Upon exiting the lock context within the method and then outside the method, thread A has released all locks allowing other threads to continue.
You can simply allow any consumer to call into the Add method as the lock statement within your SharedDictionary class Add method will have the same effect.  At this point in time, you have redundant locking.  You would only lock on SyncRoot outside of one of the dictionary methods if you had to perform two operations on the dictionary object that needed to be guaranteed to occur consecutively.


q:
Given an array of type Element[]:

Element[] array = {new Element(1), new Element(2), new Element(3)};

How do I convert this array into an object of type ArrayList<Element>?

ArrayList<Element> arrayList = ???;

[A]
```
```
new ArrayList<>(Arrays.asList(array));
```
```


q:
In low latency trading applications we are very conscious of latency issues.  There is some concern that our application may experience increased latency if the server on which it is running changes PowerNow state.

Any kernel developers familiar with calling PowerNow changes and how much processor time is used for the operation and what the latency/delay characteristics are like?

The same information for Intel SpeedStep would be useful but PowerNow is what we actually use.

Thanks!

[A]
I doubt it has any latency. PowerNow just lowers core frequency and core voltage. I don't know that it will halt the CPU for a short time to do so and then resume processing after the change. AFAIK the change happens on the fly, the processing is not interrupted for that.
Thus the bigger problem might be that you rely on a certain speed (e.g. you assume the processor can perform that many operations a second), however when the core frequency is lowered, it will behave like a slower CPU (less operations per second) and the core frequency doesn't jump to max just because the CPU is not 100% idle. It will jump up again, when the CPU thinks it needs more processing power than it currently has.
On Linux PowerNow can cause bad issues if you run VMWare with Windows on it. Windows fails to correctly update the internal clock, as it seems to not detect that PowerNow is in effect (I guess because it runs within a virtual machine) and VMWare for Linux fails to handle the situation correctly as well. So the Windows clock will fall behind as soon as PowerNow is active and every now and then VMWare detects that and corrects the clock again. So far so well, but applications relying on the Windows clock will see this strange jump and behave rather oddly (e.g. a radio streaming software I know will jump within the MP3 stream and skip a couple of milliseconds every time the clock is resynced).
If your application depends strongly on a steady program flow, you may like to disable the PowerNow feature completely. With the Internet radio stream software, that was the only way to solve the skipping issue.


q: How do I use the UNIX command find to search for files created on a specific date?

[A]
You could do this:
```
```
find ./ -type f -ls |grep '10 Sep'
```
```
Example:
```
```
[root@pbx etc]# find /var/ -type f -ls | grep "Dec 24"
791235    4 -rw-r--r--   1 root     root           29 Dec 24 03:24 /var/lib/prelink/full
798227  288 -rw-r--r--   1 root     root       292323 Dec 24 23:53 /var/log/sa/sar24
797244  320 -rw-r--r--   1 root     root       321300 Dec 24 23:50 /var/log/sa/sa24
```
```


q:
I have a hidden DIV which contains a toolbar-like menu.

I have a number of DIVs which are enabled to show the menu DIV when the mouse hovers over them.

Is there a built-in function which will move the menu DIV to the top right of the active (mouse hover) DIV? I'm looking for something like $(menu).position("topright", targetEl);

[A]
tl;dr:
(try it
here
)
If you have the following HTML:
```
```

Menu item

Hover over me to show the menu here

```
```
then you can use the following JavaScript code:
```
```
$(".parent").mouseover(function() {
    // .position() uses position relative to the offset parent,
    var pos = $(this).position();

    // .outerWidth() takes into account border and padding.
    var width = $(this).outerWidth();

    //show the menu directly over the placeholder
    $("#menu").css({
        position: "absolute",
        top: pos.top + "px",
        left: (pos.left + width) + "px"
    }).show();
});
```
```
But it doesn't work!
This will work as long as the menu and the placeholder have the same offset parent. If they don't, and you don't have nested CSS rules that care where in the DOM the
```
#menu
```
element is, use:
```
```
$(this).append($("#menu"));
```
```
just before the line that positions the
```
#menu
```
element.
But it still doesn't work!
You might have some weird layout that doesn't work with this approach. In that case, just use
jQuery.ui's position plugin
(as mentioned in an
answer
below), which handles every conceivable eventuality. Note that you'll have to
```
show()
```
the menu element before calling
```
position({...})
```
; the plugin can't position hidden elements.
Update notes 3 years later in 2012:
(The original solution is archived
here
for posterity)
So, it turns out that the original method I had here was far from ideal. In particular, it would fail if:
the menu's offset parent is not the placeholder's offset parent
the placeholder has a border/padding
Luckily, jQuery introduced methods (
```
position()
```
and
```
outerWidth()
```
) way back in 1.2.6 that make finding the right values in the latter case here a lot easier. For the former case,
```
append
```
ing the menu element to the placeholder works (but will break CSS rules based on nesting).


q: I've got a couple DNN portals I manage and I need a solution to keep them "alive" during slack traffic times.  After a given time of inactivity IIS will unload the DNN application from memory which will effect load time for the first client request.  DNN has the "KeepAlive.aspx" file that I hit with a wget command from a CRON job every 5 minutes.  I'm dubious of the effectiveness of the this method.  Does anyone have any others ideas?

[A] In the Global application start event, you could set up a cache item or timer with a timeout of 5 minutes, and in the callback code, ping a simple page that should return HTTP 200 - reset the cache/timer, and repeat.


q: They both seem to fulfill the same purpose. When would I chose one over the other?

[A]
Use the events when you've got a thread that is waiting on one of or all of a number of events to do something.
Use the monitor if you want to restrict access to a data structure by limiting how many threads can access it.
Monitors usually protect a resource, whereas events tell you something's happening, like the application shutting down.
Also, events can be named (see the OpenExisting method), this allows them to be used for synchronization across different processes.


q:
Is there a way to validate on the client side browser whether the size of a file being uploaded from a JSP page is over a set size limit without forcing the user to upload the entire file only to find out it was too large?

I would like to stay away from any proprietary controls or techniques like Flash or ActiveX if possible.

Thanks!

[A]
This isn't a perfect solution, but if you check the Content-Length HTTP header with
```
request.getHeader("Content-Length")
```
then you can choose to not transfer the entire file.
By way of explanation, an extremely large file will not be transferred all at once.  You'd have to actually open a stream representing that chunk of POST data and read from it for the entire thing to be transfered.
On the other hand, if you're worried about denial-of-service attacks, then you can't really trust the Content-Length header, because it can easily be forged.  In this case, you should set a limit and stream a transfer of this file, stopping as soon as you've exceeded that limit.


q:
I have a .NET TCP Client that sends high volumes of messages to a (.NET async) TCP server.

I need to keep sending messages to the server but I run out of ports on the client due to TIME_WAIT.

How can a program continually and reliably send messages without using all of the available ports?

Is there a method to keep reusing the same socket.  I have looked at Disconnect() and the REUSEADDRESS socket flag but cannot find any good examples of their use.  In fact most sources say not to use Disconnect as it is for lower level use (i.e. it only recycles the socket handle).

I'm thinking that I need to switch to UDP or perhaps there is a method using C++ and IOCP?

[A]
Can your client just keep the same socket open and send messages in a loop?
```
```
open socket connection

while(running)
    send messages over socket

close socket connection
```
```


q: We could also include IFrames as well.

[A]
With standard frames/frameset:
Bookmarking can be difficult to accomplish.
The Back button can be broken.
Arrival from search engines could be into an inner frame.
Printing won't work the same across browsers.
Scrollbars could be in non-standard/unexpected places.
More here.


q:
This page mentions how to trunc a timestamp to minutes/hours/etc. in Oracle.

How would you trunc a timestamp to seconds in the same manner?

[A]
Since the precision of
```
DATE
```
is to the second (and no fractions of seconds), there is no need to
```
TRUNC
```
at all.
The data type
```
TIMESTAMP
```
allows for fractions of seconds.  If you convert it to a
```
DATE
```
the fractional seconds will be removed - e.g.
```
```
select cast(systimestamp as date)
  from dual;
```
```


q:
After following the instructions in INSTALL.W64 I have two problems:

The code is still written to the "out32" folder. I need to be able to link to both 32-bit and 64-bit versions of the library on my workstation, so I don't want the 64-bit versions to clobber the 32-bit libs.

The output is still 32-bit! This means that I get "unresolved external symbol" errors when trying to link to the libraries from an x64 app.

[A]
To compile the static libraries (both release and debug), this is what you need to do:
Install Perl -
www.activestate.com
Run the "Visual Studio 2008 x64 Cross Tools Command Prompt" (Note: The regular command prompt WILL NOT WORK.)
Configure with
perl Configure VC-WIN64A no-shared no-idea
Run: ms\do_win64a
EDIT ms\nt.mak and change "32" to "64" in the output dirs:
```
# The output directory for everything intersting
    OUT_D=out64.dbg
    # The output directory for all the temporary muck
    TMP_D=tmp64.dbg
    # The output directory for the header files
    INC_D=inc64
    INCO_D=inc64\openssl
```
EDIT ms\nt.mak and remove bufferoverflowu.lib from EX_LIBS if you get an error about it.
Run: nmake -f ms\nt.mak
EDIT the ms\do_win64a file and ADD "debug" to all lines, except the "ml64" and the last two lines
Run: ms\do_win64a
Repeat steps 4 and 5
EDIT the ms\nt.mak file and ADD /Zi to the CFLAG list!
Run: nmake -f ms\nt.mak


q:
What I want to do is to remove all accents and umlauts from a string, turning "lärm" into "larm" or "andré" into "andre". What I tried to do was to utf8_decode the string and then use strtr on it, but since my source file is saved as UTF-8 file, I can't enter the ISO-8859-15 characters for all umlauts - the editor inserts the UTF-8 characters.

Obviously a solution for this would be to have an include that's an ISO-8859-15 file, but there must be a better way than to have another required include?

echo strtr(utf8_decode($input),
           'ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ',
           'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy');

UPDATE: Maybe I was a bit inaccurate with what I try to do: I do not actually want to remove the umlauts, but to replace them with their closest "one character ASCII" equivalent.

[A]
Okay, found an obvious solution myself, but it's not the best concerning performance...
```
```
echo strtr(utf8_decode($input),
           utf8_decode('ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ'),
           'SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy');
```
```


q:
I have a basic model in which i have specified some of the fields to validate the presence of. in the create action in the controller i do the standard:

@obj = SomeObject.new(params[:some_obj])

if @obj.save
  flash[:notice] = "ok"
  redirect...
else
  flash[:error] = @obj.errors.full_messages.collect { |msg| msg + "<br/>" }
  redirect to new form
end

however when i redirect to the new form, the errors show, but the fields are empty. is there a way to repopulate the fields with the entered values so the errors can be corrected easily?

[A]
You
```
render :action => :new
```
rather than redirecting.


q:
I am starting a project for which we will have a thin client, sending requests and getting responses from a server.

We are still in the planning stages, so we have a choice to settle on either an Eclipse based GUI (Eclipse plugin) or using GWT as a fromtend for the application.

I am not very familiar with Eclipse as a GUI (Nor with GWT) but do know 'normal' Java.

What would be the main benefits and drawbacks of either approach?

Edit: Addressing the questions posed:

The project, if Eclipse based, would be using the core Eclipse gui (No coding tools, just bare bones) and the GUI would be packaged with it.

I have been looking at GWT and so far seems the best choice, but still have some research to do.

Communication method is a variant of CORBA (In house libraries)


q:
I need to remove temp files on Tomcat startup, the pass to a folder which contains temp files is in applicationContext.xml.

Is there a way to run a method/class only on Tomcat startup?

[A]
You could write a
```
ServletContextListener
```
which calls your method from the
```
contextInitialized()
```
method. You attach the listener to your webapp in web.xml, e.g.
```
```
<listener>
   <listener-class>my.Listener</listener-class>
</listener>
```
```
and
```
```
package my;

public class Listener implements javax.servlet.ServletContextListener {

   public void contextInitialized(ServletContext context) {
      MyOtherClass.callMe();
   }
}
```
```
Strictly speaking, this is only run once on webapp startup, rather than Tomcat startup, but that may amount to the same thing.


q: Is there a way to turn this 'feature' off?

[A]
Awesome, I just found it:
```
Tools -> Options -> Sql Server Object Explorer -> General Scripting Options
```
```
Script USE <database> -> False
```


q:
I've got a request from a customer to automatically detect the type of mobile device (not the browser, the type. ex: Moto Q, Blackjack II, etc.) and automatically select the device from a drop down with a list of supported devices.

So far I've found that the HTTP Headers (submitted by mobile IE) contain information such as

Resolution

UA-CPU (i've seen ARM from WM 2003 and x86 from WM5)

User Agent (which basically just says Windows CE)

The only thing I can think of right now is possibly using a combination of the resolution/cpu and making a "best guess"

Any thoughts?

[A]
What exactly does the customer mean by "supported". Surely it means that the phone in question supports the web application and it's inner functionality - wouldn't it be better then to forget device detection and simply focus on detecting those capabilities required for the app to function properly? For example, if my mobile website requires Ajax to work then instead of listing all the devices which are said to "support Ajax" I could do some simple object detection to find out for myself.
Device detection, just like browser detection is unreliable. Yes, it's possible but I wouldn't recomend it... on a project I've done we used the User Agent string to detect various devices. The indexOf javaScript method came in handy! :)


q:
Our company uses Citrix to remote into a terminal server for remote users to launch smart client apps within a virtual window on their machine.

The problem is that smartclient apps are being downloaded each time the user launches them eventhough the version on the remote citrix server has not change.  This is due to the user's profile being purged each time they close their Citrix session.

Is there any way to avoid this and still continue to purge the user's profile?  Not purging the profile leads to wasted space on the citrix servers and corrupt profile issues.

[A]
I can't speak to details on Citrix servers.  However, with ClickOnce you have no say over where an application is installed.  It's installed under the user profile, no ifs, ands, or buts.  One of the major goals with ClickOnce was improved security and installing apps to the profile makes that easier.   So, if you're clearing the profile, you're stuck.
However, couldn't you just deploy the app to the Citrix server without ClickOnce?  Most .Net apps can just be xcopy deployed, so it seems it would be pretty easy to write a few batch files to copy the latest deployment to your Citrix server and skip ClickOnce all together.


q:
I'm currently designing a brand new database. In school, we always learned to put a primary key in each table.

I read a lot of articles/discussions/newsgroups posts saying that it's better to use unique constraint (aka unique index for some db) instead of PK.

What's your point of view?

[A]
Can you provide references to these articles?
I see no reason to change the tried and true methods.  After all, Primary Keys are a fundamental design feature of relational databases.
Using UNIQUE to serve the same purpose sounds really hackish to me.  What is their rationale?
Edit: My attention just got drawn back to this old answer.  Perhaps the discussion that you read regarding PK vs. UNIQUE dealt with people making something a PK for the sole purpose of enforcing uniqueness on it.  The answer to this is, If it IS a key, then make it key, otherwise make it UNIQUE.


q:
I want to separate concerns here. Create and embed all the UI logic for the Custom XML designer, object model, validations etc in to a separate assembly. Then the Package framework should only register the designer information and ask for a UI Service and everything works magically.

This way I don't need to play with the Package framework (Visual Studio Package) assembly, when I need to modify the UI designer.

This question also applies to anything where you have to separate the UI logic from the Skeleton framework that loads it up, like a plugin.

I have several choices a ServiceProvider model, a plugin model or may be other.

Any samples, suggestions for patterns, links are welcome.

Update 1: What I am looking for is a thought such as - "Does Prism (Composite WPF) fit the bill? Has anyone worked on a project/application which does the separation of concerns just like I mentioned above? etc"
(I am still looking out for answers)

[A]
What you're asking about seams very much like the separation of concerns that the
MVC
pattern tries to enforce.
ASP.NET MVC
is already out there with a
preview 5
.
It's mainly for web but I think they are planning on using it also for WinForms, but I'm not sure.


q:
So I have a daemon running on a Linux system, and I want to have a record of its activities: a log. The question is, what is the "best" way to accomplish this?

My first idea is to simply open a file and write to it.

FILE* log = fopen("logfile.log", "w");
/* daemon works...needs to write to log */
fprintf(log, "foo%s\n", (char*)bar);
/* ...all done, close the file */
fclose(log);

Is there anything inherently wrong with logging this way? Is there a better way, such as some framework built into Linux?

[A]
Unix has had for a long while a special logging framework called
syslog
. Type in your shell
```
```
man 3 syslog
```
```
and you'll get the help for the C interface to it.
Some
examples
```
```
#include <stdio.h>
#include <unistd.h>
#include <syslog.h>

int main(void) {

 openlog("slog", LOG_PID|LOG_CONS, LOG_USER);
 syslog(LOG_INFO, "A different kind of Hello world ... ");
 closelog();

 return 0;
}
```
```


q: Supposedly, it is possible to get this from Google Maps or some such service. (US addresses only is not good enough.)

[A]
The term you're looking for is geocoding and yes Google does provide this service.
New V3 API
:
http://code.google.com/apis/maps/documentation/geocoding/
Old V2 API:
http://code.google.com/apis/maps/documentation/services.html#Geocoding


q:
This question is based on another question of mine(thankfully answered).

So if in a model I have this:

def self.find_extended
    person = Person.find(:first)
    complete_name = person.firstname + ', ' + person.lastname
    return person
end

How can I inject complete name in the person object so in my controller/view I can access it by person.complete_name?

Thank you for your time,

Silviu

[A]
You could define:
```
```
attr_accessor :complete_name
```
```
in the person model and then just do
```
person.complete_name= person.firstname + ', ' + person.lastname
```


q: How do I perform a network login, to access a shared driver for instance, programmatically in c#? The same can be achieved by either attempting to open a share through the explorer, or by the net use shell command.

[A]
You'll need to use Windows Identity Impersonation, take a look at these links
http://blogs.msdn.com/shawnfa/archive/2005/03/21/400088.aspx
http://blogs.msdn.com/saurabhkv/archive/2008/05/29/windowsidentity-impersonation-using-c-code.aspx


q:
I have some formulas in my reports, and to prevent divsion by zero I do like this in the expression field:

=IIF(Fields!F1.Value <> 0, Fields!F2.Value/Fields!F1.Value, 0)

This normally works fine, but when both F1 and F2 are zero, I get "#Error" in the report, and I get this warning: "The Value expression for the textbox ‘textbox196’ contains an error: Attempted to divide by zero."

Why is that?

[A]
IIF() is just a function, and like with any function
all
the arguments  are evaluated
before
the function is called, including
```
Fields!F2.Value/Fields!F1.Value
```
.  In other words, it will attempt to divide by zero in spite of the
```
Fields!F1.Value <> 0
```
condition.


q:
I have a working LINQ to SQL model.  I want to be able to use the same model but with a connection to a DataSet object, instead of SQL Server.

I need to be able to query the model, modify fields, as well as do insert and delete operations.  Is there an easy way to accomplish this?

I noticed another question mentions a similar scenario, but I'm not sure if this applies to my question.

[A]
You can use
LINQ to DataSet
directly but the LINQ to SQL query translator converts expression trees into SQL statements and that can't be changed.
For lists of inserts/updates/deletes for a given DataContext, you can call
```
DataContext.GetChangeSet()
```