q:
This might of been asked elsewhere (seems like a useful topic) but searches turned up nothing.

One feature I love in Eclipse when programming Java is that I don't have to worry about putting in the import statements and any missed functions from interfaces that I am implementing them - if I do miss them a simple click from a list implements them for me.

Now I am working in VisualStudio2008 with C# I am really missing that functionality. I was wondering if the functionality is in there, but buried or can be purchased through a 3rd party?

Thanks.

[A] you have to pay for this feature. Look at Resharper 4.0 from JetBrains. It is a perfect solution for me.


q: Since the speed of the top Javascript engines seems to be on par, the next criteria is footprint.  What are the code and data footprints of the leading javascript engines?

[A]
squirrelfish should have the smallest footprint ( i remember i read somewhere that it uses a really simple translation table from JS code to native code), but if you want something very small you should look at earlier js engines (that dont use native code tables) as they interpret code as they go, and dont compile the whole thing according to the current machine.
I dont see the point of comparing js engines though as they are basically single-threaded(well new engines are multithreaded but this is from the new "highly-optimized" engines) and they are only loaded once, and then interpret megabytes of JS code... The speed is more important than size..even for mobile devices, because i dont expect a JS engine to use more than 1-2Mb of memory(even that is waaay too much in my opinion..) but the sum of JS scripts in a JS based page can easily pass that.

s: huggingface

c: devops

d: intermediate


q:
I have a method to return a group of objects as a generic list which I then bind to a Repeater. I want to implement paging on the repeater using the PagedDataSource class but I'm not sure that this is possible as it doesn't seem to work.

Will I have to change the return type of my method or is it possible to bind the PagedDataSource to the generic list?

[A]
I've just modified some of my code to use a generic list and seems to have worked fine, hope this helps:
Note that this entire method can be called with or without a page number to automatically set the page, it also builds a paging control inside of a panel calling PagingPanel.
The line that sets the DataSource on the PagedDataSource instance (dataSource) did take an array of NewsItems (searchResults), I've updated it to consume a List that's created using the NewItem array.
```
```
void PopulateNewsItems (int? pageNo)
{
    var model = ModelFactory.GetNewsModel ();
    var searchResults = model.GetNewsItems ();

    var dataSource = new PagedDataSource ();

    // CHANGED THE ARRAY OF NEWSITEMS INTO A GENERIC LIST OF NEWSITEMS.
    dataSource.DataSource = new List<NewsItem> (searchResults);
    dataSource.AllowPaging = true;

    var pageSizeFromConfig = ConfigurationManager.AppSettings["NewsItemsPageCount"];
    var pageSize = 10;

    int.TryParse (pageSizeFromConfig, out pageSize);

    dataSource.PageSize = pageSize;
    dataSource.CurrentPageIndex = pageNo ?? 0;

    PagingPanel.Controls.Clear ();
    for (var i = 0; i < dataSource.PageCount; i++)
    {
        var linkButton = new LinkButton ();
        linkButton.CommandArgument = i.ToString ();
        linkButton.CommandName = "PageNo";
        linkButton.Command += NavigationCommand;
        linkButton.ID = string.Format ("PageNo{0}LinkButton", i);
        if (pageNo == i || (pageNo == null && i == 0))
        {
            linkButton.Enabled = false;
            linkButton.CssClass = "SelectedPageLink";
        }

        linkButton.Text = (i + 1).ToString ();

        PagingPanel.Controls.Add (linkButton);
        if (i < (dataSource.PageCount - 1))
            PagingPanel.Controls.Add (new LiteralControl ("|"));
    }

    NewsRepeater.DataSource = dataSource;
    NewsRepeater.DataBind ();
}

void NavigationCommand (object sender, CommandEventArgs e)
{
    PopulateNewsItems (int.Parse ((string)e.CommandArgument));
}
```
```


q:
...or am I stuck rolling my own "XML chopping" functions. I'd like to create a small tasktray app so I can quickly re-point a Virual Directory to one of several of folders on my harddisk.

Bit of background:

I have 3 different svn branches of our code base on my dev machine.

Current Production Branch    ( C:\Projects\....\branches\Prod\ )
Next Release Canidate Branch ( C:\Projects\....\branches\RCX\ )
Trunk                        ( C:\Projects\....\trunk\ )

Our app integrates with a 3rd party CMS which I've installed at

http://localhost/cms/

In order to work our app has to live at the same root directory. so:

http://localhost/app/

Depending on the branch I'm working on, I'm re-pointing the /app/ directory to one of the 3 paths listed above by going into IIS Manager. Just thought it'd be handy to have a quick-app to do it for me.

[A]
I haven't used this my self, so I'm not 100% sure it will solve your problem. But take a look at System.DirectoryServices in .NET. It can access IIS.
MSDN help for DirectoryServices


q:
I want to create a compiled JavaScript file for my website.  For development I would prefer to keep the JavaScript in separate files and just as part of my automated scripts  concatenate the files into one and run the compressor over it.

My problem is that if I use the old DOS copy command it also puts in the EOF markers which the compressor complains about:

copy /A *.js compiled.js /Y

What are other people doing?

[A]
To copy without EOF use binary mode:
```
```
copy /B *.js compiled.js /Y
```
```
If the resulting file still has EOFs, that might have come from one of original files,
it can be fixed by this variant:
```
```
copy /A *.js compiled.js /B /Y
```
```
/A removes trailing EOFs from original files if any and /B prevents appending EOF to the resulting file. If an EOF is not at the end, the source file will be truncated at it. The order of switches is important. If you write
```
```
copy /A *.js /B compiled.js /Y
```
```
- EOFs in source files won't be removed but still resulting EOF won't be appended.
Try it yourself, thats where I get it. DOS commands are weird.


q:
I have a relatively powerful dev workstation - 8 cores and 3 Gig of Ram. However, Visual Studio 2008 does not seem to take full advantage, especially during large builds.
Are there any tweaks to be performed on XP VM settings etc to increase performance? I remember back in the bad old days that out of the box windows does not take best advantage of machines with lots of memory, is this still the case?

PS assume I can make no hardware changes

[A]
The biggest issue I usually have when working in large projects aren't cpu or memory, but the hard drive. Get several HD's on different channels (or use SCSI for best performance) and put the output files, intermediate files, temp folder on 3 different HD's. That should make a big difference.
I know you said no hardware changes, but since you didn't write what type of HD setup you had, I just wanted to mention this.
VS will not be able to use all your 8 cpu's efficiently unless you have a really fast HD setup.


q:
A lot of files will be stored in the DB and I need file hashes to unique identify that the file was not changed.
(In general, will be used as the Windows Personal Firewall part)

[A]
This is, of course, not possible in general. Many people still use hashing for this purpose, and
MD5
is a popular algorithm, that gives you a 128-bit "signature" for the file with a high probability of changing when the contents of the file changes.
In the general case, you need to look at every bit of the file to include it in the hash, and performance will probably be I/O-limited. It's a sequential sweep over all data in the file, updating the state of whatever hash algorithm you use for each new byte. On a modern CPU, the latter will be quicker than the former.
This rather old analysis
shows around ~45 MB/s on a Pentium 90 MHz CPU.


q:
I'm trying to load javascript code with a user web control into a page via a the Page.LoadControl method during an asyncron post back of an update panel.

I've tried the specially for that scenario designed methods of the scriptmanager, but the javascript just doens't get returned to the user.

To explain my scenario a bit better:

Master Page has the script manager and one page loads the user control via Page.LoadControl-method during an async post back. The custom control injects in the pre-render event handler the javascript. Is that a matter of timing to inject the js or is it just not possible to do so?

[A]
Have your tried
```
```
Page.ClientScript.RegisterStartUpScript(GetType(Page), "key", <your script here>, addSctiptTags:=true)
```
```
We do this in our User Controls and it works for us
HTH


q:
Here is new C# future in version 4.0 known as dynamic. Show me the way i can use it in my code and how this future can help me?

Related questions:

Does the new ‘dynamic’ C# 4.0 keyword deprecate the ‘var’ keyword ?

What do you think of the new C# 4.0 ‘dynamic’ keyword?

[A]
One of the usages is interop between static and dynamic languages.
Say you want to invoke a JavaScript function fron silverlight:
```
```
HtmlPage.Window.Invoke("HelloWorldFunction");
```
```
If the window was dynamic (and properly implemented) you would be able to use it like this:
```
```
HtmlPage.Window.HelloWorldFunction();
```
```


q:
I have a ListBox control that I want to change into having a toggle selection. i.e. Click once on an item selects it, click again it deselects it. Also, clicking another item in the list should do the default action of deselecting the previous item and selecting the new one.

What's the best way of achieving this?

[A]
I would keep the standard ListBox as that way you will keep the default behaviour you want, then for deselecting an item could you just handle it in the mouse down event? i.e. use something like this:
```
```
Point newPoint = e.GetPosition(backgroundImage);

HitTestResult result = VisualTreeHelper.HitTest(this, newPoint);

if (result.VisualHit is ListBoxItem)
```
```
I'm not sure if this is the best way, the only other way I would go about doing this is to derive my own ListBox from the standard windows control and add in a dependency property to allow me to handle the deselection in the style. If you want to take this approach I shouldn't remove the default behaviour you want to keep either, I used this approach to create a ListBox that would display an image next to the text.
If you need any pointers on where to start, then just give me a shout.


q:
We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database etc. Which language will be the easiest and fastest to work with?
(It is a web-app)

[A]
In .NET, C# 3.0 and VB9 provide excellent support for working with XML using LINQ to XML:
LINQ to XML Overview


q:
I have an offline paper based form. I need to convert it into a software that people can use on their computers to fill and submit information. Since the form (it is a tax return) requires considerable time in filling, it is not convenient to have it online. I would much rather have a simple exe which gathers information, applies validation rules and then uploads a structured data file (like an XML file) containing the filled info.

I mean that I have an offline paper based form. I need to convert it into a software that people can use on their computers to fill and submit information. Since the form (it is a tax return) requires considerable time in filling, it is not convenient to have it online only. I would much rather have a simple exe which gathers information, applies validation rules and then uploads a structured data file (like an XML file) containing the filled info.

[A]
What do you mean, exactly? When you build a project containing a form, it will already build an executable if the project type is "Windows Forms Application".
If you've got one project with several forms and you need one executable per form, you should split your project out - one project per form. (You
could
make the code display a different form based on executable name - or have several entry points and build the same code with different
```
/main
```
flags, but that would be pretty nasty.)


q:
Does anyone know how to unit test SiteMapNode? We’re building some custom navigation controls, which renders unordered html lists from Site Maps with custom attributes.

I’m trying to follow a test first approach but am finding that SiteMapNode has internal dependencies on HttpContext. To traverse the site map file it insists on using a virtual path to find the site map file.

I have build a site map, which I’d like to test against but I don’t want to create my unit testing environment in web project(!)

Any suggestions? Mocking?  Overriding the relevant members?

[A]
A rather dull question, so no surprise it didn't get a response! For anyone else who may stumble across this problem, here's my preferred solution:
I've found the best way to handle this is to load the physical site map into an xml document. I then have a NavigationNodeFactory, which validates and builds my own composite NavigationNode tree from the xml document.
My NavigationNode class is as opinionated as I like and circumnavigates the issues I found with SiteMap and SiteMapProvider, namely poor testability for implementers.


q:
I am working on a big C++ project. It is building using single Ant script which makes possible to compile the same source targeting more than one platform and compiler.

But, I have to work only for Windows platform and Visual Studio 2005 C++ compiler. It would be really nice if I could write code and compile in Visual Studio, instead of using Notepad++ and Ant scripts, as I do now.

I tried to install Nant and Nant addin for Visual Studio 2005, and to use existing Ant script, but it seems that Ant script cannot be used as a Nant script.

Is there any way to convert Ant script to Nant? Is any other approach to the problem at all, or I must create Visual Studio solution and projects manually?

I would try to avoid such solution because I have a bunch of tests that I don't know how to use in that case.

[A]
To my knowledge, there is no
automatic
way of converting Ant script to NAnt. However, since NAnt is based off of the Ant the conversion process would not be too far from the original, as long as the tasks are the "core" ones. Possibly an XSLT translation could be made on the Ant scripts to convert to NAnt as both are XML. If one were to go down this path the conversion should be done
dynamically
based of the original Ant scripts, so that only one set of scripts would have to be maintained.
If you would like to write and compile your C++ code inside of Visual Studio it's tough to beat the functionality that is built in with the IDE. However, this requires creating project files though. Otherwise, it seems that one would risk fighting an uphill battle with the tool.
One option for the tests would be to call out through a
custom build step
to run them.


q:
I've got this date time string:

post["date"] = "2007-07-18 10:03:19"

I'd like to extract just "2007-07-18" as a date. I've seen some reference to strptime but I'm not sure how to use it.  How can I extract the date from this string?

[A]
In your case, just use split:
```
```
>>> d1="2007-07-18 10:03:19"
>>> d1.split()[0]
'2007-07-18'
>>>
```
```
(The 1st part after splitting with whitespace)
If you insist on using
```
strptime
```
, the format is
```
"%Y-%m-%d %H:%M:%S"
```
:
```
```
>>> import time
>>> time.strptime(d1,"%Y-%m-%d %H:%M:%S")
time.struct_time(tm_year=2007, tm_mon=7, tm_mday=18, tm_hour=10, tm_min=3, tm_sec=19, tm_wday=2, tm_yday=199, tm_isdst=-1)
>>> time.strftime("%Y-%m-%d", _)
'2007-07-18'
>>>
```
```


q:
I'm using the MultiPoint SDK to create a collaborative educational application for children in less affluent countries, where there is not one computer for each student in the classroom.

Because we need to support up to 40 mice connected to one computer, we need an automated way to test our software. The SDK will support as many mice that it can find on the system and detects when mice are added and removed. Each mouse appears as a 'virtual' mouse pointer within a WPF window. Each child has independent control of 'their' pointer on the screen.

We would like to create a test harness that tricks Windows into thinking that it has more than one mouse. The harness would need to create these fake devices (40+) and use them to send mouse messages like move, button down, etc

Any help would be greatly appreciated.

[A]
Faking mice to the extent that you'd need for MultiPoint is going to require a device driver. This is not an easy task, but is by no means impossible.
The best approach would probably be a
HID minidriver
that you can install using the
Setup API
. The driver would then accept
```
DeviceIoControl
```
s which would cause it to simulate mouse input reports.


q:
PHP has a var_dump() function which outputs the internal contents of an object, showing an object's type and content.

For example:

class Person {
  private $firstName;
  private $lastName;

  public function __construct($firstName, $lastName) {
    $this->firstName = $firstName;
    $this->lastName = $lastName;
  }
}

$person = new Person('Jon', 'Smith');
var_dump($person);

will output:

object(Person)#1 (2) {
  ["firstName:private"]=>
  string(3) "Jon"
  ["lastName:private"]=>
  string(5) "Smith"
}

What is the equivalent in Java that will do the same?

[A]
It is not quite as baked-in in Java, so you don't get this for free.
It is done with convention rather than language constructs.  In all data transfer classes (and maybe even
in all classes you write...
), you should implement a sensible
```
toString
```
method.  So here you need to override
```
toString()
```
in your
```
Person
```
class and return the desired state.
There are
utilities available
that help with writing a good toString method, or most IDEs have an automatic
```
toString()
```
writing shortcut.


q:
I have this SQL query:

SELECT * FROM IMAGES WHERE
IMAGENAME in ('IMG1', 'IMG2', 'IMG3', 'IMG4', 'IMG5', 'IMG6')
ORDER BY CASE IMAGENAME
  WHEN 'IMG1' THEN 1
  WHEN 'IMG2' THEN 2
  WHEN 'IMG3' THEN 3
  WHEN 'IMG4' THEN 4
  WHEN 'IMG5' THEN 5
  WHEN 'IMG6' THEN 6
  ELSE 7
END

I cannot guarantee that the list of IMAGENAMEs will be in alphabetical order, hence the case statement, but I would prefer to sort in the DB rather than in code because I trust their sorting code better than mine :)

SQL server analyses that 78% of the execution time is spent sorting - can I reduce this?

It needs to be fairly vanilla SQL as we target SQL Server and Oracle.

Any tuning advice would be fantastic.

[A]
Could you strip the
```
IMG
```
(or non-numeric) part of the
```
IMAGENAME
```
to a new column when writing to the database, then sort on the new numeric-only column?
For example:
```
```
SELECT * FROM IMAGES WHERE
IMAGENAME in ('IMG1', 'IMG2', 'IMG3', 'IMG4', 'IMG5', 'IMG6')
ORDER BY IMAGENO
END
```
```
where
```
IMAGENO
```
would contain
```
1, 2, 3, 4, 5, 6
```
for each row in your example, respectively.


q:
There's a web services I want to call in my application, I can use it with importing the WSDL or by just use "HTTP GET" with the URL and parameters, so I prefer the later because it's simple thing.

I know I can use indy idhttp.get, to do the job, but this is very simple thing and I don't want to add complex indy code to my application.

UPDATE: sorry if I was not clear, I meant by "not to add complex indy code", that I don't want add indy components for just this simple task, and prefer more lighter way for that.

[A]
Calling a RESTful web service using Indy is pretty straight forward.
Add IdHTTP to your uses clause.  Remember that IdHTTP needs the "HTTP://" prefix on your URLs.
```
```
function GetURLAsString(const aURL: string): string;
var
  lHTTP: TIdHTTP;
begin
  lHTTP := TIdHTTP.Create;
  try
    Result := lHTTP.Get(aURL);
  finally
    lHTTP.Free;
  end;
end;
```
```


q:
I want to be able to create a file, distribute it to an end-user, but prevent them from making modifications to the file.

Now, obviously, I can't actually stop anybody from modifying the file - so my approach is to detect and reject the file if it's modified.

My intention is to generate a salted hash of the file contents and append it to the file. On reading, the hash is verified before reading the rest of the file. The downside of this is that I have to distribute the fixed "salt" in the executable which reads the file. Obviously I can obfuscate it to some extent, but that still feels like a weak link.

Are there any better approaches to solving this kind of problem?

[A]
Not if you want a 100% solution. Just look at the movie and music industry. They have tried and failed for many years now :)
I think your solution is good enough. To make it harder to modify the file you could encrypt it, but then they can't read it, so it will only work if that is an ok limitation.


q:
I am having a postgres production database in production (which contains a lot of Data). now I need to modify the model of the tg-app to add couple of new tables to the database.

How do i do this? I am using sqlAlchemy.

[A]
If you are just adding tables, and not modifying any of the tables which have the existing data in it, you can simply add the new sqlAlchemy table definitions to model.py, and run:
```
```
tg-admin sql create
```
```
This will not overwrite any of your existing tables.
For schema migration, you might take a look at
http://code.google.com/p/sqlalchemy-migrate/
although I haven't used it yet myself.
Always take a backup of the production database before migration activity.


q: How to create a WCF application without using the svcutil.exe tool?

[A]
What version of Visual Studio are you using?
VS2008 incorporates the functionality of the svcutil tool.  To generate the proxy, click on the Solution Explorer and select 'Add Service Reference', you can then enter the URL of the server, give the namespace a name and off you go.
You may want to expand your question to provide some more details of what you are wanting to achieve.


q:
I'm trying to load spring beans using XmlWebApplicationContext setConfigLocations method.  However, I keep getting a

BeanIsAbstractException

I know that the bean is abstract, I have it configured this way, so Spring should know not to try to instantiate it.

I'm using Spring2.0.8.jar with jetspeed2.1.

Spring bean:

<bean id="ThreadPool" abstract="true" class="com.sample.ThreadPoolFactoryBean"/>

Code:

ctx = appContext;
    appContext.refresh();
    BeanFactory factory = appContext.getBeanFactory();
    String[] beansName = appContext.getBeanFactory()
            .getBeanDefinitionNames();

...

map.put(beansName[mnCnt], factory.getBean(beansName[mnCnt]));

Anyone have any ideas?

[A]
The following code will try, and fail to create an instance of your abstract class:
```
```
map.put(beansName[mnCnt], factory.getBean(beansName[mnCnt]));
```
```
Just so there is no confusion, 'abstract' beans are
not the same
as abstract classes.They are primarily a convenient mechanism for reducing duplicate property settings.
A child bean definition will inherit constructor argument values,
      property values and method overrides from the parent, with the option
      to add new values. If init method, destroy method, factory bean and/or
      factory method are specified, they will override the corresponding
      parent settings.
A contrived example:
```
```
class Fruit {
    private String colour;
    private String name;
    // setters...
}

class Car {
    private String colour;
    private String manufacturer;
    // setters...
}
```
```
And:
```
```
<!-- specifying a class for an abstract bean is optional -->
<bean id="sharedPropsBean" abstract="true">
    <property name="colour" value="red" />
</bean>

<bean id="myFruit" parent="sharedPropsBean" class="Fruit">
    <property name="name" value="apple" />
</bean>

<bean id="myCar" parent="sharedPropsBean" class="Car">
    <property name="manufacturer" value="Ferrari" />
</bean>
```
```


q:
I need to perform a HTTP GET from PHP.

More specifically, from within /index.php I need to get the content of /trac/ and /svn/, find the "ul" element and then render then inline on the index.php.

/trac and /svn are relative URLs and not filesystem folders.
http://myserver/trac and http://myserver/svn

[A]
Have a look at
file_get_contents
- it can be used to open urls under some conditions as can some of the other
filesystem functions
:
A URL can be used as a filename with
  this function if the fopen wrappers
  have been enabled. See fopen() for
  more details on how to specify the
  filename and List of Supported
  Protocols/Wrappers for a list of
  supported URL protocols.


q:
Can anyone explain to me what this means?

"Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call.  This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention."

[A]
Possibility #1 is your object got Aliased wrong. That means the compiler mistakenly casted an object incorrectly, most commonly as an optimization.
Possibility #2 your using a reference to an object that isn't valid.
Possibility #3 something totally unrelated broke your stack, likely a buffer overflow.
Without code sample It's hard to predict beyond these possibilities, but they cover 90% of what might be happening.


q:
How do you set a break points in server tags in .aspx pages. e.g.

<%   dim breakhere =new object() %>

The web application is running in debug mode with the <compilation debug="true" ... in the web.config. But the page says:

The break point will not currently be
  hit. No symbols have been loaded for
  this document.

Is there anything else i need to set?

[A]
I havent tried this myself but in ASP (VBScript) you can inject a STOP statement and that will trigger the IDE to break on that line
Example
```
```
<%
STOP
Dim o as Object = new Object()
%>
```
```
HTH


q:
Edit: This behaviour is reproducible with query globals on.

I have the following:

  $_SESSION['query_key'] = $_GET['query_key'];
  print($query_key);

Vs.

  $_SESSION['query_key'] = clone $_GET['query_key'];
  print($query_key);

The former prints out the value of $query_key, while the latter prints nothing.
What sort of weird side effect is this of clone?

[A]
You must be doing something very weird with your code.
clone
is for use on objects.  Unless you're stuffing objects into $_GET then that code will result in a fatal error (or a warning in older PHP versions).
@Michael Haren - clone actually does a shallow copy of an object, that is, it copies all the properties, but if a property is a reference to another object it will copy the reference, not clone the other object.


q:
In the grails-framework some objects are using log. This is normally injected by grails. It works on execution of grails test-app. But the same test (an integration-test) fails on execution of grails test-app -integration.

What goes wrong here and can I force the injection of the log-object somehow?

[A]
What version of grails are you using?  It's working fine for both situations for me on 1.0.4 (the latest).
I create a new blank app and created a service class with an integration test:
FooService.groovy:
```
```
class FooService {
    def logSomething(message) {
        log.error(message)
        return true
    }
}
```
```
FooServiceTests.groovy:
```
```
class FooServiceTests extends GroovyTestCase {
    def fooService
    void testSomething() {
    assert fooService.logSomething("it works")
    }
}
```
```
When running just test-app, I get the log message:
```
```
% grails test-app

Welcome to Grails 1.0.4 - http://grails.org/
....
-------------------------------------------------------
Running 1 Integration Test...
Running test FooServiceTests...
                        testSomething...[4174] service.FooService it works
SUCCESS
Integration Tests Completed in 440ms
-------------------------------------------------------
...
```
```
When running only integration tests, it also works:
```
```
% grails test-app -integration

Welcome to Grails 1.0.4 - http://grails.org/
....
-------------------------------------------------------
Running 1 Integration Test...
Running test FooServiceTests...
                    testSomething...[4444] service.FooService it works
SUCCESS
Integration Tests Completed in 481ms
-------------------------------------------------------
....
```
```
Are you munging around with the logger class (or overriding any metaclass stuff on the logger, in any previous integration classes or unit tests and not then re-initializing the metaClass?


q:
I have a web app that is heavily loaded in javascript and css. First time users log in it takes some time to load once it is downloading js etc. Then the caching will make everything faster.

I want my users to be aware of this loading time. How can I add some code to "show" some loading information while js and css are downloaded?

[A]
Sweet mother of mercy, Ricardo, how much Javascript and CSS are involved with this application?
You could, I guess, do something where you load the JS and CSS using an AJAX request and do nothing with them.  This will load your JS and CSS files into the cache.  You could do all of this on a "Loading" page, and redirect to the real page once you've loaded the files.  But IMO you really shouldn't have to do this.  Use
Fiddler
to really see what's going on behind the scenes -- make sure people are really having to wait for their JS/CSS files to come down before doing this optimization.


q:
I would like to do the equivalent of the following:

#define print_max(TYPE) \
#  ifdef TYPE##_MAX \
     printf("%lld\n", TYPE##_MAX); \
#  endif

print_max(INT);

Now the #ifdef or any nested preprocessor directive is
not allowed as far as I can see in a function macro.
Any ideas?

Update: So it seems like this is not possible. Even a hack to check at runtime seems unachievable. So I think I'll go with something like:

#ifndef BLAH_MAX
#  define BLAH_MAX 0
#endif
# etc... for each type I'm interested in

#define print_max(TYPE) \
    if (TYPE##_MAX) \
       printf("%lld\n", TYPE##_MAX);

print_max(INT);
print_max(BLAH);

[A]
I don't think it's a case of the ## operator not being allowed in an #ifdef. I tried this:
```
```
#define _print_max(TYPE) \
#ifdef TYPE \
printf("%lld\n", _TYPE); \
#endif

#define print_max(TYPE) _print_max(MAX##_TYPE)

void main()
{
    print_max(INT)
}
```
```
and it still didn't work (it didn't like #ifdef TYPE). The problem is that #ifdef will only accept #defined symbols, not #define arguments. Those are two different things.


q:
My scenario is:

I have a WPF Window with 3 data-bound text boxes

SettingsUI : Window

<Grid Name="SettingsUIGrid1">
    <TextBox Text="{Binding val1}" ....
    <TextBox Text="{Binding val2}" ....
    <TextBox Text="{Binding val3}" ....
</Grid>

In the constructor I do this:

SettingsUIGrid1.DataContext = coll[0]; // collection first value

When the Cancel button is clicked, I close my window:

private void btnCancel_Click(object sender, RoutedEventArgs e) {
Close();
}

When I click the Show button, is shows values from the DB in text boxes, if user changes a text box value, and reloads the window the new value is displayed not the old one.  Can someone suggest what to do to reload the values again and clear the in memory object?

[A]
I would suggest putting some code into your cancel button click event to check whether any of the data has been changed from what was initially loaded as I am assuming that if they don't click cancel the other button would be save/ok meaning that the data would be committed to the database.
What is coll?
if it is a DataTable then you could use this:
```
```
private static bool DataRowReallyChanged(DataRow row)
    {
        if (row == null)
        {
            return false;
        }

        if (!row.HasVersion(DataRowVersion.Current) || (row.RowState == DataRowState.Unchanged))
        {
            return false;
        }

        foreach (DataColumn c in row.Table.Columns)
        {
            if (row[c, DataRowVersion.Current].ToString() != row[c, DataRowVersion.Original].ToString())
            {
                return true;
            }
        }

        return false;
    }
```
```
then simply add a call into the cancel button event like:
```
```
if (DataRowReallyChanged((DataRow)SettingsUIGrid1.DataContext))
{
     ((DataRow)SettingsUIGrid1.DataContext).RejectChanges();
}
```
```
I hope this helps. If you are not using a DataTable then let me know what you are using and ill see if i can help further.


q:
I have a form with a DIV, 3 INPUTS, each INPUT sits within a LABEL element. I would like to change the background image of the DIV element when focusing on each INPUT.

I can't move back up the DOM to fix this with CSS, so could someone suggest a few lines of jQuery please?

Thanks

[A]
```
```
$('input').focus(function(){
    $(this).parent().parent().addClass('highlight');
}).blur(function(){
     $(this).parent().parent().removeClass('highlight');
});
```
```


q:
How can I return to the start of a line and overwrite what has already been output on the console? The following does not appear to work:

System.out.print(mystuff+'\r');

[A]
If you just want to write a new line to the console, you should use the println() method:
```
```
System.out.println(mystuff);
```
```
However, this will not delete what is already on the line. Actually, since System.out is a PrintStream, which is a type of OutputStream, that is basically hard to do, although you may find terminal-specific ways to do it.
You might have better luck using a Java implementation of a curses library, such as
JavaCurses
.


q: I would like to know if there is any easy way to print multiple emails(about 200) so that they continue on as opposed to printing one per page. I have tried with thunderbird and evolution and this does not seem possible. Would concatenating the individual mail files work or are there other unix utilities that could do this? WOuld sed or awk be suited for this?

[A]
Why don't you put all the data from the mails in one text file and print that one.
This could be done by something like:
```
```
cat *.eml > file.txt
```
```
Or print it directly with
```
```
cat *.eml | lpr
```
```


q:
I need to purchase SQL Server 2008 Standard edition, because it's features fit what I need. On the features page, it says it can handle 32,767 user connections, but how does that connect with CALs?

What are CALs and how can they affect a project?

[A]
A CAL is a client access license.
SQL Server 2008 has 3 licensing models (explained
here
):
Processor Licensing Model
Server Plus Device CALs Licensing Model
Server Plus User CALs Licensing Model
You try and select the cheapest model that meets your requirements.
From this
page
:
Q: What is the difference between device client access licenses (CALs) and user CALs?
A. A device CAL allows any number of users to gain access to licensed server software from a particular device. A user CAL lets a particular user gain access to licensed server software from any number of devices. In other words, a user CAL covers a particular user's access to the server software from work computers and laptops, as well as from home computers, handheld computers, Internet kiosks, and other devices. A device CAL covers access by multiple users to server software from a single, shared device.


q:
I am trying to accomplish the following in MySQL (see pseudo code)

SELECT DISTINCT gid
FROM `gd`
WHERE COUNT(*) > 10
ORDER BY lastupdated DESC

Is there a way to do this without using a (SELECT...) in the WHERE clause because that would seem like a waste of resources.

[A]
```
```
SELECT COUNT(*)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC;
```
```
EDIT (if you just want the gids):
```
```
SELECT MIN(gid)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC
```
```


q:
There has been a lot of sentiment to include a nameof operator in C#. As an example of how this operator would work, nameof(Customer.Name) would return the string "Name".

I have a domain object. And I have to bind it. And I need names of properties as strings then. And I want them to be type-safe.

I remember coming across a workaround in .NET 3.5 which provided the functionality of nameof and involved lambda expressions. However, I have not been able to locate this workaround. Can anyone provide that workaround to me?

I am also interested in a way to implement the functionality of nameof in .NET 2.0 if that is possible.

[A]
The workaround is to use an expression tree, and to take that expression tree apart to find the relevant
```
MemberInfo
```
. There's slightly more detail and comment in
this note
(although not the code to pull out the member - that's in another SO question somewhere, I believe).
Unfortunately as expression trees don't exist in .NET 2.0, there's really no equivalent.
One solution to avoid typos is to have a set of accessors which fetch the relevant
```
PropertyInfo
```
for a particular property, and unit test them. That would be the only place which had the string in it. This would avoid duplication and make refactoring easier, but it's a bit draconian.


q: I'm wondering if there's some kind of criteria that can be used to determine where a script or file should go.

[A]
If you don't mind the possibility that anyone might be able to see the contents then put it inside the web path. Otherwise keep it outside.
Inside:
anything publicly available - images, javascript, css, static content. You'll be putting less strain on the server and will automatically be taking advantage of whatever caching and compression services it has.
Outside:
Anything private. Script files, with password and other sensitive details, might be vulnerable if a server failure results in them being served as text instead of being parsed.


q:
Currently, I am splitting all my tests by package (projects). So if I have 12 projects, I will create 1 more project for Unit Test with 12 classes that will test all my package.

Do you do the same way or do you have 1 testing class by class? How do you organize all your test?

[A]
We have it organized like this (C++):
```
```
package/Class.cpp
package/Class.hpp
package/test/ClassUnitTest.cpp
package/test/ClassIntegrationTest.cpp
test/unit-test/main.cpp
test/integration-test/main.cpp
test/data
test/tmp
```
```
Where
unit-test
and
integration-test
are just the test runners,
test/data
holds data files that are used by the integration tests and
test/tmp
holds temporary files created by the same tests and is cleared for each test suite.


q:
Am I right to think that there is no way to set the selected value in the C# class SelectList after it is created?
Isn't that a bit silly?

[A]
You mean client-side, in the browser?
```
```
var select = document.getElementById('mySelect');
select.options[newIndex].selected = true;
```
```


q:
I need to check whether the user executing the script has administrative privileges on the machine.

I have specified the user executing the script because the script could have been executed with a user other than the logged on using something similar to "Runas".

@Javier: Both solutions work in a PC with an English version of Windows installed but not if the installed is in different language. This is because the Administrators group doesn't exist, the name is different for instance in Spanish. I need the solution to work in all configurations.

[A]
You can use script if you want to see if the logged on user is an administrator
```
```
Set objNetwork = CreateObject("Wscript.Network")
strComputer = objNetwork.ComputerName
strUser = objNetwork.UserName

isAdministrator = false

Set objGroup = GetObject("WinNT://" & strComputer & "/Administrators")
For Each objUser in objGroup.Members
    If objUser.Name = strUser Then
        isAdministrator = true
    End If
Next

If isAdministrator Then
    Wscript.Echo strUser & " is a local administrator."
Else
    Wscript.Echo strUser & " is not a local administrator."
End If
```
```
I am not sure how to handle it when the script is run with "Runas" I am afraid.


q:
There seem to be so many color wheel, color picker, and color matcher web apps out there, where you give one color and the they'll find a couple of other colors that will create a harmonic layout when being used in combination. However most of them focus on background colors only and any text printed on each background color (if text is printed at all in the preview) is either black or white.

My problem is different. I know the background color I want to use for a text area. What I need help with is choosing a couple of colors (the more, the merrier) I can use as font colors on this background. Most important is that the color will make sure the font is readable (contrast not being too low, also maybe not being too high to avoid that eyes are stressed) and of course that the combination of foreground and background just looks good.

Anyone being aware of such an application? I'd prefer a web application to anything I have to download. Thanks.

[A] This is an interesting question, but I don't think this is actually possible.  Whether or not two colors "fit" as background and foreground colors is dependent upon display technology and physiological characteristics of human vision, but most importantly on upon personal tastes shaped by experience.  A quick run through MySpace shows pretty clearly that not all human beings perceive colors in the same way.  I don't think this is a problem that can be solved algorithmically, although there may be a huge database somewhere of acceptable matching colors.


q:
I have the following table in MySQL (version 5):

id     int(10)       UNSIGNED             No    auto_increment
year   varchar(4)    latin1_swedish_ci    No
title  varchar(250)  latin1_swedish_ci    Yes   NULL
body   text          latin1_swedish_ci    Yes   NULL

And I want the db to auto add the current year on insert, I've tried the following SQL statement:

ALTER TABLE `tips` CHANGE `year` `year` VARCHAR(4) NOT NULL DEFAULT year(now())

But it gives the following error:

1067 - Invalid default value for 'year'

What can I do to get this functionality? Thanks in advance!

[A]
The following should work:
```
```
ALTER TABLE tips MODIFY COLUMN year YEAR(4) NOT NULL DEFAULT CURRENT_TIMESTAMP
```
```
Please see
Year Data Type
for further information.
So, I tested this once I got access and it doesn't work. As another poster pointed out CURRENT_TIMESTAMP only works on the
TIMESTAMP
data type.
Is there a specific problem with storing a complete time stamp and then only using the year in your code? If not, then I would recommend storing this value as a timestamp.
Your other option would be to create a
trigger
:
```
```
CREATE TRIGGER example_trigger AFTER INSERT ON tips
FOR EACH ROW BEGIN
UPDATE tips SET year = YEAR(NOW()) WHERE tip_id = NEW.tip_id
END;
```
```
Otherwise, assign this value to the INSERT statement from within your code.
The best solution in your case will depend entirely on the circumstances surrounding your particular application.


q:
I have an abstract base class called Shape from which both Circle and Rectangle are derived, but when I execute the following code in VS 2005 I get the error Debug assertion failed. At the same time I have not overloaded == operator in any class

Expression:Vector iterator not dereferencable, what is the reason for this.

  vector<Shape*> s1;
  s1.push_back(new Circle(point(1,2),3));
  s1.push_back(new Circle(point(4,3),5));
  s1.push_back(new Rectangle(point(1,1),4,5));

  vector<Shape*> s2(s1);
  reverse(s1.begin(),s1.end());

  (*find(s1.begin(),s1.end(),new Circle(point(1,2),3)))->move(point(10,20));

[A]
Simple :
find fails since your newly created Circle can't be found in the vector with comparing Shape *
a failed find returns the end iterator which is not deferencable as caught by a Debug assertion
For it to work like you want, you do need to compare Shape, not Shape*
As pointed out in other answers,
boost::ptr_vector
is an easy way to achieve this.


q: I heard that Visual Studio came with an Image Library, but I can't find it anywhere. Does anyone know where it is?

[A]
In VS 2008 they're under:
PROGRAMFILES\Microsoft Visual Studio 9.0\Common7\VS2008ImageLibrary\1033


q:
I am looking for an alternative to my old "Font Navigator" that I... borrowed... from the CorelDraw Suite :-)

Googling for it, took me to hundreds of pages with old software, so I hope to find a quick idea from here (waiting for FontExplorer X from Linotype).

Which Font Explorer for Windows do you currently use?
My "requisites" are:

browse and preview installed/uninstalled fonts

install/uninstall fonts

free :-)

Thanks in advance

[A]
This
thread
references the main font explorers like
Bitstream Font Navigator
,
Typograf
(both already mentioned) and
OT1 Font Manager
... but they are not free.
The only one which
might
be free would be
Font Explorer X
, which has a
beta version for PC
, but that version is quite "dangerous"
“It IS very glitchy. Not totally useless but you have to get over the fact that it totally messes up any directory of fonts. So make a seperate folder for the fonts you want to import into the program as it will delete those fonts from the original folder. Also make a backup copy of your windows fonts folder just in case it decides to remove the fonts from there too.”


q: I am working on an ASP.NET MVC application where I need to export data to an excel spreadsheet.  Previously, in webforms apps, I used some code I found to render a GridView as an excel-compatible file.  This was quite handy. I was wondering what the quickest/most effective method would be to do this in MVC. Thanks.

[A]
One simple option would be to create a view to render an XML-version of an Excel File. You could either use the new Office 2007 version, or the older 2003 version. We chose the 2003 version so that more people could use it, but that's up to you, of course.
XML 2003 ref on MSDN
XML 2007 ref on MSDN


q:
I'm writing an MFC App to automatically configure Postgresql with ODBC for use by another app. The idea being that the user runs the app and it automatically creates the database and the tables within it. My problem is that when I set up the File DSN it seems to require the name of the database it will access. This appears in the DSN file as ..

DATABASE=mydb

However I haven't created mydb yet so can't connect to Postgresql ! I have tried editing the DSN file so this line reads ..

DATABASE=

and removing it totally but then I get an error and can't connect.

Is it possible for a DSN file to allow access to any database ? If so how do I do this ?

Thanks

Ian


q:
Inspired by the question What’s the simplest way to call Http GET url using Delphi?
I really would like to see a sample of how to use POST. Preferably to receive XML from the call.

Added: What about including an image or other file in the post data?

[A]
Using Indy.  Put your parameters in a StringList (name=value) and simply call Post with the URL and StringList.
```
```
function PostExample: string;
var
  lHTTP: TIdHTTP;
  lParamList: TStringList;
begin
  lParamList := TStringList.Create;
  lParamList.Add('id=1');

  lHTTP := TIdHTTP.Create;
  try
    Result := lHTTP.Post('http://blahblahblah...', lParamList);
  finally
    lHTTP.Free;
    lParamList.Free;
  end;
end;
```
```


q:
I try to write to a large file, but it seems like it does not work for files larger than 2GB.
I have tried with boost::iostreams::file_sink. Is this just a limit with the boost stream? Is there some other way I can write a large file on Win64 and win32?

[A]
This depends on:
The file system which you're using. Old file systems like FAT allow only files up to 2GB. Use NTFS.
Your library must be compiled to allow large files (64bit seek offsets). If they use 32bit ints to seek in file (check the arguments and results of the calls "seek" and "tell"), you can only ever access 2GB (2^31bits, the 32th is the sign +/-)
This might also help:
http://www.boost.org/doc/libs/1_37_0/libs/iostreams/doc/faq.html#offsets


q:
What's the best way to move a document from one doc library to another? I don't care about version history or preserving CreatedBy and ModifiedBy metadata...

SPList lib1 = (SPDocumentLibrary) web.Lists["lib1"];
SPList lib2 = (SPDocumentLibrary) web.Lists["lib2"];
SPItem item1 = lib1.Items[0];
//insert code to move item1 to lib2

I'm currently looking at SPItem.MoveTo() but wonder if anyone already solved this problem and has some advice.

Thanks in advance.

[A]
Got it:
```
```
SPList lib1 = (SPDocumentLibrary) web.Lists["lib1"];
SPList lib2 = (SPDocumentLibrary) web.Lists["lib2"];
SPListItem item1 = lib1.Items[0];
byte[] fileBytes = item1.File.OpenBinary();
string destUrl = lib2.RootFolder.Url + "/" + item1.File.Name;
SPFile destFile = lib2.RootFolder.Files.Add(destUrl, fileBytes, true /*overwrite*/);
```
```


q:
I have created a Registry class in .NET which is a singleton. Apparently this singleton behaves as if it were kept in the Cache (the singleton object is available to each session). Is this a good practice of should I add this Singleton to the Cache?
+ do I need to wacth out for concurrency problems with the GetInstance() function?

namespace Edu3.Business.Registry
{
    public class ExamDTORegistry
    {
        private static ExamDTORegistry instance;
        private Dictionary<int, ExamDTO> examDTODictionary;

        private ExamDTORegistry()
        {
            examDTODictionary = new Dictionary<int, ExamDTO>();
        }

        public static ExamDTORegistry GetInstance()
        {
            if (instance == null)
            {
                instance = new ExamDTORegistry();
            }
            return instance;
        }
    }
}

[A]
Well, your GetInstance method certainly isn't thread-safe - if two threads call it at the same time, they may well end up with two different instances. I have a
page on implementing the singleton pattern
, if that helps.
Does your code
rely
on it being a singleton? Bear in mind that if the AppDomain is reloaded, you'll get a new instance anyway.
I don't really see there being much benefit in putting the object in the cache though. Is there anything you're thinking of in particular?


q: does anybody know any resources that I can refer to?

[A]
I believe you are referring to the
JQuery FadeOut effect
(since
Stackoverflow uses JQuery
)


q: In VB.NET, what is the difference between And and AndAlso? Which should I use?

[A]
The
```
And
```
operator evaluates both sides, where
```
AndAlso
```
evaluates the right side if and only if the left side is true.
An example:
```
```
If mystring IsNot Nothing And mystring.Contains("Foo") Then
  ' bla bla
End If
```
```
The above throws an exception if
```
mystring = Nothing
```
```
```
If mystring IsNot Nothing AndAlso mystring.Contains("Foo") Then
  ' bla bla
End If
```
```
This one does not throw an exception.
So if you come from the C# world, you should use
```
AndAlso
```
like you would use
```
&&
```
.
More info here:
http://www.panopticoncentral.net/2003/08/18/the-ballad-of-andalso-and-orelse/


q: I want to allow only users with a 3G phone to use a particular GPS function.  How do I run a check on the device before allowing that feature to be used?

[A]
The following code with allow you to determine the exact device that is in use but I would first consider the fact that a 3G device may not actually be able to obtain a GPS lock as the process of doing so is quite slow and requires a more or less clear view of the sky.
For an iPhone 3G the result of this method will be iPhone1,2
```
```
- (NSString *)deviceModel
{
    NSString *deviceModel = nil;
    char buffer[32];
    size_t length = sizeof(buffer);
    if (sysctlbyname("hw.machine", &buffer, &length, NULL, 0) == 0) {
        deviceModel = [[NSString alloc] initWithCString:buffer encoding:NSASCIIStringEncoding];
    }
    return [deviceModel autorelease];
}
```
```


q:
I have a generic method with this (dummy) code (yes I'm aware IList has predicates, but my code is not using IList but some other collection, anyway this is irrelevant for the question...)

    static T FindThing<T>(IList collection, int id) where T : IThing, new()
    {
        foreach (T thing in collection)
        {
            if (thing.Id == id)
                return thing;
        }
        return null;  // ERROR: Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead.
    }

This gives me a build error

"Cannot convert null to type parameter
'T' because it could be a value type.
Consider using 'default(T)' instead."

Can I avoid this error?


q:
With jQuery, how do I find out which key was pressed when I bind to the keypress event?

$('#searchbox input').bind('keypress', function(e) {});

I want to trigger a submit when ENTER is pressed.

[Update]

Even though I found the (or better: one) answer myself, there seems to be some room for variation ;)

Is there a difference between keyCode and which - especially if I'm just looking for ENTER, which will never be a unicode key?

Do some browsers provide one property and others provide the other one?

[A]
Okay, I was blind:
```
```
e.which
```
```
will contain the ASCII code of the key.
See
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which


q:
I'm writing a java app using eclipse which references a few external jars and requires some config files to be user accessable.

What is the best way to package it up for deployment?

My understanding is that you cant put Jars inside another jar file, is this correct?

Can I keep my config files out of the jars and still reference them in the code? Or should the path to the config file be a command line argument?

Are there any third party plugins for eclipse to help make this easier? I'm using an ant build file at the moment but I'm not sure I know what I'm doing.

Is there an equivelent of the deployment projects in Visual studio, that will figure out everything you need and just make an installer? I've used install4j before, and it was powerful if no where near as automated as  .Net deployment projects.

Cheers.

[A]
Ant. It's not the best thing in the world, but it's standard, it's apache, and it works.
There's some good examples on the web how to make a simple build.xml for any, and it's got some features like the 'war' task that knows how to put all the basic stuff (classes, web.xml etc) in the jar file for you.
You can also tell it to pick up other config files and jars and it will happily do it.
It's also really smart about what to compile. You give it a directory, and it finds all the java files and builds them only if their classfile is out of date, so you get some of the traditional make functionality for free without much effort.


q:
I have a base class vehicle and some children classes like car, motorbike etc.. inheriting from vehicle.
In each children class there is a function Go();
now I want to log information on every vehicle when the function Go() fires, and on that log I want to know which kind of vehicle did it.

Example:

public class vehicle
{
      public void Go()
      {
           Log("vehicle X fired");
      }
}
public class car : vehicle
{
       public void Go() : base()
       {
           // do something
       }
}

How can I know in the function Log that car called me during the base()?
Thanks,

Omri

[A]
Calling
```
GetType()
```
from Vehicle.Go() would work - but only if Go() was actually called.
One way of enforcing this is to use the
template method pattern
:
```
```
public abstract class Vehicle
{
    public void Go()
    {
        Log("vehicle {0} fired", GetType().Name);
        GoImpl();
    }

    protected abstract void GoImpl();
}

public class Car : Vehicle
{
    protected override void GoImpl()
    {
        // do something
    }
}
```
```


q:
I'm compiling library for a private project, which depends on a number of libraries. Specifically one of the dependencies is compiled with Fortran. On some instances, I've seen the dependency compiled with g77, on others I've seen it compiled with gfortran. My project then is ./configure'd to link with either -lg2c or -lgfortran, but so far I've been doing it by hand.

If it is possible, how can I find out, from looking into the dependent library (via e.g. nm or some other utility?), whether the used compiler was g77 (and then I'll use -lg2c in my link options) or gfortran (and then I'll use -lgfortran)?

Thanks in advance!

[A] You might be able to figure it out by using nm, and seeing if the compiled code uses functions from one or the other, but that's quite a hack.  You may be able to figure it out based on which library is available (if there's no libg2c available, then it wasn't g77, for example), but then you still have some ambiguity if both are available.  If you can build the dependency yourself, then you can use have one part of your build process tell another part somehow (variable, file, etc.) which one you used.


q:
I've built the x86 Boost libraries many times, but I can't seem to build x64 libraries. I start the "Visual Studio 2005 x64 Cross Tools Command Prompt" and run my usual build:

bjam --toolset=msvc --build-type=complete --build-dir=c:\build install

But it still produces x86 .lib files (I verified this with dumpbin /headers).
What am I doing wrong?

[A]
You need to add the
```
address-model=64
```
parameter.
Look e.g.
here
.


q: I am having problems when connecting to my SQL server 2008 and think it might be a problem related to MDAC. Is there a download to re-install these?

[A]
MDAC 2.8 SP1
Remember, MDAC is client software that should not be installed on the server.
Your problem is more likely a protocol or firewall error.
Can you give more info please?


q:
does anybody know how to save and retrieve files in MS SQL-Server 2000?  I guess the image data type could be used as a container.

I want to import/export the following file types: DOC, XLS, PDF, BMP, TIFF, etc.

Due to resource issues we are using MS-Access 2007 as the front end, so I am looking for VBA code.

Thanks in Advance.

[A]
You can do this using GetChunk and AppendChunk.
From
this post
you might find
this link
helpful!
One thing to watch out for:
When using certain providers, most
  notably ODBC to SQL Server and other
  databases, you may have to take
  special care in retrieving BLOB data,
  such as placing BLOB columns at the
  end of the field list and referencing
  all non-BLOB fields prior to access
  BLOB columns.
Best of luck!


q:
A class has a property (and instance var) of type NSMutableArray with synthesized accessors (via @property). If you observe this array using:

[myObj addObserver:self forKeyPath:@"theArray" options:0 context:NULL];

And then insert an object in the array like this:

[myObj.theArray addObject:NSString.string];

An observeValueForKeyPath... notification is not sent. However, the following does send the proper notification:

[[myObj mutableArrayValueForKey:@"theArray"] addObject:NSString.string];

This is because mutableArrayValueForKey returns a proxy object that takes care of notifying observers.

But shouldn't the synthesized accessors automatically return such a proxy object? What's the proper way to work around this--should I write a custom accessor that just invokes [super mutableArrayValueForKey...]?

[A]
You need to wrap your
```
addObject:
```
call in
```
willChangeValueForKey:
```
and
```
didChangeValueForKey:
```
calls. As far as I know, there's no way for the NSMutableArray you're modifiying to know about any observers watching its owner.


q: I'm just starting out with WiX as I need to be able to automate building an MSI on our CI server.  Is there anyway to automatically include all the dependencies of a project?

[A] In my experience, Wix is a still a very manual process.  You have to add each dependency singly - I think the idea was that you would build the Wix installer at the same time you are building your project and add each item in as you are adding it in the code.  This way it seems less daunting than having to go back and do a retrospect on the project.  It certainly would be a great suggestion for an enhancement though!


q:
Somehow my iPhone Simulator is unable to play sounds.  First an app I'm working on using AudioServicesPlaySystemSound() stopped working.. I spent a while debugging this but sound is still working on the iPhone when I run the app on the device.  I get the same results with other iPhone apps such as the sample Crash Landing app.

I can't find a sound setting anywhere in the simulator or Xcode preferences.  I've tried resetting the simulator through "Reset Content and Settings" menu item to no avail.

[A]
I've found sound to be very inconsistent in the simulator (2.1 SDK).  Sometimes it works, sometimes it doesn't.  Even when it does work, it's usually very choppy and distorted (when playing audio files such as mp3).
A few things to remember:
call
```
AudioSessionInitialize
```
as soon as your app finishes launching
set the
```
kAudioSessionProperty_AudioCategory
```
property for the session via
```
AudioSessionSetProperty
```
(with a value such as
```
kAudioSessionCategory_MediaPlayback
```
)
call
```
AudioSessionSetActive(YES)
```
Of course when all else fails, just run it on your hardware!
EDIT: Now that the 2.2 SDK has been released, I haven't had any problems with sound in the simulator. They must have fixed the bugs! I highly recommend you upgrade to the 2.2 SDK.


q: Delphi strings use single quotes, for example 'a valid string'. How does one specify the ' character within a literal string? How would one refer to the null byte (Unicode code point U+0000)?

[A]
To add a single quote to a string, you include two
```
'
```
marks e.g.
```
```
str := '''test string''';
Writeln(str)
```
```
In the string above, you have the normal single quotation to start a string and then two for the single quote. Same goes for the end of the string.
You can also use
```
#
```
followed by a number for other escape character e.g.
For a new line:
```
```
str := 'Newline' + #13 + #10
```
```
or just
```
```
str := 'Newline'#13#10
```
```
Of course, using the platform-dependent constant for newline is better.


q: I want to make my .Net application display a notification in the system tray. So I want to show an icon for that, can anyone tell how to do that?

[A]
In .Net apps you can specify the file to use as an icon - it can be a bitmap or png etc. so just use your favourite image editing program to create you icon.
This
article
gives advice on getting your app to put an icon in the system tray.
Hope this helps.


q:
What's the most efficient way to calculate the last day of the prior quarter?

Example:  given the date 11/19/2008, I want to return 9/30/2008.

Platform is SQL Server

[A]
I came up with this (tested for all months):
```
```
select dateadd(dd,-1,dateadd(qq,datediff(qq,0,'11/19/2008'),0)),
       dateadd(dd,-1,dateadd(qq,datediff(qq,0,'10/19/2008'),0)),
       dateadd(dd,-1,dateadd(qq,datediff(qq,0,'12/19/2008'),0))
```
```
It might turn out to be the simplest.


q:
About a half dozen times now, I’ve been doing a regular chore in Visual Studio – either running a unit test or simply compiling, updating something from SVN or whatever, and visual studio just disappears… it shuts down and goes away instantly… it is fine when I restart it, and I don’t see the problem again for a while… it keeps happening, and for random reasons… has anyone else experienced this?

One thought is that i'm using AnkhSVN, but if you've had this problem and don't experience this, please let me know.

[A]
All of the devs on my team see this problem quite often. It isn't AnkhSVN because we don't use it. I believe it is C++ intellisense, but that is just a feeling. Sometimes it happens when we are not doing anything. We will go for coffee, come back and it is just gone.
It never happens to me on smaller projects, but happens frequently on our large (several million lines, dozens of projects) solution with a mix of unmanaged C++, managed C++ and C#.
We have seen it less frequently since upgrading to SP1.


q:
I am looking in the Collections framework of Java for a LIFO Structure (Stack) without any success. Basically I want a really simple stack; my perfect option would be a Deque, but I am in Java 1.5.

I would like not to have to add another class to my structure but I am wondering if that is possible:

Is there any class in the Collections framework (1.5) that does the job?

If not, is there any way to turn a Queue in a LIFO Queue (aka Stack) without reimplementation?

If not, which Interface or class should I extend for this task? I guess that keep the way that the guys of Sun have made with the Deque is a good start.

Thanks a lot.

EDIT: I forgot to say about the Stack class: I have my doubts about this class when I saw that it implements the Vector class, and the Vector class is a little bit obsolete, isn't it?

[A]
There is a
Stack class in the API
.  Will this meet your needs?


q:
This is a followup to Avoiding @property-itis.

UIWebView has the following property declarations:

@property(nonatomic,readonly,getter=canGoBack) BOOL canGoBack;
@property(nonatomic,readonly,getter=canGoForward) BOOL canGoForward;

UIScrollView has these:

@property(nonatomic) BOOL canCancelContentTouches;

Yet, UIResponder has

- (BOOL)isFirstResponder;
- (BOOL)canBecomeFirstResponder;
- (BOOL)canResignFirstResponder;

Is the UIResponder case one where they should have been declared as properties, but, for whatever reason, were not?

Or is it a case where declaring them as properties was inappropriate? If inappropriate, why?

[A] My best guess is that UIResponder is meant to match NSResponder, which of course was designed before Objective-C 2.0 introduced properties. Why UIWebView doesn't do the same with regard to WebView, I don't know. I'd expect properties in Cocoa to be a little schizophrenic in this way for some time, and I wouldn't think into it too much when considering your own code.


q:
Would it be benefical to add a generic way to add info to a Throwable without creating a new Throwable?

I often see code like this:

try {
    foo();
} catch (Exception e) {
    throw new Exception(e.getMessage() + " extra info=" + blah, e);
}

Would it be better to instead add Throwable.setProperty(String key, String value) so that the code above becomes the following?

try {
    foo();
} catch(Exception e) {
    e.setProperty("extra info", blah);
    throw e;
}

The extra info could print (one per line) between the message and stack list.

Benefits:
 1. Would not require creating new Throwables just to add extra information.
 2. Stack traces would not have multiple layers of cause traces
    (and therefore be easier to read)
 3. Reduce cost of creating extra stack traces.

[A]
In general, I think that it is better to use the standard idioms in cases like this. In this case, the standard idiom is to wrap the exception, like this:
```
```
try {
  foo();
} catch (Exception e) {
  throw new MySpecificException("extra info=" + blah, e);
}
```
```
Also, in general it is best not to catch generic Exceptions. If you want to catch and add information to RuntimeException, then do that, and create a new RuntimeException. Otherwise, think carefully about which checked exceptions you want to catch and throw.


q: We need to get all the instances of objects that implement a given interface - can we do that, and if so how?

[A]
I don't believe there is a way... You would have to either be able to walk the Heap, and examine every object there, or walk the stack of every active thread in the application process space, examining every stack reference variable on every thread...
The other way, (I am guessing you can't do) is intercept all Object creation activities (using a container approach) and keep a list of all objects in your application...


q:
I would like to use ON DUPLICATE KEY UPDATE in Zend Framework 1.5, is this possible?

Example

INSERT INTO sometable (...)
VALUES (...)
ON DUPLICATE KEY UPDATE ...

[A]
I worked for Zend and specifically worked on Zend_Db quite a bit.
No, there is no API support for the
```
ON DUPLICATE KEY UPDATE
```
syntax.  For this case, you must simply use
```
query()
```
and form the complete SQL statement yourself.
I do not recommend interpolating values into the SQL as harvejs shows.  Use query parameters.
Edit: You can avoid repeating the parameters by using
```
VALUES()
```
expressions.
```
```
$sql = "INSERT INTO sometable (id, col2, col3) VALUES (:id, :col2, :col3)
  ON DUPLICATE KEY UPDATE col2 = VALUES(col2), col3 = VALUES(col3)";

$values = array("id"=>1, "col2"=>327, "col3"=>"active");
```
```


q:
I would like to serve a different content from a single URL depending on whether the user is a browser or a RSS reader (hence avoiding an example.com/feed URL). Thus www.example.com/posts will return an (X)HTML page to a browser and an RSS feed to a feed reader.

What the architecturally most appropriate way of accomplishing this?

PS How is that for a soft-ball question... :)

[A]
Let me introduce you to the User-Agent
HTTP header
. It will contain an identifying string for the client accessing your page. It can be faked but you just can't be 100% sure if it's a RSS reader or a browser.
Additionally, RSS readers might send Accept headers for rss content-types, which you may use to implement
content negotiation
(
MultiViews
in Apache).
But as there is no sure fire way, you better fail on the side of serving HTML more often than RSS, or better yet, do as everybody else does and provide a different feed for RSS.


q:
If it's harder to explain using words, let's look at an example
I have a generic function like this

void FunctionA<T>() where T : Form, new()
{
}

If I have a reflected type, how do I use it with the above function? I'm looking forward to do this

Type a = Type.GetType("System.Windows.Forms.Form");
FunctionA<a>();

Of cause the above method doesn't work.

[A]
You can't.  Generics in .NET must be resolved at compile time.  You're trying to do something that would resolve them at runtime.
The only thing you can do is to provide an overload for FunctionA that takes a type object.
Hmmm... the commenter is right.
```
```
class Program
{
    static void Main(string[] args)
    {
        var t = typeof(Foo);
        var m = t.GetMethod("Bar");
        var hurr = m.MakeGenericMethod(typeof(string));
        var foo = new Foo();
        hurr.Invoke(foo, new string[]{"lol"});
        Console.ReadLine();
    }
}

public class Foo
{
    public void Bar<T>(T instance)
    {
        Console.WriteLine("called " + instance);
    }
}
```
```
MakeGenericMethod
.


q:
How do I calculate the last business day of month in VBScript? It is for a Reporting Services report.

Thanks

[A]
If you mean the last
week
day of the month (M-F), then try:
```
```
Dim d

d = DateAdd("m", 1, Now)

d = Month(d) & "/1/" & Year(d)
d = DateAdd("d", -1, d)

If Weekday(d) = 7 Then
    d = DateAdd("d", -1, d)
ElseIf Weekday(d) = 1 Then
    d = DateAdd("d", -2, d)
End If

MsgBox d
```
```


q:
I've seen the following code to enable double buffering on a winform:

// Activates double buffering
this.SetStyle(ControlStyles.DoubleBuffer |
   ControlStyles.OptimizedDoubleBuffer |
   ControlStyles.UserPaint |
   ControlStyles.AllPaintingInWmPaint, true);
this.UpdateStyles();

Is this different in any way from simply setting Form.DoubleBuffering = true?

[A]
Setting a form's DoubleBuffering will set double buffering for that form. It's the same as calling
```
```
form.SetStyle(ControlStyles.OptimizedDoubleBuffer, value);
```
```
The other flags like UserPaint and AllPaintingInWmPaint are styles that aren't set by simply setting control.DoubleBuffering = true


q: Can you recommend a minimalistic python webserver that I can embedded in my Desktop Application.

[A]
See the
WSGI reference
implementation.


q:
Given a java.util.Date object how do I go about finding what Quarter it's in?

Assuming Q1 = Jan Feb Mar, Q2 = Apr, May, Jun, etc.

[A]
Since Java 8, the quarter is accessible as a field using classes in the
java.time
package.
```
```
import java.time.LocalDate;
import java.time.temporal.IsoFields;

LocalDate myLocal = LocalDate.now();
quarter = myLocal.get(IsoFields.QUARTER_OF_YEAR);
```
```
In older versions of Java, you could use:
```
```
import java.util.Date;

Date myDate = new Date();
int quarter = (myDate.getMonth() / 3) + 1;
```
```
Be warned, though that
getMonth
was deprecated early on:
As of JDK version 1.1, replaced by Calendar.get(Calendar.MONTH).
Instead you could use a
```
Calendar
```
object like this:
```
```
import java.util.Calendar;
import java.util.GregorianCalendar;

Calendar myCal = new GregorianCalendar();
int quarter = (myCal.get(Calendar.MONTH) / 3) + 1;
```
```


q:
I have a sqlite3 table that I'm trying to map to an object in objective-C. One attribute of the table is 'completed_at' which is stored as a DATETIME.

I want to create a property on my objective-C class (which inherits from NSObject) that will map well to the 'completed_at' attribute.

Objective-C has an NSDate type but I'm not sure if that will map directly?

[A]
I have zero experience with Objective-C, but I found Apple's
NSDate Class Reference
with a google search. With the information provided on the linked page you should be able to figure out how to manipulate 32-bit epoch times in Objective-C, and this would work well in SQLite. I would probably create the completed_at column as type INTEGER for 32-bit times.
SQLite really prefers Julian dates, which are floats. I haven't found any documentation explaining how one might coerce the NSDate class into working with Julians.
timeIntervalSince1970
looks very interesting.


q:
I'm looking to have a simple custom dialog box, like a message box, that has a label and a TextBox. If there's a simple way to do this, sorry! I'm really not well versed in the dialog stuff.

Thanks for any help, guys!

[A]
I'm assuming you basically want a custom dialog box that returns a string entered by the user.  One way is to add a reference to Microsoft.VisualBasic to your project, which gives you access to the InputBox method, which is basically a message box with a text box on it.  But that's no fun and I'm not sure it would work on a smartphone anyway.
To roll your own, you just add a form (named CustomDialog) to your project and drag a textbox (textBox1), a label (label1), and a button (labeled "OK") onto it.
To set the label text, add a parameter to the form's constructor like this:
```
```
public CustomDialog(string textCaption)
{
    label1.Text = textCaption;
}
```
```
To expose the entered text to the caller, add this code to the form:
```
```
public override string Text
{
    get
    {
        return textBox1.Text;
    }
}
```
```
In the OK button's click event, put this code:
```
```
this.DialogResult = DialogResult.OK; // this will close the form, too
```
```
To use this dialog from your main form, you create an instance of this form, show it, check to see that the OK button was clicked, and then read its Text property (which returns what the user entered) like so:
```
```
using (CustomDialog dialog = new CustomDialog("What is your name"))
{
    if (dialog.ShowDialog(this) == DialogResult.OK)
    {
        string enteredText = dialog.Text;
    }
}
```
```
You can get fancier, but those are the basics.


q: I'm trying to move my database.mdf file from a development environment to a SQL Server Express server that is hosted on my VPS - but I can't figure out how to attach the file to my database server. Help!

[A]
```
sp_attach_db
```
(or CREATE DATABASE FOR ATTACH) - don't forget to bring the LDF (log) files, too.


q:
I'm having a weird problem, where tagging works fine on my development machine, but when I deploy to the production server, I get this error in the log:

ActionView::TemplateError (undefined method `tags' for #<Person:0x98bb9d4>) on line...

There is an entry in the production.log file that states that has_many_polymorphs is loaded, so it's not like the plugin isn't available on the production machine.

My Google-fu has failed me trying to find the answer, so if anyone knows what could be wrong it would be greatly appreciated!

Edit: I should have mentioned that on both production and development I'm using the same database. I downloaded the production one, and used it on the development machine and it works fine.


q:
What is the difference between

if(null==object)

and

if(object==null)

Please give the advantage for using the above.

[A]
The difference comes if you accidentally type
```
=
```
instead of
```
==
```
:
```
if (null = object)
```
- Compiler error
```
if (object = null)
```
- Bug!


q:
I have the following string in the smarty (php templating system) variable $test:

<img height="113" width="150" alt="Sunset" src="/test.jpg"/>

I want to add "em" to the height and width like this:

{$test|replace:'" w':'em" w'|replace:'" a':'em" a'}

But this doesn't work... What's the problem and the solution?

[A]
my regex isn't the greatest, or i'd give you a better matcher, but maybe using what you have through the regex replace would work.
```
```
{$test|regex_replace:'/".w/':'em" w'|regex_replace:'/".a/':'em" a'}
```
```
other matchers to try
```
```
'/\".w/'
'/".*w/'
'/\".*w/'
```
```
i can't play with my smarty sites at the moment, but i'd first remove the " from the replacement value, to see if the bug is there, then remove it from the matcher and just look for height/width.
otherwise i'd do the replace in PHP if you can.


q:
I need to use C++ to read in text with spaces, followed by a numeric value.

For example, data that looks like:

text1
1.0
text two
2.1
text2 again
3.1

can't be read in with 2 "infile >>" statements. I'm not having any luck with getline
either. I ultimately want to populate a struct with these 2 data elements. Any ideas?

[A]
If you can be sure that your input is well-formed, you can try something like this sample:
```
```
#include <iostream>
#include <sstream>

int main()
{
    std::istringstream iss("text1 1.0 text two 2.1 text2 again 3.1");

    for ( ;; )
    {
        double x;
        if ( iss >> x )
        {
            std::cout << x << std::endl;
        }
        else
        {
            iss.clear();
            std::string junk;
            if ( !(iss >> junk) )
                break;
        }
    }
}
```
```
If you do have to validate input (instead of just trying to parse anything looking like a double from it), you'll have to write some kind of parser, which is not hard but boring.


q: We have a multi threaded java program. Multiple-threads will write to a file, and one thread will read from that file. I am looking for some design ideas. Is synchronization necessary?

[A]
I would consider synchronization in this case. Imagine that 2 threads (t1 and t2) open the file at the same time and start writing to it. The changes performed by the first thread are overwrited by the second thread because the second thread is the last to save the changes to the file. When a thread t1 is writing to the file, t2 must wait until t1 finishes it's task before it can open it.
Also, if you care about the latest possible update of the file, you should synchronize the writing threads with the thread that reads the file so that if there's any thread writing the the file, the reading thread should wait.


q:
I need a way of calling a web page from inside my .net appliction.

But i just want to send a request to the page and not worry about the response.

As there are times when the response can take a while so i dont want it to hang the appliction.

I have been trying in side the page_load event

WebClient webC = new WebClient();
Uri newUri = new Uri("http://localhost:49268/dosomething.aspx");
webC.UploadStringAsync(newUri, string.Empty);

Even though its set to Async, it still seams to hang as the page wont finish rendering until the threads have finsished

[A]
Look at
```
System.Net.WebClient
```
, specifically use the
```
DownloadDataAsync()
```
method to send the request without blocking the rest of the app.


q:
How can I accomplish this?

<% for agent in @broker.agents %>
  ...
  <% if agent.cell %><span class="cell-number">Cell: <%= agent.cell %></span><% end %>
  ...
<% end %>

I want to test to see if the agent has a cell number, and if so, display what's inside the conditional.  What I have currently doesn't seem to work; it just displays "Cell: ".

Thoughts?

[A]
```
```
if !agent.cell.blank?
```
```
It works.


q:
My rails model has code that is attempting to define_method(method_name) inside the model.

I keep getting:

NoMethodError: undefined method `define_method'

What am I doing wrong? Am I doing this in the wrong place. I need this method attached to this model. Where else can I define this method?

EDIT:
For those asking to see the code:

for field in rdev_fields
  next if self.attributes.include?(field)
  count = count + 1
  rdev_hash[field.to_sym] = self.attributes["attribute#{count}"]
  if !self.respond_to?(field) then
    define_method("#{field}") do
      self.send("attribute#{count}".to_sym)
    end
  end
end

[A]
was able to cobble this together. Very little understanding of what's actually going on though.
My instance method foo is opening the class and defining bar on it so that I can then call that on my instance. More experienced folks will let us know if this is opening a can of worms at the same time.
Would be useful to know your specific use for this though.
```
```
class User < ActiveRecord::Base

  def foo
    (class << self; self; end).class_eval do
      define_method(:bar) {puts "bar"}
    end
  end
end

u = User.first
u.foo
u.bar #=> "bar"
```
```


q:
I'm looking to implement the Observer pattern in VB.NET or C# or some other first-class .NET language. I've heard that delegates can be used for this, but can't figure out why they would be preferred over plain old interfaces implemented on observers. So,

Why should I use delegates instead of defining my own interfaces and passing around references to objects implementing them?

Why might I want to avoid using delegates, and go with good ol'-fashioned interfaces?

[A]
A delegate is, in effect, passing around a reference to a method, not an object... An Interface is a reference to a subset of the methods implemented by an object...
If, in some component of your application, you need access to more than one method of an object, then define an interface representing that subset of the objects' methods, and assign and implement that interface on all classes you might need to pass to this component... Then pass the instances of these classes by that interface instead of by their concrete class..
If, otoh, in some method, or component, all you need is one of several methods, which can be in any number of different classes, but all have the same signature, then you need to use a delegate.


q:
Anyone getting this error when using the new free chart controls MS bought from Dundas?

"Error executing child request for ChartImg.axd"

On the MSDN forum they suggested it was my web.config:
 MSDN forum post

So far that hasn't fixed the problem though.  Any other ideas?

[A]
I posted a way I fixed this problem on the MSDN forum:
Well I still don't know why I was getting the exception but I seem to have found a workaround.  I did an experiment where I took the supposed offending web.config and copied it to a new project where I added a new web form and chart control and the chart control rendered fine with the "UseHttpHandler" option.  This led me to believe that it wasn't actually the web.config that was the problem in my case, so I went back to the original project and added a chart to another web form as an experiment, and it worked!  Even more surprising was that after that I went to the offending page and it worked too!  Then I took the new chart off the other page and checked the original offending page and it was broken again.  Then I found out if I put a chart control on any page before the offending page, it would work, otherwise it threw the exception.  These controls are so cool though that I didn't have a problem finding another page to put one on in the path of the offending page :)
This fixed the problem but if anyone has any theory why I'd be interested...maybe a bug?


q:
I am making a mp3 id3tag editor, and a regex is not matching.
Could anyone help me please?
my code:

arquivo = "[coletanea] album [CD #] [faixa] [artista] musica.mp3"

r = New Regex("^\[(?<1>[^\]]+?)\]\s*(?<2>[\w\s]+)\s*\[CD\s*(?<3>\d+)\]\s*\[(?<4>\d+)\]\s*\[(?<5>[^\]]+)\]\s*(?<6>.+)", RegexOptions.Compiled)
m = r.Match(Mid(arquivo, 1, Len(arquivo) - 4))
        If m.Success Then
            mAuthor = Trim(m.Groups(5).ToString)
            mWM_AlbumTitle = Trim(m.Groups(2).ToString)
            mWM_TrackNumber = Trim(m.Groups(4).ToString)
            mTitle = Trim(m.Groups(6).ToString)
            mWM_PartOfSet = Trim(m.Groups(3).ToString)
            mMW_AlbumArtist = Trim(m.Groups(1).ToString)
        End If

[A]
That's because your string will never match the regexp you are using.
The regexp expects a number instead of # and a number instead of 'faixa'
Try this, for example:
```
```
"[coletanea] album [CD 20] [89] [artista] musica.mp3"
```
```
If you wish to allow for any character instead of just numbers, replace \d for . in the groups 3 and 4


q:
I am looking to do the following (see pseudo code); I want to select 4 rows for each gd.id (7, 11 or 9). I've incorrectly use limit because that only brings up 4 rows in total. Anyone have an idea on how to change this query to accomplish my goal?

SELECT gd.gid, gd.aid, li.ads, li.til
FROM gd
JOIN li ON li.a_id = gd.aid
WHERE gd.gid
IN (
'7', '11', '9'
)
ORDER BY li.timestamp DESC
LIMIT 4 #FOR EACH ;-)

Thank you!

Ice

p.s. Maybe sometype of group_by?


q:
I have two classes that are associated with a one-to-one mapping:

<class name="Employee" table="Employees">
  ...
  <one-to-one name="Address" class="AddressInfo">
  ...
</class>

I would like to use a criteria expression to get only Employees where the the associated Address class is not null, something like this (which I know doesn't work):

IList employeesWithAddresses = sess.CreateCriteria(typeof(Employee))
    .Add( Expression.IsNotNull("Address") )
    .List();

I guess this is either a really difficult question or almost no one has tried to do this?

[A]
Have you tried creating an alias for the Address property and checking if the ID/primary key of the Address is not null?
Something like:
```
```
IList employeesWithAddresses = sess.CreateCriteria(typeof(Employee))
    .CreateCriteria("Address", "address").Add( Expression.IsNotNull("Id") )
    .List();
```
```


q:
I am a recent college graduate working for a large corporation that has an aging workforce. I am curious for peoples experiences on working with an age gap preferably from both sides.

Examples Issues I have encountered so far:

Agile practices vs Waterfall

Collaboration between programmers vs individuality

Working early in the morning vs late at night

I learned primarily agile programming in school while the project I am on (and most of the developers are used to waterfall)

I am used to collaborating with classmates and friends on projects while I tend to see older programmers like to do their own thing. I feel like I pester them asking them questions.

I find myself more of a night programmer, but most of my older colleagues are early morning (5am)

Any experiences on the age gap in the technology work is relevant.

[A]
Waterfall
is an example of a flawed, non-working software development model.  Unfortunately, it doesn't sound like you're in a position to point this out to your aging co-workers.  :)
I recommend you keep asking questions to different people until you find someone (or a few) who seem interested in mentoring you.  No education or training that I've received in my career has ever been as valuable as the advice of a few really good mentors that I've had.
Once you find a mentor, I suggest you try to work around their schedule, at least for awhile.  Don't feel too bad about asking questions, since that's the only way you can learn (Google it, or ask your question on here first, so you don't ask them
too
many easy questions).
Good luck!
EDIT:  Since only the first two sentences of my original answer seem to be getting read, I thought I'd better provide some more links to support what I said.
The Staggered Iterative Waterfall (Anti-)Pattern
Waterfall development model considered harmful
Don’t draw diagrams of wrong practices - or: Why people still believe in the Waterfall model
Managing the development of Large Software Systems (PDF)
Note that the last one is Royce's original paper.


q:
I've seen a couple of web pages say that a = b || 'blah' should assign 'blah' to a if b is undefined or null.  But if I type that into Firebug or use it in code, it complains that b is not defined, at the list on FF3/win.  Any hints?

Edit: I'm looking for the case where b may not exist at all.  For example, a DOM node without an id.

[A]
If b existed, and was false, null, etc, then it works in the way that you would expect. All you'll need to do is on the line above that, put
```
var b = null
```
;
This makes sense if you think about it. It basically does something like this...
```
```
a = function(){ if(b){return b;} else{ return 'blah' } }();
```
```
Note it is checking that the value of b is truthy... if b doesn't exist, you get an exception.
Regarding Undefined variables
"Undefined" in javascript doesn't mean 'variable doesn't exist'. It means "the value of the variable is the special value of
```
undefined
```
". Example:
```
```
alert(nosuchvariable);
=> throws exception

var somevariable; // note it's never assigned
alert(somevariable);
=> This alerts with 'undefined'
```
```
Regarding Checking if variables exist.
So if we try to read
```
b
```
and there is no such variable as b, we get an exception. If we're trying to find out if b is defined, then this isn't helpful.
You can see if global variables exist by checking the top-level
```
window
```
object. All global variables are actually just fields in the
```
window
```
object. Example:
```
```
foo = 'Hello';
alert( window.foo );
=> alerts 'Hello'
```
```
Because you know the window object already exists, you can check it's fields.
Checking for fields that don't exist in javascript will give you
```
undefined
```
and won't crash, so you can then do the coalesce, or put the
```
undefined
```
in a variable or whatever
For
local
variables (things declared with
```
var
```
),
you can't check for their existence.
they don't "live" anywhere in the way that global variables "live" in the window object, and any normal attempt to reference one will cause an exception: eg:
```
```
alert(a);
=> exception because a is meaningless
alert(d45pwiu4309m9rv43);
=> exception because that is equally meaningless
```
```
There is however one exception (that I know of, thanks J c in the comments), the
```
typeof
```
operator. If you try and get the type of something that doesn't exist, it
won't
crash, it will return
the string
```
"undefined"
```
.
This gives you a way of checking for non-existent local variables. eg:
```
```
if( typeof(djfsd) === "undefined" )
  alert('no such variable');
```
```
Regarding DOM elements that don't exist
There have been several comments mentioning DOM elements without ID's and so forth...
The fact that it's a DOM element isn't really relevant. Think of the DOM as a database or a file, and an element as a row in that database or word in that file. In order to
do
anything with it, you have to go searching through the database, find the right row, and pull it's data out. The data gets put into a javascript object. You then access it by manipulating that object, and maybe putting the object in a variable if you like. Example:
```
```
document.getElementById('foo');
```
```
this goes into the dom and looks for an element with an ID of 'foo'. If it finds one, it puts some information about that element into a javascript object, and then hands that object back to you. If it can't find the element, it will hand you back
```
null
```
, but all the normal rules still apply (you can stick the
```
null
```
in a variable, or whatever).
It doesn't affect the coalesce at all.


q:
I am working on a Perl script to read CSV file and do some calculations.
CSV file has only two columns, something like below.

One Two
1.00 44.000
3.00 55.000

Now this CSV file is very big ,can be from 10 MB to 2GB.

Currently I am taking CSV file of size  700 MB. I tried to open this file in notepad, excel but it looks like no software is going to open it.

I want to read may be last 1000 lines from CSV file and see the values.
How can I do that? I cannot open file in notepad or any other program.

If I write a Perl script then I need to process complete file to go to end of file and then read last 1000 lines.

Is there any better way to that? I am new to Perl and any suggestions will be appreciated.

I have searched net and there are some scripts available like File::Tail but I don't know they will work on windows ?

[A]
In *nix, you can use the tail command.
```
```
tail -1000 yourfile | perl ...
```
```
That will write only the last 1000 lines to the perl program.
On Windows, there are
gnuwin32
and
unxutils
packages both have
```
tail
```
utility.


q:
According to the adobe flex docs: http://livedocs.adobe.com/flex/3/html/help.html?content=controls_15.html

Using an image multiple times

You can use the same image multiple times in your application by using the normal image import syntax each time. Flex only loads the image once, and then references the loaded image as many times as necessary.

However, in testing we have found that if you request the same image (same url, etc.) in IE flash 9/10 a new http request will not be issued, but with Firefox, Safari (PC and MAC) a new request is always issued.

I want to prevent the image from being pulled from the server each time I try and use it anyone have any idea why this is working only in IE?

[A]
The best way to load an image a single time and then reuse that image multiple times in a flex application is to embed the image and tie it to a class representation, then just reference that class from then on.
Example:
```
```
[Embed(source="myImage.jpg")]
[Bindable]
public var myImageClass:Class;
```
```
HTH


q:
I am looking to find out the logic , if any , which shrinks hashtable in c# when elements are removed from it.

Regards
Harish

[A]
The only indication of size changes for a hashtable in the documentation is when the load factor is exceeded and the size of the hashtable is increased.  There is no mention of a hastable ever shrinking.
There is some further detail of the load factor on
MSDN
.


q: Assuming this is a multi-user system

[A]
I don't know that it's inherently good or bad.  If there's no reason to centralize the data access from a business standpoint, having a client app talk directly to the database isn't a problem.  You'll want to build a decent data access layer regardless of whether it's done in the client or through a centralized data access server.
You mentioned multi-user, depending on the data and usage you may have transactional issues to deal with which might be an argument for centralizing things, but they can be handled from multiple clients as well.


q: I've scoured the groovy doc and haven't found an analogue, but things there are organized a bit haphazardly. I'm switching from beanshell to groovy and was using the source("fileloc") method in beanshell to inline-include other, utility beanshell scripts for reuse. Is there a standard function to do this in groovy or a best practice?

[A]
The reason you're not finding this is because Groovy is compiled.  Your Groovy code gets compiled into Java bytecode that gets run by the JVM right along side any Java code in your app.  This is why things like writing Groovified unit tests for large bodies of Java code requires zero extra effort.
The BeanShell is a Java-like
interpreted
language, so slurping in another got of code at run time is no big deal.
That said, you might be interested in
groovysh
and its
```
load
```
command.


q:
A co-worker asked me how the word "Nuke" relates to CMS? To be honest I never thought about it, and there wasn't any information on the web that I could find.

Francisco Burzi wrote that his Perl script that he used to manage content was called NUKE. His knowledge of that system fueled his adaptation of thatware to phpNuke.

Does anyone know what NUKE stands for and how it is related to content management?

[A]
From the faq (
http://www.dotnetnuke.com/Resources/Knowledge/FrequentlyAskedQuestions/tabid/546/Default.aspx
)
"The new name was chosen to reflect
  the applications .NET (DOTNET)
  framework, and coupled with the term
  “nuke” (due to *nuke’s inherent,
  industry-recognized inclusion in
  several existing open source portal
  initiatives.)"


q:
Parameterized Queries in .Net always look like this in the examples:

SqlCommand comm = new SqlCommand(@"
   SELECT *
   FROM   Products
   WHERE  Category_ID = @categoryid
",
   conn);
comm.Parameters.Add("@categoryid", SqlDbType.Int);
comm.Parameters["@categoryid"].Value = CategoryID;

But I'm running into a brick wall trying to do the following:

SqlCommand comm = new SqlCommand(@"
   SELECT *
   FROM   Products
   WHERE  Category_ID IN (@categoryids)
      OR  name LIKE '%@name%'
",
   conn);
comm.Parameters.Add("@categoryids", SqlDbType.Int);
comm.Parameters["@categoryids"].Value = CategoryIDs;
comm.Parameters.Add("@name", SqlDbType.Int);
comm.Parameters["@name"].Value = Name;

Where

CategoryIDs is a comma separated list of numbers "123,456,789" (without quotes)

Name is a string, possibly with single quotes and other bad characters

What's the right syntax for this?

[A]
You need "%" in value of sql parameter.
```
```
SqlCommand comm = new SqlCommand("SELECT * FROM Products WHERE Category_ID IN (@categoryid1, @categoryid2) OR name LIKE @name", conn);
comm.Parameters.Add("@categoryid1", SqlDbType.Int);
comm.Parameters["@categoryid1"].Value = CategoryID[0];
comm.Parameters.Add("@categoryid2", SqlDbType.Int);
comm.Parameters["@categoryid2"].Value = CategoryID[1];
comm.Parameters.Add("@name", SqlDbType.NVarChar);
comm.Parameters["@name"].Value = "%" + Name + "%";
```
```