q:
I have a directory with several subdirectories with files.

How can I copy all files in the subdirectories to a new location?

Edit: I do not want to copy the directories, just the files...

As this is still on XP, I chose the below solution:

 for /D %S IN ("src\*.*") DO  @COPY "%S\" "dest\"

Thanks!

[A]
The Xcopy command should help here.
```
```
XCOPY /E SrcDir\*.* DestDir\
```
```
Or if you don't want any of the files in SrcDir, just the sub directories, you can use XCOPY in conjunction with the FOR command:
```
```
FOR /D %s IN (SrcDir\*) DO @XCOPY /E %s DestDir\%~ns\
```
```


q:
Is there a Winform caching library out there? I need to pass a few datasets aroung in a Winform Application, and probably persist to storage upon close.

I've seen some samples around via Google, using System.Web.

What's the recommendation and where can I get some details. I am using VS 2008 for 2.0. 3.0 Framework.

Thanks

[A] Starting with .NET 2.0 you can use the System.Web.Caching.Cache class with non-ASP.NET apps. The Microsoft recommended approach these days though is to use the Enterprise Library Caching Application Block.

s: huggingface

c: devops

d: intermediate


q:
We can use Bitmapsource object as the content of a Image control, However if I only have Bitmap object, can I use it directly, if I convert Bitmap to Bitmapsouce using the following method:

        Bitmap bitmap = imageObjToBeConvert;
        IntPtr HBitmap = bitmap.GetHbitmap();
        result = Imaging.CreateBitmapSourceFromHBitmap
            (HBitmap,
            IntPtr.Zero,
            Int32Rect.Empty,
            BitmapSizeOptions.FromEmptyOptions());
        DeleteObject(HBitmap);
        bitmap.Dispose();

It take some time. Is there any way to use Bitmap directly?

And I found BitmapSource seems can't be released directly, Is there a sample method to release the memory immediately, after the Bitmapsouce is not used again.

[A]
I think REST would make more sense than traditional RPC. Even the
Micorosft Robotics Studio runtime application model
uses REST.
The robot can consist of different resources that are identified by URI, including one for each sensor and actuator or composite abstractions thereof.
REST puts emphasis on guaranteeing what the side effects of certain methods are and also it facilitates caching, both of which can be useful for something like controlling and monitoring a distant robot. And just because you can use REST it
doesn't
have to be the HTTP protocol.
A SAFE and IDEMPOTENT method like GET, though, is good for tracking the state of the robot and polling its sensor data. You can use something like the Last-Modified header to retrieve cached sensor data that doesn't change often (e.g., humidity or light levels).
For long distances you can use relay proxies for caching.
For commands that move the robot, something like POST would be used where every such message will change the robot (e.g., turn right ). A status code can be returned indicating whether the command was immediately executed or queued for processing.
The absolute state of any resources can be set using something like PUT where multiple messages will not change things any more than just a single message (e.g., point to north pole or dim front lights to 10% brightness). This allows for reliable messaging in case of probablity of messages getting lost en route.
A new resource may be created via a POST-like operation as well, e.g., a data-collection routine and a set of parameters. The POST request can send back a CREATED result with a URI for the new resource, which can be used to DELETE when no longer needed.
A group of robots may also speak to each other using the same REST based protocol and can enjoy the same benefits.
Granted, for something simple like one person controlling a single isolated local robot, a REST API may be overkill. But for multi-user and/or unreliable-communications-channels and/or Web-scale-networking, REST is something to consider.


q:
I am trying to convert an int into three bytes representing that int (big endian).

I'm sure it has something to do with bit-wise and and bit shifting.  But I have no idea how to go about doing it.

For example:

int myInt;

// some code

byte b1, b2 , b3; // b1 is most significant, then b2 then b3.

*Note, I am aware that an int is 4 bytes and the three bytes have a chance of over/underflowing.

[A]
An int doesn't fit into 3 bytes.  However, assuming that you know these particular ones do:
```
```
byte b1 = (myInt & 0xff);
   myInt >>= 8;
   byte b2 = (myInt & 0xff);
   myInt >>= 8;
   byte b3 = (myInt & 0xff);
```
```


q: It seems redundant to have zlib compress a web page during every request. It is also the bottleneck of my files' response times. Is there a way to cache the zlib'd file so that it is compressed only once at each modification? Or should I just keep wishing?

[A]
Hm, I think mod_cache will do the job.
http://httpd.apache.org/docs/2.0/mod/mod_cache.html


q:
What is the best way to initialize a private, static data member in C++?  I tried this in my header file, but it gives me weird linker errors:

class foo
{
    private:
        static int i;
};

int foo::i = 0;

I'm guessing this is because I can't initialize a private member from outside the class.  So what's the best way to do this?

[A]
The class declaration should be in the header file (Or in the source file if not shared).
File: foo.h
```
```
class foo
{
    private:
        static int i;
};
```
```
But the initialization should be in source file.
File: foo.cpp
```
```
int foo::i = 0;
```
```
If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.
The initialisation of the
```
static int i
```
must be done outside of any function.
Note:
Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of
const integer type
(
```
bool
```
,
```
char
```
,
```
char8_t
```
[since C++20],
```
char16_t
```
,
```
char32_t
```
,
```
wchar_t
```
,
```
short
```
,
```
int
```
,
```
long
```
,
```
long long
```
, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants.
). You can then declare and initialize the member variable directly inside the class declaration in the header file:
```
```
class foo
{
    private:
        static int const i = 42;
};
```
```


q:
Using the Qt Visual studio integration, adding a new Qt class adds two separate moc.exe generated files - one for debug and one for release (and one for any other configuration currently existing). Yet the two eventual generated files seem to be identical.

On the other hand when adding a UI class, the uic.exe generated files don't have this separation and are the same file for all configurations.

Does anybody have an idea why there's a need for a separate moc file for every configuration? When is there a difference between the two?

[A]
My guess would be that separate debug and release versions are needed because the moc output is generated from user-defined source code. So the moc output might be different between debug and release builds if the preprocessed class source differs between debug and release (for example, a signal that exists only in the debug build).
This doesn't apply to the uic-generated files because those are generated from the .ui XML, which can't vary between debug and release configurations.


q:
I have a production server running with the following flag: -XX:+HeapDumpOnOutOfMemoryError

Last night it generated a java-38942.hprof file when our server encountered a heap error. It turns out that the developers of the system knew of the flag but no way to get any useful information from it.

Any ideas?

[A]
You can use
JHAT
, The Java Heap Analysis Tool provided by default with the JDK.  It's command line but starts a web server/browser you use to examine the memory.  Not the most user friendly, but at least it's already installed most places you'll go.  A very useful view is the "heap histogram" link at the very bottom.
ex:
```
jhat -port 7401 -J-Xmx4G dump.hprof
```
```
jhat
```
can execute OQL "these days" as well (bottom link "execute OQL")


q: Recently I was asked this during a job interview. I was honest and said I knew how a symbolic link behaves and how to create one, but do not understand the use of a hard link and how it differs from a symbolic one.

[A]
Underneath the file system, files are represented by inodes. (Or is it multiple inodes?  Not sure.)
A file in the file system is basically a link to an inode.
A hard link, then, just creates another file with a link to the same underlying inode.
When you delete a file, it removes one link to the underlying inode. The inode is only deleted (or deletable/over-writable) when all links to the inode have been deleted.
A symbolic link is a link to another name in the file system.
Once a hard link has been made the link is to the inode. Deleting, renaming, or moving the original file will not affect the hard link as it links to the underlying inode. Any changes to the data on the inode is reflected in all files that refer to that inode.
Note: Hard links are only valid within the same File System. Symbolic links can span file systems as they are simply the name of another file.


q:
It appears that in PHP objects are passed by reference. Even assignment operators do not appear to be creating a copy of the Object.

Here's a simple, contrived proof:

<?php

class A {
    public $b;
}

function set_b($obj) { $obj->b = "after"; }

$a = new A();
$a->b = "before";
$c = $a; //i would especially expect this to create a copy.

set_b($a);

print $a->b; //i would expect this to show 'before'
print $c->b; //i would ESPECIALLY expect this to show 'before'

?>

In both print cases I am getting 'after'

So, how do I pass $a to set_b() by value, not by reference?

[A]
According to the docs (
http://ca3.php.net/language.oop5.cloning
):
```
```
$a = clone $b;
```
```


q:
How can I delete the contents of a local folder in Python?

The current project is for Windows, but I would like to see *nix also.

[A]
```
```
import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
    file_path = os.path.join(folder, filename)
    try:
        if os.path.isfile(file_path) or os.path.islink(file_path):
            os.unlink(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)
    except Exception as e:
        print('Failed to delete %s. Reason: %s' % (file_path, e))
```
```


q: I know this can be done in IE by creating an ActiveX object, but how do I do it in FF. The navigator.plugins['Adobe Acrobat'] object lets me know if it's installed or not, but it doesn't contain the version number. Any ideas?

[A]
```
navigator.plugins[n].name
```
where
```
n
```
is the index of the Acrobat plugin is supposed have the version number in it. Unfortunately, starting with Adobe Reader 8, they changed the name to
```
"Adobe PDF Plug-In for Firefox and Netscape"
```
, with no version information. So, if this is the name you've detected at least Reader 8, but can't tell versions 8 from 9.
Also, make sure you take into account that Macs don't need Acrobat Reader to render PDF files. (I booted my Windows partition just to test this.)


q: What is the best way to create a custom title for pages in a Rails app without using a plug-in?

[A]
Look into
```
content_for
```
:
http://railscasts.com/episodes/8


q:
In javascript, we can do:

["a string", 10, {x : 1}, function() {}].push("another value");

What is the Scala equivalent?

[A]
Arrays in Scala are very much homogeneous.  This is because Scala is a statically typed language.  If you really need pseudo-heterogeneous features, you need to use an immutable data structure that is parametrized covariantly (most immutable data structures are).
```
List
```
is the canonical example there, but
```
Vector
```
is also an option.  Then you can do something like this:
```
```
Vector("a string", 10, Map("x" -> 1), ()=>()) + "another value"
```
```
The result will be of type
```
Vector[Any]
```
.  Not very useful in terms of static typing, but everything will be in there as promised.
Incidentally, the "literal syntax" for
arrays
in Scala is as follows:
```
```
Array(1, 2, 3, 4)     // => Array[Int] containing [1, 2, 3, 4]
```
```
See also
:
More info on persistent vectors


q:
My friend accidentally bought a laptop with Windows Vista Home Basic Edition. He figured out how to install IIS on it, but it doesn't seem to have either the management console or the admin tools. Is there any way for him to configure a site or import an IIS 6 config file?

EDIT: "Windows Vista Home Edition" --> "Windows Vista Home Basic Edition".

[A]
Okay, not being on Vista I don't know for sure, but on XP the application which controls IIS is
```
%SystemRoot%\system32\inetsrv\iis.msc
```
. Perhaps hunting around for
```
iis.msc
```
would be a first step.


q: I use log4net in just about every code project. I was wondering what other generally useful code projects are available?

[A]
I like the C5 collection classes, from the IT University of Copenhagen:
http://www.itu.dk/research/c5/
It's one of the most well-designed libraries, of any kind, I've ever used.


q:
I have had to do this several times, usually when trying to find in what files a variable or a function is used.

I remember using xargs with grep in the past to do this, but I am wondering if there are any easier ways.

[A]
```
```
grep -r REGEX .
```
```
Replace
```
.
```
with whatever directory you want to search from.


q:
(function()
 {
     //codehere
 }
)();

What is special about this kind of syntax?
What does ()(); imply?

[A]
The creates an anonymous function, closure and all, and the final () tells it to execute itself.
It is basically the same as:
```
```
function name (){...}
name();
```
```
So basically there is nothing special about this code, it just a 'shortcut' to creating a method and invoking it without having to name it.
This also implies that the function is a one off, or an internal function on an object, and is most useful when you need to the features of a closure.


q:
I was developing a web page, where I was laying out a board for a Chess-like game, along with a couple of piece trays. It's all done using HTML (with jQuery for dynamic updating as the game is played). Somewhere I'd got the notion that using absolute positioning of elements within a page was considered a bad practice, and that it was preferable to use relative positioning.

After struggling with relative positioning for too long, I realized that absolute positioning of the board elements would be much, much easier to get right... and it was.

Is anyone aware of a reason that relative positioning is preferable over absolute? Are there any guidelines or rules of thumb that you apply when deciding which approach to take?

[A]
For a chess like game such as you are developing, there is nothing inherently wrong with using absolute positioning.  As you said, relative positioning and normal flow layout make this sort of task quite difficult.
Of course, if you were developing a more standard website, such as a site providing some public service, absolute positioning overrides the default flow layout of browsers and so will reduce accessibility for many users.  In this case I would avoid it.
Having said that, a lesser known benefit of absolute positioning is that it allows localized absolute positioning
within
the nearest "positioned" parent element.
Note:
A "positioned" element can be any of the following: relative, fixed, absolute, or sticky.
To explain:
```
```

          I'm absolutely positioned within parentDIV.

```
```
Here,
```
childDIV
```
is actually positioned 20px from the left and 20px from the top of
```
parentDIV
```
,
NOT
the overall document.  This gives a nice precise control over nested elements on a page, without sacrificing the overall page flow-layout.
So to answer your question (relative positioning being preferred over absolute): I don't believe there is a correct answer, it depends on what you are needing to build.  However in general positioning (absolute or relative) versus default flow layout, my approach is as described above.


q: I'd like to create a sparse file such that all-zero blocks don't take up actual disk space until I write data to them.  Is it possible?

[A]
As in other Unixes, it's a feature of the filesystem.  Either the filesystem supports it for ALL files or it doesn't.  Unlike Win32, you don't have to do anything special to make it happen.  Also unlike Win32, there is no performance penalty for using a sparse file.
On MacOS, the default filesystem is HFS+ which does
not
support sparse files.
Update:
MacOS used to support UFS volumes with sparse file support, but that has been removed. None of the currently supported filesystems feature sparse file support.


q: Just this - How do you add a timer to a C# console application? It would be great if you could supply some example coding.

[A]
Use the System.Threading.Timer class.
System.Windows.Forms.Timer is designed primarily for use in a single thread usually the Windows Forms UI thread.
There is also a System.Timers class added early on in the development of the .NET framework. However it is generally recommended to use the System.Threading.Timer class instead as this is just a wrapper around System.Threading.Timer anyway.
It is also recommended to always use a static (shared in VB.NET) System.Threading.Timer if you are developing a Windows Service and require a timer to run periodically.  This will avoid possibly premature garbage collection of your timer object.
Here's an example of a timer in a console application:
```
```
using System;
using System.Threading;
public static class Program
{
    public static void Main()
    {
       Console.WriteLine("Main thread: starting a timer");
       Timer t = new Timer(ComputeBoundOp, 5, 0, 2000);
       Console.WriteLine("Main thread: Doing other work here...");
       Thread.Sleep(10000); // Simulating other work (10 seconds)
       t.Dispose(); // Cancel the timer now
    }
    // This method's signature must match the TimerCallback delegate
    private static void ComputeBoundOp(Object state)
    {
       // This method is executed by a thread pool thread
       Console.WriteLine("In ComputeBoundOp: state={0}", state);
       Thread.Sleep(1000); // Simulates other work (1 second)
       // When this method returns, the thread goes back
       // to the pool and waits for another task
    }
}
```
```
From the book
CLR Via C#
by Jeff Richter.  By the way this book describes the rationale behind the 3 types of timers in Chapter 23, highly recommended.


q: My boss thinks the VS 2008 IDE Window Manager(autohiding, docking of Solution Explorer, Properties, etc) is the best thing since sliced bread.  I can't find a control that resembles that functionality in the Toolbox.  Is there a control like that available that you know of?  Or should I go ahead and implement it myself?  Btw, we're using VS 2008 Express.

[A]
You should check out
SandDock
. The older versions were freely licenced (dunno if they are still available) and the newer versions are relatively cheap, especially considering the amount of time/money/sanity they would save you.
I would strongly recommend against trying to roll your own VM component. There is just too much work involved, and it wouldn't be worth it, if it wasn't your primary product.


q:
I have been trying to change the background color of Eclipse's windows to black and customize the font colors. There doesn't seem to be a way to do this, at least not in an obvious way. I am using version 3.3.

How do I do this or are there any plugin's that might be able to assist in doing this?

[A]
If you go to Windows, Preferences then select General, Editors, Text editors, you can set colors on that property page (and there's a link for setting MORE colors - General, Appearance, Colors and fonts).
That's with an Eclipse 3.3 build anyway.


q:
I would like to use a secure SSL login on my website! I have not used SSL before, so I am looking for some good reading. Can anyone tell me where I can find some sample code of SSL snippets or page code. (Not too technical)

I do have a static IP

My host is set-up to handle SSL Pages.

Interested in: Basic page code. / Tree structure. / Other

Paul

[A]
My first thought would be to simply call a function to redirect to the https: version of the current page when you need to be secure.
Some code like this:
```
```
if($requireSSL && $_SERVER['SERVER_PORT'] != 443)
{
   header("HTTP/1.1 301 Moved Permanently");
   header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
   exit();
}
```
```
Reference


q:
He're an interesting problem that looks for the most Pythonic solution. Suppose I have a list of mappings {'id': id, 'url': url}. Some ids in the list are duplicate, and I want to create a new list, with all the duplicates removed. I came up with the following function:

def unique_mapping(map):
    d = {}
    for res in map:
        d[res['id']] = res['url']

    return [{'id': id, 'url': d[id]} for id in d]

I suppose it's quite efficient. But is there a "more Pythonic" way ? Or perhaps a more efficient way ?

[A]
Your example can be rewritten slightly to construct the first dictionary using a generator expression and to remove necessity of construction of another mappings. Just reuse the old ones:
```
```
def unique_mapping(mappings):
    return dict((m['id'], m) for m in mappings).values()
```
```
Although this came out as a one-liner, I still think it's quite readable.
There are two things you have to keep in mind when using your original solution and mine:
the items will not always be returned in the same order they were originally
the later entry will overwrite previous entries with the same id
If you don't mind, then I suggest the solution above. In other case, this function preserves order and treats first-encountered ids with priority:
```
```
def unique_mapping(mappings):
    addedIds = set()
    for m in mappings:
        mId = m['id']
        if mId not in addedIds:
            addedIds.add(mId)
            yield m
```
```
You might need to call it with
```
list(unique_mappings(mappings))
```
if you need a list and not a generator.


q:
I want to use implicit linking in my project , and nmake really wants a .def file . The problem is , that this is a class , and I don't know what to write in the exports section .
Could anyone point me in the right direction ?

The error message is the following :

NMAKE :  U1073: don't know how to make 'DLLCLASS.def'

P.S: I'm trying to build using Windows CE Platform Builder .

[A]
If I recall correctly, you can use
```
__declspec(dllexport)
```
on the
class
, and VC++ will automatically create exports for all the symbols related to the class (constructors/destructor, methods, vtable, typeinfo, etc).
Microsoft has more information on this
here
.


q: Are there any "all-in-one" installers for php + mysql on iis? Preferably with a gui configuration interface.

[A]
I don't know of any all-in-one installers for both MySql and PHP, but PHP itself comes with an automated installer that will attach itself to IIS - but the preferred method is still manual (the automated procedure only uses CGI). There are plenty of how-to pages on the web that give you the step-by-step procedure required to get setup (and these differ based on your version of IIS) - I suggest you use one of those instead.
Some links to get you started:
PHP Documentation
Installing PHP 5 on IIS in 5 simple steps


q:
A project I'm working on will pull XML from a web-server and build a data store from it. The data will have certain core fields but needs to be extendable... for example I have a  and later might want to have  which adds extra fields.

In the Flex app, I don't want the central data store to be working on XML objects or simply putting the properties into Objects. I want to have strong types, e.g a Person class, which are created/populated from the XML.

How can this be done in a flexible way? Is Flex able to automatically build a Person from an XML  if the attribute names match, or do I need to write conversion functionality for , , etc?

[A]
I don't think this can be done automatically. I generally create the a class to mirror the XML structure I have and then create a static class method to create an instance of the object given an XML node. For example:
```
```
package {

  public class Foo{

     public function Foo(barparam1:String, barparam2:uint, barparam3:String, barparam4:Number){
       this._bar1 = barparam1;
       this._bar2 = barparam2;
       this._bar3 = barparam3;
       this._bar4 = barparam4;
       }

     protected var _bar1:String;
     protected var _bar2:uint;
     protected var _bar3:String;
     protected var _bar4:Number;

     public function get bar1():String{ return this._bar1; }
     public function get bar2():uint    { return this._bar2; }
     public function get bar3():String  { return this._bar3; }
     public function get bar4():Number  { return this._bar4; }

     public function toString():String{
        return "[Foo bar1:\"" + this.bar1 + "\", bar3:\"" + this.bar3 + "\", bar2:" + this.bar2 + ", bar4:" + this.bar4 + "]";
        }

     public static function createFromXml(xmlParam:XML):Foo{

        /* XML Format:
          <foo bar1="bar1value" bar2="5">
            <bar3>bar3 data</bar3>
            <bar4>10</bar4>
          </foo>
        */

       return new Foo(xmlParam.@bar1, xmlParam.@bar2, xmlParam.bar3[0], xmlParam.bar4[0]);
       }
    }
  }
```
```


q:
I have a list of Date objects, and a target Date. I want to find the date in the list that's nearest to the target date, but only dates that are before the target date.

Example:
2008-10-1
2008-10-2
2008-10-4

With a target date of 2008-10-3, I want to get 2008-10-2

What is the best way to do it?

[A]
I currently use the following method, but I'm not sure it's the most effective one, because this assumes an already sorted list, and (potentially) iterates over every single date in the list.
```
```
private Date getDateNearest(List<Date> dates, Date targetDate){
  for (Date date : dates) {
    if (date.compareTo(targetDate) <= 0) return date;
  }

  return targetDate;
}
```
```


q:
I'm looking at creating a server in python that I can run, and will work as an SSH server. This will then let different users login, and act as if they'd logged in normally, but only had access to one command.

I want to do this so that I can have a system where I can add users to without having to create a system wide account, so that they can then, for example, commit to a VCS branch, or similar.

While I can work out how to do this with conch to get it to a "custom" shell... I can't figure out how to make it so that the SSH stream works as if it were a real one (I'm preferably wanting to limit to /bin/bzr so that bzr+ssh will work.

It needs to be in python (which i can get to do the authorisation) but don't know how to do the linking to the app.

This needs to be in python to work within the app its designed for, and to be able to be used for those without access to add new users

[A]
While Python really is my favorite language, I think you need not create you own server for this. When you look at the
OpenSSH Manualpage for sshd
you'll find the "command" options for the authorized keys file that lets you define a specific command to run on login.
Using keys, you can use one system account to allow many user to log in, just put their public keys in the account's authorized keys file.
We are using this to create SSH tunnels for SVN and it works just great.


q:
Is there an event like onLoad?

just at closing the Site (onClose)?

[A]
The closest you can get it UnLoad.
http://msdn.microsoft.com/en-us/library/ms178472.aspx


q:
I have a HTML select list with quite a few (1000+) names. I have a javascript in place which will select the first matching name if someone starts typing. This matching looks at the start of the item:

var optionsLength = dropdownlist.options.length;
  for (var n=0; n < optionsLength; n++)
  {
    var optionText = dropdownlist.options[n].text;
    if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)
    {
      dropdownlist.selectedIndex = n;
      return false;
    }
  }

The customer would like to have a suggest or autofilter: typing part of a name should 'find' all names containing that part. I've seen a few Google Suggest like options, most using Ajax, but I'd like a pure javascript option, since the select list is already loaded anyway. Pointers anyone?

[A]
Change
```
```
if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)
```
```
to
```
```
if (optionText.indexOf(dropdownlist.keypressBuffer) > 0)
```
```
To find
```
dropdownlist.keypressBuffer
```
anywhere in the
```
optionText
```
.


q:
While designing a table my colleague here says that I should avoid identity column as it is specific to SQL Server and MS Access, But I differ with his views as it makes my coding simpler.

Should I use identity column or not? If not what is best way to create the identity columns from application code?

[A]
You can't completely divorce an application from the database vendor. If you do you won't be able to take advantages of whatever features your database provides you.
I'd say use the identity column. If you move over to Oracle (for example), you can use a Sequence. Hardly a big change.
I don't know what technology you're using, but one thing that would help is using a tool such as Hibernate or iBATIS (I think they're both available for Java and .NET) which separates you a bit from the database implementation details. Then if you change database vendor you won't need to change application code, just configuration. (In theory, at least!)


q:
Which is the best timer approach for a C# console batch application that has to process as follows:

Connect to datasources

process batch until timeout occurs or processing complete. "Do something with datasources"

stop console app gracefully.

related question: How do you add a timer to a C# console application

[A]
When you say "until timeout occurs" do you mean "keep processing for an hour and then stop"? If so, I'd probably just make it very explicit - work out at the start when you want to finish, then in your processing loop, do a check for whether you've reached that time or not. It's incredibly simple, easy to test etc. In terms of testability, you may want a fake clock which would let you programmatically set the time.
EDIT: Here's some pseudocode to try to clarify:
```
```
List<DataSource> dataSources = ConnectToDataSources();
TimeSpan timeout = GetTimeoutFromConfiguration(); // Or have it passed in!
DateTime endTime = DateTime.UtcNow + timeout;

bool finished = false;
while (DateTime.UtcNow < endTime && !finished)
{
    // This method should do a small amount of work and then return
    // whether or not it's finished everything
    finished = ProcessDataSources(dataSources);
}

// Done - return up the stack and the console app will close.
```
```
That's just using the built-in clock rather than a clock interface which can be mocked, etc - but it probably makes the general appropriate simpler to understand.


q:
When you create a procedure (or a function) in Oracle PL/SQL, you cannot specify the maximum length of the varchar2 arguments, only the datatype. For example

create or replace procedure testproc(arg1 in varchar2) is
begin
  null;
end;

Do you know the maximum length of a string that you can pass as the arg1 argument to this procedure in Oracle ?

[A]
In PL/SQL procedure it may be up to 32KB
Futher information here:
http://it.toolbox.com/blogs/oracle-guide/learn-oracle-sql-and-plsql-datatypes-strings-10804


q:
This is a very basic problem that's frustrating me at the moment. Let's say within a single solution, I have two projects. Let's call the first project SimpleMath. It has one header file "Add.h" which has

int add(int i, int j)

and the implementation "Add.cpp" which has

int add(int i, int j) {
  return i+j;
}

Now let's say in a second project I want to use the add function. However, this code:

#include "..\SimpleMath\Add.h"

int main() {

    add(1, 2);

}

results in "unresolved external symbol". How do I get the second program to "know" about the actual implementation in the .cpp file. As a side note all code is fictional this is not how I actually program.

[A]
You either have to make Add.cpp part of a library and include it in both projects. or you have to add Add.cpp to your second project too.
Edit: to make SimpleMath a library go into the project settings on General and change the Configuration Type to Static Lib.
Then go into your solution settings, click on Project Dependencies, then select your second project in the drop down list, and put a check mark next to SimpleMath. That will automatically link SimpleMath to your second project, and will also make sure that any changes to SimpleMath will be rebuilt when you rebuild your second project.


q:
I need to add a xml:lang attribute on the root xml node in the outbound document from BizTalk.

This is a fixed value, so it may be set in the schema or something.

This is what I want to get out:

<Catalog xml:lang="NB-NO">
...
</Catalog>

I've tried to define the attribute "xml:lang", but it doesn't allow me to use ":" in the schema.

This is the error message I get:

Invalid 'name' attribute value
  'xml:lang': The ':' character,
  hexadecimal value 0x3A, at position 3
  within the name, cannot be included in
  a name.

Is there another way to insert a ':' as part of the attribute name in BizTalk?

Can anyone tell me how to do this?

I'm using BizTalk 2006 and no orchestration.

[A]
Try to add the xml namespace declaration to the schema
```
```
xmlns:xml="http://www.w3.org/XML/1998/namespace"
```
```
Beware that this addition will be removed when the schema file is recreated.


q:
we're running in this issue. We're using a web service (using soap4r) to run some kind of searches and the problem appears when the webservice server is down and our aplication is trying to connect to it.
At that point the application is unreachable, and all the customers are blocked.

What can we do to avoid that? Is possibile to block the routing to a mongrel that it is blocked? (I suppose that the apache's proxy uses a round-robin algohritm)

Thanks
Roberto

[A]
This sounds to me like it may be more of a mod_proxy problem than one with Mongrel or Apache - are you setting Proxy Timeouts as described
here
?


q:
I would like to use databinding when displaying data in a TextBox. I'm basically doing like:

 public void ShowRandomObject(IRandomObject randomObject) {
        Binding binding = new Binding {Source = randomObject, Path = new PropertyPath("Name")};
        txtName.SetBinding(TextBox.TextProperty, binding);
    }

I can't seem to find a way to unset the binding. I will be calling this method with a lot of different objects but the TextBox will remain the same. Is there a way to remove the previous binding or is this done automatically when I set the new binding?

[A]
When available
```
```
BindingOperations.ClearBinding(txtName, TextBox.TextProperty)
```
```
For older SilverLight versions, but not reliable as stated in comments:
```
```
txtName.SetBinding(TextBox.TextProperty, null);
```
```
C# 6.0 features enabled
```
```
this.btnFinish.ClearBinding(ButtonBase.CommandProperty);
```
```


q:
I'm trying to write a Mono C# daemon for linux.

I'd like to do a starts and stops of it when its done processing instead of just killing the process.

Does anyone have any examples of this?

Edit: I figured out how to use start-stop-daemon --background in debian, so I think I'll just use that for now.

Edit: I'm implementing this in java as well and they have this nice addShutdownHook that catches terminating the app. I need to spend a little more time sorting out the dependencies for mono service, or find a way to catch app termination.

There is the SessionEnd event, but thats only available for services and not console apps

Answer:
using mono-service to wrap a windows service on linux

[A]
A simple method would be to listen on a (local, high) port and receive commands from a management client, like bind does.
A more unix-ish way would be to
register a signal handler
using
UnixSignal
and shutdown properly on receiving a certain signal. See the
Mono FAQ, "Can I use signal handlers with Mono?"
for caveats and an example.
lupus
has found
mono-service
, which is a hosting process using the
```
ServiceProcess
```
interfaces. Sadly this requires setting
```
MONO_DISABLE_SHM
```
, which disables some features in Mono, in particular cross-process IPC systems.


q:
So which is better.
Do we start letting Tests design our code. Do we start introducing constructor injection for dependencies just to make code testable? or do we use the "override" protected method & sub class the class under test.

[A]
I generally think that testable code is good code. For code to be testable, you need better decoupling so each component can be tested in isolation with a test harness. However, there shouldn't be code in the implementation that is just used by the unit tests.
Also, keep in mind that what you need to test is the public API of an object, not it's protected/private methods. Finding bugs in private/protected method should be what logging/debuggers are for. After all, a bug in those will also propagate up to the public methods. So as long as the public methods fulfill tests, the protected methods will be covered too.
If you are using java, and have package scoped classes that implement public interfaces in the same package, I would put the unit tests in the same package in a separate folder to test those classes. You can also put unit tests in the same package as the tested class to test protected methods.


q:
Is it possible to receive DllMain like notifications about thread attach/detach in stand-alone exe without using any extra dlls?

Edit: This is just a theoretical question that has to do with some testing I'm doing. not a real life situation.

[A]
There is no external code that runs on the thread and loads the executable, hence no thread attach/detach notifications [1]. The code in the executable usualy control the threading [2].
If you describe your scenario, people might be able to give you some ideas how to achieve it.
[1] Well, most of the time. It is possible to load an executable in another process, but people don't do it usually.
[2] There are certain exceptions where the threading model and the threads are created by the OS, instead of the executable code. These are mostly related to COM/RPC.


q:
Is there a better way to profile code then:

$start1 = microtime(TRUE);
for($i=0;$i<count($array);$i++)
 {
    //do something
 }
$time1 = microtime(TRUE) - $start1;

[A]
Xdebug or Zend Debugger if you have some difficulty to install Xdebug.
Their profiler will time everything for you without any modification of your code.
http://www.xdebug.org/
http://www.zend.com/en/community/pdt
http://devzone.zend.com/article/2899-Profiling-PHP-Applications-With-xdebug
- a serie of tutorials about xdebug.


q:
Which other restrictions are there on names (beside the obvious uniqueness within a scope)?

Where are those defined?

[A]
From the
PDF of ECMA-335
, Partition II, section 22:
Metadata preserves name strings, as created by a compiler or code generator, unchanged.  Essentially, it treats
each string as an opaque blob.  In particular, it preserves case.  The CLI imposes no limit on the length of names stored in metadata and subsequently processed by the CLI
If I've read this correctly and the context is correct then there's no actual limit to the length of an identifier in the CLR.


q: There is the button control in silverlight application . Can I send a mouse click event to it programmatically?

[A]
I've not used Silverlight but I assume it's the same process as Windows.Forms and WebControls. You'll just need to call the button's
```
.Click(Object o, EventArgs e)
```
method.


q: Using SQL Server - which is the fastest or best practice method to use for date retrieval? Is there a difference?

[A]
Books Online tells us that
```
CURRENT_TIMESTAMP
```
"is equivalent to
```
GETDATE()
```
".


q:
When you limit the number of rows to be returned by a SQL query, usually used in paging, there are two methods to determine the total number of records:

Method 1

Include the SQL_CALC_FOUND_ROWS option in the original SELECT, and then get the total number of rows by running SELECT FOUND_ROWS():

SELECT SQL_CALC_FOUND_ROWS * FROM table WHERE id > 100 LIMIT 10;
SELECT FOUND_ROWS();

Method 2

Run the query normally, and then get the total number of rows by running SELECT COUNT(*)

SELECT * FROM table WHERE id > 100 LIMIT 10;
SELECT COUNT(*) FROM table WHERE id > 100;

Which method is the best / fastest?

[A]
It depends.  See the MySQL Performance Blog post on this subject:
To
```
SQL_CALC_FOUND_ROWS
```
or not to
```
SQL_CALC_FOUND_ROWS
```
?
Just a quick summary:  Peter says that it depends on your indexes and other factors.  Many of the comments to the post seem to say that
```
SQL_CALC_FOUND_ROWS
```
is almost always slower - sometimes up to 10x slower - than running two queries.


q: Can i override fetchall method in a model? I need to check sth everytime fetchAll is called. The model extends Zend_db_table_abstract

[A]
To override this method you would need to subclass the Zend_Db_Table_Abstract.  Like so:
```
```
<?php
abstract class My_Db_Table_Abstract extends Zend_Db_Table_Abstract
{
    ...

    public function fetchAll($where, $order)
    {
        ...
    }

    ...
}
```
```
Then make sure your models extend My_Db_Table_Abstract instead.  This way, you will always inherit your overridden fetchAll method.


q:
I need to profile a java application for a customer. It's an eclipse/maven project, so I decided on using eclipse TPTP ( http://www.eclipse.org/tptp ).

I tried to install eclipse TPTP through the update manager from a standard eclipse installation, but I gave up because of the unbelievable complex setup and downloading of dependencies with very cryptic names.

Then I downloaded the "all in one TPTP 4.5.1" package from http://www.eclipse.org/tptp/home/downloads/?ver=4.5.1 but when I start it up, it pops up an error saying "The eclipse executable launcher was unable to locate it's companion shared library".

I'm running Windows XP, Sun Java 1.5, and clicked on "eclipse.exe" in the unpacked eclipse TPTP installation.

What do I need to do to get eclipse TPTP running?

[A]
Maybe try downloading the "Java 1.5+ (JVMTI) Profiler SDK" (runtime) from
http://www.eclipse.org/tptp/home/downloads/?ver=4.5.1
I also think IBM's latest Rational Developer integrates this technology (there is 60 days trial). You can see how they configure it there.


q:
I have a WCF service and I want to expose it as both a RESTfull service and as a SOAP service.
Anyone has done something like this before?

[A]
You can expose the service in two different endpoints.
the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration
```
```
<endpointBehaviors>
  <behavior name="jsonBehavior">
    <enableWebScript/>
  </behavior>
</endpointBehaviors>
```
```
An example of endpoint configuration in your scenario is
```
```
<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="ITestService"/>
  </service>
</services>
```
```
so, the service will be available at
http://www.example.com/soap
http://www.example.com/json
Apply [WebGet] to the operation contract to make it RESTful.
e.g.
```
```
public interface ITestService
{
   [OperationContract]
   [WebGet]
   string HelloWorld(string text)
}
```
```
Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.
Reply to the post for SOAP and RESTful POX(XML)
For plain old XML as return format, this is an example that would work both for SOAP and XML.
```
```
[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
    [OperationContract]
    [WebGet(UriTemplate = "accounts/{id}")]
    Account[] GetAccount(string id);
}
```
```
POX behavior for REST
Plain Old XML
```
```
<behavior name="poxBehavior">
  <webHttp/>
</behavior>
```
```
Endpoints
```
```
<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="xml" binding="webHttpBinding"  behaviorConfiguration="poxBehavior" contract="ITestService"/>
  </service>
</services>
```
```
Service will be available at
http://www.example.com/soap
http://www.example.com/xml
REST request
try it in browser,
http://www.example.com/xml/accounts/A123
SOAP request
client endpoint configuration for SOAP service after adding the service reference,
```
```
<client>
    <endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
      contract="ITestService" name="BasicHttpBinding_ITestService" />
  </client>
```
```
in C#
```
```
TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");
```
```
Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.


q:
We have several common libs. Ideally we want them all to use the latest version of a dll even if they have been compiled against an older different version (assume the latest version is backward compatible)

e.g we have:

Project dll

Common controls dll

Logging dll

Database access dll

Project and common controls reference v2 of database dll. Logging however references v1.

If different versions are referenced in different components how does VS pick which one to use?

Do we have to recompile v1 dll to use the latest database (v2) or can we get this to pick up automatically?

Is it possible to force a particular version to be used?

Thanks,

Alex

[A]
By default, for versioned DLLs I believe VS will force an exact match. If you look in the properties of the reference, however, you'll find a property called "Specific Version". Set that to "false" and it will match later versions.
I don't have the full version of VS with me to find an appropriate MSDN link, unfortunately.
In addition, you can use the
assemblyBinding
element in app.config.


q: I coded something using Date statement in Access VBA. It was working fine until the start of this month, but now I am seeing that the Date has automatically changed the format from dd/mm/yyyy to mm/dd/yyyy. Has anyone else encountered the same problem?

[A]
The default Access SQL date format, regardless of locale, is mm/dd/yyyy. If you use an invalid date format, it will 'helpfully' try to convert that to a valid date for you.
So, if you use '30/09/2008', it will recognize you're using dd/mm/yyyy, and convert it appropriately. However, a value like '10/01/2008' is a valid mm/dd/yyyy value to begin with, so it will not be converted, and stored incorrectly in case you actually meant dd/mm/yyyy....
The solution is to always convert your date values to a mm/dd/yyyy string prior to using them in Access SQL statements. You have to be a bit careful here, as using VBA date format masks may not work entirely as you'd expect on non-US locales (e.g. 'helpfully' interpreting "mm/dd/yyyy" as "the localized short date format"), so please test carefully using your particular Access/VBA version.


q:
When I disable ViewState for the page. It does not allow any other control to use ViewState .. even if I set EnableViewState="true" for that particular control ..

is it possible to enable ViewState for a control when ViewState is disabled for the page itself?

if not how can disable viewstate for controls on page except for few without specifying EnableViewState="false" explicitly .. typing the same into so many controls is hectic ..

[A]
If you set turn page's ViewState off, then there is no way for you to enable ViewState for specific components. This is because ViewState is serialzed recursively, so when if the Page is not allowing ViewState, it will not serialize the ViewState for any of it's child controls.
In answer to your question, if you don't want to explicitly turn ViewState off on individual controls, but want to keep some controls ViewState aware, the best way would be writing a small utility method which turns ViewState off for all controls (using recursion or otherwise). Then enable ViewState for the controls that you would like to enable ViewState for.
Alternatively, a middle ground and less forceful way may possible if controls are groups inside other container controls (such as Panel). You can disable ViewState for all controls inside a Panel by disabling ViewState of the Panel.


q:
What avenues are there for using an XSD to generate message instances?  I seem to remember reading about generating classes from XSD, but can't find anything specific now.  I know you can generate classes and datasets from XSD, but I'm looking for a pattern for automating the actual generation of the messages.

BTW, SO is my knowledge sharer of choice, not Google.

[A]
```
```
xsd /c yourschema.xsd > yourschema.cs
```
```


q:
Mobile Safari is a very capable browser, and it can handle my website as it is perfectly. However, there are a few elements on my page that could be optimized for browsing using this device; such as serving specific thumbnails that are smaller than the desktop counterparts to help fit more content into the screen.

I would like to know how I can detect Mobile Safari (all versions, preferably) using PHP, so then I can serve a) a specific css file and b) different sized image thumbnails.

[A]
```
```
$_SERVER['HTTP_USER_AGENT']
```
```
That will give you the user-agent string back which you can compare to mobile safari.
p.s.
http://wurfl.sourceforge.net/
WURFL may help you determine which UAs you want.


q:
How do I generate a range of consecutive numbers (one per line) from a MySQL query so that I can insert them into a table?

For example:

nr
1
2
3
4
5

I would like to use only MySQL for this (not PHP or other languages).

[A]
```
```
DECLARE i INT DEFAULT 0;

WHILE i < 6 DO
  /* insert into table... */
  SET i = i + 1;
END WHILE;
```
```


q:
Due to the lack of clientaccesspolicy.xml, there appears to be problems with using Amazon S3 via Flex. Are there any work arounds?

Edit: Both of the below answers are great and work, I've upvoted both (I'm not going to assign an answer to the question as they both work):

Can you use Amazon S3 via Flex?

Can you use Amazon S3 via Flex?

[A]
You can CNAME a subdomain you control at Amazon S3 (to a bucket with the name of the subdomain), like so:
http://s3.ceejayoz.com/
(goes to my 's3.ceejayoz.com' bucket)
Uploading your own clientaccesspolicy.xml file to the root of that bucket (and setting the permissions to be globally viewable) should do the trick, if I'm understanding your question correctly, as it will be accessible at
http://s3.ceejayoz.com/clientaccesspolicy.xml
.
More information in the S3 docs:
http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?VirtualHosting.html
edit:
From looking at that, you could also use the "Example Virtual Hosted Style Method" without a CNAME:
http://bucketname.s3.amazonaws.com/clientaccesspolicy.xml


q:
I currently have a functioning in-house Windows Forms application which extensively uses the DataGridView control for data entry. There are some support issues which are expected when we roll this out to more locations, so one of our consultants has recommended putting together an AJAX application with substantially the same functionality.

I have used ASP.NET a bit in the past with the old model where basically everything goes to the server, but I've heard AJAX applications can be made more UI responsive than that.

So my question is, what's the best way to get started with AJAX, for someone who has worked mostly in WinForms C#?

[A]
The easiest way, but not neccessarly the best way is to get familiar with the UpdatePanel, which is part of the ASP.net AJAX controls.
You can use an ASP.net GridView control (which shares much of the Winforms equiv. functionality), wrap an UpdatePanel around it and you're away.
Further on from that you will want to get involved with web/wcf services to make calls from javascript to the server and update your UI based on the responce. That of course involved more time, effort and knowledge!
There are many gridview controls you can buy that will help e.g. One from essential objects is nice, not perfect, but very cheap compared to Telerik and other big names.
ASP.net is still a server based technology, but with the inclusion of ASP.net AJAX calls to the server are easy and with jQuery updating the UI is getting easier!!
Hope this helps


q:
I have named_scope which is reused in multiple ActiveRecord models.
For example:

  named_scope :limit, lambda {|limit| {:limit => limit}}

What is the best practice to extract this code to be shared across models.
Is it possible to extract it to a module or should I rather reopen ActiveRecord::Base class?

[A]
Use a module. Something like this should work:
```
```
module CommonScopes
  def self.included(base)
    base.class_eval do
      named_scope :limit, lambda {|limit| {:limit => limit}}
    end
  end
end
```
```
Then just include CommonScopes and you'll be good to go.


q:
How do I invoke a console application from my .NET application and capture all the output generated in the console?

(Remember, I don't want to save the information first in a file and then relist as I would love to receive it as live.)

[A]
This can be quite easily achieved using the
ProcessStartInfo.RedirectStandardOutput
property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application.
```
```
Process compiler = new Process();
compiler.StartInfo.FileName = "csc.exe";
compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();

Console.WriteLine(compiler.StandardOutput.ReadToEnd());

compiler.WaitForExit();
```
```


q:
I need to send email through an (external) SMTP server from Java however this server will only accept CRAM-MD5 authentication, which is not supported by JavaMail.

What would be a good way to get these emails to send? (It must be in Java.)

[A]
This doesn't help you directly, however, IMAP connections in JavaMail do support SASL (and thus CRAM-MD5, see the
Java SASL documentation
) if you set the
```
mail.imap.sasl.enable
```
boolean property to
```
true
```
.
Unfortunately, there is no
```
mail.smtp.sasl.enable
```
property, and SASL cannot be enabled for SMTP in JavaMail. :-(
However, you can download the
JavaMail source code
, and you can try to edit the SMTP code to support SASL in a similar manner to the IMAP code. Good luck!


q:
My company runs a webmail service, and we were trying to diagnose a problem with Word downloads not opening automatically - the same *.doc file download from Yahoo Mail would open, but one from ours would not.

In the course of investigating the headers we saw this coming from Yahoo:

content-disposition attachment; filename*="utf-8''word document.doc";

Whereas our headers were like this:

content-disposition attachment; filename="word document.doc";

What exactly is Yahoo doing with the additional asterisk and utf-8'' designation?

[A]
What Mime-Type are you using?
The asterisk is required as per RFC 2183 (
http://www.ietf.org/rfc/rfc2183.txt
):
In the extended BNF notation of [RFC 822], the Content-Disposition
   header field is defined as follows:
```
```
disposition := "Content-Disposition" ":"
                disposition-type
                *(";" disposition-parm)

 disposition-type := "inline"
                   / "attachment"
                   / extension-token
                   ; values are not case-sensitive

 disposition-parm := filename-parm
                   / creation-date-parm
                   / modification-date-parm
                   / read-date-parm
                   / size-parm
                   / parameter

 filename-parm := "filename" "=" value

 creation-date-parm := "creation-date" "=" quoted-date-time

 modification-date-parm := "modification-date" "=" quoted-date-time

 read-date-parm := "read-date" "=" quoted-date-time

 size-parm := "size" "=" 1*DIGIT

 quoted-date-time := quoted-string
                  ; contents MUST be an RFC 822 `date-time'
                  ; numeric timezones (+HHMM or -HHMM) MUST be used
```
```


q: I can hookup to AppDomain.CurrentDomain.UnhandledException to log exceptions from background threads, but how do I prevent them terminating the runtime?

[A]
From Joe Albahari's excellent
threading
article:
The .NET framework provides a
  lower-level event for global exception
  handling:
  AppDomain.UnhandledException. This
  event fires when there's an unhandled
  exception in any thread, and in any
  type of application (with or without a
  user interface). However, while it
  offers a good last-resort mechanism
  for logging untrapped exceptions, it
  provides no means of preventing the
  application from shutting down – and
  no means to suppress the .NET
  unhandled exception dialog.
In production applications, explicit
  exception handling is required on all
  thread entry methods. One can cut the
  work by using a wrapper or helper
  class to perform the job, such as
  BackgroundWorker (discussed in Part
  3).


q:
I have a string that looks like this:

"Name1=Value1;Name2=Value2;Name3=Value3"

Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:

dict = {
    "Name1": "Value1",
    "Name2": "Value2",
    "Name3": "Value3"
}

I have looked through the modules available but can't seem to find anything that matches.

Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.

I'll do it myself then.

[A]
There's no builtin, but you can accomplish this fairly simply with a generator comprehension:
```
```
s= "Name1=Value1;Name2=Value2;Name3=Value3"
dict(item.split("=") for item in s.split(";"))
```
```
[Edit]
From your update you indicate you may need to handle quoting.  This does complicate things, depending on what the exact format you are looking for is (what quote chars are accepted, what escape chars etc).  You may want to look at the csv module to see if it can cover your format.  Here's an example:  (Note that the API is a little clunky for this example, as CSV is designed to iterate through a sequence of records, hence the .next() calls I'm making to just look at the first line.  Adjust to suit your needs):
```
```
>>> s = "Name1='Value=2';Name2=Value2;Name3=Value3"

>>> dict(csv.reader([item], delimiter='=', quotechar="'").next()
         for item in csv.reader([s], delimiter=';', quotechar="'").next())

{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1=2'}
```
```
Depending on the exact structure of your format, you may need to write your own simple parser however.


q: I need to stream a file to the Response for saving on the end user's machine.  The file is plain text, so what content type can I use to prevent the text being displayed in the browser?

[A]
I don't think it works that way.
Use a
```
Content-Disposition: attachment
```
header, but stick with the correct Content-Type.


q:
I'm trying to catch a ClassCastException when deserializing an object from xml.

So,

try {
    restoredItem = (T) decoder.readObject();
} catch (ClassCastException e){
    //don't need to crash at this point,
   //just let the user know that a wrong file has been passed.
}

And yet this won't as the exception doesn't get caught. What would you suggest?

[A]
Well, I can't use
```
instanceof
```
operator as the method is a parametrized one:
```
```
public T restore(String from){
...
restoredItem = (T) decoder.readObject();
...
}
```
```
And generics in Java are compile-time only.


q:
I am using the YUI layout manager which seems to work at an OK speed. However if the page contains a large <Table> with about 500 rows, the YUI render() function takes about a minute longer to run.

When I open the same page without the layout manager it opens in less than a second.

My only concern is with IE 7. I tried it on firefox and it only took about three seconds.

Any ideas on what is taking so long? Can I somehow tell the layout manager to ignore the table?

[A]
I finally figured it out myself.
The trick is to hide the content that should be ignored by the layout manager.
Before calling
```
render()
```
set the
```
style.display = 'none'
```
for a tag that contains a large chunk of the page you don't need the layout manager to manage. Set it back to normal after with
```
style.display = 'block'
```
.


q:
I have this script:

select name,create_date,modify_date from sys.procedures order by modify_date desc

I can see what procedures were modified lately.
I will add a "where modify_date >=  "
And I'd like to use some system stored procedure, that will generate me :
drop + create scripts for the (let's say 5 matching) stored procedures

Can i do this somehow?

thanks

ok. i have the final version:

http://swooshcode.blogspot.com/2008/10/generate-stored-procedures-scripts-for.html

you guys helped a lot

thanks

[A]
You could use a cursor to iterate through each record:
```
```
DECLARE @spName NVARCHAR(128)
DECLARE myCursor CURSOR FOR SELECT name FROM sys.procedures ORDER BY modify_date DESC
OPEN myCursor
FETCH NEXT FROM myCursor INTO @spName
WHILE @@fetch_status = 0
BEGIN
    -- Process each stored procedure with a dynamic query
    PRINT @spName
FETCH NEXT FROM myCursor INTO @spName
END
CLOSE myCursor
DEALLOCATE myCursor
```
```


q:
What ReSharper 4.0 templates for C# do you use?

Let's share these in the following format:

[Title]

Optional description

Shortcut: shortcut

Available in: [AvailabilitySetting]

// Resharper template code snippet
// comes here

Macros properties (if present):

Macro1 - Value - EditableOccurence

Macro2 - Value - EditableOccurence

One macro per answer, please!

Here are some samples for NUnit test fixture and Standalone NUnit test case that describe live templates in the suggested format.

[A]
Create new unit test fixture for some type
Shortcut:
ntf
Available in:
C# 2.0+ files where type member declaration or namespace declaration is allowed
```
```
[NUnit.Framework.TestFixtureAttribute]
public sealed class $TypeToTest$Tests
{
    [NUnit.Framework.TestAttribute]
    public void $Test$()
    {
        var t = new $TypeToTest$()
        $END$
    }
}
```
```
Macros:
TypeToTest
- none - #2
Test
- none - V


q: I Have an old vbs script file being kicked off by an AutoSys job. Can I, and how do I, return an int return value to indicate success or failure?

[A]
Try:
```
```
WScript.Quit n
```
```
Where n is the ERRORLEVEL you want to return


q:
Has anyone seen a tool that will integrate code coverage results with SCM/VCS to attribute untested lines of code to developers?
For example, is there a tool that will take NCover's Coverage.Xml, combine it with SVN blame, and produce a report that tells me things like developer who commits most untested code?


q:
It seems the ObservableCollection only support add, remove, clear operation from the UI thread, It throw Not Support Exception if it is operated by a NO UI thread. I tried to override methods of ObservableCollection, unfortunatly, I met lots of problems.
Any one can provide me a ObservableCollection sample which can be operated by multi-threads?
Many thanks!

[A]
Using the link provided by
Kent
, you could use the following code to modify a collection across threads:
```
```
while (!Monitor.TryEnter(_lock, 10))
{
   DoEvents();
}

try
{
   //modify collection
}
finally
{
   Monitor.Exit(_lock);
}
```
```
If however you're just looking to modify the collection on your original thread you can try using a callback to your UI thread. I normally do something like this:
```
```
this.Dispatcher.Invoke(new MyDelegate((myParam) =>
{
  this.MyCollection.Add(myParam);
}), state);
```
```


q:
I'm using the sortable function in jquery to sequence a faq list.  Needless to say, i'm new to this concept.  Anybody have any good examples of the backend for this.  I have the front working fine, but updating the sequence in the database is another story. My backend is ColdFusion btw.

Thanks in advance

[A]
Define the faq:
```
```

...

...

  (...)

..

```
```
Make faq sortable:
```
```

```
```
Form submitted:
```
```
<form action="..." id="faq_form">
  <input type="hidden" name="faqs" id="faqs" />
  ...
</form>
```
```
Add sorted sequence to form
```
```

```
```
When form is submitted, field "faqs" will contain comma separated id's from #faq like this:
q1,q3,q10,q11,q2,q100...
Just parse it and save to DB


q:
I am writing a dhtml application that creates an interactive simulation of a system.  The data for the simulation is generated from another tool, and there is already a very large amount of legacy data.

Some steps in the simulation require that we play "voice-over" clips of audio. I've been unable to find an easy way to accomplish this across multiple browsers.

Soundmanager2 comes pretty close to what I need, but it will only play mp3 files, and the legacy data may contain some .wav files as well.

Does anyone have any other libraries that might help?

[A]
I believe that the simplest and most convenient way would be to play the sound using a small Flash clip. I appreciate it's not a JavaScript solution but it IS the easiest way to achieve your goal
Some extra links from the previous
similar question
:
Scriptaculous, a Javascript library:
http://github.com/madrobby/scriptaculous/wikis/sound
an opensource Flash project: Easy Musicplayer For Flash
http://emff.sourceforge.net/


q:
I have an object that needs a test if the object data is valid. The validation itself would be called from the thread that instatiated the object, it looks like this:

 {
  if (_step.Equals(string.Empty)) return false;
  if (_type.Equals(string.Empty)) return false;
  if (_setup.Equals(string.Empty)) return false;
  return true;
}

Would it be better to implement this as a property, or as a method, and why? I have read the answers to a related question, but I don't think this specific question is covered there.

[A]
I would say as a Property.
```
```
if(something.IsValid) { ...
```
```
looks better then
```
```
if(something.IsValid()) { ...
```
```
Also an example from MSDN:
http://msdn.microsoft.com/en-us/library/system.web.ui.page.isvalid(VS.71).aspx


q:
Is there a FOSS batch compiling solution for Delphi that takes version as an input parameter?

I am using Delphi 7 and this remains the most tedious operation. Are there any other solutions, workarounds to make this easy.

[A]
Not really sure on your question, but I'm going to assume you are asking how to set the version number for a product from a batch file when compiling.  I previously used a program called
StampVer
,   You will need to already have version information in the file to use StampVer.  StampVer is Freeware but not Open Source.
A good commercial solution that I strongly recommend would be
FinalBuilder
, which also has the ability to manipulate the version information in an executable as well as compile your Delphi application.


q: How would you store formatted blocks of text (line breaks, tabs, lists - etc.) in a database (nothing specific) to be displayed on the web (XHTML) while maintaining a level of abstraction so that the data can be used in other applications or if the structure of the website were to change in the future?

[A]
This actually has very little to do with CodeIgniter and a lot with how mysql_fetch_assoc provides the query results.
The solution is that you should rename the columns inside the query using
```
"AS"
```
, e.g.
```
```
select type_of_source.description as type_of_source_description, origin.descripotion as origin_descripotion from ....
```
```


q: Let's say you already "know" what your client wants from you (i.e. you already did some analysis and have some clue about what are you supposed to deliver). What are the next steps you usually go through after this phase? In other words, what are the steps (in terms of preparation of the framework, plugins, repository, etc.) you do in the beginning of every RoR based application development?

[A]
I have an empty Rails application with my can't-live-without plugins (haml & rspec in the main) and with Rails frozen to vendor/plugins. I've also modified configuration stuff to fit my environment. The whole thing lives in my svn repository. When I start a new project, I check out my starting point and continue from there. Usually by writing (or trying to remember to write) a test.
It only saves an hour or so, but not having to mess around with stuff I do infrequently (and thus have to look up) is a big plus.
EDIT: Whoops, I forgot to mention
Bort
which is much more comprehensive...


q:
Our organization started on the SharePoint path about two years ago.  Before that, we (the developers) wrote mostly asp.net front ends for SQL back ends.  Now it seems like every time a new project comes up, we are asked to “make” it fit in SharePoint; and we have stuffed some things into SharePoint that probably should have been stand alone applications or web applications due to complexity and interactions with other technologies.

My question is: Where do you draw the line as to developing a project in SharePoint versus Web/Winform application, and how do you convince your manager(s) that SharePoint may not be the best solution for a particular project?

[A]
I sort of agree with you that this is sometimes a tough question.  In general, though, I agree with the cliche that you just have to think about a sharepoint app a little differently.  If your data can be considered as list-based, then SharePoint probably isn't a necessarily bad development framework.  It may seem like more work on the surface, but IMO the challenges just move from one place to another.  If you use things like custom field templates and web parts, you can relatively naturally handle all sorts of data.  And you get the positive aspects of SharePoint for free (an already mature security framework, built-in searching, site and list templates/definitions, personalized page customizations, yada, yada).
I also I don't know what you mean by "complexity and interactions with other technologies" here, so it's hard to imagine what specific issues might be introduced when SharePoint is added to the mix.
If your dev team is relatively inexperienced with SharePoint and you care about quality and deadlines, I can definitely see your point.  It's not an easy learning curve, but I think the SharePoint product is more naturally extensible than many people give it credit for.


q:
What is the best way for converting phone numbers into international format (E.164) using Java?

Given a 'phone number' and a country id (let's say an ISO country code), I would like to convert it into a standard E.164 international format phone number.

I am sure I can do it by hand quite easily - but I would not be sure it would work correctly in all situations.

Which Java framework/library/utility would you recommend to accomplish this?

P.S. The 'phone number' could be anything identifiable by the general public - such as

* (510) 786-0404
* 1-800-GOT-MILK
* +44-(0)800-7310658

that last one is my favourite - it is how some people write their number in the UK and means that you should either use the +44 or you should use the 0.

The E.164 format number should be all numeric, and use the full international country code (e.g.+44)

[A]
Speaking from experience at writing this kind of thing, it's really difficult to do with 100% reliability.  I've written some Java code to do this that is reasonably good at processing the data we have but won't be applicable in every country.  Questions you need to ask are:
Are the character to number mappings consistent between countries?  The US uses a lot of this (eg 1800-GOT-MILK) but in Australia, as one example, its pretty rare.  What you'd need to do is ensure that you were doing the correct mapping for the country in question if it varies (it might not).  I don't know what countries that use different alphabets (eg Cyrilic in Russia and the former Eastern block countries) do;
You have to accept that your solution will not be 100% and you should not expect it to be.  You need to take a "best guess" approach.  For example, theres no real way of knowing that 132345 is a valid phone number in Australia, as is 1300 123 456 but that these are the only two patterns that are for 13xx numbers and they're not callable from overseas;
You also have to ask if you want to validate regions (area codes).  I believe the US uses a system where the second digit of the area code is a 1 or a 0.  This may have once been the case but I'm not sure if it still applies.  Whatever the case, many other countries will have other rules.  In Australia, the valid area codes for landlines and mobile (cell) phones are two digits (the first is 0).  08, 03 and 04 are all valid.  01 isn't.  How do you cater for that?  Do you want to?
Countries use different conventions no matter how many digits they're writing.  You have to decide if you want to accept something other than the "norm".  These are all common in Australia:
(02) 1234 5678
02 1234 5678
0411 123 123 (but I've never seen 04 1112 3456)
131 123
13 1123
131 123
1 300 123 123
1300 123 123
02-1234-5678
1300-234-234
+44 78 1234 1234
+44 (0)78 1234 1234
+44-78-1234-1234
+44-(0)78-1234-1234
0011 44 78 1234 1234 (0011 is the standard international dialling code)
(44) 078 1234 1234 (not common)
And thats just off the top of my head.  For one country.  In France, for example, its common the write the phone number in number pairs (12 34 56 78) and they pronounce it that way too: instead of:
un (one), deux (two), trois (three), ...
its
douze (twelve), trente-quatre (thirty four), ...
Do you want to cater for that level of cultural difference?  I would assume not but the question is worth considering just in case you make your rules too strict.
Also some people may append extension numbers on phone numbers, possibly with "ext" or similar abbreviation.  Do you want to cater for that?
Sorry, no code here.  Just a list of questions to ask yourself and issues to consider.  As others have said, a series of regular expressions can do much of the above but ultimately phone number fields are (mostly) free form text at the end of the day.


q:
I'm using ccl/openmcl on Mac OS X. (latest versions of both). When the lisp prompt is displayed, using the cursor keys to navigate the current line results in escape codes, rather than movement, eg:

Welcome to Clozure Common Lisp Version 1.2-r9226-RC1  (DarwinX8664)!

? (^[[D

Here I've pressed the ( key, and then the left cursor key.

When I run ccl/openmcl on a Debian Etch box, the cursor behaves as expected, and moves the insert point one position left.

I guess this is some sort of terminal configuration option?

[A]
If Clozure CL doesn't provide native readline/editline/whatever support or is configured not to use it, you can run it with rlwrap, for example:
```
```
rlwrap openmcl
```
```
rlwrap can be obtained via
MacPorts
or directly from
http://utopia.knoware.nl/~hlub/rlwrap/
.


q:
Why does this work:

$(window).keydown(function(event){
    alert(event.keyCode);
});

but not this:

$('#ajaxSearchText').keydown(function(event){
    alert(event.keyCode);
});

I'm testing with Firefox 3.
Interestingly, neither of them work in IE7.

[A]
Try using
```
```
$('#ajaxSearchText').keyup(function(event){
    alert(event.keyCode);
});
```
```
works for me perfectly. Also check the id of the textarea


q:
I'm having trouble selecting elements that are part of an specific namespace.  My xpath expression works in XMLSpy but fails when using the Xalan libraries..

<item>
   <media:content attrb="xyz">
     <dcterms:valid>VALUE</dcterms:valid>
  </media:content>
</item>

My expression is ./item/media:content/dcterms:valid.  I've already added both namespace definitions to my XSLT.  Again, this selects the right values in XMLSpy but fails when running through Xalan library.

Any ideas?

[A]
Have you tried to define the namespace of the XML blob?
```
```
<item xmlns:dcterms="http://dcterms.example" xmlns:media="http://media.example">
   <media:content attrb="xyz">
     <dcterms:valid>VALUE</dcterms:valid>
  </media:content>
</item>
```
```
i.e.
xmlns:dcterms="http://dcterms.example"
xmlns:media="http://media.example"


q:
Where I work, we maintain an FTP site that needs occasional cleanup.

Are there any tools out there to create a site map of an FTP site? It would greatly simplify clean up tasks.

Thanks!

[A]
There is no public built-in way to stream from a string, as of .NET 3.5.
You can implement a simple StringStream class that inherits from Stream, which will free you from having to convert the string to an array of bytes.


q:
I'm trying to make a select that calculates affiliate payouts.

my approach is pretty simple.

SELECT
 month(payments.timestmap)
,sum(if(payments.amount>=29.95,4,0)) As Tier4
,sum(if(payments.amount>=24.95<=29.94,3,0)) As Tier3
,sum(if(payments.amount>=19.95<=24.94,2,0)) As Tier2
FROM payments
GROUP BY month(payments.timestamp)

The above does not work because MySQL is not evaluating the second part of the condition. Btw it does not cause a syntax error and the select will return results.

Before the above I tried what I was assuming would work like "amount between 24.94 AND 29.94" this caused an error. so then I tried "amount >= 24.94 AND <= 29.94"

So is it possible to have a range comparison using IF in MySql?

[A]
The second part of the expression evaluates when you use
```
AND
```
-
```
```
SELECT
 month(payments.timestmap)
,sum(if(payments.amount>=29.95,4,0)) As Tier4
,sum(if(payments.amount>=24.95 AND payments.amount<=29.94,3,0)) As Tier3
,sum(if(payments.amount>=19.95 AND payments.amount<=24.94,2,0)) As Tier2
FROM payments
GROUP BY month(payments.timestamp)
```
```
I'm not entirely sure why the
```
between
```
clause didn't work for you, but the above should do the job.


q:
I want to create a simple box with a header bar containing a title and some tool buttons. I have the following markup:

<div style="float:left">
    <div style="background-color:blue; padding: 1px; height: 20px;">
        <div style="float: left; background-color:green;">title</div>
        <div style="float: right; background-color:yellow;">toolbar</div>
    </div>
    <div style="clear: both; width: 200px; background-color: red;">content</div>
</div>

This renders fine in Firefox and Chrome:

http://www.boplicity.nl/images/firefox.jpg

However IE7 totally messes up and puts the right floated element to the right of the page:

http://www.boplicity.nl/images/ie7.jpg

Can this be fixed?

[A]
Make this
```
<div style="background-color:blue; padding: 1px; height: 20px;>
```
the parent of the 2 floating divs also
```
clear:all
```


q:
I am using link to sql, I have a connected set of objects.

I start out and do a linq statement like this

Dim L= from II in context.InventoryItems select II
Dim L2 = L.tolist

The second line was so that I could narrow down where the problem was occuring. When the second line is hit I get an error "The EntitySet is already loaded and the source cannot be changed"

Any ideas what might be causing this?

[A]
Omer's comment brings up a very good point: is this DataContext being re-used from a previous operation?  If so, you may want to check out Dino Esposito's
blog post
regarding lifetime of the DataContext to make sure you're not keeping it around too long.
That error sounds like maybe you have already loaded data from the InventoryItems table using that DataContext and possibly made some changes to entities bound to the DataContext that you have not yet submitted.  If you try your code with a brand new DataContext without specifying any special DataLoadOptions it should work.


q:
I could use some help writing a regular expression.  In my Django application, users can hit the following URL:

http://www.example.com/A1/B2/C3

I'd like to create a regular expression that allows accepts any of the following as a valid URL:

http://www.example.com/A1
http://www.example.com/A1/B2
http://www.example.com/A1/B2/C3

I'm guessing I need to use the "OR" conditional, but I'm having trouble getting my regex to validate.  Any thoughts?

UPDATE: Here is the regex so far.  Note that I have not included the "http://www.example.com" portion -- Django handles that for me.  I'm just concerned with validating 1,2, or 3 subdirectories.

^(\w{1,20})|((\w{1,20})/(\w{1,20}))|((\w{1,20})/(\w{1,20})/(\w{1,20}))$


q:
Like, testing for :

invalid inputs (strings containing "'"s)

giving random id's in url parameters to access "unauthorized" pages

prevent sql injection

...

[A]
I would recommend reading this brilliant
book
to learn more about the test plans.
In particular a test plan is much more than a list of techniques like you mentioned (these should most likely go into the details for the security testing)
It should at least contain:
The answers to the main questions:
why bother (what is gained by testing)
who cares (who are we working for)
how much (..testing will be done)
You would not go wrong providing also:
Platforms
Methods (positive testing, load testing etc)
Functionality you're planning to test
Acceptance criteria
And there is plenty more things to talk about in the plan.


q:
Consider this:

var query = from r in this._db.Recipes
            where r.RecipesID == recipeID
            select new { r.RecipesID, r.RecipesName };

How would i get individual columns in my query object without using a for-loop?

Basicly: how do I translate DataTable.Rows[0]["ColumnName"] into Linq syntax?

[A]
Sorry, misunderstood your question.  As others are saying, you can use ToList() to get a List back.  An alternative if all you need is the first one, just use:
```
```
query.First().ColumnName
```
```
or if you want to avoid an exception on empty list:
```
```
var obj = query.FirstOrDefault();
if (obj != null)
   obj.ColumnName;
```
```
Original Answer (so the comment makes sense):
Use
Linq to Datasets
.  Basically would be something like:
```
```
var query = from r in yourTable.AsEnumerable()
select r.Field<string>("ColumnName");
```
```


q:
I am using a List Control to display a representation of elements within a vector. When the list is clicked on another control shows information about that element. The index of the element is currently determined by its index in the control, however if I wish to sort or filter the results this will no longer work.

I have been told that I could use a virtual list control, but the MSDN is not very friendly, can someone run me through how I could use a virtual list control for this?

[A]
Frankly - tying data (the position in your data vector) to the presentation of the data in the list control (the position in the list ctrl) is something I would stay away from.
In MFC each control has a "Data" DWORD member variable - when coding in MFC I Always called "SetItemData" for each item added and passed in a pointer that the relevant row referred to e.g.
```
YourListCtrl.SetItemData((DWORDPTR)&YourData);
```
Then when the ListCtrl item is selected, you just call
```
DataTypeYouWant* pData =  (DataTypeYouWant*)(YourListCtrl.GetItemData(indexofselecteditem));
```
Or somesuch thing.
Alternatively - if you don't want to use pointers - hold the index of the item in your original vector in the itemdata for your row (just pass it into the above fns).


q:
I need to create a cherrypy main page that has a login area.  I want the login area to be secure, but not the rest of the page.  How can I do this in CherryPy?

Ideally, any suggestions will be compatible with http://web.archive.org/web/20170210040849/http://tools.cherrypy.org:80/wiki/AuthenticationAndAccessRestrictions


q: I have currently an installed pgsql instance that is running on port 1486. I want to change this port to 5433, how should I proceed for this?

[A]
There should be a line in your
```
postgresql.conf
```
file that says:
```
```
port = 1486
```
```
Change that.
The location of the file can vary depending on your install options. On Debian-based distros it is
```
/etc/postgresql/8.3/main/
```
On Windows it is
```
C:\Program Files\PostgreSQL\9.3\data
```
Don't forget to
```
sudo service postgresql restart
```
for changes to take effect.


q:
Using OpenXML SDK, I want to insert basic HTML snippets into a Word document.

How would you do this:

Manipulating XML directly ?

Using an XSLT ?

using AltChunk ?

Moreover, C# or VB examples are more than welcome :)

[A]
I'm not sure, what you actually would like to achieve. The OpenXML documents have an own html-like (WordprocessingML) notation for the formatting elements (like paragraph, bold text, etc.). If you would like to add some text to a doc, with basic formatting, than I rather suggest to use the OpenXML syntax and format the inserted text with that.
If you have a html snippet, that you must include into the doc as it is, you can use the "external content" feature of OpenXML. With external content, you can include the HTML document to the package, and create a reference (altChunk) in the doc in the position, where you want to include this. The disadvantage of this solution, that not all tools will support (or support properly) the generated document, therefore I don't recommend this solution, unless you really cannot change the HTML source.
How to include any content (the wordml) to a openxml word doc is an independent question IMHO, and the answer depends very much on how complex modifications you want to apply, and how big the document is. For a simple document, I would simply read out the document part from the package, obtain it's stream and load it to an XmlDocument. You can insert additional content to the XmlDocument quite easily, and then save it back to the package. If the document is big, or you need complex modifications in multiple places, XSLT is a good option.


q: How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.

[A]
The method len() returns the number of elements in the list.
Syntax:
```
```
len(myArray)
```
```
Eg:
```
```
myArray = [1, 2, 3]
len(myArray)
```
```
Output:
```
```
3
```
```


q:
I'm trying to create a logger for a GWT application as an exercise to evaluate GWT. What I specifically want to do is have it so that I can post messages to a client side label at any point from the server side. So, if some interesting stuff has happened on the server the client can be updated.

My First question is, is this possible, I can understand it not being.

Second, if it is possible, where should I look for information, I've tried google and their documentation and all the showcases have nothing on this.

Thanks

[A]
Well, there are a couple of Options.  You need to get the data from the server... So you either need to poll the server, or use server push.
Polling is pretty easy.  Just use the
Timer
class to repeatedly call a service to see what value it should be displaying.
Server push is done using something like comet.
here
is one implementation for gwt that looks somewhat promising.  They basic concept behind this is the browser sends a request to the server and keeps the connection open so the server is free to keep sending data back.
Comet is the better option if you can get it working.  It will probably be simpler and scale better.
Good Luck!


q:
Any ideas how i can best drive a USB POS printer from c#.
POS printers are usually serial, TCP/IP or USB based.
I know how to accomplish serial and TCP/IP but have no idea about communications through USB in C#.
I know that there is a layer available from Microsoft called POS.NET, but I want to try and avoid using this.
Any ideas or any C# libraries that people can recomend would be really appreciated.  Thanks

[A]
If the printer registers itself as a Human Interface Device, you can
P/INVOKE into the appropriate Win32 APIs
. Here are the signatures:
```
```
[ DllImport( "hid.dll", SetLastError=true ) ]
    public static extern Boolean
    HidD_FlushQueue( SafeFileHandle HidDeviceObject );

    [ DllImport( "hid.dll", SetLastError=true ) ]
    public static extern Boolean
    HidD_FreePreparsedData( ref IntPtr PreparsedData );

    [ DllImport( "hid.dll", SetLastError=true ) ]
    public static extern Boolean
    HidD_GetAttributes(  SafeFileHandle HidDeviceObject
                       , ref HIDD_ATTRIBUTES Attributes );

    [ DllImport( "hid.dll", SetLastError=true ) ]
    public static extern Boolean
    HidD_GetFeature(  SafeFileHandle HidDeviceObject
                    , ref Byte lpReportBuffer
                    , Int32 ReportBufferLength );

    [ DllImport( "hid.dll", SetLastError=true ) ]
    public static extern Boolean
    HidD_GetInputReport( SafeFileHandle HidDeviceObject
                        ,ref Byte lpReportBuffer
                        ,Int32 ReportBufferLength );

    [ DllImport( "hid.dll", SetLastError=true ) ]
    public static extern void HidD_GetHidGuid( ref System.Guid HidGuid );

    [ DllImport( "hid.dll", SetLastError=true ) ]
    public static extern Boolean
    HidD_GetNumInputBuffers(  SafeFileHandle HidDeviceObject
                            , ref Int32 NumberBuffers );

    [ DllImport( "hid.dll", SetLastError=true ) ]
    public static extern Boolean
    HidD_GetPreparsedData( SafeFileHandle HidDeviceObject
                          ,ref IntPtr PreparsedData );

    [ DllImport( "hid.dll", SetLastError=true ) ]
    public static extern Boolean
    HidD_SetFeature(  SafeFileHandle HidDeviceObject
                    , ref Byte lpReportBuffer
                    , Int32 ReportBufferLength );

    [ DllImport( "hid.dll", SetLastError=true ) ]
    public static extern Boolean
    HidD_SetNumInputBuffers( SafeFileHandle HidDeviceObject
                            ,Int32 NumberBuffers );

    [ DllImport( "hid.dll", SetLastError=true ) ]
    public static extern Boolean
    HidD_SetOutputReport( SafeFileHandle HidDeviceObject
                         ,ref Byte lpReportBuffer
                         ,Int32 ReportBufferLength );

    [ DllImport( "hid.dll", SetLastError=true ) ]
    public static extern Int32
    HidP_GetCaps( IntPtr PreparsedData, ref HIDP_CAPS Capabilities );

    [ DllImport( "hid.dll", SetLastError=true ) ]
    public static extern Int32
    HidP_GetValueCaps(  Int16 ReportType
                      , ref Byte ValueCaps
                      , ref Int16 ValueCapsLength
                      , IntPtr PreparsedData );
```
```


q:
In my program, how can I read the properties set in AssemblyInfo.cs:

[assembly: AssemblyTitle("My Product")]
[assembly: AssemblyDescription("...")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Radeldudel inc.")]
[assembly: AssemblyProduct("My Product")]
[assembly: AssemblyCopyright("Copyright @ me 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

I'd like to display some of these values to the user of my program, so I'd like to know how to load them from the main program and from komponent assemblies I'm using.

[A]
This is reasonably easy. You have to use reflection. You need an instance of Assembly that represents the assembly with the attributes you want to read. An easy way of getting this is to do:
```
```
typeof(MyTypeInAssembly).Assembly
```
```
Then you can do this, for example:
```
```
object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);

AssemblyProductAttribute attribute = null;
if (attributes.Length > 0)
{
   attribute = attributes[0] as AssemblyProductAttribute;
}
```
```
Referencing
```
attribute.Product
```
will now give you the value you passed to the attribute in your AssemblyInfo.cs. Of course, if the attribute you look for can occur more than once, you may get multiple instances in the array returned by GetCustomAttributes, but this is not usually an issue for assembly level attributes like the ones you hope to retrieve.


q:
I have two arrays. One contains id=>count and the other contains id=>name. I'm trying to produce a single array that is name=>count. Any suggestions on a straightforward way to do this?

I have looked at the Array Functions in the PHP Manual and didn't see anything that stood out as doing what I want, so I'm guessing I'll need a combination of functions, but I'm having trouble coming up with something that's not convoluted.

[A]
Something like:
```
```
foreach($countA as $id => $count)
{
    $newArray[$nameA[$id]] = $count;
}
```
```
This does assume that the keys are in correspondence between the two arrays, since your requirements are ambiguous otherwise.


q:
I have a package that I just made and I have an "old-mode" that basically makes it work like it worked before: importing everything into the current namespace.  One of the nice things about having this as a package is that we no longer have to do that.  Anyway, what I would like to do is have it so that whenever anyone does:

use Foo qw(:oldmode);

I throw a warning that this is deprecated and that they should either import only what they need or just access functions with Foo->fun();

Any ideas on how to do this?

[A]
You write your own
```
sub import
```
in
```
package Foo
```
that will get called with the parameter list from
```
use Foo
```
.
An example:
```
```
package Foo;
use Exporter;

sub import {
    warn "called with paramters '@_'";

    # do the real import work
    goto &{Exporter->can('import')};
}
```
```
So in sub
```
import
```
you can search the argument list for the deprecated tag, and then throw a warning.
Update
: As Axeman points out, you should call
```
goto &{Exporter->can('import')}
```
. This form of goto replaces the current subroutine call on the stack, preserving the current arguments (if any). That's needed because Exporter's import() method will export to its caller's namespace.


q: Is there a case insensitive version of the :contains jQuery selector or should I do the work manually by looping over all elements and comparing their .text() to my string?

[A]
What I ended up doing for jQuery 1.2 is :
```
```
jQuery.extend(
    jQuery.expr[':'], {
        Contains : "jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0"
});
```
```
This will extend jquery to have a :Contains selector that is case insensitive, the :contains selector remains unchanged.
Edit: For jQuery 1.3 (thanks @user95227) and later you need
```
```
jQuery.expr[':'].Contains = function(a,i,m){
     return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
```
```
Edit:
Apparently accessing the DOM directly by using
```
```
(a.textContent || a.innerText || "")
```
```
instead of
```
```
jQuery(a).text()
```
```
In the previous expression speeds it up considerably so try at your own risk if speed is an issue. (see
@John
's
question
)
Latest edit: For jQuery 1.8 it should be:
```
```
jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) {
    return function( elem ) {
        return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});
```
```


q:
Besides the unit testing benefits, what I heard regarding MVP pattern was that the reusability of the presentation layer.  So, you would design one presentation layer and use it for WinForms (rich) and Web.

I am currently working on a windows forms application in .NET with possibility of creating a web UI in the future.  However, when I am designing the presentation layer and the interaction between the UI layer, I am not certain whether this notion of reusability is worth all the trouble.  I sometimes feel like I am "dumbing down" my presentation for the possible web UI, when it can be so much more when designed specifically for the windows forms UI.

So, how many of you are reaping the benefits of the reusable presentation layer?
Does this reusability thing pan out in the real world?

[A]
The value of MVC/MVP really lies in two different separations.
Separation between your presentation layer and your models (however you decide to implement them) is one of the more important principals software design for anything but simple systems. If you have any business logic or nonvisual logic in your application, you will definitely see the benefits of that separation.
The separation between presentation layer and controller seems a little less important to me. In rich client applications, you'll rarely see benefit from this separation; in web front ends, it's a lot more common (e.g., ASP.NET aspx and code-behind or J2EE jspx and servlet).
Maybe I don't completely grasp the way you've explained MVP, but I wouldn't say that one of the benefits is the
reusability
of the presentation layer--rather, I would say that the primary benefit is the reusability of the models. This is also one of the primary benefits of using any n-tier system. If you want to expand and build a new type of front-end (e.g., WinForms, WPF, etc.), you can do so without trying to separate all your logic out of the web application you just built.


q:
What's the best way of capturing an mp3 stream coming off of http and saving it to disk with python?

Thus far I've tried

target = open(target_path, "w")
conn = urllib.urlopen(stream_url)
while True:
    target.write(conn.read(buf_size))

This gives me data but its garbled or wont play in mp3 players.

[A]
If you're on Windows, you might accidentally be doing CRLF conversions, corrupting the binary data.  Try opening
```
target
```
in binary mode:
```
```
target = open(target_path, "wb")
```
```


q:
I used Visual Studio's Application Wizard to create a skeleton MFC program with a multi-document interface.  When I start this program, it automatically creates a child frame, which I don't want it to do - I need the main frame's client area to be empty until the user chooses to open a file.

The debugger tells me that a CChildFrame object is created when the application class's InitInstance() function calls ProcessShellCommand(), but what is a good entry point for me to override this behaviour?

[A]
This worked for me -- change
```
```
if (!ProcessShellCommand(cmdInfo))
```
```
to
```
```
if (cmdInfo.m_nShellCommand != CCommandLineInfo::FileNew && !ProcessShellCommand(cmdInfo))
```
```
in your app's InitInstance() function.