q:
I am using the FlexiGrid jQuery plug in and I need to get a JSON object back form my MVC App, simple enough if the FlexiGrid took just the object but I need to add a few items to the response string for it to work properly with FlexiGrid.

So here is a portion of my controller code:

If Request.QueryString("json") IsNot Nothing Then
    Dim data As New StringBuilder()
    data.Append("page: " & pageIndex & "," & vbCrLf)
    data.Append("total: " & ViewData.TotalCount & "," & vbCrLf)
    data.Append("rows: ")
    data.Append(Json(objCustomerList))

    Return Content(data.ToString())
End If

Unfortunately in the above code Json(objCustomerList) returns 'System.Web.MVV.JsonResult' instead of the desired JSON string data.  I also tried Json(objCustomerList).ToString() just to see what would happen and the same thing again.

Any ideas?

[A]
```
Json()
```
method in ASP.NET MVC is just using the
```
JavaScriptSerializer
```
class via the
```
JsonResult
```
class.  You could use that yourself if you wanted to serialize the objCustomerList object using JSON to a string.
My recommendation would be to take a slightly different approach.
Create a Model that represented the .NET equivalent of the JavaScript object you were trying to create.  Maybe a FlexiGridModel object with Page, Total, Rows, and CustomerList properties.
Then when you pass that FlexiGridModel to
```
Json()
```
it would just work, no need to build a JSON string using
```
StringBuilder
```
.
If you just want your code to work there is an
override on
```
JavaScriptSerializer.Serialize()
```
that takes the object to serialize and the
```
StringBuilder
```
to append the results to.  Which should be exactly what you are looking for.
Some relevant links:
JavaScriptSerializer example
ASP.NET MVC JsonResult source
Codeproject: ASP.NET MVC Flexigrid sample


q:
In T-SQL, SPACE() function is used to add spaces to a string. For e.g.

@s = 'He' + space(5) + 'llo'

Output

He     llo

So is there any function in PL/SQL that is equivalent to SPACE()?

Thank you.

[A]
You can use RPAD or LPAD functions
```
```
select 'He'  || rpad(' ',5,' ') || 'llo'
from dual;
/
```
```
or in PL/SQL it would be:
```
```
declare
  x varchar2(20);
begin
  x:= 'He'  || rpad(' ',5,' ') || 'llo';
end;
/
```
```

s: huggingface

c: devops

d: intermediate


q:
How to declare a static dictionary object inside a static class? I tried

public static class ErrorCode
{
    public const IDictionary<string, string> ErrorCodeDic = new Dictionary<string, string>()
    {
        { "1", "User name or password problem" }
    };
}

But the compiler complains that "A const field of a reference type other than string can only be initialized with null".

[A]
```
```
public static class ErrorCode
{
    public const IDictionary<string , string > m_ErrorCodeDic;

    public static ErrorCode()
    {
      m_ErrorCodeDic = new Dictionary<string, string>()
             { {"1","User name or password problem"} };
    }
}
```
```
Probably initialise in the constructor.


q:
Reporting Services 2000 SP2

I've got a matrix displaying the number of employees

                 Business1      Business2      Business3
StartBefore99    9              14             4
StartAfter99     30             20             34

I'd like to display percentages eg

                 Business1      Business2      Business3
StartBefore99    9 (23%)        14 (41%)       4 (10%)
StartAfter99     30 (77%)       20  (59%)      34 (90%)

Any suggestions?  I could do it in SQL, but would prefer to do an expression in RS.

Cheers


q:
When editing PHP code (I'm not sure if it's specific to that language) and I create a new line in the middle of comma-separated lists that span multiple lines, the indent rules always unindent the line I'm leaving. Here's a video of it. This happens in arrays, function argument lists, etc.

Is there anything I can do to stop this from happening, or any quicker methods of fixing the error than moving up, re-indenting it, moving down, re-indenting (since it gets cleared when you leave the line), and continuing?

.vimrc

[A]
Try
```
:set indentexpr=""
```
and see if that helps. See
```
:help filetype-indent-off
```
for the section that deals with filetype plugins (which is probably where this indentexpr is coming from).


q:
I'm a complete beginner when it comes to programming. I'm taking a stab at PHP, and have seen how powerful the frameworks can be. But should I even consider trying to work with a framework until I have a strong grasp of PHP itself?

Note: I'd most likely be using CodeIgnitor, but the question applies to any of the frameworks.

[A]
Preferably, you should have a strong grasp of the language (and programming in general) before you start using frameworks. Frameworks can and will save you a lot of work, but you they also introduce advanced concepts and implementations.
After you gain some experience and start to wonder what's the best way to solve some common problems you have faced before - that will be a good time to give frameworks a try.
I would suggest you try to read some of the source code of the different frameworks and see if it makes sense to you. If it doesn't - you are probably not ready yet.


q: What is SSL and how does it relate to HTTPS?

[A]
HTTPS is just HTTP over SSL.  Or Hypertext Transfer Protocol over Secure Socket Layer.
SSL is an encrypted channel for communication.  HTTP is the way to transfer web pages and other web content across the network.


q:
I'm a C/Python programmer in C++ land working with the STL for the first time.

In Python, extending a list with another list uses the .extend method:

>>> v = [1, 2, 3]
>>> v_prime = [4, 5, 6]
>>> v.extend(v_prime)
>>> print(v)
[1, 2, 3, 4, 5, 6]

I currently use this algorithmic approach to extend vectors in C++:

v.resize(v.size() + v_prime.size());
copy(v_prime.begin(), v_prime.end(), v.rbegin());

Is this the canonical way of extending vectors, or if there is a simpler way that I'm missing?

[A]
From
here
```
```
// reserve() is optional - just to improve performance
v.reserve(v.size() + distance(v_prime.begin(),v_prime.end()));
v.insert(v.end(),v_prime.begin(),v_prime.end());
```
```


q:
I am having trouble setting the path to jquery in an mvc app. In my master page I have the script declared and jquery works at the root of my app. When I navigate to a content view page in my app jquery does not get loaded properly. Do I need to set the path in the content page as well or declare the path differently?

<script src="Views/Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>

[A] The src on the masterpage is relative, which won't work on child pages. It should work if you declare the path as an absolute path (e.g. "/Views/Scripts/jquery-1.2.6.min.js");


q:
Is there any way to save the state of vim settings with a document?

To clarify: I'm editing a document and I change a bunch of settings. I don't necessarily recall which; and I don't want to use these settings again, except for the current document. I don't want to manually try to remember what I've changed; or what the magic abbreviations are for the settings I've changed. I just want to have, say, for "mydoc.txt", a "mydoc.vim" file that puts me back where I left off, and the settings file would be saved automatically based on a vim setting, say, or maybe a ctrl-key does it before I exit. It would be handy if vim could automatically look for such a file.

And it would be preferable not to have to edit the settings into and out of the document itself.

[A]
Yes, vim settings can be included within the document.
They are mostly found within comments, so they don't mess up the original file. An example for tab-specific settings is:
```
```
/* ex: set tabstop=8 expandtab: */
```
```
Note that this command works in most cases, however, servers are often setup without
```
modeline
```
turned on for security reasons. To turn on that feature add the following in your $HOME/.vimrc or the system $VIM/vimrc:
```
```
set modeline
```
```


q:
I am using the rounded corners plugin for jquery and have it working rounding elements in my page. The only issue I have is that the elements appear on the page un-rounded and then round. What do I need to do so that the elements only appear rounded?

I originally put my script tags in the head element but should they go somewhere else in a master page to improve perf?


q:
I am a Winforms and business engine developer who is using asp.net for the first time in over 2 years, and in that time I have noticed a few convention changes.

What is the logic behind the anti-'tables for layout' movement?

Is it to allow css classes to be used to handle layout, and if so, should this really be an issue on pages you are fairly sure will remain static, or is it just considered 'ugly'?

[A]
There are a number of reasons. One reason is accessibility...layout tables do not add semantics to the content so screen readers have trouble with them. So only use tables for tabular data.
Here
are a few points that answer the question in more details
Tables are slow
Tables can be inflexible
Accessibility issues are easier with CSS
Tables don’t degrade
Tables don’t print as well


q: I would like to start a small part time business other than my full time programming job. Have you guys done that before? I know programmers who teach in evening schools after work. But then again, that is not business. What would you recommend to get another income stream going?

[A]
I would recommend having some sort of business plan. Don't just start writing some application or creating some web site and think it will sell. Do some research on the actual market for your product.
Also, having done it before, I would suggest having at least 1 other partner in the business. Doing it all yourself quickly becomes a waste of effort. You can do it, but it sure is a heck of a lot easier if you have someone to help with ideas, programming, accounting, web design, etc.
Also, think hard about whether you really want another job outside of your current job. I don't know what your life is like outside of your day job, but having another job (particularly one that requires daily attention like a website that has to be constantly updated) can be a real drain on your life.
If you do come up with a business plan and start a business, make it something you thoroughly enjoy! It can be very rewarding if you do.


q:
I got my Xampp server running and can run my html in subdirectories now, as well (can't have spaces in the subdirectory names).

SSI Includes or PHP Includes:

Xampp says SSI is deactivated. Tried uncommenting the lines for includes, but it doesn't change the deactivation.

How do I activate SSI?

Then, how do I implement either SSI include statements or PHP include statements into my html to call up html files that include html, images, javascript and commands that call other javascript menu files?

[A]
I don't know if Xampp has a special way of activating SSI or not, but the
normal Apache way
should work.
The normal way to include files in SSI is
```
```
<!--#include virtual="/something/file.html" -->
```
```
where the url to the file is actually
http://www.example.com/something/file.html
.


q:
I'm writing an application in PHP 5. I want to delete some rows in a SQLite v2 database file. I'm doing something like this:

$sqliteConnection = new SQLiteDatabase('path/to/db');
$queryString = "DELETE FROM myTable WHERE status='not good'";
$result = $sqliteConnection->query($queryString);

how can I know how many rows were affected by this query? how many rows have I deleted?

[A]
The PHP function
```
sqlite_changes()
```
does this for you.
Returns the numbers of rows that were changed by the most recent SQL statement executed against the
```
dbhandle
```
database handle.
Call it either in procedural-style:
```
```
echo 'Number of rows modified: ', sqlite_changes($sqliteConnection);
```
```
or in object-style:
```
```
echo 'Number of rows modified: ', $sqliteConnection->changes();
```
```


[A]
May be a
JXTree
from
SwingLab
could approach what you are looking for.
Illustration
here
, from the
Swingx
project
http://avatar21.superihost.com/images/JXTableJXTreeTable.png


q:
We are using OpenLDAP client library to conect to an LDAP server. The problem is that if there is no activity for some time, server (or firewall in the middle) drops TCP connection.

Our current implementation of "keep-alive" just does search for baseDN from time to time - any better ideas ?

[A]
The only alternative seems to be reconnect:
```
```
ldap_set_option( ld, LDAP_OPT_RECONNECT, LDAP_OPT_ON );
```
```


q:
I have a N-Ary non sorted in any way tree and each node can have 0-N children. Given the data structure below, how can I fill the tree view assuming you have an array of TermNodes and that array is the first level of the TreeView? I have not been able to come up with a recursive way to do this.

class TermNode
{
   public string Name;
   public string Definition;
   public List<TermNode> Children
}

[A]
Here is a bit of code to get you started with the recursion. It's not tested (I can't right now), but you should get the idea:
```
```
public static void BuildTreeView(TreeNodeCollection Parent, List<TermNode> TermNodeList)
{
  foreach (TermNode n in TermNodeList)
  {
    TreeNode CurrentNode = Parent.Add(n.Name);
    // no need to recurse on empty list
    if (n.List.Count > 0) BuildTreeView(CurrentNode.Nodes, n.List);
  }
}

// initial call
List<TermNode> AllTermNodes = /* all your nodes at root level */;

BuildTreeView(treeView1.Nodes, AllTermNodes);
```
```


q: What is the concept of erasure in generics in Java?

[A]
It's basically the way that generics are implemented in Java via compiler trickery. The compiled generic code
actually
just uses
```
java.lang.Object
```
wherever you talk about
```
T
```
(or some other type parameter) - and there's some metadata to tell the compiler that it really is a generic type.
When you compile some code against a generic type or method, the compiler works out what you really mean (i.e. what the type argument for
```
T
```
is) and verifies at
compile
time that you're doing the right thing, but the emitted code again just talks in terms of
```
java.lang.Object
```
- the compiler generates extra casts where necessary. At execution time, a
```
List<String>
```
and a
```
List<Date>
```
are exactly the same; the extra type information has been
erased
by the compiler.
Compare this with, say, C#, where the information is retained at execution time, allowing code to contain expressions such as
```
typeof(T)
```
which is the equivalent to
```
T.class
```
- except that the latter is invalid. (There are further differences between .NET generics and Java generics, mind you.) Type erasure is the source of many of the "odd" warning/error messages when dealing with Java generics.
Other resources:
Oracle documentation
Wikipedia
Gilad Bracha's Java generics guide
(PDF - highly recommended; link may need to change periodically)
Angelika Langer's Java Generics FAQ


q:
I have a controller that returns either JSON or partial html depending on if the user is logged in.

Is there anyway to tell the difference once the result has been returned??
What is the best way.

Obviously i have different actions to complete if the response is json or if it is the partial html. With the json one i do a redirect to the login page, and with the html one i just display it. If only i could render the html server side and send it back in json format?? From what i have heard this cannot be done as yet. Thoughts?

Cheers.

DUPLICATE: Can I evaluate the response type of an $.ajax() call in success callback?

[A]
I'd say, assuming you have control of the thing returning JSON or partial HTML, that you should change the Content-Type header of the JSON result to something like
```
application/x-format-json
```
or an equally obvious type.


q:
I have two UIActionSheets and I am thinking that I will control them with one delegate (the UIViewController that instantiates them).  The delegate will capture an actionSheet call and try to figure out which of the two threw the event.

I tried to get the modalView's title to differentiate, but it seems to be invalid...

Should this work?

If not, is there some other way to distinguish which UIActionSheet did the event?

Or do I need to create two different classes that will be separate delegates for each UIActionSheet?

Thanks in advance.

[A]
I think you need the
tag
property of the
UIActionSheet
.
Something like:
```
```
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle ... ];
actionSheet.tag = 10;
[actionSheet showInView:self.view];
```
```
Then in your delegate:
```
```
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  switch (actionSheet.tag) {
    case 10:
      ...
  }
}
```
```
tag
is a property of
UIView
and can be set in Interface Builder for components that appear there too. Quite handy, though I've never actually used it in this context myself.


q: How can I differentiate a Workflow system from a normal application that automates some work? Are there any specific feature a system must have to be categorized as a workflow system?

[A]
Workflow systems manage objects (often logically or actual electronic replacements for documents) that have an associated state. The state of an object in the system is node in a
state machine
(or a
Petri net
).
State transitions move an object from one state to another. The transitions can be triggered by people, automated events, timers, calendars, etc. Usually the transitions represent steps in a process in the real world.
That's pretty abstract, so consider an example: bug tracking software. A bug report probably starts out unvalidated, and as such is in a QA tester's queue. The QA tester will validate the report and make sure the steps are clear, grade the report for severity etc., and assign it to a developer or developer group. It is then in the developer's queue, who will ultimately fix or decide not to fix the bug, which will send it back to QA for validation. If there's a dispute over the bug, it might go into a state in which it bubbles up the management stack.
A trivial implementation of the above is to use an enumeration for the state associated with every object, and make everybody's inbox be a query for objects with a state of a particular enumeration value.
That's the gist of it, but things can get more complex, such as splitting off new objects, reacting to non-human events such as timing, internal or external (i.e. third-party) services, etc.


q: When I publish my ASP.NET site in RELEASE mode, and set compilation debug="false", will my ASP.NET and System.Diagnostics Tracing still work?

[A]
I believe that tracing is set separately from debugging in the configuration, so yes, if properly configured.
```
```
<configuration>
 <system.web>
  <trace enabled="true" requestLimit="40" localOnly="false"/>
 </system.web>
</configuration>
```
```


q: Does anyone have any experience with doing this?  I'm working on a Java decompiler right now in C++, but would like a higher level language to do the actual transformations of the internal trees.  I'm curious if the overhead of marshaling data between languages is worth the benefit of a more expressive and language for better articulating what I'm trying to accomplish (like Haskell).  Is this actually done in the "real world", or is it usually pick a language at the beginning of a project and stick with it?  Any tips from those who have attempted it?

[A]
I'm a big advocate of always choosing the right programming language for each challenge. If there is another language which handles some otherwise tricky task easily, I'd say go for it.
Does it happen in the real world? Yes. I am currently working on a project which is made up of both PHP and objective-c code.
The trick is, as you pointed out, the communication between the two languages. If at all possible, let each language stick to its own domain, and have the two sections communicate in the simplest way possible. In my case, it was XML documents sent via http. In your case, some kind of formatted text file might be the answer.


q:
What does STRAIGHT_JOIN do in this code ?

SELECT  STRAIGHT_JOIN ClosingBalance
FROM   Accounts
WHERE idAccounts = FidDebit;

[A]
From
here
:
STRAIGHT_JOIN is similar to JOIN, except that the left table is always read before the right table. This can be used for those (few) cases for which the join optimizer puts the tables in the wrong order.


q: What is best way to allow user to pick date from a mobile device from usability prospective?

[A] Are you building WAP page in asp.net? You have a DatePicker control in the mobile toolset. On devices that supports it this will render as a regular date picker (as in regular asp.net) while on more limited devices it will render as a series of selectors where you first select the year, then the month and finally the date. Unless you have a good reason to do otherwise you should use this I think.


q:
Hej,

assuming I have a code that looks like this:

List<User> userList = GetUserByName (u => u.Name == name);
DoSomethingWithTheUsers (userList.ToArray ());

Now I want to know the type of the objects in the Array in the method DoSomethingWithTheUsers (object[] myObjects)

Simply done by myObjects.First ().GetType () but what is to be done if the array is empty?
Is there a possibility to still get the Type?

[A]
The array type will be an array of User, i.e. User[]. Why not just use Type.GetElementType() on the GetType() of the array? I.e. using your example:
```
```
myObjects.GetType().GetElementType()
```
```


q:
I'm using a Delphi 2009 VCL TProgressBar as a kind of "empty/full" gauge.

On Vista, with Aero theme enabled, this has an animation associated with it, which is annoying and inappropriate for an gauge.

Is there any way of disabling this (NOT by adjusting user's theme settings!) to prevent the animation on this control?

To clarify, I want something basically identical to the 'disk space used' meters in Windows Explorer. No animation, but still with a nice border and shading effects.

Update:

I understand that I need a "meter", rather than a true progress bar. How can a themed meter be implemented using the standard windows progress bar control?

[A]
As per the
Vista UI guidelines for progress bars
you should not be using a TProgressBar for such purposes at all, it states:
Use progress bars only for progress. Use meters to indicate percentages that aren't related to progress.
There are a lot of Third-Party components (for example
Abakus VCL
) that are aimed at Process Automation applications and the like, maybe you could use one of these controls instead?


q:
I would like to automate the deployment of my SSIS and SSAS artifacts to remote development SQL Server 2005 & 2008 instances on a scheduled basis.

What would be the best solution for this?  I am using TFS 2008 as the source control system, so I'd like to integrate the solution with MSBuild and a scheduled Team Build.

[A]
SSIS is the easiest, when I was using SSIS, we stored our packages in a file and all we to do was copy the file to the correct directory in C:\Program Files\Microsoft SQL Server\90\DTS\Packages. Which you can do by adding a Copy task to the end of your MSBuild. I am not sure if the xml will be available by default in the output directory, so watch for that.
As for SSAS, I never got around to automating it but, you will want to look into Analysis Management Objects (AMO), pulling from Books online it says:
Analysis Management Objects (AMO) provides a programmatic interface to
  the complete command set for Analysis Services as available to the
  developer. Therefore, AMO can be used for deployment and also to the
  many administrative commands it otherwise supports. For more
  information about the user of AMO to automate any kind of
  administrative task, see Analysis Management Objects (AMO).


q:
I don't want to have the user install Google Gears so I can show him his guessed location. Is there a way to get the location without having to use Google Gears?

I have found http://www.wipmania.com/de/blog/google-geolocation-api/ but it does not offer an example.

[A]
This is typically called IP Geolocation.
An example is
here
.
The thing is, most sites (if you plan on calling this as a web service) will charge you for it.  Otherwise, throw together a web service that grabs a geolocation page, parses it for the address, and returns that piece of information.
In PHP, this seems to work pretty well:
```
```
<?php
 if(isset($_GET["ip"])){
   echo geolocate($_GET["ip"]);
 }

 function geolocate($ip){
   $raw_html = file_get_contents("http://www.geody.com/geoip.php?ip=$ip");
   if(preg_match('/Location:(.*)/',$raw_html,$matches)){
     $location_raw = $matches[1];

     //Get rid of pesky HTML tags
     $location = preg_replace("/<[^>]*>/","",$location_raw);
     return $location;
   }else{
     return "ERROR";
   }
 }
```
```


q:
all! Typing from Italy
This little piece of code works if the matrix size is less then 800 and fails with a segmentation fault for higher sizes....
I have tried it with gcc 4.3.2 compiler in linux and macosx and VisualStudio compiler in windows.
Seemsthe problem is in the stack size..... how can I increase it ?
How can I solve the problem for bigger matrix sizes ?
The code works fine in serial put fails in parallel execution.
 Thanks.

#include <omp.h>
#include <stdio.h>
#define Nu 4000
int main() {
float A[Nu][Nu],B[Nu][Nu],C[Nu][Nu];
int i,j;
#pragma omp parallel
printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
#pragma omp parallel for private(j,i) shared(A,B,C) schedule(static)
for(j=0;j<Nu;j++){
for(i=0;i<Nu;i++){
//printf("Hello from thread %d, i,j %d %d\n", omp_get_thread_num(),i,j );
A[i][j]=0;
B[i][j]=0;
C[i][j]=0;

}}

}

[A]
Default stack size in OpenMP is 4-8 MB. There's an environment variable called STACKSIZE you can change (for example to 16384, which is 16 MB). See chapter 5-5 of
this PDF
.


q:
How to find and remove unused Delphi runtime packages from a project that uses packages?

I have a Delphi project that is made up of several packages, in the requires part of the packages there are several Borland/3rd party packages listed (rtl.dcp, vcl.dcp ect) I know I need most of them, but there are ones I know I don't need that have crept in there over time, maybe a component used them once but then that component was removed, or maybe it was from me testing code.

How do I find out which are needed and which are not? and if they are not needed will they still need to be distributed with the final application or have any impact on the size/ memory requirement of the app?

I am trying to make it all as streamline as possible.

[A] If you specify a package to be used as runime package, all the packages that package requires need to be deployed as runtime package as well. Delphi's compiler automatically checks if this is the case. So you don't need to explicitly require rtl.dcp, as long as you require one of your other packages that does. This means you could only specify the runtime packages you are sure of you need and the rest will be added by the compiler. Then you only need to check what packages you need to deploy in the end.


q:
I have a space delimited list of files names, where spaces in the file names are prefixed by '\'

e.g. "first\ file second\ file"

How can I get my regex to match each file name?

[A]
```
```
(\\ |[^ ])+
```
```
Everything except spaces, except when they're escaped.  Should work, sorry for misunderstanding your question initially.


q: I understand SSO as the one time login for all the applications connected. I would like to know more about SSO and how exactly it is achieved.

[A]
This is Donnie. He's a friend of mine.
The basic mechanism is to trust your friend's friend.
Another metaphor that's used is the sticker they give you when you enter a secured building.  In the morning, you show your valid ID (credential) to the security person, and for the rest of the day, the sticker acts as the pass (token). When you come back next day, you have to show your ID again.
Key technology is how you trust your friend or security guy or anyone in hostile network. See how Kerberos or asymmetric encryption work.


q:
Are there Windows API functions that allows reading what the current password policy is?  For instance, minimum length, complexity etc.

If not reading, is there a way to verify a password against the policy programmatically?

[A]
See
Security Watch Windows Domain Password Policies
. You can hit AD using
ADSI
or its wrappers. I found a
VBScript sample
. You can translate it to any language you want:
```
```
Sub ListPasswordPolicyInfo( strDomain )
    Dim objComputer
    Set objComputer = GetObject("WinNT://" & strDomain )
    WScript.Echo "MinPasswordAge: " &  ((objComputer.MinPasswordAge) / 86400)
    WScript.Echo "MinPasswordLength: " &  objComputer.MinPasswordLength
    WScript.Echo "PasswordHistoryLength: " &  objComputer.PasswordHistoryLength
    WScript.Echo "AutoUnlockInterval: " &  objComputer.AutoUnlockInterval
    WScript.Echo "LockOutObservationInterval: " &  objComputer.LockOutObservationInterval
End Sub

Dim strDomain
Do
    strDomain = inputbox( "Please enter a domainname", "Input" )
Loop until strDomain <> ""

ListPasswordPolicyInfo( strDomain )
```
```
As a bonus, check out
LDAP Admin
. It's an open source LDAP directory editor, which you can use to test things, and also checkout the code written in Delphi.


q:
I need to deploy a web application on several laptops (although it is a web application, it is intended to run via localhost only - thus the need to deploy on several different machines).

Normally I would go to IIS and right click a directory to create a web application, but I would very much like to automate this leg of the installation. Can it be done?

I want to use IIS, but I want to create the web application automatically without opening the IIS Microsoft Management Console (MMC).

[A]
To implement a minimal web server you can use HTTP.SYS (the core component of IIS deployed with Windows XP SP2 or higher). In .NET this can be done e.g. by using the HttpListener class in the
System.Net
namespace.


q:
After creating a instance of a class, can we invoke the constructor explicitly?
For example

class A{
    A(int a)
    {
    }
}

A instance;

instance.A(2);

Can we do this?

[A]
You can use
placement new
, which permits
```
```
new (&instance) A(2);
```
```
However, from your example you'd be calling a constructor on an object twice which is very bad practice. Instead I'd recommend you just do
```
```
A instance(2);
```
```
Placement new is usually only used when you need to pre-allocate the memory (e.g. in a custom memory manager) and construct the object later.


q:
Using ICU 4.0 regex library, I find that the following regex is exhibiting exponential time:

actual: "[^<]*<\?"
C code: "[^<]*<\\?"

Aim: find "<?" where there is no other "<" before it

When running this regex on plain text with no "<" characters at all it appears to take exponential time. If the text has at least a single "<" then it is quick. I don't understand why.

Shouldn't the required match on "<?" prevent this from needing to backtrack? I would have thought that it would try to find the first "<" and then test the rest of the expression. If it can't find a "<" then it would give up because the pattern obviously can't match.

Is this a bug in the ICU regex or is it expected?

[A]
The regex engine isn't that smart. It will try to match from
every
position, and
each
time seach for
```
<?
```
from the end, and backtrack until the start of the match-attempt. This gives a quadratic time complexity, O(
n
2
).


q:
At the moment, I have some functions which look like this:

private bool inFunction1 = false;
public void function1()
{
    if (inFunction1) return;
    inFunction1 = true;

    // do stuff which might cause function1 to get called
    ...

    inFunction1 = false;
}

I'd like to be able to declare them like this:

[NoReEntry]
public void function1()
{
    // do stuff which might cause function1 to get called
    ...
}

Is there an attribute I can add to a function to prevent reentry?  If not, how would I go about making one?  I've heard about AOP attributes that can be used to add code before and after function calls; would they be suitable?

[A]
There is no such attribute predefined. You can make new attributes, but that won't help you. The issue is making the custom attribute prevent the method being called again, which I don't think is doable.
The lock statement is not what you want, since that will cause calls to block and wait, not return immediately.
PS: use a try ... finally block in the above sample. Otherwise, if an exception is thrown in the middle of the function, inFunction1 will be left true and all calls will return immediately.
e.g. :
```
```
if (inFunction1)
   return;

try
{
  inFunction1 = true;

  // do stuff which might cause function1 to get called
  ...
}
finally
{
  inFunction1 = false;
}
```
```


q:
I have a Java Swing application, developed on Mac OS X 10.5 using Java 1.5.

I'm trying to make a custom cursor appear when the user moves the mouse over some text in a dialog. The cursor never changes, though.

When I don't use a JFrame instead of a JDialog, the cursor does change. But then I'll have to write all the dialog code myself.

How can I get the cursor to appear?

Here's the simplest code I could create to demonstrate the problem:

import javax.swing.*;
import java.awt.*;

public class CursorTest {

    public static void main(String[] args) {
        JLabel label = new JLabel("Move mouse here for hand cursor");
        label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        JOptionPane pane = new JOptionPane(label);
        pane.setOptions(new Object[]{"OK"});

        JDialog dialog = pane.createDialog(null, "Test Dialog");
        dialog.setVisible(true);
    }
}

[A]
Looks like it is a bug in Java 1.5: I first tried with Java 1.6.0_07 and it worked as expected (on Windows XP). Then I recompiled with Java 1.5.0_06 and indeed the cursor remains in default state.
Knowing the difficulties of Java 1.6 on MacOS, I see it will be hard to fix that...
Bug ID: 5079694 JDialog doesn't respect setCursor
They give a workaround...
[EDIT] Tested workaround:
```
```
public class CursorTest extends JFrame
{
  private CursorTest()
  {
  }

  private void ShowDialog()
  {
        JLabel label = new JLabel("Move mouse here for hand cursor");
        label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        JOptionPane pane = new JOptionPane(label);
        pane.setOptions(new Object[] { "OK" } );

        JDialog dialog = pane.createDialog(this, "Test Dialog");
        dialog.setVisible(true);
  }

  public static void main(String[] args)
  {
    SwingUtilities.invokeLater(new Runnable()
    {
      public void run()
      {
        CursorTest testFrame = new CursorTest();
        testFrame.setTitle("Test GUI");
        testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        testFrame.setSize(500, 300);
        testFrame.setVisible(true);
        testFrame.ShowDialog();
      }
    });
  }
}
```
```
Works fine with my JDK & system.


q:
I've got a 1-based array of four items which I need to traverse. For a given index in the array, I need to work out the index of the next item, and the index of the previous item. This sounds simple but the array needs to wrap around. So when you are at the beginning of the array, the previous item is considered to be the last item. Likewise, if you are at the end of the array, the next item is considered to be the first item.

I realise this can be solved by using conditional statements, but I wondered if it was possible to do it using mathematical equations. I've got one that works nicely for the next item

NextItem = Modulus(CurrentItem, 4) + 1

(the modulus function returns the remainder of one number divided by another).

Has anyone got any ideas as to how I can work out the previous item?

[A]
Since modulo always works better on 0-based ranges, you can turn it into one of these using
```
CurrentItem - 1
```
.
Then, with modulo 4, adding 3 is the same as subtracting 1 but has the advantage of never going negative (some modulo operators may not like negatives).
Then you once again add 1 to get back to a 1-based number.
This gives:
```
```
PrevItem = Modulus(CurrentItem - 1 + 3, 4) + 1
```
```
or, simplified:
```
```
PrevItem = Modulus(CurrentItem + 2, 4) + 1
```
```


q:
class Score
{
    var $score;
    var $name;
    var $dept;
    var $date;

    function Score($score, $name, $dept, $date)
    {
        $this->scores = ($score);
        $this->name = ($name);
        $this->dept = ($dept);
        $this->date = ($date);
    }

    function return_score(){
        return $this->scores;
        return $this->name;
        return $this->dept;
        return $this->date;
    }
}

$newscore = new Score("131313","James", "Marketing", "19/05/2008");
echo $newscore->return_score();

The above code is only echoing 131313. I am just beginning to learn OO PHP so please go easy! Totally lost, so any help would be much appreciated.

[A]
You can only return one value in each function or method.
In your situation, you should have a method for each of the class members:
```
```
public function getScore() {
   return $this->score;
}

public function getName() {
   return $this->name;
}

public function getDept() {
   return $this->dept;
}

public function getDate() {
   return $this->date;
}
```
```
Edit after the comments:
You could also need a method that returns all the members as a single string:
```
```
public function getAll() {
   return $this->getScore(). " " .$this->getName() . " " .$this->getDept(). " " .$this->getDate();
}
```
```


q:
I am working in a project where there are configuration files, one in number for each of the environments where the application would be deployed.

When a developer modifies one of these files, the developer should not be allowed to check-in the file individually, but check-in all the files together or at least the developer should be informed that this needs to be done.

How can we achieve it?

[A]
I would think you could write a pre-commit hook to do this - just have a list of files where if one is committed then they must all be committed.
You can write hooks in any language that you can write a command-line application in.  The only gotcha is that they run in the context of the SVN server, and (at least traditionally, I don't know if this is improved), they aren't given much environment when they start - you can be caught out by a lack of 'PATH' for example.
Your repository will have example batchfile/shell-script hooks in the 'hooks' directory, but I've also written them in C# in the past.
This
http://wordaligned.org/articles/a-subversion-pre-commit-hook
looks like a good general introduction to pre-commit hooks.


q:
I'm currently using the following SQL for retrieving the last seven days worth of entries from a table:

purchased >= date_sub(now() ,interval 7 day)

However, I need to change this so it retrieves the last full weeks worth of entries (midnight Saturday to midnight Saturday). So basically, throughout the week the results never change, but when someone visits on Sunday morning they will have refreshed.

I just can't get my head around how to work out the days etc. Also, are there built in MySQL functions for doing this?

I hope I've explained that clearly enough.
This is in a PHP application.

[A]
MySQL has a
WEEK()
function, that allows you to get the numeric week of the year from a date.  You can get (the week of today) -1, and compare that to the week of your records you are filtering on.


q:
I want to convert a std::string to lowercase. I am aware of the function tolower(). However, in the past I have had issues with this function and it is hardly ideal anyway as using it with a std::string would require iterating over each character.

Is there an alternative which works 100% of the time?

[A]
Boost provides a string algorithm for this
:
```
```
#include <boost/algorithm/string.hpp>

std::string str = "HELLO, WORLD!";
boost::algorithm::to_lower(str); // modifies str
```
```
Or, for non-in-place
:
```
```
#include <boost/algorithm/string.hpp>

const std::string str = "HELLO, WORLD!";
const std::string lower_str = boost::algorithm::to_lower_copy(str);
```
```


q:
I have been given a .Hive file from a registry which i have to parse and use the contents as part of a html report(from this i assume i have to convert to text somehow). The whole thing must be done within the program so i cant just convert the hive file and then run it through my program. I currently have no idea how to even start this so any help on this would be great.

Any ideas would be fantastic!

[A]
Without seeing the input, it is hard to tell what the best approach is.  You are probably going to need to use the RegExp class to parse out your keys and values.  If you can get clean enough paths to the values, you might be able to get away with string.Split() to split the path into arrays of keys and walk the registry using those values.
Does the input set include the type of values, or can you assume that the values already exist in the registry?
A little more information on the input set would be useful.  An example, possibly?


q:
When I am single stepping through one thread of a multi threaded program, the debugger gets interrupted with:

0x(some hex ref) : tdb_event_death      : ret
dbx: thread has exited -- next aborted

My guess is a thread somewhere in the program I am debugging has stopped, but it's not the one I'm debugging so I can't see why I have to restart the debugging process to continue.

I have a work around,  I set a breakpoint on the next line then rerun, which works but is very annoying, it is really slowing down my debugging. Does anyone know a better way ?  (single step ALL threads for example)


q:
This is a contrived example, but lets say I have declared objects:

CustomObj fooObj;
CustomObj barObj;
CustomObj bazObj;

And I have an string array:

string[] stringarray = new string[] {"foo","bar","baz"};

How can I programmatically access and instantiate those objects using the string array, iterating using something like a foreach:

foreach (string i in stringarray) {
    `i`Obj = new CustomObj(i);
}

Hope the idea I'm trying to get across is clear. Is this possible in C#?

[A]
You need to be clear in your mind about the difference between an object and a variable. Objects themselves don't have names. Variable names are decided at compile-time. You can't access variables via an execution-time-determined name except via reflection.
It sounds like you
really
just want a
```
Dictionary<string, CustomObj>
```
:
```
```
Dictionary<string, CustomObj> map = new Dictionary<string, CustomObj>();

foreach (string name in stringArray)
{
    map[name] = new CustomObj(name);
}
```
```
You can then access the objects using the indexer to the dictionary.
If you're really trying to set the values of variables based on their name at execution time, you'll have to use reflection (see
Type.GetField
). Note that this won't work for local variables.


q:
I have a function which searches an STL container then returns the iterator when it finds the position, however I am getting some funny error messages, can tell me what I am doing wrong?

Function:

std::vector< CClass >::iterator CClass::SearchFunction( const std::string& strField )
{
...

   return it;

...
}

Error:

error C2664: 'std::_Vector_iterator<_Ty,_Alloc>::_Vector_iterator(const std::_Vector_iterator<_Ty,_Alloc> &)' : cannot convert parameter 1 from 'std::_Vector_const_iterator<_Ty,_Alloc> *__w64 ' to 'const std::_Vector_iterator<_Ty,_Alloc> &'

[A]
Your search function is returning a const_iterator. You should either return the same type, i.e.
```
std::vector< CClass >::const_iterator
```
, or cast it to a
```
std::vector< CClass >::iterator
```
if you intend the caller to be able to modify the found item through the iterator.
EDIT: after seeing your update, it seems the problem is your iterator (it) has a different type than your function return. They should be the same.
```
```
std::vector< CClass >::iterator it;
```
```


q:
My understanding is that you have to write unit tests that isolate functionality. So given a repository class that has this method:

Entity GetById(Guid id)

and a fake implementation (using a Dictionary for storage), how would you write a test without first adding an entity? Is it ok to use a known set of guids for testing? Then in the fake repository constructor I could fill the dictionary with a couple of entities where the guids follow a pattern, so that I can test the GetById() method with a guid that I know will return an entity.

Thanks for reading!

PS. This is my first time writing unit tests.

[A]
Yes, you could use known test ids in your test - that is what I would do.  Although I have become a fan of
Rhino Mocks
which lets you put more directly in the test about what you'd expect to the mock object to do.
For example just before your call to the repository, you would do this:
```
```
Expect.Call(repository.GetById("someObject")).Return(new RepositoryThing());
```
```
It appeals to me anyway :)


q: Windows Programming: How to put a file that is frequently accessed in the OS cache?

[A]
Disclaimer : I dont work all that much under Windows
In the general case, you shouldnt mess with your OS cache. It should be smart enough to cache data that are accessed often. If it isnt, you should use an application level cache. I dont know which language you are using, but most probably there is a good cache framework for your language.


q:
I know there is some similar issue.

But, still the question is not answered! I need to modify the connection string not add a new one.

[A]
This will help you out!
```
```
/// <summary>
        /// Add a connection string to the connection
        /// strings section and store it in the
        /// configuration file.
        /// </summary>
        /// <param name="csName">The name of the property.</param>
        /// <param name="connectionString">The connectionstring as specified.</param>
        public static void AddConnectionStrings(string csName, string connectionString)
        {

            // Get the configuration file.
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

            // Add the connection string.
            ConnectionStringsSection csSection = config.ConnectionStrings;
            csSection.ConnectionStrings.Add(
                new ConnectionStringSettings(csName,
                    connectionString, "System.Data.SqlClient"));

            // Save the configuration file.
            config.Save(ConfigurationSaveMode.Full);
        }
```
```
Well for updating it was hard to find any usefull
code to update a connectionstring. It wasn't possible
to update a connectionstring, so I had the remove the
connectionstring, and add a new one. Well isn't that odd??
Microsoft left something undone... Well maybe it isn't usefull
to change your app.config, but well, I had to make it anyhow.
So dynamic app.config or web.config files is little bit strange, because you can't dynamically update it. No you have to remove it first by the configurationmanager.
```
```
/// <summary>
        /// First remove the old connectionstring and after that
        /// add a connection string to the connectionstrings
        /// section and store it in the configuration file.
        /// </summary>
        /// <param name="csName">The name of the property.</param>
        /// <param name="connectionString">The connectionstring as specified.</param>
        public static void UpdateConnectionStrings(string csName, string connectionString)
        {
            // Get the configuration file
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

            // Remove the existing connectionstring.
            config.ConnectionStrings.ConnectionStrings.Remove(csName);
            // Add the connectionstring
            ConnectionStringsSection csSection = config.ConnectionStrings;
            csSection.ConnectionStrings.Add(
                new ConnectionStringSettings(csName,
                connectionString, "System.Data.SqlClient"));

            // Save the configuration file
            config.Save(ConfigurationSaveMode.Full);
        }
```
```


q:
Is there a way to get MVEL 2.0 ( http://mvel.codehaus.org/ ) to work with functions with optional parameters?

I would like to be able to eval this:

trunc('blahblah',2)

but also

trunc('blahblah',2,'[...]');

Now i have tried:

def trunc(param1,param2,param3) { ... impl ... }

That gives an exception if i try to call it with only 3 parameters.
I also tried:

def trunc(param1,param2,param3) { ... impl ... }
def trunc(param1,param2) { ... impl ... }

But the second one seems to completely overwrite the first definition.

Thanks

[A]
In java you can declare multiple methods with the same name, but a different arguments.
That way you can support (in a limited way) optional parameters.
Eg.:
```
```
private void method(Object obj1) {
    Object obj2 = new Object("Default");
    method(obj1, obj2);
}

private void method(Object obj1, Object obj2) {
    doStuff(...);
}
```
```
Calling method() is possible with one or two arguments :)


q:
How can I make this java generic cast ?

public interface IField {

}

class Field implements IField { // package private class

}

public class Form {
  private List<Field> fields;

  public List<IField> getFields() {
    return this.fields;

  }

}

The return statement throws a compiler error (I know the reason - I read the generics tutorial) but it would be very handy to write such code.

If I declared "fields" as List I would need to use a lot of casts to Field in other methods of a Form class .

Can I force that damn compiler to bend it's rules and compile that return statement ?

Thanks in advance.

[A]
As it happens, you can, because Java generics are just grafted on, not part of the type system.
You can do
```
```
return (List<IField>)(Object)this.fields;
```
```
because all
```
List<T>
```
objects are the same underlying type.
Bear in mind that this allows anyone to put any type implementing
```
IField
```
in your list, so if your collection is not read-only, you may run into difficulties.


q:
With PHP, I can make numerous PHP websites locally and then upload each of them to its own sub-directory of my PHP hosting service.

However, with ASP.NET, it seems that I can only upload my ASP.NET to the root of my hosting service. If I upload to a sub-directory, I get an error in

section registered as allowDefinition='MachineToApplication' beyond application level
<authentication mode="Windows"/>

is there a way to get around this so I can have numerous ASP.NET websites each in its own directory?

if not, would using ASP.NET MVC be able to get around this problem?

or is it generally not possible to FTP multiple ASP.NET sites to a shared hosting provider?


q:
I am looking for a good Environment (GUI based Editor) for blackberry webapps.
e.g., is there a Eclipse plugin out there ?

[A]
The Blackberry Applications are developed in Java and RIM provides the needed tools and simulators here:
http://na.blackberry.com/eng/developers/resources/devtools.jsp


q:
I'm trying to create a pimped-out version of the slider that has a user control in the "thumb"-part (meaning: the moving thingy on the slider) that reacts to the slider's movements. Basically my current demo / development version is just a UserControl with 5 visual states that just make it change a smiley face to an angry face in 5 phases. I'd like to put that user control into the thumb.

My only problem is as follows: I can get the UserControl into the thumb no problem, by editing the Slider-control's template in Expression Blend. However, once the UserControl is in the ControlTemplate, it's no longer visible to the new user control class and thus is not changeable with VisualStateManager.

So basically, my question is two-fold:

Is there any better way to replace the thumb of the Slider-control than editing it's template?

If not, how can I access stuff I've added to the template?

Thanks for any answers!

[A]
I'm answering myself. After visiting every single page on the internet, I finally figured out a solution by myself!
I added a Loaded-event handler to my control in the ControlTemplate and in that event handler I took the reference to that control for the actual class! After that I was able to refer to that control with that reference and for example visualstate changes worked like a charm!
I've now got a hopped-up slider that has a smiley in the handle part and the face on the smiley changes in relation to the position of the slider! Pretty cool!


q:
Here's a simplified version of my scenario:

I have a table named Project that I reference via an 'id' field.

I have a table named Photo that has a field named 'project_id' which I use to relate multiple photos to a single project. The Photo table also has an auto-incrementing 'id' field that I use for ordering, amongst other things.

Here's what I want to accomplish: For a collection of Project id values, I wish to retrieve the last 5 photos added to each project -- ideally in a single query, of course. :-)

Put another way, instead of imposing a single query limit, I would ideally like to specify a per project limit on the number of photos returned.

I am currently implementing this as one-query per project, so N projects = N queries (a good caching strategy will certainly reduce the hurt, but that'll come later).

Anyone have a solution?

Thanks.

[A]
For the "last n items" problem in MySQL, take look here:
How to select maximum 3 items per users in MySQL?
(it's right in the top answer).
When you take it from there, all you are missing is a JOIN with your
```
Projects
```
table, which should be easy to do.


q: I'm looking for way to grab the content of my opengl (as UIImage) and then save it into a file. I'm now giving glReadPixels a try though I'm not sure I'm doing the right thing as of what kind of malloc I should be doing. I gather that on OSX it's GL_BGRA but on the iPhone that doesn't work...

[A]
All OpenGL|ES complient GL-implementations have to support GL_RGBA as a parameter to glReadPixels.
If your OpenGL|Es supports the
```
```
GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES
```
```
extension you can also query the native format. glReadPixels will understand this format as a parameter to glReadPixels and allows you to directly get the pixel-data in native format. This is usually a bit faster than GL_RGBA.
Take a look at the header-file or query the extension-support via glGetString.


q:
My Cocoa app needs some small dynamically generated windows. How can I programmatically create Cocoa windows at runtime?

This is my non-working attempt so far. I see no result whatsoever.

NSRect frame = NSMakeRect(0, 0, 200, 200);
NSUInteger styleMask =    NSBorderlessWindowMask;
NSRect rect = [NSWindow contentRectForFrameRect:frame styleMask:styleMask];

NSWindow * window =  [[NSWindow alloc] initWithContentRect:rect styleMask:styleMask backing: NSBackingStoreRetained    defer:false];
[window setBackgroundColor:[NSColor blueColor]];
[window display];

[A]
This is what I've come up with myself:
```
```
NSRect frame = NSMakeRect(100, 100, 200, 200);
NSUInteger styleMask =    NSBorderlessWindowMask;
NSRect rect = [NSWindow contentRectForFrameRect:frame styleMask:styleMask];
NSWindow * window =  [[NSWindow alloc] initWithContentRect:rect styleMask:styleMask backing: NSBackingStoreBuffered    defer:false];
[window setBackgroundColor:[NSColor blueColor]];
[window makeKeyAndOrderFront: window];
```
```
This displays a blue window. I hope this is the optimal approach.


q: I have an application that needs to send a moderately high volume of messages between a number of AppDomains.  I know that I could implement this using remoting, but I have also noticed that there are cross-domain delegates.  Has anyone looked at this kind of problem?

[A]
This is just a quick thought, but I heard that even for cross-domain communication
WCF
would be the recommended approach, starting from .NET 3.0 of course. Actually this makes sense, as remoting is just another technology wrapped by WCF.


q:
I am getting an vba error 3271; Invalid property value.  This happens when trying to append a memo field in a querydef.  Any ideas on how to get around this?

Example:

public sub TestMemoField
    Dim qdf As QueryDef
    Set qdf = CurrentDb.QueryDefs("AppendRecord")
    qdf.Parameters("@SomeBigText").value = string(1000,"A")
    qdf.Execute
end sub

Thanks in advance.

[A]
Apparently you cannot have a parameter longer than 255 characters (
http://support.microsoft.com/kb/275116
).
It is possible to use a recordset, or to use:
```
```
qdf.SQL="INSERT INTO Sometable (SomeField) Values('" & String(1000, "A") & "')"
```
```


q:
I am using Oracle BPEL Process manager and have a task assigned to a group of users.
I try to mark it approved using Java class oracle.bpel.services.workflow.task.ITaskService.updateTaskOutcome(). This works if the task is assigned to an individual user, but if the task is assigned to a group of users, I get an error message about the task not being acquired.

If I acquire the task using oracle.bpel.services.workflow.task.ITaskService.acquireTask(), I get an error message when trying to mark it approved: "The task has been acquired by some other user".

Can anybody point to sample code that changes status of an Oracle BPEL task assigned to a group programmatically?

[A]
use
```
updateTaskOutcomes()
```
method instead of
```
updateTaskOutcome()
```
when it is assigned to multiple users


q:
I have two tables: a source table and a target table.  The target table will have a subset of the columns of the source table.  I need to update a single column in the target table by joining with the source table based on another column.  The update statement is as follows:

UPDATE target_table tt
SET special_id = ( SELECT source_special_id
                   FROM source_table st
                   WHERE tt.another_id = st.another_id )

For some reason, this statement seems to run indefinitely.  The inner select happens almost immediately when executed by itself.  The table has roughly 50,000 records and its hosted on a powerful machine (resources are not an issue).

Am I doing this correctly?  Any reasons the above wouldn't work in a timely manner?  Any better way to do this?

[A]
Update:
Ok, now that the query has been fixed -- I've done this exact thing many times, on unindexed tables well over 50K rows, and it worked fine in Oracle 10g and 9i.  So something else is going on here; yes, you are calling for nested loops, but no, it shouldn't run forever, even so.  What are the  primary keys on these tables? Do you by any chance have multiple rows from the second table matching the same row for the first table?  You could be trying to rewrite the whole table over and over, throwing the locking system into a fit.
Original Response
That statement doesn't really make sense -- you are telling it to update all the rows where ids match, to the same id (meaning, no change happens!).
I imagine the real statement looks a bit different?
Please also provide table schema information (primary keys for the 2 tables, any available indexes, etc).


q:
I have a rather large (many gigabytes) table of data in SQL Server that I wish to move to a table in another database on the same server.

The tables are the same layout.

What would be the most effecient way of going about doing this?

This is a one off operation so no automation is required.

Many thanks.

[A]
If it is a one-off operation, why care about
top
efficiency so much?
```
```
SELECT * INTO OtherDatabase..NewTable FROM ThisDatabase..OldTable
```
```
or
```
```
INSERT OtherDatabase..NewTable
SELECT * FROM ThisDatabase..OldTable
```
```
...and let it run over night. I would dare to say that using SELECT/INSERT INTO on the same server is not far from the best efficiency you can get anyway.


q:
I've looked this up a thousand times, and I always forget it, so, here for eternity:

Solaris has a bit of an awkward syntax for tail.

How do I do the equivalent of BSD's tail -nN?

What I want are the last N lines from tail's input.

[A]
Just remove the "n"
```
```
tail -100
```
```


q: Which is a better way to force GC on ThreadLocal instance?

[A]
Simple answer: you can't force the GC in java. Some may posts tricks but all in all you simply can't.
Well, in fact you can. With exit!


q:
Say I have a file with any number of lines, say, 125. I want to get all the lines except the first n, say, 20. So, I want lines 21–125.

Is there a way to do this with with tail/head, or some other tool?

[A]
Try
```
```
tail -n +21 myfile.txt
```
```


q: How to generate the Symbols file of a PowerBuilder program for dump analysis?


q:
I need to upgrade my current version of DNN this week. I am currently using 2.1.1. I don't want to do everything twice, so, I have several questions.

Is there an upgrade tool or some scripts somewhere that will help me to do an upgrade.

Am I better off installing 4.9 or 5.0. It is production.

If I go with 4.9, will I be able to upgrade to 5.0 when it releases?

[A] To be honest, I don't know.  But I see that the DNN download page very strongly states that the 5.0 release-candidates are "NOT RECOMMENDED FOR PRODUCTION USE".


q:
I am using an Infragistics UltraGrid in a WinForms application.

Which event is raised on "check change" of checkbox in Infragistics UltraGrid?

[A]
The AfterUpdate event of the checkbox is what you'll want to use.
If you're not able to trigger it, though, try adding this as well:
```
```
Private Sub YourGridcontrol_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles YourGridcontrol.MouseDown
    YourGridcontrol.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.EnterEditMode)
End Sub

Private Sub YourGridcontrol_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles YourGridcontrol.MouseUp
    YourGridcontrol.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.ExitEditMode)
End Sub
```
```
By default, just toggling the checkbox doesn't seem to trigger an Update. By making it enter/exit edit mode, the AfterUpdate should work as you want.
UPDATE: Or, like Vincent suggested, doing the PerformAction on the CellChange event should work, too.  The gist is the same.


q:
How do you parse a CSV file using gawk?  Simply setting FS="," is not enough, as a quoted field with a comma inside will be treated as multiple fields.

Example using FS="," which does not work:

file contents:

one,two,"three, four",five
"six, seven",eight,"nine"

gawk script:

BEGIN { FS="," }
{
  for (i=1; i<=NF; i++) printf "field #%d: %s\n", i, $(i)
  printf "---------------------------\n"
}

bad output:

field #1: one
field #2: two
field #3: "three
field #4:  four"
field #5: five
---------------------------
field #1: "six
field #2:  seven"
field #3: eight
field #4: "nine"
---------------------------

desired output:

field #1: one
field #2: two
field #3: "three, four"
field #4: five
---------------------------
field #1: "six, seven"
field #2: eight
field #3: "nine"
---------------------------

[A]
Here's what I came up with.  Any comments and/or better solutions would be appreciated.
```
```
BEGIN { FS="," }
{
  for (i=1; i<=NF; i++) {
    f[++n] = $i
    if (substr(f[n],1,1)=="\"") {
      while (substr(f[n], length(f[n]))!="\"" || substr(f[n], length(f[n])-1, 1)=="\\") {
        f[n] = sprintf("%s,%s", f[n], $(++i))
      }
    }
  }
  for (i=1; i<=n; i++) printf "field #%d: %s\n", i, f[i]
  print "----------------------------------\n"
}
```
```
The basic idea is that I loop through the fields, and any field which starts with a quote but does not end with a quote gets the next field appended to it.


q:
What is the simplest way to read a full line in a C console program
The text entered might have a variable length and we can't make any assumption about its content.

[A]
You need dynamic memory management, and use the
```
fgets
```
function to read your line. However, there seems to be no way to see how many characters it read. So you use fgetc:
```
```
char * getline(void) {
    char * line = malloc(100), * linep = line;
    size_t lenmax = 100, len = lenmax;
    int c;

    if(line == NULL)
        return NULL;

    for(;;) {
        c = fgetc(stdin);
        if(c == EOF)
            break;

        if(--len == 0) {
            len = lenmax;
            char * linen = realloc(linep, lenmax *= 2);

            if(linen == NULL) {
                free(linep);
                return NULL;
            }
            line = linen + (line - linep);
            linep = linen;
        }

        if((*line++ = c) == '\n')
            break;
    }
    *line = '\0';
    return linep;
}
```
```
Note
: Never use gets ! It does not do bounds checking and can overflow your buffer


q:
Why use a GlobalClass? What are they for? I have inherited some code (shown below) and as far as I can see there is no reason why strUserName needs this. What is all for?

public static string strUserName
    {
        get { return m_globalVar; }
        set { m_globalVar = value; }
    }

Used later as:

GlobalClass.strUserName

Thanks

[A]
When you want to use a
static
member of a type, you use it like
```
ClassName.MemberName
```
. If your code snippet is in the same class as the member you're referring (in this example, you're coding in a GlobalClass member, and using strUserName) you
can
omit the class name. Otherwise, it's required as the compiler wouldn't have any knowledge of what class you're referring to.


q:
How can I go through each of the properties in my custom object? It is not a collection object, but is there something like this for non-collection objects?

For Each entry as String in myObject
    ' Do stuff here...
Next

There are string, integer and boolean properties in my object.

[A]
By using reflection you can do that. In C# it looks like that;
```
```
PropertyInfo[] propertyInfo = myobject.GetType().GetProperties();
```
```
Added a VB.Net translation:
```
```
Dim info() As PropertyInfo = myobject.GetType().GetProperties()
```
```


q:
I am using Visual Studio 2005 and StarTeam 2008 (cross-platform client and VS integration). At some point, I added an 'App.config' to a project. I notice now that this file will not check-in.

The 'StarTeam Pending Checkins' window in VS reports the file 'Not in View'. Selecting it for check in and clicking 'Check In Files' causes a dialog to appear - 'Any operation... requires completing the pending renames/deletes'. I click 'Yes' to proceed and nothing happens.

The StarTeam client reports this file as 'Modified'. If I check-in from the client, I get no 'complete pending renames/deletes' dialog and the file quickly appears with a 'Current' status.

Refreshing StarTeam from VS, I still see the file as 'Not in View'.

I have tried forcing the check-in. I completely removed my working files and pulled the solution fresh in hopes that the StarTeam status ('Current') would apply in VS.


q:
If you call a web service from Silverlight like this:

MyServiceClient serviceClient = new MyServiceClient();
void MyMethod()
{
  serviceClient.GetDataCompleted += new EventHandler<GetDataCompletedEventArgs>(serviceClient_GetDataCompleted);
  serviceClient.GetDataAsync();

  // HOW DO I WAIT/JOIN HERE ON THE ASYNC CALL, RATHER THAN BEING FORCE TO LEAVE THIS METHOD?

}

I would rather wait/join with the asych service thread inside "MyMethod" rather than leaving "MyMethod" after calling "GetDataAsync", what is the best way to do this?

Thanks,
Jeff

[A]
To do this you would use a
ManualResetEvent
in your class (class level variable) and then wait on it.
```
```
void MyMethod()
{
  wait = new ManualResetEvent(false);
  // call your service
  wait.WaitOne();
  // finish working
}
```
```
and in your event handler code
```
```
void serviceClient_GetDataCompleted(...)
{
  // Set values you need from service
  wait.Set();
}
```
```


q:
In Team Build 2008, the Drop Location for a build is no longer specified in the .proj file, and instead is stored in the database and maintained in the GUI tool.

The GUI tool only accepts a network path as a drop location (i.e. \\server\share) and will not accept a local path.

Our build server also hosts the dropped files, so it seems that forcing a file copy operation to go through the network share introduces a lot of lag time when copying a large number of files. I would like to override this feature so that I can specify a local directory for drop location, but I can't figure out how.

[A]
The connections only seem to stay in the pool and not being reused in case you get an exception, just like the example. If you increase the timeout the connection will be reused.
A workaround to this problem is to clear the connection pool in case you get an exception like this:
```
```
using (SqlConnection con = new SqlConnection(connectionString))
{
    con.Open();
    try
    {
        Console.WriteLine("Server is {0}", con.ServerVersion);
        Console.WriteLine("Clr is {0}", Environment.Version);
        for (int i = 0; i < 5; i++)
        {
            using (SqlCommand cmd = con.CreateCommand())
            {
                cmd.CommandText = "insert into TXTEST values ( " + i + " )";
                cmd.ExecuteNonQuery();
            }
            Console.WriteLine("Row inserted");
        }
        Thread.Sleep(TimeSpan.FromSeconds(1));
    }
    catch
    {
        SqlConnection.ClearPool(con);
        throw;
    }
}
```
```
In most cases the transaction will complete within the timeout and everything will be fine and dandy. When the transaction
actually do
timeout you clear the pool in order to clean up the dirty connections that won't get reused. This will of course affect other connections in the pool that isn't affected by this problem.
This is a ugly workaround but it seems to work.


q: Is there an easy way to generate an array containing the letters of the alphabet in C#? It's not too hard to do it by hand, but I was wondering if there was a built in way to do this.

[A]
I don't think there is a built in way, but I think the easiest would be
```
```
char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
```
```


q:
I'm looking for articles, forum or blog posts dealing with SharePoint and thread safety? I'm quite sure there are some special aspects regarding thread safety that have to be considered when working with the SharePoint object model.

Actually I didn't find many information about this, yet.

So I'm looking forward to your answers.

Bye,
Flo

[A]
There are much worse pitfalls in the SharePoint OM than just plain old thread safety. Pay particular attention to working with objects retrieved from properties. You should
always
keep a pointer to an object while you work on it; example:
```
```
var list = web.List["MyList"]
list.Items[0]["Field1"] = "foo"
list.Items[0]["Field2"] = "bar"
list.Items[0].Update() // nothing is updated!
```
```
You might expect Field1 and Field2 to be updated by the final Update() call, but nope. Each time you use the indexer, a NEW reference to the SPListItem is returned.
Correct way:
```
```
SPListItem item = list.Items[0]
item["Field1"] = "foo"
item["Field2"] = "bar"
item.Update() // updated!
```
```
Just a start. Also google for pitfalls around the IDisposabe/Dispose pattern.
-Oisin


q:
I am fetching data in  from an SQL table using a DataSet in VB.Net. When there is data in table, it displays the data properly in the grid, but when there is no data in the table, it only shows the UltraGrid's basic view.

How can I display the column names of the table as headings of the UltraGrid even when there is no data in Table?

Thanks for the reply, but I think the problem that JD is having is a bit different from mine - in my application the data got fetched properly from SQL Server. My problem is that when there is no data in the table, I want to display the columns of the table as the headings of the grid with 0 rows. This is not happening.

It just shows a message box saying that no data is found, and the UltraGrid shows as it does by default in the application.

[A]
Have you checked to make sure that the Active Directory change has propagated to TFS?  I've seen issues before where users information is changed and TFS doesn't pick up the change and gets confused about your user.
Also take a look at the following blog post.  It details how to sync up TFS with a user name change in Active Directory
http://blogs.msdn.com/teams_wit_tools/archive/2007/03/15/handling-display-name-changes-in-team-foundation-server.aspx


q:
I've got an array of char* in a file.
The company I work for stores data in flat files.. Sometimes the data is sorted, but sometimes it's not.
I'd like to sort the data in the files.

Now I could write the code to do this, from scratch.
Is there an easier way?

Of course an in-place sort would be the best option. I'm working on large files and have little RAM. But I'll consider all options.

All strings are the same length.

This is some sample data:

the data is of fixed length
the Data is of fixed length
thIS data is of fixed lengt

This would represent three records of length 28. The app knows the length. Each record ends with CRLF (\r\n), though it shouldn't matter for this sort.

[A]
```
```
template<size_t length> int less(const char* left, const char* right) {
    return memcmp(left, right, length) < 0;
}

std::sort(array, array + array_length, less<buffer_length>);
```
```


q:
I have an xml web service which I use at work to make a request to. This request, an xml document, includes information such as recipients, subject, body, etc (as a newsletter would contain).

I have an ASP.NET form to enter the above information to, to form the Xml document, and I can type foreign characters (non latin - Japanese, Chinese, Russian etc).

If I step through my code, the foreign characters are displayed ok. The xml has an encoding of utf-8 and I load the strings into the attributes of my xml document so I shouldn't need to do anything at a string level with encoding.

I am on webmail because of an unrelated technical matter, but my boss has Outlook 2007 Pro and hasn't got an email with a foreign text subject line. However, if the xml is manually posted via the internal test harness, as opposed to the .NET way of methods/variables (OOP) etc, it will work. So there is a failing in .NET somewhere.

Any ideas?


q:
Possible Duplicate:

  How do I mark a method as Obsolete/Deprecated? - C#

How do you mark a class as deprecated? I do not want to use a class any more in my project, but do not want to delete it before a period of 2 weeks.

[A]
You need to use the
```
[Obsolete]
```
attribute.
Example:
```
```
[Obsolete("Not used any more", true)]
public class MyDeprecatedClass
{
    //...
}
```
```
The parameters are optional. The first parameter is for providing the reason it's obsolete, and the last one is to throw an error at compile time instead of a warning.


q:
When obtaining the DPI for the screen under Windows (by using ::GetDeviceCaps) will the horizontal value always be the same as the vertical?  For example:

HDC dc = ::GetDC(NULL);
const int xDPI = ::GetDeviceCaps(dc, LOGPIXELSX);
const int yDPI - ::GetDeviceCaps(dc, LOGPIXELSY);
assert(xDPI == yDPI);
::ReleaseDC(NULL, dc);

Are these values ever different?

[A]
I have never seen them be different, but on
this
MSDN page I see a comment that suggests that they might be:
```
```
int nHorz = dc.GetDeviceCaps(LOGPIXELSX);
   int nVert = dc.GetDeviceCaps(LOGPIXELSY);

   // almost always the same in both directions, but sometimes not!
```
```


q:
I'm code reviewing a change one of my co-workers just did, and he added a bunch of calls to Date.toMonth(), Date.toYear() and other deprecated Date methods.  All these methods were deprecated in JDK 1.1, but he insists that it's ok to use them because they haven't gone away yet (we're using JDK 1.5) and I'm saying they might go away any day now and he should use Calendar methods.

Has Sun/Oracle actually said when these things are going away, or does @deprecated just mean you lose style points?

[A]
They're not going away.  That said, they're usually deprecated because a) they're dangerous ala Thread.stop(), or b) there is a better or at least more accepted way to do it.  Usually deprecated method javadoc will give you a hint as to the better way.  In your case, Calendar is the recommended way to do this.
While it's conceivable that they will be removed at some point in the future, I wouldn't bet on it.  If anyone ever forks Java however, they'll probably be the first thing to go...


q:
In Linqtosql how do I show items from multiple rows in a single field.

eg I have a 3 table setup for tagging(entity, tag, entitytag) all linked via foreign keys.

For each entity I would like to return the name in one field and then all relevant tags in 2nd field.

eg Item1, tag1; tag2; tag3
   Item2, tag4, tag5....

VB statements preferred.

Thanks
Geoff

[A]
Okay, not sure if this is the most efficient way but it works.
```
```
Dim dc As New DataContext

Dim query = From i In dc.Items _
            Let tags = (From t In dc.ItemTags _
                        Where t.ItemID = i.ID _
                        Select t.Tag.Name).ToArray _
            Select i.ItemName, Tags = String.Join(" | ", tags)
```
```


q:
I'm trying to use route constraints in an Asp.Net MVC Application.

routes.MapRoute(
    "theRoute",
    "MyAction/{page}",
    new { controller = "TheController", action = "MyAction", page = 1 },
    new { page = @"[0-9]" });

When I enter an url like ~/MyAction/aString, an YSOD is shown with an invalid operation exception. What can I do to redirect invalid url to the 404 page?

I know I can solve the issue with a string parameter in the controller action and int.TryParse, but then the route constaint is useless.

How can I choose the exceptiontype that is thrown by the route constraints?

[A]
The problem is that you do not have a route that matches the route that ends in a string.
Modify your routes similar to:
```
```
routes.MapRoute(
    "Default",                                              // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = 0 },
    new { id = "[0-9]" }// Parameter defaults
);
routes.MapRoute(
    "Default2",                                              // Route name
    "{controller}/{action2}/{sid}",                           // URL with parameters
    new { controller = "Home", action = "Index2", sid = "" }  // Parameter defaults
);
```
```
and modify your controller
```
```
public ActionResult Index(int id)
    {
        ViewData["Title"] = "Home Page";
        ViewData["Message"] = "Welcome to ASP.NET MVC! Your id is: "+ id.ToString();

        return View();
    }

    public ActionResult Index2(string sid)
    {
        ViewData["Title"] = "Home Page 2."+sid.ToString();
        ViewData["Message"] = "Welcome to ASP.NET MVC! \"" + sid.ToString() +"\" is an invalid id";

        return View("index");
    }
```
```
now when you pass a string for the ID, Index2 will be called and you can do whatever you need to do to handle the incorrect parameter.


q:
Can somebody please give me an example of a unidirectional @OneToOne primary-key mapping in Hibernate ? I've tried numerous combinations, and so far the best thing I've gotten is this :

@Entity
@Table(name = "paper_cheque_stop_metadata")
@org.hibernate.annotations.Entity(mutable = false)
public class PaperChequeStopMetadata implements Serializable, SecurityEventAware {

private static final long serialVersionUID = 1L;

@Id
@JoinColumn(name = "paper_cheque_id")
@OneToOne(cascade = {}, fetch = FetchType.EAGER, optional = false, targetEntity = PaperCheque.class)
private PaperCheque paperCheque;
}

Whenever Hibernate tries to automatically generate the schema for the above mapping, it tries to create the primary key as a blob, instead of as a long, which is the id type of PaperCheque.  Can somebody please help me ?  If I can't get an exact solution, something close would do, but I'd appreciate any response.

[A]
I saved
this discussion
when I implemented a couple of @OneToOne mappings, I hope it can be of use to you too, but we don't let Hibernate create the database for us.
Note the GenericGenerator annotation.
Anyway, I have this code working:
```
```
@Entity
@Table(name = "message")
public class Message implements java.io.Serializable
{
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "message_id")
    public MessageContent getMessageContent()
    {
        return messageContent;
    }
}

@Entity
@Table(name = "message_content")
@GenericGenerator(name = "MessageContent", strategy = "foreign",
    parameters =
    {
      @org.hibernate.annotations.Parameter
      (
        name = "property", value = "message"
      )
    }
)
public class MessageContent implements java.io.Serializable
{
    @Id
    @Column(name = "message_id", unique = true, nullable = false)
    // See http://forum.hibernate.org/viewtopic.php?p=2381079
    @GeneratedValue(generator = "MessageContent")
    public Integer getMessageId()
    {
            return this.messageId;
    }
}
```
```


q:
I have written a program in C to parse large XML files and then create files with insert statements.  Some other process would ingest the files into a MySQL database.
This data will serve as a indexing service so that users can find documents easily.

I have chosen InnoDB for the ability of row-level locking.  The C program will be generating any where from 500 to 5 million insert statements on a given invocation.

What is the best way to get all this data into the database as quickly as possible?  The other thing to note is that the DB is on a separate server.  Is it worth moving the files over to that server to speed up inserts?

EDIT:  This table won't really be updated, but rows will be deleted.

[A]
I'd do at least these things according to
this link
:
Move the files there and connect over the unix socket
Generate, instead of the INSERTS, a
LOAD DATA INFILE
file
Disabling indexes during the loading


q:
I have a bunch of generic interfaces and classes

public interface IElement {
// omited
}

class Element implements IElement {
// omited
}

public interface IElementList<E extends IElement>  extends Iterable {
   public Iterator<E> iterator();
}

class ElementList implements IElementList<Element> {

    public Iterator<Element> iterator() {
       // omited
       }
}

public interface IElementListGroup<E extends IElementList<? extends IElement>> {
    public E getChosenElementList();
}

class ElementListGroup implements IElementListGroup<ElementList> {
    public ElementList getChosenElementList() {
        // omited
    }
}

And then a simple code

ElementListGroup group;

for(Element e : group.getChosenElementList())
{
 // omited
}

And the line with for keyword throwe a "cannot convert from element type Object to Element" compiler error.

Thanks in advance.

[A]
```
IElementList
```
needs to implement
```
Iterable<E>
```
. Otherwise, the interface specifies
```
Iterator iterator()
```
, not
```
Iterator<E> iterator()
```
. This makes the compiler think that you're iterating over
```
Object
```
s.
I made this change, and it compiled fine (after adding some null returns).


q:
If you know the Index, Value or Text. also if you don't have an ID for a direct reference.

This, this and this are all helpful answers.

Example markup

<div class="selDiv">
  <select class="opts">
    <option selected value="DEFAULT">Default</option>
    <option value="SEL1">Selection 1</option>
    <option value="SEL2">Selection 2</option>
  </select>
</div>

[A]
Answering my own question for documentation. I'm sure there are other ways to accomplish this, but this works and this code is tested.
```
```

Update

        <select class="opts">
            <option selected value="DEFAULT">Default</option>
            <option value="SEL1">Selection 1</option>
            <option value="SEL2">Selection 2</option>
        </select>

```
```


q:
I'm trying to get a regex that will match:

somefile_1.txt
somefile_2.txt
somefile_{anything}.txt

but not match:

somefile_16.txt

I tried

somefile_[^(16)].txt

with no luck (it includes even the "16" record)

[A]
Some regex libraries allow lookahead:
```
```
somefile(?!16\.txt$).*?\.txt
```
```
Otherwise, you can still use multiple character classes:
```
```
somefile([^1].|1[^6]|.|.{3,})\.txt
```
```
or, to achieve maximum portability:
```
```
somefile([^1].|1[^6]|.|....*)\.txt
```
```
```
[^(16)]
```
means: Match any character but braces, 1, and 6.


q:
I have this rewrite rule

RewriteEngine On
RewriteBase /location/
RewriteRule ^(.+)/?$ index.php?franchise=$1

Which is suppose to change this URL

http://example.com/location/kings-lynn

Into this one

http://example.com/location/index.php?franchise=kings-lynn

But instead I am getting this

http://example.com/location/index.php?franchise=index.php

Also, adding a railing slash breaks it. I get index.php page showing but none of the style sheets or javascript are loading.

I'm clearly doing something very wrong but I have no idea what despite spending all day R'ingTFM and many online primers and tutorials and questions on here.

[A]
Your problem is you are redirecting twice.
```
'location/index.php'
```
matches the regex
```
^(.+)/?$
```
You want to possibly use the "if file does not exist" conditional to make it not try mapping a second time.
```
```
RewriteEngine on
RewriteBase /location/
RewriteCond %{REQUEST_FILENAME} !-f   # ignore existing files
RewriteCond %{REQUEST_FILENAME} !-d   # ignore existing directories
RewriteRule ^(.+)/?$ index.php?franchise=$1  [L,QSA]
```
```
And additonally, theres the [L,QSA] which tries to make it the "last" rule ( Note, this is not entirely obvious how it works ) and append the query string to the query, so that
```
```
location/foobar/?baz=quux  ==> index.php?franchise=$1&baz=quux
```
```
( i think )


q:
Every example I've seen of CGI/Perl basically a bunch of print statements containing HTML, and this doesn't seem like the best way to write a CGI app.  Is there a better way to do this?  Thanks.

EDIT: I've decided to use CGI::Application and HTML::Template, and use the following tutorial: http://docs.google.com/View?docid=dd363fg9_77gb4hdh7b.  Thanks!

[A]
Absolutely (you're probably looking at tutorials from the 90s). You'll want to pick a framework. In Perl-land these are the most popular choices:
CGI::Application
- very lightweight with lots of community plugins
Catalyst
- heavier with more bells and whistles
Jifty
- more magical than the above


q:
I've got a maintenance plan that executes weekly in the off hours. It's always reporting success, but the old backups don't get deleted. I don't want the drive filling up.

DB Server info: SQL Server Standard Edition 9.00.3042.00

There is a "Maintenance Cleanup Task" set to

"Search folder and delete files based on an extension"

and "Delete files based on the age of the file at task run time" is checked and set to 4 weeks.

The only thing I can see is that my backups are each given their own subfolder and that this is not recursive. Am I missing something?

Also: I have seen the issues pre-SP2, but I am running service pack 2.

[A]
My understanding is that you can only include the first level of subfolders.  I am assuming that you have that check-box checked already.
Are your backups deeper than the just one level?
Another thought is, do you have one single maintenance plan that you run to delete backups of multiple databases?  The reason I ask this is because the way I could see that you would have to do that would be to point it to a folder that was one level higher meaning that your "include first-level subfolders" would not be deep enough.
The way I have mine set up is that the Maintenance Cleanup Task is part of my backup process.  So once the backup completes for a specific database the Maintenance Cleanup Task runs on that same database backup files.  This allows me to be more specific on the directory so I don't run into the directory structure being too deep.  Since I have the criteria set the way I want, items don't get deleted till I am ready for them to be deleted either way.
Tim


q:
Given a collection of user specified tags how do I determine which ones are not in the tags table with 1 SQL Statement?

Assuming a table schema tags (id, tag) and I'm using mysql, if there's an optimization I'm unaware of.

thanks

[A]
```
```
select * from canonical_list_of_tags where tag not in (select tag from used_tags)
```
```
At least that works in T-SQL for SQL Server ...
Edit:
Assuming that the table
```
canonical_list_of_tags
```
is populated with the result of "
Given a collection of user specified tags
"


q: How do I make an instance of gwtext.client.widgets.Window  appear at specific DIV in my html ? I tried window.anchorTo(DOM.getElementById("Some_Div"),"left", new int[]{0,0}), thinking the window will anchor itself to div id="Some_Div"   in my html. it didnt.

[A]
I haven't used the gwt-ext library in a couple of months, but you might want to try this if you haven't already. It
should
attach the widget where you want it. That said, there are some cases where the gwt-ext widgets react in ways that are not intuitive to someone who really understands the normal GWT widgets.
```
```
RootPanel.get("Some_Div_Id").add( someWidget )
```
```


q:
How would you handle cross database queries in different environments.  For example, db1-development and db2-development, db1-production and db2-production.

If I want to do a cross-database query in development from db2 to db1 I could use the fully qualified name, [db1-development].[schema].[table].  But how do I maintain the queries and stored procedures between the different environments?  [db1-development].[schema].[table] will not work in production because the database names are different.

I can see search and replace as a possible solution but I am hoping there is a more elegant way to solve this problem. If there are db specific solutions, I am using SQL Server 2005.

[A]
Why are the database names different between dev and prod? It'd, obviously, be easiest if they were the same.
If it's a single table shared, then you could create a view over it - which only requires that you change that view when moving to production.
Otherwise, you'll want to
create a SYNONYM
for the objects, and make sure to always reference that. You'll still need to change the SYNONYM creation scripts, but that can be done in a build script fairly easily, I think.


q:
With the age of text messages and things like that, what's a good way to store phone numbers in a database?

In the USA, text messages are handled by phone numbers but in other countries I hear they use email addresses so I guess there needs to be a way to differentiate between countries that use cell phone numbers as their address.

Addition:
For example, people in the USA might use 432-342-3333 or 1-432-342-3333 while in the UK they might use +44 800 400000 or they might even leave out the 44.  The 44 and the 1 makes a difference when automatically sending out SMS.  However, checking the phone number for each country can get tedious.  In this case, would you split the country code or would you merge it into a single column and deal it with it there?

[A]
I don't know if you have read these two questions, but they might help you a little.
Phone Number Columns in a Database
Is there a standard for storing normalized phone numbers in a database?
Perhaps it would be wise to store the type of number (landline, cell, fax) and/or the messages that can be received on it (voice, text, email). Note that in the US, it is also possible to send text messages to a phone via email, but I believe that is dependent on the carrier.


q:
Does anyone know of a simple way of getting the raw xml that is returned from querying a webservice?

I have seen a way of doing this via Web Services Enhancements, but I don't want an added dependency.


q: I keep finding files which show a size of 10kb but a size on disk on 10gb.  Trying to figure out how this is done, anyone have any ideas?

[A]
You can make sparse files on NTFS, as well as on any real filesystem. :-)
Seek to (10 GB - 10 kB), write 10 kB of data. There, you have a so-called 10 GB file, which in reality is only 10 kB big. :-)


q:
I have an application for which log4j logging is configured in a log4j.properties file.  Currently, this application runs on UNIX and creates a log file in /tmp.  This application needs to run on Windows, and on that platform I would like for it to select the correct temporary directory, which I believe is C:\temp.

How can I change my log4j.properties file to make this happen?  Do I need to switch to using an XML configuration file?

[A]
I think you would just use
```
${java.io.tmpdir}
```
in place of a hard-coded path.


q:
I'm running Xorg and my (Qt) program daemonises itself. Now I log out and restart the X server. When I log in again my process is still running fine, but I can't see it.

Is there a way of attatching the new incarnation of the X server to the old process?
If I don't restart the whole server, but log out and in again, is there a way to look at the old process?

Thanks

[A]
After the connection to the X server is lost, it is not possible to regain it.
There was an xserver proxy called xmove, but it is quite deprecated and doesn't work with several newer X extension, which are likely used by modern toolkits.
You could try to run your process in another virtual X server like xvnc or (better) NX. NX is a X proxy technology developed by NoMachine. There exist free implementations of NX servers as well.
If you run your program inside such a server, it is possible to attach and detach from it from arbitrary graphical environments.


q:
Googling has turned up little to nothing.

I need to develop some heavy stuff in m4 and I'd love to do it in my favorite environment with all the bells and whistles thereof.

There are packages for running m4 on just about every platform, such as windows. So I know at the very least I can create a default project and test from the CLI. But I'd rather not :)

[A]
I'm not aware of any specific editing support for m4. However, if you have some time to spare (!) and the BNF for m4, then you could use Xtext (
http://wiki.eclipse.org/Xtext
) to create a syntax-coloring and -completing editor, with an outline view.
Updated
an answer below suggests that m4 doesn't have a BNF, or is not BNeFfable, and certainly a short search of the literature shows no claims that an m4 BNF is available - and it appears, though not explicitly stated, that the m4 language is inexpressible in this way.
Obviously this negates my suggestion, so I must retract it, unless of course Xtext has been extended to deal with such languages. Consult the Xtext website linked above for FAQs and mailing list links.


q:
In a legacy project that I'm on, we have several processing that are preformed via DTS. DTS is not something I worked with a lot back in its hey day.... I was in college.

More specificity, these process are in ActiveX code blocks -- which is basically VBScript for database. It is really hard to debug.

Anyway, I'm wondering if any past or present experienced DTS professionals can offer tips on how to deal with debugging, troubleshooting or otherwise dealing with DTS package development.

This this question is marked as community wiki, I'm hoping to have general and targeted ideas and methods for all types of DTS package implementations.

[A]
In the scripting portion, I have used the MsgBox to display "I got here" or "xfer worked" or whatever you want to indicate something happened which is not so obvious at run time.
You can also use conditional statements to branch off to an 'End' if you are testing a particular portion of the flow.
If you are stuck working with DTS, but are also running a SQL Server 2005 instance, you might see if you cant upgrade the DTS packages to DTSX (SQL Server Integration Services) and re-do them there.  I know this isn't a 'trick' but you work in the VS2005 IDE, can write in .NET and also you can set break-points and will make life in 'DTS' world much easier.
There are also some articles here:
http://www.databasejournal.com/article.php/1503191
Scroll down and you will see the "SQL Server 2000 DTS" articles.


q:
So, I'd like to be able to set the max log file size to 64M, but after doing so with innodb_log_file_size=64M MySQL starts OK, but nothing seems to work properly.

EDIT: and by properly I mean not at all. Setting other InnoDB variables aren't causing any problems.

How should I go about troubleshooting this one?

[A]
Make sure MySQL shuts down cleanly, and delete (or move elsewhere) all
```
ib_logfile*
```
files from MySQL data directory (
```
/var/lib/mysql/
```
usually).
I've tested it and worked for me. Here's
source of this hint
.
InnoDB reports some errors in
```
show table status
```
comment field. You'll find other problems in MySQL error log (
```
hostname.err
```
in MySQL data directory).


q:
I am working on a windows form application. How do i use the find method of a datatable to find a row if the datatable has a compound key?

Table Structure
Col A, Col B, Col C

Col A and Col B make up the compound key.
I want to find the row where the value in Col A is 6 and Col B is 5

[A]
When you "set" the Primary key of the datatable, the parameter value is an array of DataColumns...
if your datatable is in variable dt...,
```
```
dt.PrimaryKey = new DataColumn[] {dt.Columns["ColA"], dt.Columns["ColB"]};
```
```
Then pass an array of object values to the Find() method
```
```
object[] keyVals = new object[] {6, 5};
DataRow dr = dt.Rows.Find(keyVals);
```
```
or, just
```
```
DataRow dr = dt.Rows.Find(new object[] {6, 5});
```
```


q:
I have two SQL scripts which get called within a loop that accept a number parameter. Here is what I'm currently using:

for /l %%i in (1, 1, 51) do (
    sqlplus u/p@name @script.sql a%%i.html %%i
    sqlplus u/p@name @script.sql b%%i.html %%i
)

Everything works fine, but it seems like a waste of time and resources to connect twice for each pass through. Is there a way I could simply log into sqlplus, run the for loop, then exit? I tried many alternatives such as putting

sqlplus u/p@name

before the for loop, but then it would simply hang at the SQL> prompt without executing any of my two scripts.

Thank you.

[A]
You can create a masterscript.sql that contains your two script.sql statements.
The only thing I'm not sure about is if it will pass in your variables.
MasterScript.sql would contain:
```
```
@@script1.sql
@@script2.sql
```
```
and neither of your sub-scripts should contain an exit.
Differences between "@" and "@@"
:
http://www.orafaq.com/wiki/SQL
*Plus_FAQ#What_is_the_difference_between_.40_and_.40.40.3F