q:
What is the PHP preg_replace in C#?

I have an array of string that I would like to replace by an other array of string. Here is an example in PHP. How can I do something like that in C# without using .Replace("old","new").

$patterns[0] = '/=C0/';
$patterns[1] = '/=E9/';
$patterns[2] = '/=C9/';

$replacements[0] = 'à';
$replacements[1] = 'é';
$replacements[2] = 'é';
return preg_replace($patterns, $replacements, $text);

[A]
You are looking for
```
System.Text.RegularExpressions
```
;
```
```
using System.Text.RegularExpressions;

Regex r = new Regex("=C0");
string output = r.Replace(text);
```
```
To get PHP's array behaviour the way you have you need multiple instances of `Regex
However, in your example, you'd be much better served by .Replace(old, new), it's much faster than compiling state machines.


q:
Possible Duplicate:

  VS2008 Setup Project: Shared (By All Users) Application Data Files?

Please can someone advice what is the best place (path) to put some application data which should be accessible and editable by all users.

This is considering both Windows XP and Windows Vista and i expect that change in any file of above path does NOT trigger UAC!

[A]
```
```
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
```
```
Should resolve to C:\Documents and Settings\All Users\Application Data\
From there, make subfolders such as MyCompany\MyApp

s: huggingface

c: devops

d: intermediate


q:
Is it possible to have a different set of dependencies in a maven pom.xml file for different profiles?

e.g.

mvn -P debug
mvn -P release

I'd like to pick up a different dependency jar file in one profile that has the same class names and different implementations of the same interfaces.

[A]
To quote the
Maven documentation on this
:
A profile element contains both an optional activation (a profile trigger) and the set of changes to be made to the POM if that profile has been activated. For example, a project built for a test environment may point to a different database than that of the final deployment.
Or dependencies may be pulled from different repositories based upon the JDK version used
.
(Emphasis is mine)
Just put the dependency for the
```
release
```
profile inside the profile declaration itself and do the same for
```
debug
```
.
```
<profiles>
    <profile>
        <id>debug</id>
        …
        <dependencies>
            <dependency>…</dependency>
        </dependencies>
        …
    </profile>
    <profile>
        <id>release</id>
        …
        <dependencies>
            <dependency>…</dependency>
        </dependencies>
        …
    </profile>
</profiles>
```


q:
I have a problem similar to the one found here : JSF selectItem label formatting.

What I want to do is to accept a double as a value for my  and display it with two decimals. Can this be done in an easy way?

I've tried using  but that seems to be applied on the value from the inputText that is sent to the server and not on the initial value in the input field.

My code so far:

<h:inputText id="december" value="#{budgetMB.december}" onchange="setDirty()" styleClass="StandardBlack">
    <f:convertNumber maxFractionDigits="2" groupingUsed="false" />
</h:inputText>

EDIT: The above code actually works. I was fooled by JDeveloper that didn't update the jsp page even when I did a explicit rebuild of my project and restarted the embedded OC4J server. However, after a reboot of my computer everything was fine.

[A]
If I'm not misunderstanding your requirement, I was able to achieve formatting of the value in the input box during the rendering of the view with:
```
```
<h:inputText id="text1" value="#{...}">
    <f:convertNumber pattern="#,###,##0.00"/>
</h:inputText>
```
```
I was using the Standard Faces Components in my vendor-branded Eclipse so I'm assuming the
```
pattern
```
attribute is part of standard JSF.


q:
I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.

I don't want to go through the minor trouble of installing mod_python or mod_wsgi on my Mac, so I was just going to do a system() or popen() from PHP to call the Python script.

Any better ideas? Thanks in advance!

[A]
Depending on what you are doing,
system()
or
popen()
may be perfect.  Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser.  Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php.  popen() will only let you read or write, but not both.  If you want both, check out
proc_open()
, but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.
If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection.  If you aren't careful, your user could send you data like "; evilcommand ;" and make your program execute arbitrary commands against your will.
escapeshellarg()
and
escapeshellcmd()
can help with this, but personally I like to remove everything that isn't a known good character, using something like
```
```
preg_replace('/[^a-zA-Z0-9]/', '', $str)
```
```


q:
I generally stay away from regular expressions because I seldom find a good use for them. But in this case, I don't think I have choice.

I need a regex for the following situation.  I will be looking at three character strings. It will be a match if the first character is 1-9 or the letters o,n,d (lower or upper)  AND the second character is 1,2 or 3 and the third character is 0-9.

Can anybody help me out?

[A]
```
```
[1-9ondOND][123][0-9]
```
```
I omitted the
```
^
```
and
```
$
```
(beginning and end of string markers) because you said you'd have three-character strings, but there's no harm in including them, and they may improve speed, not that that'll be a big deal on such short input.
Of course, this assumes you're working in a language and locale where the uppercase equivalent of
```
o
```
,
```
n
```
, and
```
d
```
are
```
O
```
,
```
N
```
, and
```
D
```
. If not, you'll need to tell your regex interpreter to ignore case. The mechanism varies by language/framework.
For python, you'd use something like:
```
```
re.match('[1-9ond][123][0-9]', inputstring, re.IGNORECASE)
```
```
The
```
re.match
```
forces a match at the beginning of string, so you wouldn't need the
```
^
```
in any case.


q:
Our team (5-10 developers)  plans to adopt Subversion for our .NET (Visual Studio) projects/solutions (VisualSVN Server, TortoiseSVN / VisualSVN).

What is the best way to organize a new repository tree? Is it okay to use one big repository or is it better to create different repositories for every solution / product line etc.?

Our projects can be categorized this way (example):

Main Product Line

Main Web App

Library 1

Library 2

...

Windows Client

Another Windows Client

Windows Service

Tools

Tool A

Tool B

Product Line 2

Software 1

Software 2

Product Line 3

App 1

App 2

[A]
We use one big repository, and just have everything structured in subfolders (/project1, /project2 etc) and that seems to work fine.
The Apache project has a
huge svn repository
and it seems to do OK for them! :)
In terms of organisation, the structure you gave looks quite reasonable. I think anything goes, pretty much, so long as it's rational (i.e. mixing up every single tool with every single project is probably a bad idea etc). So pick something which works for you (tools/, projects/ etc). Subversion has pretty good support for moving things around in the repository, too, so you can always change if necessary.


q: I have a need to display many numerical values in columns. These values need to be easily editable so I cannot just display them in a table. I am using textboxes to display them. Is there a way for me to right-justify the text displayed in a textbox? It would also be nice if when the user is entering data for it to start displaying what they type from the right.

[A]
Did you try setting the style:
```
```
input {
    text-align:right;
}
```
```
Just tested, this works fine (in FF3 at least):
```
```
<html>
    <head>
        <title>Blah</title>
        <style type="text/css">
        input { text-align:right; }
        </style>
    </head>
    <body>
        <input type="text" value="2">
    </body>
</html>
```
```
You'll probably want to throw a class on these inputs, and use that class as the selector.  I would shy away from "rightAligned" or something like that.  In a class name, you want to describe what the element's function is, not how it should be rendered.  "numeric" might be good, or perhaps the business function of the text boxes.


q: Does anyone know the API call I can use to change the keyboard layout on a windows machine to Dvorak?  Doing it through the UI is easy but I'd like to have a script that I can run on new VM's to automate the process.


q:
I'm trying to understand the best way to get the connection to my databases.

At the moment I've got a method which parses the URL (depending on the URL called the application has to connect to a different database, like customer1.example.com will connect to the customer1 database) and calls

ActiveRecord::Base.establish_connection(conn_string)

where conn_string contains the name of the database.

This method (set_db) is called with a

before_filter :set_db

in my Application controller, so basically for each request I get, the URL is parsed and the application try to do an establish_connection.

I was wondering if I can have a connection pool somewhere....do you have any suggestion about that? Is it better to have a Singleton which keep all the connections made and gives back the right one?

Thanks!
Roberto

[A]
I'm not a Ruby programmer, but generally speaking a connection pool is a good idea. You can make that connection pool a singleton and hand out/take back connections. The pool can check after taking back a connection whether everything is still in order.
You should have a distinct life cycle and ownership for each connection so two threads don't use a connection at the same time.
Be careful with temporary tables because they belong to one database session. We've had a bug where in high load situations we encountered weird errors. Finally we remembered that we were using temporary tables in our application. In the high load situation database connections broke down and were automatically regenerated by the connection object without the application code knowing it (we had implemented the reconnect, but forgot that it was a problem in such a situation). The temporary table we wanted to read had disappeared.


q: I have an application which is supposed to work on both windows and Mac and is localized in Portuguese, Spanish and German. I have an ini file from where the localized strings are read from. But the ini file doesn't work with same encoding for the files on both platforms. For Windows I have to have the file in ANSI format or else the accented letters in the localized strings get messed up and on the Mac the same file should be in Western( Mac OS) encoding or else the same result. Is there any way I can get a single file to work on both platforms?

[A]
(1) There is no such thing as
the
ANSI format. That's an unfortunate term for what on Windows means "the local codepage". In particular, this means that in Europe the interpretation of bytes 128-255 as "ANSI format" will differ between countries. So, I am strongly inclined to argue that it won't even work on your first platform, let alone both.
The solution you will eventually migrate to is Unicode. That works everywhere, with all characters, and the number of a character does not depend on the country or the current date (See introduction of €).


q:
Given a SCHEMA for implementing tags

ITEM
ItemId, ItemContent

TAG
TagId, TagName

ITEM_TAG
ItemId, TagId

What is the best way to limit the number of ITEMS to return when selecting with tags?

SELECT i.ItemContent, t.TagName FROM item i
INNER JOIN ItemTag it ON i.id = it.ItemId
INNER JOIN tag t ON t.id = it.TagId

is of course the easiest way to get them all back, but using a limit clause breaks down, because you get an duplicate of all the items for each tag, which counts toward the number of rows in LIMIT.

[A]
Maybe something like
```
```
select i.ItemContent, t.TagName from (SELECT ItemId, ItemContent FROM item limit 10) i
INNER JOIN ItemTag it ON i.ItemId = it.ItemId --You will miss tagless items here!
INNER JOIN tag t ON t.id = it.TagId
```
```


q:
I changed the MembershipProvider in my ASP.net MVC website, and now the stylesheet for the login page isn't referenced correctly. Below is a copy of the forms tag in my web.config if that could be the reason. It looks identical though to the one generated by a new project with the exception of the name and timeout attribute.

<authentication mode="Forms">
      <forms loginUrl="~/Account/Login" name=".ADAuthCookie" timeout="10" />
</authentication>

When I visit the page now, the link tag for the CSS looks like this:

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

When it should look like this:

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

[A]
I haven't used ASP.NET MVC yet myself, but you could try using
ResolveClientUrl
when writing out the href for your CSS:
```
```
<link href="<%= ResolveClientUrl("../../content/Site.css") %> rel="stylesheet" type="text/css" />
```
```


q:
Having recently discovered this method of development, I'm finding it a rather nice methodology. So, for my first project, I have a small DLL's worth of code (in C#.NET, for what it's worth), and I want to make a set of tests for this code, but I am a bit lost as to how and where to start.

I'm using NUnit, and VS 2008, any tips on what sort of classes to start with, what to write tests for, and any tips on generally how to go about moving code across to test based development would be greatly appreciated.

[A]
See the book
Working Effectively with Legacy Code
by Michael Feathers.
In summary, it's a lot of work to refactor existing code into testable and tested code; Sometimes it's too much work to be practical. It depends on how large the codebase is, and how much the various classes and functions depend upon each other.
Refactoring without tests will introduce changes in behaviour (i.e. bugs). And purists will say it's not really refactoring because of the lack of tests to check that the behaviour doesn't change.
Rather than adding test across the board to your whole application at once, add tests when  you work in an area of code. Most likely you'll have to return to these "hotspots" again.
Add tests from the bottom up: test little, independent classes and functions for correctness.
Add tests from the top down: Test whole subsystems as black boxes to see if their behaviour changes with changes in code. And so you can step through them to find out what's going on. This approach will probably get you the most benefit.
Don't be too concerned at first with what the "correct" behaviour is while you are adding tests, look to detect and avoid changes in behaviour. Large, untested systems often have internal behaviours that may seem incorrect, but that other parts of the system depend on.
Think about isolating dependencies such as database, filesystem, network, so that they can be swapped out for mock data providers during testing.
If the program doesn't have internal interfaces, lines which define the boundary between one subsystem/layer and another, then you may have to try to introduce these, and test at them.
Also, automatic mocking frameworks like
Rhinomocks
or
Moq
might help mock existing classes here. I haven't really found the need for them in code designed for testability.


q:
What is the the best of detecting and later altering the screen resolution and multiple desktop within .net

I have a small app that while runs at work on my multiple monitor/high(ish) resolution however what I want to be able to detect is the users primary monitor and set the application to that (main objective) and adjust the resolution to ensure the application fits(more for my own curiosity)

[A]
I would never suggest altering a user's resolution unless you're doing something like a full-screen game, you can use
```
```
System.Windows.Forms.Screen.PrimaryScreen
```
```
to give you metrics about that main monitor.


q:
This is really only easy to explain with an example, so to remove the intersection of a list from within a dict I usually do something like this:

a = {1:'', 2:'', 3:'', 4:''}
exclusion = [3, 4, 5]

# have to build up a new list or the iteration breaks
toRemove = []
for var in a.iterkeys():
    if var in exclusion:
        toRemove.append(var)

for var in toRemove:
    del a[var]

This might seem like an unusual example, but it's surprising the number of times I've had to do something like this. Doing this with sets would be much nicer, but I clearly want to retain the 'values' for the dict.

This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this.

[A]
Consider
dict.pop
:
```
```
for key in exclusion:
     a.pop(key, None)
```
```
The
```
None
```
keeps pop from raising an exception when
```
key
```
isn't a key.


q:
What is the functional programming approach to convert an IEnumerable<string> to a delimited string?  I know I can use a loop, but I'm trying to wrap my head around functional programming.

Here's my example:

var selectedValues =
from ListItem item in checkboxList.Items
where item.Selected
select item.Value;

var delimitedString = ??

.. or could I do this in just the first var assignment (append each result to the previous)?

[A]
```
```
string.Join(", ", string[] enumerable)
```
```


q: Is there a PHP module that you can use to programmatically read a torrent to find out information about it, Seeders for instance?

[A]
Google comes up with this
PHP client
on sourceforge and
this torrent class
on PHP classes. Should be all you need.


q:
So I want to start using RSpec stories, but I am not sure where writing controller, model and view specs fit in.

For example, you have the story "Logging in" with "User provides wrong password" scenario, don't you end up testing the same stuff than controller/model specs (response.should render..., user.should be_nil, etc.)

So my question is: for those who are used to doing bdd (or story dd) with RoR, do you still write model/controller specs? If so, how is the workflow you follow ("first story, then narrow to specific specs")?

[A]
If you are starting with stories now (as opposed to having a lot of legacy stories) you may want to look at
Cucumber
which is the long term replacement for the RSpec story runner.
The easiest way of splitting between specs and stories is to use stories for full-stack testing of business requirements and specs for isolated low-level specifications of the components (views, helpers, controllers and models). 'Full stack' can a range from controller/model/database through client simulation with Webrat to in-browser testing with Watir or Selenium.
The ultimate 'outside in' BDD way of doing things is to start with stories based on customer requirements and then add in specs for the components you find you need when implementing the stories. Ideally you will fully cover the individual components with specs and have stories for the most important workflows of your users so you can check at the highest level that your app is delivering the functionality you have been asked for.


q:
I have a variable of type Number, and i like to obtain the sign (if is '-' i like to have -1 and if '+' i like to have 1). So, i made this:

var sign = Math.abs(n) / n;

But, there is any other way? Better than this?

[A]
You'll be in trouble if n == 0... how about this:
```
```
var sign = n < 0 ? -1 : 1;
```
```


q: Is there a way to configure a Visual Studio 2005 Web Deployment Project to install an application into a named Application Pool rather than the default app pool for a given web site?

[A]
There is a good article describing custom actions here:
ScottGu's Blog
The question you asked is answered about halfway through the comments by 'Ryan', unfortunately it's in VB, but it shouldn't be hard to translate:
```
```
Private Sub assignApplicationPool(ByVal WebSite As String, ByVal Vdir As String, ByVal appPool As String)
   Try
     Dim IISVdir As New DirectoryEntry(String.Format("IIS://{0}/W3SVC/1/Root/{1}", WebSite, Vdir))
     IISVdir.Properties.Item("AppPoolId").Item(0) = appPool
     IISVdir.CommitChanges()
   Catch ex As Exception
     Throw ex
   End Try
 End Sub

 Private strServer As String = "localhost"
 Private strRootSubPath As String = "/W3SVC/1/Root"
 Private strSchema As String = "IIsWebVirtualDir"
 Public Overrides Sub Install(ByVal stateSaver As IDictionary)
   MyBase.Install(stateSaver)
   Try
     Dim webAppName As String = MyBase.Context.Parameters.Item("TARGETVDIR").ToString
     Dim vdirName As String = MyBase.Context.Parameters.Item("COMMONVDIR").ToString
     Me.assignApplicationPool(Me.strServer, MyBase.Context.Parameters.Item("TARGETVDIR").ToString, MyBase.Context.Parameters.Item("APPPOOL").ToString)
   Catch ex As Exception
     Throw ex
   End Try
 End Sub
```
```
...Where APPPOOL is supplied as an argument in the Custom Action.


q:
rsync -auve ssh --backup --suffix='2008-10-03-1514539' --backup-dir='/tmp/' module.pm root@web1:/path/to/module.pm

I run this command without the --backup-dir option and when it copies the file over, it creates a backup with a current timestamp. When I include the --backup-dir option, it makes the backup into the /tmp/ directory but never attaches my suffix.

There is nothing in the manual to suggest that you can't use both these options together. I've played around with the order also and nothing seems to fix it.

Does anyone have a solution to this?

[A]
the manual says:
--backup                make backups (see --suffix & --backup-dir)
--backup-dir=DIR        make backups into hierarchy based in DIR
--suffix=SUFFIX         backup suffix (default ~ w/o --backup-dir)
so it seems that you can use one or the other, not both (as I guess you want a way to determine what's a backup you use a suffix or a directory).
As a way to fix this, why don't you keep the suffix and modify the destination to include the backup directory.


q:
How do I stop a function/procedure in a superclass from been overridden in a subclass in Delphi (2007)?

I want to mark it so it can not be altered, I believe there is a final keyword but can not for the life of me find the documentation for it, so I am not 100% sure that's what I need.

[A]
The keyword is
```
final
```
as you thought. See
http://dn.codegear.com/article/34324
and
http://blogs.teamb.com/rudyvelthuis/2005/05/13/4311
. Also you can mark your class as sealed to prevent anyone from inheriting from it. You need a Delphi version higher than 7.
```
```
type
  TSomeClass = class
  protected
    procedure SomeVirtualMethod; virtual;
  end;

  TOtherClass = class(TSomeClass)
  protected
    procedure SomeVirtualMethod; override; final;
  end;
```
```


q:
Is there a better way to watch for new entries in a table besides selecting from it every n ticks of time or something like that?

I have a table that an external program updates very often, and clients can watch for this new data as it arrive, how can I make that without having to set a fixed period of repeatable select statements?

[A]
Here's what I do:
I've got some triggers set up for the table (insert, delete, update) and those triggers increment a counter in another table.  My DB access code keeps a local counter and compares it to the returned value, ultimately sending a bool back to the caller, answering the question IsDataCurrent().
Our programs that use this DB access code either poll or check it on-request and then make the appropriate calls to keep themselves up to date.
I'm sure there are other ways to solve this.  It worked for me pretty well, though.


q: If two users are accessing same database table, how do we prevent users from overwriting each other’s data?

[A]
There is no straightforward way to do that. You could use transactions to make sure that updates are resolved correctly (i.e. that you do not get partial updates) but you would probably lose the first set of changes as it will be overwritten by the second.
Two options you probably have are:
implement some locking mechanism on the application level (i.e. when someone start editing a record put some flag somewhere which would prevent another user from doing the same)
implement version control so each time someone writes to the database a
new
record is created. This way both sets of data will be in the database and you could have a logic in your application to merge them or select the one you like


q:
I have a https link that requires user login & password. If I run it in FX like this:
https://usernameassword@www.example.com/link/sublink

it will return the xml data as expected.

However, what i'm trying to do, is to automate this process.
I try to use file_get_contents() in PHP.

I even tried to use AJAX, but still doesn't work.

I tried to get the content (XML) either in Server or in the front-end (ajax), but both don't work.

Does anyone know what I need to go in order to get the content? Do I need to obtain the SSL certificate?

Solution in any ohter languages will be welcome too.


q:
In my Winforms application, I want to export the data from my DataGridView to a Excel spreadsheet.

Is it simply a job of looping and outputting the results comma seperated?

[A]
Is it simply a job of looping and outputing the results comma seperated?
Yes. It is a simpler way without any dependencies.
If you need more control, you can always automate excel from
vb.net
or from
C#
..


q: I'm trying to achieve the last possible time of a particular day eg for Date of 2008-01-23 00:00:00.000 i would need 2008-01-23 23:59:59.999 perhaps by using the dateadd function on the Date field?

[A]
```
```
SELECT DATEADD(ms, -2, DATEADD(dd, 1, DATEDIFF(dd, 0, GetDate())))
```
```
I thought you had c# at first.. I will leave this here in case anyone else stumbles across this.
```
```
DateTime now = DateTime.Now;
DateTime endofDay = now.Date.AddDays(1).AddMilliseconds(-1);
```
```
You can replace the 'now' variable with whatever day you are trying to figure out


q:
I just want to see what files were modded/added/deleted between 2 arbitrary revisions. How do I do this?

Can I do this in tortoise as well?

[A]
```
```
svn log -v -rX:Y .
```
```
The -v for "verbose" switch will give you detailed output on which files were affected on that revision.
Note that "." assumes you are currently in a working copy directory, but you can also use a URL such as "
http://svn.myawesomesoftwareproject.com/trunk/lib/foo.c
".
This information can be found by typing "svn help log", or by reading the
SVN Book
, available free online.  Don't forget to
R
ead
T
he
F
riendly
M
anual!


q:
I have a "Date of Birth" field, and trying to use the timespan() method to get the age in years. But returns "28 Years, 2 Months, 2 Weeks, 3 Days, 15 Hours, 16 Minutes".

Any idea how I can just get the "28 Years" portion?

[A]
There are many ways to do this, with the string in $date, like so:
```
```
$date = '28 Years, 2 Months, 2 Weeks, 3 Days, 15 Hours, 16 Minutes';
```
```
This will give you "28 Years"
```
```
$yearsPart = substr($date, 0, strpos($date, 'Years') + 5);
```
```
So will this:
```
```
$parts = split(', ', $date);
$yearsPart = $parts[0];
```
```


q:
We are migrationg from CVS to SVN and embracing some kind of revision management in order to enforce order to development/testing/release cycle. We are currently testing, developing and releasing on the same code line, we know its a bad practice and we want to make end to it.

What are your experience, know how, suggestions working with source code tree.

We are building small/average (2-5 months) custom projects and we have to give early access to customer for review. Requirement creep is common.

EDIT:
please note, i need not only advice on subversion, but more on how whole devel/test/deploy cycle is reflected in trunk/branches/tags/versions etc

[A]
"Branch early, branch often."
All builds should be completely reproducible without having to pour through logs (consider tagging every build)
If you use an issue tracker then require all check-ins to have a (valid) issue ID included in the commit message (add a pre-hook to check this).
Only the build team should be allowed to make production branches (developers should be encouraged to make personal branches for any non-trivial task)
Build continuously and ensure that everyone is aware that breaking the build is a big deal.
Read the whole SVN book, then read it again. You need to know this tool backwards and forwards. Hold training sessions for your developers ("how to create a temporary branch for my work", "how to merge", etc).
... There is an lack of good reading on this subject, but if I had to recommend one book to a shop completely green in SCM it would be "The Build Master" by Vincent Maraia. It's very short on details but easy to read and provides a (very very brief) overview of SCM good-ideas that make great sense once you know them but which for some reason so many shops completely lack.
Good luck!


q:
On POSIX systems rename(2) provides for an atomic rename operation, including overwriting of the destination file if it exists and if permissions allow.

Is there any way to get the same semantics on Windows? I know about MoveFileTransacted() on Vista and Server 2008, but I need this to support Win2k and up.

The key word here is atomic... the solution must not be able to fail in any way that leaves the operation in an inconsistent state.

I've seen a lot of people say this is impossible on win32, but I ask you, is it really?

Please provide reliable citations if possible.

[A]
you still have the rename() call on Windows, though I imagine the guarantees you want cannot be made without knowing the filesystem you're using - no guarantees if you're using FAT for instance.
However, you can use MoveFileEx and use the MOVEFILE_REPLACE_EXISTING
 and MOVEFILE_WRITE_THROUGH options. The latter has this description in MSDN:
Setting this value guarantees that a
  move performed as a copy and delete
  operation is flushed to disk before
  the function returns. The flush occurs
  at the end of the copy operation.
I know that's not necessarily the same as a rename operation, but I think it might be the best guarantee you'll get - if it does that for a file move, it should for a simpler rename.


q:
Hi I want to have two tables each have an INT "id" column which will auto-increment but I don't want either "id" columns to ever share the same number. What is this called and what's the best way to do it? Sequence? Iterator? Index? Incrementor?

Motivation: we're migrating from one schema to a another and have a web-page that reads both tables and shows the (int) ID, but I can't have the same ID used for both tables.

I'm using SQL Server 9.0.3068.

Thanks!

[A]
I think using a
GUID
would be the most straightforward way, if I understand you correctly.
```
```
SELECT NEWID()
```
```


q:
What's the best way to go about creating a vertical and horizontal ruler bars in an SDI app?  Would you make it part of the frame or the view?  Derive it from CControlBar, or is there a better method?

The vertical ruler must also be docked to a pane and not the frame.

To make it a little clearer as to what I'm after, imagine the vertical ruler in the Dialog Editor in Visual Studio (MFC only). It gets repositioned whenever the tree view is resized.

[A]
I would
not
use control bars. I have no good reason other then (IMOHO) are difficult to get to do what you want - if what you want if something other than a docking toolbar.
I would just draw them directly on the View window using GDI calls.
I guess I
might
think about making each ruler its own window, and draw the rulers on their own window. I would then create these two CWnd derived classes in the view and position as child windows. This is good if you want to interact with the mouse on these rulers (easier to sort out what messages are for the rulers).


q:
Example

G76 I0.4779 J270 K7 C90

X20 Y30

If a number begins with I J K C X Y and it doesn't have a decimal then add decimal.
Above example should look like:

G76 I0.4779 J270 K7. C90.

X20. Y30.

Purpose of this code is to convert CNC code for an older Fanuc OPC controller

[A]
```
```
```
Set RegEx = New RegExp
RegEx.Global = True
RegEx.Pattern = "([IJKCXY]\d+)([^\.]|$)"
newVar = RegEx.Replace (oldString, "$1.$2")
```
```
```
Where oldString is the original string, and newVar is the string with the decimals added.


q:
I've evaluated some plugins from official IntelliJ repository, but none of them seems to provide more then basic syntax highlighting. Even highlighting is limited. For example, Database Navigator doesn't highlight IF. It would be great to have proper highlighting. And if it would have auto-complete feature and provide file structure view I would be completely happy.
I use SQL Query Plugin when I need to post some little stuff to database or to query something from it. I use PL/SQL Developer when I need to make more complex things, or when I need to modify PL/SQL. But most of the time I need to navigate through mix of Java, JavaScript and PL/SQL code. Unfortunately, SQL Query Plugin doesn't help with that as well as PL/SQL Developer.

[A]
Have you tried
SQL Query Plugin
? It comes with a great host of features, including multiple query windows, direct editing of tables, and of course, proper highlighting for PL/SQL syntax and a browser of the internal database structure.
It also integrates well with the main editor: you can right-click on any selected Java string containing SQL and "Send to SQLPlugin" to strip out all of the quotes and non-SQL syntax.


q:
I'm exploring the XML -> XSLT -> HTML meme for producing web content. I have very little XSLT experience.

I'm curious what mechanisms are available in XSLT to handle abstractions or "refactoring".

For example, with generic HTML and a service side include, many pages can be templated and decomposed to where there are, say, common header, nav, and footer segments, and the page itself is basically the body.

The common markup languages, JSP, PHP, ASP, go as far as to allow all of those segments to have dynamic content (such as adding the user name to every header block).

JSP goes even farther by allowing you to create Tag files, which can accept arguments to be used when generating the content, and even surround and work on content within the tags themselves.

I'm curious similar functionality is done within XSLT.  What facilities are there to make reusable block of XSLT for things like creating HTML pages?

[A]
Templates, Includes.
Xsl is very different from any other programming language.
```
Its rule based.
```
I recommend you to read
something
about Xslt and then ask a bit more spedific.


q:
In Oracle, given a simple data table:

create table data (
    id       VARCHAR2(255),
    key      VARCHAR2(255),
    value    VARCHAR2(511));

suppose I want to "insert or update" a value. I have something like:

merge into data using dual on
    (id='someid' and key='testKey')
when matched then
    update set value = 'someValue'
when not matched then
    insert (id, key, value) values ('someid', 'testKey', 'someValue');

Is there a better way than this? This command seems to have the following drawbacks:

Every literal needs to be typed twice (or added twice via parameter setting)

The "using dual" syntax seems hacky

If this is the best way, is there any way around having to set each parameter twice in JDBC?

[A]
I would hide the MERGE inside a PL/SQL API and then call that via JDBC:
```
```
data_pkg.merge_data ('someid', 'testKey', 'someValue');
```
```
As an alternative to MERGE, the API could do:
```
```
begin
   insert into data (...) values (...);
exception
   when dup_val_on_index then
      update data
      set ...
      where ...;
end;
```
```


q:
Is it possible to have a HasMany relationship of a basic type such as String, on an ActiveRecord class, without the need for creating another entity such as (TodoListItem) to hold the value.

[ActiveRecord]
public class TodoList
{

  [PrimaryKey]
  public int Id
  {
    get { return _id; }
    set { _id = value; }
  }

  [HasMany(typeof(string)]
  public IList<string> Items
  {
    get { return _items; }
    set { _items= value; }
  }
}

Can anyone help?

[A]
In ActiveRecord, your types map to a record in a table (by default).  It seems like you are confusing how this type should map to your table.
The MyClass type should have a definition something like this (excluding the PK settings):
```
```
[ActiveRecord(Table = "MyTable")]
public class MyClass : ActiveRecordBase<MyClass>
{
    [Property]
    public int Id { get; set; }

    [Property]
    public int MyClassId { get; set; }

    [Property]
    public string ListItem { get; set; }
}
```
```
Then, to load the list:
```
```
public void LoadMyClasses()
{
    MyClass[] results = MyClass.FindAll();
}
```
```
I'd suggest you spend some time with the
ActiveRecord documentation
(or
tutorial
) as that should also help clear up any confusion.


q:
If I spawn a new thread, and then within it I push a new controller onto my UINavigationController, using code like this...

(a) not working

-(void)myCallbackInThread
{
    // move on...
    UIApplication* app = [UIApplication sharedApplication];
    [app changeView];
}

then I find that the view appears, but does not respond to user input.

If I change the code like this

(b) working

-(void)myCallbackInThread
{
    // move on...
    UIApplication* app = [UIApplication sharedApplication];
    [app performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE];
}

Then everything works just fine.

Any hints as to why?

[A]
Just found this in the iPhone threading docs
If your application has a graphical
  user interface, it is recommended that
  you receive user-related events and
  initiate interface updates from your
  application’s main thread. This
  approach helps avoid synchronization
  issues associated with handling user
  events and drawing window content.
  Some frameworks, such as Cocoa,
  generally require this behavior, but
  it also has the advantage of
  simplifying the logic for managing
  your user interface.
I still don't see what would actually cause something to display but not be able to receive user input, but I'll follow that guideline in future.


q: How do I in SQL Server 2005 use the DateAdd function to add a day to a date

[A]
```
```
DECLARE @MyDate datetime

-- ... set your datetime's initial value ...'

DATEADD(d, 1, @MyDate)
```
```


q:
I have a GridView where one column is bound to an object property containing a nullable integer. I set SortExpression to the name of the property, and sorting works perfectly as long as all rows contain a value. If any rows contain null, however, I get an exception:

System.InvalidOperationException : Failed to compare two elements in the array. Object reference not set to an instance of an object.

How do I customize the sorting or comparison logic to handle the null case?

[A]
The Nullable type exposes a comparison method for comparing nullable types, so the solution is to override the gridview sorting logic and manually specify a comparison:
```
```
gridview.Sorting += new GridViewSortEventHandler(gridView_Sorting);

protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
    // Only add custom handling for the sort expression on the
    // Nullable<int> column
    if (e.SortExpression == "MySortExpression")
    {
        // Convert datasource to a List<T>
        list.Sort(new Comparison<MyObjectType>(delegate(MyObjectType item1, MyObjectType item2)
        {
            return Nullable.Compare<int>(item1.NullableIntProp, item2.NullableIntProp);
        }));

        // Bind the sorted list back to the gridview
    }
    else
    {
        // delegate to the gridview to handle its own sorting
    }
}
```
```


q: We have some raw voice audio that we need to distribute over the internet. We need decent quality, but it doesn't need to be of musical quality. Our main concern is usability by the consumer (i.e. what and where they can play it) and size of the download. My experience has shown that mp3s do not produce the best compression numbers for voice audio, but I am at a loss for what the best alternatives are. Ultimately we would like to automate the conversion process to allow the consumer to choose the quality vs. size level that they would like.

[A] Assuming your users will be running Windows, there is a WMA speech compression codec that you can use with the Windows Media Encoder SDK. Failing that, you can use ACM to use something like G723/G728, ADPCM, mu-law or a-law, some of which are installed as standard on Windows XP & above. These can be packaged inside WAV files. You'll need to experiment a little to find the right bitrate/quality (probably don't bother with mu-law or a-law). With voice data you can get away with quite low sample rates - e.g. 16000 or 8000, as there isn't much above 4Khz in the human spoken voice.


q: I'm  trying to create a table with two columns comprising the primary key in MySQL, but I can't figure out the syntax.  I understand single-column PKs, but the syntax isn't the same to create a primary key with two columns.

[A]
Example:
```
```
CREATE TABLE `synthesis`.`INV_MasterItemList` (
   `MasterItemList_ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
   `Customer_ID` INTEGER UNSIGNED NOT NULL,
   `Model_ID` INTEGER UNSIGNED NOT NULL,
   `Serial` VARCHAR(45) NOT NULL,
   PRIMARY KEY (`MasterItemList_ID`),
   UNIQUE INDEX `INDEX_UNIQUE`(`Customer_ID`, `Model_ID`, `Serial`)
 )
```
```


q:
I can't seem to get my application up and running on my dev server and I'm not sure why.

I have compiled my code in VS 2008 with a target framework of 3.5.  I am using 3.5 mainly because I have implemented LINQ rather extensively.  Compiling and runs local without any problems.

The hang up is that my server only has the 2.0 .Net framework and upgrading to 3.5 is apparently not going to happen.

I was under the impression after doing some research that as long as I was trying to execute compiled code the server would not need 3.5 installed.

Today I am trying to publish to the server and I can't get past this error in my WEB.CONFIG

Configuration Error

Parser Error Message: Child nodes not allowed.

providerOption name="CompilerVersion" value="v3.5"/

EDIT ADD ON QUESTION:
I have seen some posts about possibly setting my references to "copy local" which might allow me to run on the 2.0 server.  Thoughts?

[A]
You're not going to be able to run code targetted to 3.5 on the server unless you get 3.5 installed on it.
The problem isn't your code, rather that the required libraries will be missing.


q:
Recently I was working with generating a PDF from Crystal Reports through a webform.  It was failing, which I determined to be caused by the permissions settings on the c:\windows\temp dir.   I gave the Network Service account full access to this folder, which promptly fixed the issue.   But is there a reason the Network Service account didn't have these permissions by default?

Rick Strahl asks this question here.  It sounds like there shouldn't be any issues with doing this, but Rick wasn't clear on why the default is set that way.

Web Server is Windows Server 2003

[A]
These days, the default option will tend to be the more secure one.  I don't think there's any other reason.
I've had the same issue as you, and in my environment just gave the permission and moved on.
This post
suggests it is the fault of Crystal Reports, which is explicitly referencing %WINDIR%\Temp instead of using an API such as Path.GetTempPath().  In fact I have seen Path.GetTempPath() return %WINDIR%\Temp when running under the Network Service account on Windows 2003.


q:
I am building an application using Spring MVC. I want to make certain changes to my Model for every Controller in the application. In particular, I want to insert certain extra data into the model which will be present for all pages of the application.

I could do this several ways: just add the data at the end of every Controller, use a subclass of Model that adds my extra data, use a subclass of ModelAndView that wraps my Model, use a subclass of VelocityView that wraps the Model before using it... I'm sure there are other options.

But I have an "elegance" constraint: I don't want to write code in each and every Controller, I want this behavior defined in one-and-only-one place. Ideally, it would be controlled by my IOC bean config file.

Does anyone have a recommendation of how to achieve this elegantly?

[A]
You could take a look at using Aspects.  Spring even has an
AOP
extension that you could use.
In brief an aspect would allow you to define code once that would then get "woven" into your classes either when you compile the classes or when they are loaded by the classloader.  It's relatively advanced stuff and isn't the most intuitive thing for new programmers to pick up, but it's intended to solve exactly the problem you're referring to.


q:
Let's say I 've added a library foo.so.1.1.1 to a path that is included in /etc/ld.so.conf
When I run ldconfig on the system I get the links foo.so.1.1 and foo.so.1 to foo.so.1.1.1

How can I change the behavior to also get the foo.so link to foo.so.1.1.1?

[A]
Just make the symlink yourself:
```
```
ln -s /usr/lib/foo.so.1.1.1 /usr/lib/foo.so
```
```
Note that for applications to use libraries in this manner, they need to be explicitly linked against the unversioned shared object.  IE: this is a mechanism to bypass the dynamic loader's version matching system completely.


q: How do I write the SQL code to INSERT (or UPDATE) an array of values (with probably an attendant array of fieldnames, or with a matrix with them both) without simple iteration?

[A]
I construct the list as an xml string and pass it to the stored procs. In SQL 2005, it has enhanced xml functionalities to parse the xml and do a bulk insert.
check this post:
Passing lists to SQL Server 2005 with XML Parameters


q:
I recently began profiling an osgi java application that I am writing using VisualVM.  One thing I have noticed is that when the application starts sending data to a client (over JMS), the number of loaded classes starts increasing at a steady rate.  The Heap size and the PermGen size remains constant, however.  The number of classes never falls, even after it stops sending data. Is this a memory leak?  I think it is, because the loaded classes have to be stored somewhere, however the heap and permgen never increase even after I run the application for several hours.

For the screenshot of my profiling application go here

[A]
Yes, it's usually a memory leak (since we don't really deal with memory directly, it's more of a class instance leak).  I've gone through this process before and usually it's some listener added to an old toolkit that didn't remove it self.
In older code, A listener relationship causes the "listener" object to remain around.  I'd look at older toolkits or ones that haven't been through many revs.  Any long-existing library running on a later JDK would know about reference objects which removes the requirement for "Remove Listener".
Also, call dispose on your windows if you recreate them each time.  I don't think they ever go away if you don't (Actually there is also a dispose on close setting).
Don't worry about Swing or JDK listeners, they should all use references so you should be okay.


q:
As a programmer I found it very hard to use my laptop and workstation with two different input devices, Can anyone suggest a good solution to use single mouse and keyboard to control my two machines

I am not looking for a Virtual Machine or RDP solution to see my machines in a single monitor,

[A]
Synergy.
Synergy lets you easily share a single mouse and keyboard between
  multiple computers with different
  operating systems, each with its own
  display, without special hardware.
  It's intended for users with multiple
  computers on their desk since each
  system uses its own monitor(s).
  Redirecting the mouse and keyboard is
  as simple as moving the mouse off the
  edge of your screen. Synergy also
  merges the clipboards of all the
  systems into one, allowing
  cut-and-paste between systems.
  Furthermore, it synchronizes screen
  savers so they all start and stop
  together and, if screen locking is
  enabled, only one screen requires a
  password to unlock them all.
P. S.
See also
how to fix Synergy problems on Vista
.


q:
I have created a user control to handle adding comments to certain business entities, like contacts and customers.  Works great ... except for one issue.

I am using a ListView control to edit and delete comments, and a separate area, on the same user control to add a new comment.  All of this is wrapped in an UpdatePanel.

Here is my scenario ... the user adds a new comment ... the page does a postback, the data is successfully saved, and the ListView control is updated to show the new comment.  Now, if the user refreshes the browser, it will naturally postback again and will add another duplicate record.

Any ideas on how best to prevent this?

[A]
I haven't used ASP.NET in a few years, but you should wrap your "do this on postback" code in
```
Page.IsPostBack
```
:
```
```
if(IsPostBack) {
    //do your data-saving code...
}
```
```
MSDN link


q: I'm specifically thinking about the BugMeNot service, which provides user name and password combos to a good number of sites. Now, I realize that pay-for-content sites might be worried about this (and I would suspect that most watch for shared accounts), but how about other sites? Should administrators be on the lookout for these accounts? Should web developers do anything differently to take them into account (and perhaps prevent their use)?

[A]
Not make registration mandatory to read something? i.e. Ask people to register when you are providing some functionality for them that 'saves' some settings, data, etc. I would imagine site like stackoverflow gets less fake registrations (reading questions doesn't require an account) than say New York Times, where you need to have an account to read articles.
If that is not upto your control, you may consider removing dormant accounts. i.e. Removing accounts after a certain amount of inactivity.


q:
I need to do some communications over a serial port in Ruby.  From my research, it appears that there aren't many modern libraries for serial communications and the newest material I can find is from 2006.  Are there any gems that I'm not aware of?

I ultimately need to maintain communications with a serial device attached to USB (I can figure out the port no problem) for back and forth communications like so (somewhat Ruby-esque pseudo code).

def serial_write_read
  if serial.read == "READY"
    serial.write "1"
    until serial.read == "OK"
      serial.write "5"
    end
    return when serial.read == "DONE"
  end
end

[A]
The serial port specification has not changed in forever, I wouldn't worry about how old the libraries are.
I'm assuming you saw
this
article from 2006 about ruby and serial ports
Here's
someone who got the
Ruby-SerialPort
library mentioned there to work on macs this year.
There's also
this old post
from ruby talk, about interfacing to the Win32 Serial API.


q:
One of the vagaries of my development system (Codegear C++Builder) is that some of the auto-generated headers insist on having...

using namespace xyzzy

...statements in them, which impact on my code when I least want or expect it.

Is there a way I can somehow cancel/override a previous "using" statement to avoid this.

Maybe...

unusing namespace xyzzy;

[A]
No you can't
unuse
a namespace. The only thing you can do is putting the
```
using namespace
```
-statement a block to limit it's scope.
Example:
```
```
{
    using namespace xyzzy;

} // stop using namespace xyzzy here
```
```
Maybe you can change the template which is used of your auto-generated headers.


q:
I need to be able to GZip compress a file in an Excel VBA function. Specifically I need to be able to use the 'deflate' algorithm.

Is there a way to do this without having to exec a command line application? With no dependency on external tools the code will be more robust.

Ideally the code would make use of pre-installed VBA or COM library functions - I don't want to have to implement this logic myself or install DLLs etc.

If possible, I want installation of the function to be as simple as adding a .xla to the available Excel Add-Ins. No DLLs, EXEs, registry entries etc. required.

Edit Can I make use of the .NET GZipStream to do this?

[A]
If you want to implement the algorithm in VBA, you would need to (in VBA) save the spreadsheet and then use VB's I/O functions to open the file, deflate it, and save it again. For all intents and purposes it's identical to writing an ordinary VB application that works on a file. You might need to put the VBA macro in a separate workbook to avoid "file in use" types of errors, but if you reopen the file as read-only and save it with a different filename you should be OK keeping everything in one workbook.
But I'm almost certain that shelling out to gzip from within the VBA would be functionally identical and infinitely easier.
EDIT:
Some code. It didn't fail when I ran it, so it's OK to keep everything in the same workbook.
```
```
Sub main()
    ActiveWorkbook.Save
    Open "macrotest.xls" For Binary Access Read As #1
    Open "newfile.zip" For Binary Access Write As #2
        'do your stuff here
    Close #2
    Close #1
End Sub
```
```


q:
I have a few questions about optimizing this type of load.

One builds a new table of data to be loaded into a partitioned table and then builds the indexes on this new table.

Should you build the index with the COMPUTE STATISTICS option or use the Cascade option of the DBMS_Stats?

Should you gather stats on the table before the swap or on the partition after the swap?

If you do it after the swap and you specify the partition name in the parameter list, what interplay does the granularity parameter have? For instance, if I specify a partition name and then set granularity to 'GLOBAL AND PARTITION' does that do Global at all? Does it do just that one partition?

[A]
```
DBMS_STATS
```
is considered the proper way to calculate statistics for this version. Building the index with the
```
COMPUTE STATISTICS
```
is doable, but usually you want to calculate all your stats at one time and take snapshots.
You want to gather stats after the swap. This way the optimizer will make the best guess for executing queries using that partitions' data.
Why would you put both?


q:
So I build an array of various dates. Birthdays, anniversaries, and holidays. I'd like to order the array by which one is happening next, essentially sort October to September (wrapping to next year)

so if my array is

$a = ([0]=>"1980-04-14", [1]=>"2007-06-08",
  [2]=>"2008-12-25", [3]=>"1978-11-03")

I'd like to sort it so it is arranged

$a = ([0]=>"1978-11-03", [1]=>"2008-12-25",
  [2]=>"1980-04-14", [3]=>"2007-06-08")

because the november 'event' is the one that will happen next (based on it being october right now).

I'm trying usort where my cmp function is

function cmp($a, $b)
{
  $a_tmp = split("-", $a);
  $b_tmp = split("-", $b);
  return strcmp($a_tmp[1], $b_tmp[1]);
}

I am not sure how to modify this to get my desired effect.

[A]
Don't compare strings, instead use seconds since 1970 (ints):
```
```
$date1 = split("-", $a);
$date2 = split("-", $b);
$seconds1 = mktime(0,0,0,$date1[1],$date1[2],$date1[0]);
$seconds2 = mktime(0,0,0,$date2[1],$date2[2],$date2[0]);
// eliminate years
$seconds1 %= 31536000;
$seconds2 %= 31536000;
return $seconds1 - $seconds2;
```
```
Also I don't know PHP but I think the gist is correct.
Edit: The comparison function is encapsulated to perform comparison, nothing more.  To order a list in regards to the original question sort an array with today's date included, locate today's date in the array, and then move the elements before that position to the end in ascending order by position.


q:
I am developing a small web app project (ColdFusion) and I am trying to keep my project split into multiple files during development, but deploy just one file on completion.

I have references to external files, for instance:

<script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
<link type="text/css" rel="stylesheet" href="project.css" />

And when I build my project, I want to have the files included and embedded within the single finished product file.

<script type="text/javascript">eval(function(p,a,c,k,e,r) [...]</script>
<style type="text/css">div{font:normal;} [...]</style>

Anyway, it doesn't look like there is a basic way for Ant to do this. Anyone know?

[A]
Does this do what you want?
```
```
<property
    name="filename"
    value="jquery-1.2.6.pack.js"
/>

<loadfile
    property="contents"
    srcfile="${filename}"
/>

<replace dir=".">
    <include name="index.cfm"/>
    <replacetoken><![CDATA[<script type="text/javascript" src="${filename}"></script>]]></replacetoken>
    <replacevalue><![CDATA[<script type="text/javascript">${contents}</script>]]></replacevalue>
</replace>
```
```


q:
Does any one know how can I convert a BSTR to an int in VC++ 2008

Thanks in advance.

[A]
Google suggests
```
VarI4FromStr
```
:
```
```
HRESULT VarI4FromStr(
  _In_   LPCOLESTR strIn,
  _In_   LCID lcid,
  _In_   ULONG dwFlags,
  _Out_  LONG *plOut
);
```
```


q:
I'm currently writing a website that allows people to download Excel and text files. Is there a way to redirect to a different page when they click, so that we run javascript and do analytics (i.e. keep download count)? Currently, nothing prevents the user from simply right-clicking and saving.

Edit:

To be more specific, it would be nice for a single or double click of a file link to redirect to a temporary download page for analytics, then have the file be downloaded.

[A]
I'm not sure what you are asking here, are you trying to figure out how to redirect in the controller or are you trying to override the right-click behavior in the browser?
To redirect in the controller you can do something like this documented
here
.
```
```
redirect(controller:"book",action:"list")
```
```
If you are trying to change button or link behavior that's client side and will require some Javascript most likely.
If you clarify I might be able to help more.


q: I'm planning to build a USB device that has buttons that some software needs to respond to, and indicators that the software needs to control. I'm new to USB, so I'm looking for any pointers that will get me started.

[A]
When I did some USB development a while ago, I found the information at
USB Central
extremely valuable.
For low bandwidth requirements, you can use something like the
FT232R
which is a single-chip USB serial implementation. The FTDI drivers are readily available and make the device appear as a regular serial port to the host computer. This is orders of magnitude easier than rolling your own USB implementation (for either end!).


q: I am looking for instructions on how to setup a PEAR channel for our project so that we can deploy it with the pear installer. I have searched the web for a while and cannot find any straightforward information. I followed this tutorial for a while, but I am having a hell of a time getting this to work. Does anyone know how to do this? Is there a simpler way?

[A]
It looks like you are one of the few people who want to do this. That tutorial you linked to appears to be the latest (!) but the package is still
somewhat in development
. The documentation in that package is also non-existent. It looks like it's up to you to write the docs. Or maybe contact
Greg Beaver
; the author of the package and blog post you linked to. He also
wrote a book about PEAR
(albeit in 2006.) The amazon writeup mentions this:
Next, you will learn how to set up
  your own PEAR Channel for distributing
  PHP applications, both open-source and
  proprietary closed-source PHP
  applications that can be secured using
  technology already built into the PEAR
  Installer
.


q:
I've been trying to get up to speed on some of the newer features in C# and one of them that I haven't had occasion to use is anonymous types.

I understand the usage as it pertains to LINQ queries and I looked at this SO post which asked a similar question.  Most of the examples I've seen on the net are related to LINQ queries, which is cool.  I saw some somewhat contrived examples too but not really anything where I saw a lot of value.

Do you have a novel use for anonymous types where you think it really provides you some utility?

[A]
The biggest use for anonymous types is LINQ, in fact that's why it was created.
I guess one reason for an anonymous type outside of linq is to create a temporary struct-like object, e.g.:
```
```
var x = new { a = 1, b = 2 };
```
```
That may make your life a little easier in some situations.


q:
Can someone provide a regular expression for parsing name/value pairs from a string?  The pairs are separated by commas, and the value can optionally be enclosed in quotes.  For example:

AssemblyName=foo.dll,ClassName="SomeClass",Parameters="Some,Parameters"

[A]
No escape:
```
```
/([^=,]*)=("[^"]*"|[^,"]*)/
```
```
Double quote escape for both key and value:
```
```
/((?:"[^"]*"|[^=,])*)=((?:"[^"]*"|[^=,])*)/

key=value,"key with "" in it"="value with "" in it",key=value" "with" "spaces
```
```
Backslash string escape:
```
```
/([^=,]*)=("(?:\\.|[^"\\]+)*"|[^,"]*)/

key=value,key="value",key="val\"ue"
```
```
Full backslash escape:
```
```
/((?:\\.|[^=,]+)*)=("(?:\\.|[^"\\]+)*"|(?:\\.|[^,"\\]+)*)/

key=value,key="value",key="val\"ue",ke\,y=val\,ue
```
```
Edit:
Added escaping alternatives.
Edit2:
Added another escaping alternative.
You would have to clean up the keys/values by removing any escape-characters and surrounding quotes.


q:
I have a webpage that pulls information from a database, converts it to .csv format, and writes the file to the HTTPResponse.

string csv = GetCSV();
Response.Clear();
Response.ContentType = "text/csv";
Response.Write(csv);

This works fine, and the file is sent to the client with no problems.  However, when the file is sent to the client, the name of the current page is used, instead of a more friendly name (like "data.csv").

My question is, how can I change the name of the file that is written to the output stream without writing the file to disk and redirecting the client to the file's url?

EDIT:  Thanks for the responses guys.  I got 4 of the same response, so I just chose the first one as the answer.

[A]
I believe this will work for you.
```
```
Response.AddHeader("content-disposition", "attachment; filename=NewFileName.csv");
```
```


q: In a recent project the "lead" developer designed a database schema where "larger" tables would be split across two separate databases with a view on the main database which would union the two separate database-tables together.  The main database is what the application was driven off of so these tables looked and felt like ordinary tables (except some quirky things around updating).  This seemed like a HUGE performance problem.  We do see problems with performance around these tables but nothing to make him change his mind about his design.  Just wondering what is the best way to do this, or if it is even worth doing?

[A]
Which version of SQL Server are you using? SQL Server 2005 has partitioned tables, but in 2000 (or 7.0) you needed to use partition views.
Also, what was the reasoning for putting the table partitions in a separate database?
When I've had to partition tables in the past (pre-2005), it's usually by a date column or something similar, with a view over the various partitions. Books Online has a section that talks about how to do this and all of the rules around it. You need to follow the  rules to make it work how it's supposed to work.
The key thing to remember is that your partitioning column must be part of the primary key and you want to try to always use that column in any access against the table so that the optimizer can ignore partitions that shouldn't be affected by the query.
Look up "partitioned table" in MSDN and you should be able to find a more complete tutorial for SQL Server 2005 partitioned tables as well as advice on how to set them up for maximum performance.


q:
I find that quite often Visual Studio memory usage will average ~150-300 MB of RAM.

As a developer who very often needs to run with multiple instances of Visual Studio open, are there any performance tricks to optimize the amount of memory that VS uses?

I am running VS 2005 with one add-in (TFS)

[A]
From
this blog post
:
[...]
These changes are all available from the Options dialog (Tools –> Options):
Environment
General
:
Disable “Animate environment tools”
Documents
:
Disable “Detect when file is changed outside the environment”
Keyboard
:
Remove the F1 key from the Help.F1Help command
Help\Online
:
Set “When loading Help content” to “Try local first, then online” or “Try local only, not online”
Startup
:
Change the “At startup” option to “Show empty environment”
Projects and Solutions
General
:
Disable “Track Active Item in Solution Explorer”
Text Editor
General
(for each language you want):
Disable “Navigation bar” (this is the toolbar that shows the objects and procedures drop down lists allowing you to choose a particular object in your code.
Disable “Track changes”
Windows Forms Designer
General
:
Set “AutotoolboxPopulate” to false.
Set “EnableRefactoringOnRename” to false.


q: Is there a way to use .NET reflection to capture the values of all parameters/local variables?

[A]
Reflection is not used to capture information from the stack.  It reads the Assembly.
You might want to take a look at StackTrace
http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx
Good article here:
http://www.codeproject.com/KB/trace/customtracelistener.aspx


q:
I have run across an XML Schema with the following definition:

<xs:simpleType name="ClassRankType">
    <xs:restriction base="xs:integer">
        <xs:totalDigits value="4"/>
        <xs:minInclusive value="1"/>
        <xs:maxInclusive value="9999"/>
    </xs:restriction>
</xs:simpleType>

However, it seems to me that totalDigits is redundant.  I am somewhat new to XML Schema, and want to make sure I'm not missing something.

What is the actual behavior of totalDigits vs. maxInclusive?

Can totalDigits always be represented with a combination of minInclusive and MaxInclusive?

How does totalDigits affect negative numbers?

[A]
can totalDigits always be represented with a combination of minInclusive and MaxInclusive?
In this case, yes. As you're dealing with an integer, the value must be a whole number, so you have a finite set of values between
```
minInclusive
```
and
```
maxInclusive
```
. If you had decimal values,
```
totalDigits
```
would tell you how many numbers in total that value could have.
How does totalDigits affect negative numbers?
It is the total number of digits allowed in the number, and is not affected by decimal points, minus signs, etc. From
auxy.com
:
The number specified by the value attribute of the
```
<xsd:totalDigits>
```
facet will restrict the total number of digits that are allowed in the number, on both sides of the decimal point.


q: What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine?

[A]
I've done this in the past for a Python script to determine the last updated files in a directory:
```
```
import glob
import os

search_dir = "/mydir/"
# remove anything from the list that is not a file (directories, symlinks)
# thanks to J.F. Sebastion for pointing out that the requirement was a list
# of files (presumably not including directories)
files = list(filter(os.path.isfile, glob.glob(search_dir + "*")))
files.sort(key=lambda x: os.path.getmtime(x))
```
```
That should do what you're looking for based on file mtime.
EDIT
: Note that you can also use os.listdir() in place of glob.glob() if desired - the reason I used glob in my original code was that I was wanting to use glob to only search for files with a particular set of file extensions, which glob() was better suited to. To use listdir here's what it would look like:
```
```
import os

search_dir = "/mydir/"
os.chdir(search_dir)
files = filter(os.path.isfile, os.listdir(search_dir))
files = [os.path.join(search_dir, f) for f in files] # add path to each file
files.sort(key=lambda x: os.path.getmtime(x))
```
```


q:
For my current project, I need to request XML data over a tcp/ip socket connection.  For this, I am using the TcpClient class:

Dim client As New TcpClient()
client.Connect(server, port)

Dim stream As NetworkStream = client.GetStream()
stream.Write(request)
stream.Read(buffer, 0, buffer.length)

// Output buffer and return results...

Now this works fine and dandy for small responses.  However, when I start receiving larger blocks of data, it appears that the data gets pushed over the socket connection in bursts.  When this happens, the stream.Read call only reads the first burst, and thus I miss out on the rest of the response.

What's the best way to handle this issue?  Initially I tried to just loop until I had a valid XML document, but I found that in between stream.Read calls the underlying stream would sometimes get shut down and I would miss out on the last portion of the data.

[A]
You create a loop for reading.
Stream.Read returns int for the bytes it read so far, or 0 if the end of stream is reached.
So, its like:
```
```
int bytes_read = 0;
while (bytes_read < buffer.Length)
   bytes_read += stream.Read(buffer, bytes_read, buffer.length - bytes_read);
```
```
EDIT: now, the question is how you determine the size of the buffer. If your server first sends the size, that's ok, you can use the above snippet. But if you have to read until the server closes the connection, then you have to use try/catch (which is good idea even if you know the size), and use bytes_read to determine what you received.
```
```
int bytes_read = 0;
try
{
   int i = 0;
   while ( 0 < (i = stream.Read(buffer, bytes_read, buffer.Length - bytes_read) )
      bytes_read += i;
}
catch  (Exception e)
{
//recover
}
finally
{
if (stream != null)
   stream.Close();
}
```
```


q:
I have a personal wiki that I take notes on.  The wiki's pages are in a subversion working copy directory, "pages", and I set their permissions to 664, owned by www-data:www-data.  My username is in the "www-data" group, so I can checkin and mess with the pages manually.

For a while, I had an issue because every time I ran a checkin, the files would be owned by me:www-data instead of www-data:www-data, and I would no longer be able to change the wiki files through my web interface!  I solved the issue by flipping the setgid bit on the "pages" directory, but I'm still confused as to why this happened in the first place:

Every time I check something into subversion, it appears as if svn deletes it and recreates it.  Why?  Does this behavior support some functionality that I'm not aware of?  Is there a way to change it?

Thanks!

[A]
I think you are using it wrong. What you could do is still have everything in subversion and have your local working copy separate from the www directory which you develop on.
Then just have the www working-copy auto-updated (or exported if you don't want the .svn directories in the www foldeR) for the www-user by some script (perhaps as a
post-commit
hook) which then setups permissions accordingly.
Work flow would be:
edit files in /home/youruser/yourwiki-working-copy/
do svn commit
post-commit hook updates the files in /var/www/ (or wherever the wiki is located)
goto 1.
This way, you don't have to worry about permissions and you can even have more than one person work on the web site with all the benefits of version control.


q: How do you post data to an iframe?

[A]
Depends what you mean by "post data". You can use the HTML
```
target=""
```
attribute on a
```
<form />
```
tag, so it could be as simple as:
```
```
<form action="do_stuff.aspx" method="post" target="my_iframe">
  <input type="submit" value="Do Stuff!">
</form>

<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe>
```
```
If that's not it, or you're after something more complex, please edit your question to include more detail.
There is a known bug with Internet Explorer that only occurs when you're dynamically creating your iframes, etc. using Javascript (there's a
work-around here
), but if you're using ordinary HTML markup, you're fine. The target attribute and frame names isn't some clever ninja hack; although it was deprecated (and therefore won't validate) in HTML 4 Strict or XHTML 1 Strict, it's been part of HTML since 3.2, it's formally part of HTML5, and it works in just about every browser since Netscape 3.
I have verified this behaviour as working with XHTML 1 Strict, XHTML 1 Transitional, HTML 4 Strict and in "quirks mode" with no DOCTYPE specified, and it works in all cases using Internet Explorer 7.0.5730.13. My test case consist of two files, using classic ASP on IIS 6; they're reproduced here in full so you can verify this behaviour for yourself.
default.asp
```
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
  "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>Form Iframe Demo</title>
  </head>
  <body>
  <form action="do_stuff.asp" method="post" target="my_frame">
    <input type="text" name="someText" value="Some Text">
    <input type="submit">
  </form>
  <iframe name="my_frame" src="do_stuff.asp">
  </iframe>
  </body>
</html>
```
```
do_stuff.asp
```
```
<%@Language="JScript"%><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
  "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>Form Iframe Demo</title>
  </head>
  <body>
  <% if (Request.Form.Count) { %>
  You typed: <%=Request.Form("someText").Item%>
  <% } else { %>
  (not submitted)
  <% } %>
  </body>
</html>
```
```
I would be very interested to hear of any browser that doesn't run these examples correctly.


q:
Since length is a JavaScript property, does it matter whether I use

for( var i = 0; i < myArray.length; i++ )

OR

var myArrayLength = myArray.length;
for( var i = 0; i < myArrayLength ; i++ )

[A]
```
```
for(var i = 0, iLen = myArray.length; i < iLen; i++)
```
```
See
http://blogs.oracle.com/greimer/resource/loop-test.html
for benchmarks of various Javascript loop constructs.


q:
I've only started playing with both ASP.Net MVC and the new-to-VS2008 Dynamic Data Website Templates.  I note that they both use routing in their URL handling, and I'm given to understand that because of routing, ASP.Net MVC won't work under IIS6.  However my DynamicData site works just fine on IIS6.

I've had to temporarily abandon my exploration of ASP.Net MVC for an upcoming project due to the IIS7 requirement, and I'm wondering what the essential difference between the two is under the hood, i.e. what makes DynamicData sites work on IIS6 and MVC not?

[A]
ASP.NET MVC does indeed work under
IIS6
(and IIS5 for that matter) as long as you
enable wildcard mappings
to ASP.NET. I have deployed MVC applications to production using IIS6, so I can guarantree that it's possible.
The key difference is that all URLs in DynamicData end in a file with an ASPX extension so, regardless of physical existance, the ASP.NET runtime is invoked (because ASPX is associated with ASP.NET), whereas most ASP.NET MVC requests to not have an extension (or have an MVC extension, which is not mapped by default) and thus IIS configuration is required before it will work.
IIS7 works automatically because IIS7 itself is managed and thus there is no separation between IIS/ASP.NET.


q:
I didn't realize until recently that Perl 5.10 had significant new features and I was wondering if anyone could give me some good resources for learning about those.  I searched for them on Google and all I found was some slides and a quick overview.  Some of the features (to me at least) would be nice if they had more explanation.

Any links would be appreciated.

-fREW

[A]
The
perldelta
manpage has all the nitty-gritty details. There's a brief (but informative) slide presentation,
Perl 5.10 for people who aren't totally insane
. And a good
PerlMonks discussion
on the issue.


q: How can I display a tooltip over a button using Windows Forms?

[A]
Sure, just handle the mousehover event and tell it to display a tool tip.
t is a tooltip defined either in the globals or in the constructor using:
```
```
ToolTip t = new ToolTip();
```
```
then the event handler:
```
```
private void control_MouseHover(object sender, EventArgs e)
{
  t.Show("Text", (Control)sender);
}
```
```


q:
tempfile.mkstemp() returns:

a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.

How do I convert that OS-level handle to a file object?

The documentation for os.open() states:

To wrap a file descriptor in a "file
  object", use fdopen().

So I tried:

>>> import tempfile
>>> tup = tempfile.mkstemp()
>>> import os
>>> f = os.fdopen(tup[0])
>>> f.write('foo\n')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 9] Bad file descriptor

[A]
You can use
```
```
os.write(tup[0], "foo\n")
```
```
to write to the handle.
If you want to open the handle for writing you need to add the
"w"
mode
```
```
f = os.fdopen(tup[0], "w")
f.write("foo")
```
```


q:
I can do this:

$ find .
.
./b
./b/foo
./c
./c/foo

And this:

$ find . -type f -exec cat {} \;
This is in b.
This is in c.

But not this:

$ find . -type f -exec cat > out.txt {} \;

Why not?

[A]
find's -exec argument runs the command you specify once for each file it finds. Try:
```
```
$ find . -type f -exec cat {} \; > out.txt
```
```
or:
```
```
$ find . -type f | xargs cat > out.txt
```
```
xargs converts its standard input into command-line arguments for the command you specify. If you're worried about embedded spaces in filenames, try:
```
```
$ find . -type f -print0 | xargs -0 cat > out.txt
```
```


q: I am creating some build scripts that interact with Perforce and I would like to mark for delete a few files. What exactly is the P4 syntax using the command line?

[A]
```
```
p4 delete filename
```
```
(output of p4 help delete)
delete -- Open an existing file to delete it from the depot
p4 delete [ -c changelist# ] [ -n ] file ...
```
```
Opens a file that currently exists in the depot for deletion.
If the file is present on the client it is removed.  If a pending
changelist number is given with the -c flag the opened file is
associated with that changelist, otherwise it is associated with
the 'default' pending changelist.

Files that are deleted generally do not appear on the have list.

The -n flag displays what would be opened for delete without actually
changing any files or metadata.
```
```


q: I want to start working with TDD but I don't know really where to start. We coding with .NET (C#/ASP.NET).

[A]
See the questions
Why should I practice Test Driven Development and how should I start?
,
Moving existing code to Test Driven Development
,
What is unit testing?
and
What is TDD?


q:
I have a table with one column and about ten rows.  The first column has rows with text as row headers, "header 1", "header 2".  The second column contains fields for the user to type data (textboxes and checkboxes).

I want to have a button at the top labelled "Add New...", and have it create a third column, with the same fields as the first column.  If the user clicks it again, it will create another blank column with fields (as in the second column).

Does anyone know of an effective way to manipulate the DOM to achieve this?

I'm experimenting with div's and TABLES but i'm on my third day of doing this, and it feels harder than it should be.

[A]
Something along the lines of
```
```
function(table)
{
  for(var i=0;i<table.rows.length;i++)
  {
    newcell = table.rows[i].cells[0].cloneNode(true);
    table.rows[i].appendChild(newcell);
  }
}
```
```


q: Given a table or a temp table, I'd like to run a procedure that will output a SQL script (i.e. a bunch of INSERT statements) that would populate the table.  Is this possible in MS SQL Server 2000?


q:
How would you go about introducing acceptance tests into a team using the .NET framework?  What tools are available for this purpose?

Thanks!

[A]
You might want to take a look at FitNesse, which is meant to be a way for Acceptance tests to look like a wiki document (so that they can be read and written by QA or project managers)
http://fitnesse.org/
Here's a good intro
http://ablog.apress.com/?p=735


q:
I have a table on SQL2000 with a numeric column and I need the select to return a 01, 02, 03...

It currently returns 1,2,3,...10,11...

Thanks.

[A]
Does this work?
```
```
SELECT REPLACE(STR(mycolumn, 2), ' ', '0')
```
```
From
http://foxtricks.blogspot.com/2007/07/zero-padding-numeric-value-in-transact.html


q:
Can anyone recommend for/against the time-travel functions in postgresql's contrib/spi module?  Is there an example available anywhere?

Tnx

[A]
The argument for time-travel would be being able to look at tables that are updated often at an earlier insertion/deletion point. Say a table of stock prices for a firms investment portfolio.
The argument against would be the extra storage space it eats up.
Here is an
Example
of use.


q: I have an third-party applet that requires JRE v1.5_12 to work correctly.  THe user is installing JRE v1.6.07 or better.  It used to be with 1.5 and below, that I could have multiple JRE's on the machine and specify which one to use - but with 1.6 that apepars to be broken.  How do I tell the browser I want to use v1.5_12 instead of the latest one installed?

[A]
For security reasons, you can no longer force it to use older JRE's. Say release 12 has a huge security hole, and everyone installs release 13 to patch it. Evil java applets could just say "run with release 12 please" and then carry out their exploits, rendering the patches useless.
Most likely you have some code with security holes that the newer JRE is blocking, because it would cause a security risk. Fix your code, should be pretty minor changes, then you wont have to worry.
See
this page
for more info on the change.


q:
A lot of useful features in Python are somewhat "hidden" inside modules. Named tuples (new in Python 2.6), for instance, are found in the collections module.

The Library Documentation page will give you all the modules in the language, but newcomers to Python are likely to find themselves saying "Oh, I didn't know I could have done it this way using Python!" unless the important features in the language are pointed out by the experienced developers.

I'm not specifically looking for new modules in Python 2.6, but modules that can be found in this latest release.

[A]
May be
PEP 0631
and
What's new in 2.6
can provide elements of answer. This last article explains the new features in Python 2.6, released on October 1 2008.


q:
I wish to perform an experiment many different times.  After every trial, I am left with a "large" set of output statistics -- let's say, 1000.  I would like to store the outputs of my experiments in a table, but what's the best way...?

Option 1

Have a table with 1000 columns.  Seems like a bad idea.  What if the number of statistics one day exceeds the maximum number of columns?

Option 2

Have a table with three columns.  Let's say, ID, StatisticType, and StatisticValue.  That way, you can have as many statistics as you want.  However, reading a single experiments statistics becomes more complicated.  Moreover, what if different statistics are different data types??

Any suggestions?

[A]
Option 2, with ID, TrialID, StatisticID, StatisticValue
With proper indexing, it will perform fairly well (you can use PIVOT to get the values out on columns fairly easily in SQL Server 2005).
When the statistics are different datatypes, the problem becomes more interesting, but in many cases, I just up-size the datatype (sometimes ints just end up in the money field).  For other non-compatible types, the best design in my mind is really separate tables for each type, but I've also seen multiple columns or a free-form text column.


q:
I'm porting a Java library to C#. I'm using Visual Studio 2008, so I don't have the discontinued Microsoft Java Language Conversion Assistant program (JLCA).

My approach is to create a new solution with a similar project structure to the Java library, and to then copy the java code into a c# file and convert it to valid c# line-by-line. Considering that I find Java easy to read, the subtle differences in the two languages have surprised me.

Some things are easy to port (namespaces, inheritance etc.) but some things have been unexpectedly different, such as visibility of private members in nested classes, overriding virtual methods and the behaviour of built-in types. I don't fully understand these things and I'm sure there are lots of other differences I haven't seen yet.

I've got a long way to go on this project. What rules-of-thumb I can apply during this conversion to manage the language differences correctly?

[A]
Your doing it in the only sane way you can...the biggest help will be this document from Dare Obasanjo that lists the differences between the two languages:
http://www.25hoursaday.com/CsharpVsJava.html
BTW, change all getter and setter methods into properties...No need to have the C# library function just the same as the java library unless you are going for perfect interface compatibility.


q:
I am trying to visualize some values on a form. They range from 0 to 200 and I would like the ones around 0 be green and turn bright red as they go to 200.

Basically the function should return color based on the value inputted. Any ideas ?


q:
Is it more performant to have a bidimensional array (type[,]) or an array of arrays (type[][]) in C#?

Particularly for initial allocation and item access

[A]
I believe that [,] can allocate one contiguous chunk of memory, while [][] is N+1 chunk allocations where N is the size of the first dimension. So I would guess that [,] is faster on initial allocation.
Access is probably about the same, except that [][] would involve one extra dereference. Unless you're in an exceptionally tight loop it's probably a wash. Now, if you're doing something like image processing where you are referencing
between
rows rather than traversing row by row, locality of reference will play a big factor and [,] will probably edge out [][] depending on your cache size.
As Marc Gravell mentioned, usage is key to evaluating the performance...


q:
Let's say I've got two strings in JavaScript:

var date1 = '2008-10-03T20:24Z'
var date2 = '2008-10-04T12:24Z'

How would I come to a result like so:

'4 weeks ago'

or

'in about 15 minutes'

(should support past and future).

There are solutions out there for the past diffs, but I've yet to find one with support for future time diffs as well.

These are the solutions I tried:

John Resig's Pretty Date and Zach Leatherman's modification

Bonus points for a jQuery solution.


q:
Ok, I'm using the term "Progressive Enhancement" kind of loosely here but basically I have a Flash-based website that supports deep linking and loads content dynamically - what I'd like to do is provide alternate content (text) for those either not having Flash and for search engine bots. So, for a user with flash they would navigate to:

http://www.samplesite.com/#specific_page

and they would see a flash site that would navigate to the "specific_page."  Those without flash would see the "specific_page" rendered in text in the alternative content section.

Basically, I would use php/mysql to create a backend to handle all of this since the swf is also using dynamic data. The question is, does something out there that does this already exist?


q:
I need a (php) regex to match Yahoo's username rules:

Use 4 to 32 characters and start with a letter. You may use letters, numbers, underscores, and one dot (.).

[A]
A one dot limit?  That's tricky.
I'm no regex expert, but I think this would get it, except for that:
```
```
[A-Za-z][A-Za-z0-9_.]{3,31}
```
```
Maybe you could check for the . requirement separately?


q:
I have the following code making a GET request on a URL:

$('#searchButton').click(function() {
    $('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val());
});

But the returned result is not always reflected. For example, I made a change in the response that spit out a stack trace but the stack trace did not appear when I clicked on the search button. I looked at the underlying PHP code that controls the ajax response and it had the correct code and visiting the page directly showed the correct result but the output returned by .load was old.

If I close the browser and reopen it it works once and then starts to return the stale information. Can I control this by jQuery or do I need to have my PHP script output headers to control caching?

[A]
One way is to add a unique number to the end of the url:
```
```
$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&uid='+uniqueId());
```
```
Where you write uniqueId() to return something different each time it's called.


q:
I'm trying to display a series of titles varying from 60 characters to 160 or so and the capitalization varies, some of it all caps, some half caps.  When it's mostly lowercase the whole 160 characters of text fits in the width I want, but when it starts getting more caps (they must be wider), it starts over flowing.

Is there a way to use an attractive fixed witdh font (upper and lowercase widths the same too), or dynamically shrink the text to fit, or otherwise recognize how much space the text is going to take on the server side, and cut off the end dynamically?  Or do you folks have a better solution?

[A]
You could fix the width and hide the overflow,
```
style="width: Xpx; overflow: hidden;"
```
That will limit the width and cut off the end if it's too wide.


q:
I'm trying to write a regex that will parse out the directory and filename of a fully qualified path using matching groups.

so...

/var/log/xyz/10032008.log

would recognize group 1 to be "/var/log/xyz" and group 2 to be "10032008.log"

Seems simple but I can't get the matching groups to work for the life of me.

NOTE:  As pointed out by some of the respondents this is probably not a good use of regular expressions.  Generally I'd prefer to use the file API of the language I was using.  What I'm actually trying to do is a little more complicated than this but would have been much more difficult to explain, so I chose a domain that everyone would be familiar with in order to most succinctly describe the root problem.

[A]
What language? and why use regex for this simple task?
If you
must
:
```
```
^(.*)/([^/]*)$
```
```
gives you the two parts you wanted. You might need to quote the parentheses:
```
```
^\(.*\)/\([^/]*\)$
```
```
depending on your preferred language syntax.
But I suggest you just use your language's string search function that finds the last "/" character, and split the string on that index.


q:
Every time I call this method my NSMutableData is leaking and I cannot figure out how to plug it. theData's retain count is upped by one after the decoder is allocated and initialized and I have no idea why. I am stuck with a retain count of 2 at the end of the method and attempting to release it causes an app crash.

- (void)readVenueArchiveFile:(NSString *)inFile key:(NSString *)inKey
{
    NSMutableData *theData;
    NSKeyedUnarchiver *decoder;

    theData = [NSData dataWithContentsOfFile:inFile];

    decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];

    venueIOList = [[decoder decodeObjectForKey:inKey] mutableCopy];

    [decoder finishDecoding];

    [decoder release];
}

[A]
Don't worry about retain counts, worry about balance within a method.  What you're doing in this method looks correct, assuming
```
venueIOList
```
is an instance variable.
To expand on my answer a little bit:  The unarchiver might be retaining your data during the unarchive operation, and then sending the data
```
-autorelease
```
when it's done instead of
```
-release
```
.  Since that's not something
you
did, it's not something
you
have to care about.


q: My development environment is running in JDK1.6, and I need to compile some classes so they are compatible with a client running JDK1.5.  How would I do this with the 'javac' ant target?

[A]
Command line : javac -target 1.5 sourcefiles
Ant:
```
< javac srcdir="${src} destdir="${build}" target="1.5" />
```


q:
I've got a Win32 C++ app with a suite of unit tests.  After the unit tests have finished running, I'd like a human-readable report on any unfreed memory to be automatically generated.  Ideally, the report will have a stack with files & line number info for each unfreed allocation.  It would be nice to have them generated in a consistent order to make it easy to diff it from one run to the next.  (Basically, I would like the results of valgrind --leak-check=full, but on windows).

I've had success with UMDH getting this kind of info from running processes, but that tool only seems to work if you attach to an existing process.  I want this to happen automatically every time I run my unit tests.

Is there a tool that can do this?  If so, how do I use it?

Thanks!

[A]
If you're using MSVC, Microsoft's Debug heap functions can be used to generate the report you want, but it may not be as automatic as you'd like (you may need to write some custom code):
```
```
_CrtSetReportMode
_CrtSetReportFile
_CrtMemState
_CrtMemCheckpoint
_CrtMemDumpStatistics
_CrtSetReportFile
_CrtSetDbgFlag
```
```


q: How do I write a decorator that restores the current working directory to what it was before the decorated function was called?  In other words, if I use the decorator on a function that does an os.chdir(), the cwd will not be changed after the function is called.

[A]
```
```
def preserve_cwd(function):
   def decorator(*args, **kwargs):
      cwd = os.getcwd()
      result = function(*args, **kwargs)
      os.chdir(cwd)
      return result
   return decorator
```
```
Here's how it's used:
```
```
@preserve_cwd
def test():
  print 'was:',os.getcwd()
  os.chdir('/')
  print 'now:',os.getcwd()

>>> print os.getcwd()
/Users/dspitzer
>>> test()
was: /Users/dspitzer
now: /
>>> print os.getcwd()
/Users/dspitzer
```
```


q:
I'd like to be able to toggle easily between two values for "maximum number of parallel project builds" in Visual Studio 2008 (in Tools->Options->Projects and Solutions->Build and Run). (When I'm planning on doing concurrent work I'd like to reduce it from 4 to 3.) I'm not too well versed in writing macros for the IDE. When I try recording a macro, and perform all the actions (open the dialog, change the setting, click OK), the only thing that gets recorded is this:

DTE.ExecuteCommand ("Tools.Options")

Is my goal unattainable?

[A]
It appears to be impossible, according to the MSDN page for
Determining Names of Property Items in Tools Options Pages
If it
was
possible, it would have been something like this:
```
```
Dim p = DTE.Properties("ProjectsAndSolutions","BuildAndRun")
p.Item("MaxNumParallelBuilds")
```
```


q:
I have a type (System.Type) of an enum and a string containing enumeration value to set.

E.g. given:

enum MyEnum { A, B, C };

I have typeof(MyEnum) and "B".

How do I create MyEnum object set to MyEnum.B?

[A]
```
```
MyEnum enumValue = (MyEnum)Enum.Parse(typeof(MyEnum), "B");
```
```
You also have a case-insensitive overload.


q: When I try to bind port 80 to a socket in c, i always get the error, that I don't have permission to use this port. is there an easy way to get this permission?

[A]
Usually only the superuser (root) can bind to 'privileged' ports (i.e. those port numbers below 1024).
This means that you either have to run your program as root or make your executable 'suid root'.
Both of these have security consequences so you may want to consider using the suid approach and relinquishing superuser privileges once the bind call has been made.


q:
I am having a very hard time finding a standard pattern / best practice that deals with rendering child controls inside a composite based on a property value.

Here is a basic scenario. I have a Composite Control that has two child controls, a textbox and a dropdown. Lets say there is a property that toggles which child to render.

so:

myComposite.ShowDropdown = true;

If true, it shows a dropdown, otherwise it shows the textbox.

The property value should be saved across postbacks, and the the correct control should be displayed based on the postback value.

Any good examples out there?

[A]
I would think something like:
```
```
public bool ShowDropDown
{
    get{ return (bool)ViewState["ShowDropDown"]; }
    set{ ViewState["ShowDropDown"]; }
}

private  void Page_Load(object sender, EventArgs e)
{
    DropDaownControl.Visible = ShowDropDown;
    TextBoxControl.Visible = !ShowDropDown;
}
/* some more code */
```
```


q:
There is a way to keep the scroll on bottom for a multi line textbox?

Something like in the vb6

txtfoo.selstart=len(txtfoo.text)

I'm trying with txtfoo.selectionstart=txtfoo.text.length without success.

Regards.

[A]
Ok, I found that the solution was to use
```
```
txtfoo.AppendText
```
```
instead of
```
```
txtfoo.text+="something"
```
```