Question:
I have an enumeration: ENUM( 'alpha', 'beta', 'gamma', 'delta', 'omega' )

If I sort my table by this column I get them in the correct order defined above.

However, I can't find a way to select a subset of these, e.g. everything before delta. Using WHERE status < 'delta' only returns alpha and beta, not gamma. It seems MySQL uses a string comparison, not enum index comparison.

I could use the index numbers - i.e. WHERE status < 4 - but it's a bit of a code smell (magic numbers) and may break if I insert new values into the enumeration.

Answer:
You can use
```
FIELD(column, "string1", "string2", ...)
```
to find rows with any particular subset of possible
```
ENUM
```
values.
```
```
SELECT * FROM `table` WHERE FIELD(`enum_column`, "alpha", "delta", "et cetera");
```
```
If you want to use the range version, you can use
```
FIND_IN_SET("needle", "hay,stack")
```
to return the index but you'll have to extract the ENUM list out of the table definition first with another query.


Question:
I'm currently considering the use of Reflection classes (ReflectionClass and ReflectionMethod mainly) in my own MVC web framework, because I need to automatically instanciate controller classes and invoke their methods without any required configuration ("convention over configuration" approach).

I'm concerned about performance, even though I think that database requests are likely to be bigger bottlenecks than the actual PHP code.

So, I'm wondering if anyone has any good or bad experience with PHP 5 Reflection from a performance point of view.

Besides, I'd be curious to know if any one of the popular PHP frameworks (CI, Cake, Symfony, etc.) actually use Reflection.

Answer:
Don't be concerned. Install
Xdebug
and be sure where the bottleneck is.
There is cost to using reflection, but whether that matters depends on what you're doing. If you implement controller/request dispatcher using Reflection, then it's just one use per request. Absolutely negligible.
If you implement your ORM layer using reflection, use it for every object or even every access to a property, and create hundreds or thousands objects, then it might be costly.


Question:
Sorry for the newb question.  I'm still learning programming.  So I'm using C++, and I need to do something like this:

int n;
do {
    n = get_data();
    if(n != -1)
        send(n);
} while(n != -1);

This is just a sketch.  Anyway it doesn't feel real elegant.  I have to have my test twice.  I could just test once and set a flag, but that doesn't feel real elegant either since I have to check the flag twice.  It just seems like there should be a way to do this more easily, since it's so easy what I want to do.

Answer:
Howabout using
break
:
```
```
int n;
while(1) {
    n = get_data();
    if(n == -1)
        break;
    send(n);
}
```
```
This way you only test once, and quit immediately if get_data doesn't return what you want.


Question:
I'm using django and when users go to www.website.com/ I want to point them to the index view.

Right now I'm doing this:

(r'^$', 'ideas.idea.views.index'),

However, it's not working. I'm assuming my regular expression is wrong. Can anyone help me out? I've looked at python regular expressions but they didn't help me.

Answer:
What you have should work (it does for me).  Make sure it's in the top
```
urls.py
```
, and it should also be at the top of the list.


Question:
I'm interested in measuring and improving (where necessary) my team's SQL-92 skills. Can anyone recommend an appropriate on-line course and/or examination?

Ideally it would be vendor-neutral, but it could also be MSSQL/Oracle specific, as long as the proprietary bits were flagged as such.

Answer:
What you have should work (it does for me).  Make sure it's in the top
```
urls.py
```
, and it should also be at the top of the list.


Question:
What is the best way to block certain input keys from being used in a TextBox with out blocking special keystrokes such as Ctrl-V/Ctrl-C?

For example, only allowing the user to enter a subset of characters or numerics such as  A or B or C and nothing else.

Answer:
You could use the TextChanged event for the textbox.
```
```
private void txtInput_TextChanged(object sender, EventArgs e)
    {
        if (txtInput.Text.ToUpper() == "A" || txtInput.Text.ToUpper() == "B")
        {
            //invalid entry logic here
        }
    }
```
```


Question: I would like to set up a localhost server to test my site on in sql server 2005. I just installed sql server 2005 and I have never set up a database in this before. There is a login screen and I tried everything and it will not let me log into anything. What are the steps I need to do to get this to work. Thanks

Answer:
Assumptions:
sql2005 is installed on your localhost
u can connect to it via Query analyzer or Sql Server Management Studio?
when the login prompt starts up, u have two options for authentication ->  Windows authentication or Sql Server Authentication.
If those assumptions are all correct, then try connecting via the Windows Authentication option. If that fails, then try the Sql Server Authentation and use the username 'sa' (no quotes), password leave empty.
does that work? also, post some links to screenshots so we can see exactly what you see, to help you further.


Question:
I'm getting an exception which says "Access Denied" when the users permissions are sufficient, how do I catch an exception and check for "Access Denied" so that I can show the user a friendlier "Sorry Access Denied" message?

Thanks
Beginner :-)

Answer:
If you are using a try catch block...
```
```
try
{
    //error occurs
}
catch (Exception ex)
{
    MessageBox.show(ex.Message);
}
```
```
Obviously that is pretty crappy error handling, but it shows that the Exception object contains the error string.  You can narrow down the handling of different exceptions by catching different exception types.
```
```
Try
{
    //error occurs
}
catch (AccessDeniedException ex)
{
    MessageBox.show(ex.Message);
}
catch (FieldAccessException)
{

}
// etc...
```
```


Question:
What's a good algorithm to solve this problem?

I have three groups of people - group A, group B, and group C. There are the same number of people in each group. They each have a list of people in the other groups that they're willing to work with. I want to group all these people together in groups of 3 (one from A, one from B, and one from C) such that everyone in a group wants to work with the other people in their group.

How can I find these groups in a fast way? If there's no way to make everyone happy, then the algorithm should first make as many groups have three people who want to work with each other, and then make as many people in the other groups happy.

One final point: people agree on who they want to work with (if person x wants to work with person y, then y also wants to work with x). If you could also give a big-O of the running time of your algorithm, that'd be great!

Answer:
This is like the stable marriage problem, but with 3 parties instead of two.
Have a look at efficient solutions for former problem (bi-partite graph matching) and adapt them to your needs.
http://en.wikipedia.org/wiki/Stable_marriage_problem
One adaptation could be to first build working pairs from groups A and B only. Then these pairs have to be paired with a worker from group C each. Let the pairs only prefer workers which both members of the pair agree on (given their lists). Note that this will only give a local optimum.
An optimal solution to k-partite matching is NP-hard to find:
http://www.math.tau.ac.il/~safra/PapersAndTalks/k-DM.ps
See this paper for a non-optimal solution to the k-partite matching problem:
http://books.google.com/books?id=wqs31L1MF4IC&pg=PA309&lpg=PA309&dq=k-partite+matching&source=bl&ots=kgBuvi7ym_&sig=j3Y-nyo51y8qp0-HwToyUlkao4A&hl=de&sa=X&oi=book_result&resnum=1&ct=result
I'm sure you can find others on Google yourself now that you know the terms to search for. I don't know if there is an efficient algorithm giving the optimal solution for k=3.


Question: I have a MySQL table that will only have one row. What should my statement be for the first time I insert to this row, and for subsequent updates? I tried an insert where the primary key equals 1, but this doesn't account for the first time around when no row exists yet.

Answer:
```
```
INSERT INTO table(col1,col2,col3) VALUES(val1,val2,val3) ON DUPLICATE KEY UPDATE col1 = val1, col2 = val2, col3 = val3;
```
```


Question: I also want to save the font size in my .emacs file.

Answer:
Press Shift and the first mouse button.  You can change the font size in the following way:
This website
has more detail.


Question:
The application de-serializes a stream into dynamically allocated objects and then keeps base type pointers in a linked list (i.e. abstract factory).  It's too slow.  Profiling says all the time is spent in operator new.

Notes: The application already uses a custom memory allocator that does pooling.  The compiler is VC++ 6.0 and the code uses the old RogueWave collections rather than the STL.

The only idea I have right now is to introduce Object Pooling.  I'd maintain large collections of pre-allocated objects for each type and re-use them.  But this will be a lot of work in this old code, and I'm not yet sure there's enough re-use that it would even help.  I was hoping someone smarter than me has an idea.

Answer:
I'll assume that most allocations relate to the list of objects you're talking about. If you're actually allocating a bunch of other objects as part of the parsing that's too slow, then you need more information to optimize.
I don't know anything about the RogueWave collections, but if their linked list allocates an external node, then you should be able to halve the number of allocations by using an intrusive list - write your own container if necessary. This assumes that you don't need to put the same objects on multiple lists at once (or in the same list more than once).
If your app is multi-threaded, then the memory allocator will likely be doing some synchronization. But if you can arrange for these objects to be freed in the same thread they're allocated, then they could be allocated off a per-thread heap by overloading operator new. This might be faster: synchronization isn't necessarily all that slow provided there isn't contention, but it takes more time than none, and if other threads in your process are allocating at the same time then there will be contention.
For even more limited use-cases, if you find that you allocate a whole load of these things and then always free them all at once when you're done with the list, you can write an even faster "gc-style" allocator.
Operator new/delete would call functions like these (and size might be a constant rather than a parameter, if there's only one class you use the pool for):
```
```
char *alloc(POOL *pool, size_t size) {
    // if size is a parameter, and may be a non-multiple the max alignment
    // requirement on your system, and you want this to work in general:
    // size = (size + MAX_ALIGNMENT - 1) % ALIGNMENT;
    char *block = pool.current;
    char *next = block + size;
    if (next > pool.limit) throw std::bad_alloc();
    pool.current = next;
    return block;
}

void free(char *block) {
    return;
}

void freeAll(POOL *pool) {
    pool.current = pool.start;
    return;
}
```
```
This should ensure that operator new takes trivial time compared with what you spend parsing the objects you're creating. But it does require the application to identify the times at which it should create, destroy, and clear pools, and to to use a suitable new operator taking the pool pointer as a parameter, so it's not a drop-in replacement.


Question:
We have a project page which consists of users' files, multimedia stuff, etc and we want to allow the user to export all this out into a single zip file. We're using unix and mysql to store all of these currently and our primary goal is to minimize load/performance time from all the processing and compiling all the files into a zip file.

My idea was to cache the zip file into a temp dir and keep all the CRC checksum for each files in the zip into a separate text file. Each time the user tries to do an export I will first check through each file's CRC and compare it to the list before adding or removing files from the zip file.

But my other concern is also the space that the zip file will be occupying as we might have a lot of users.

IMHO, this is probably the dumbest way possible to do this,
so can any of you guys please suggest a better way to deal with this problem?

thanks
~codeNoobian

Answer:
If bandwidth/download speed is not a concern, I recommend you use an uncompressed tar file. TAR is a very simple format, so it will be easy to write code to update sections of it when a few of the files have changed.  Also, leaving it uncompressed will be a huge win on server CPU time.
Of course, leaving it uncompressed will take a lot of storage space on your server.  But since it is uncompressed, it might remove the need for you to keep a cache copy of the file at all, if you can build it fast enough you can just build it on the fly as needed.  Then you don't have to worry about storing CRCs and updating the TAR, either.


Question:
I am using the following servlet-mapping in my web.xml file:

<servlet>
    <servlet-name>PostController</servlet-name>
    <servlet-class>com.webcodei.controller.PostController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>PostController</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

To do some kind of a search. ex:
 http://www.myweb.com/The search string here

But the problem is that CSS, JS and Images are treated like a search request.

There are any patterns that strip out *.css, *.js, *.gif and etc, so the requests don't need to pass through my controller?

Thank you so much, bye bye!

Answer:
Two options come to mind:
1) Typically, in web app like this, the "action" URLs that are handled by a servlet, are given either a sub-directory like "
```
/actions/*
```
" or are given an extension like "
```
*.action
```
" or "
```
*.do
```
" (this is what Struts does). This way it's clear which URLs are intended for the servlet. This is more of an inclusive solution, rather than the exclusive one you're asking for, but I don't think what you want is possible.
2) The slightly more adventurous option is to set up your web app server behind an apache install that serves up the images, css, etc as flat files, sending only everything else onto the app server. Typically, this is done to take the load off your app server. It would require you to copy all these files to a separete directory for apache to handle.


Question:
How does the data go from the MVC to the browser and back again?   Does it use Microsoft's own technology like ASMX or WCF or something completely different?

This sounds like MVC is using a ASMX Web Service they are using but I can't seem to find any documentation which gives the real answer.

Answer:
AJAX requests are performed in the page using normal HTTP request/response. That is, in javascript the client will create a AJAX request object, send it off to a URL and it gets back a string. If that string is json, it can be eval'd and become a live javascript object.
The philosophy of MVC is that
all
http requests go through controllers. WCF is only for other types of web services that where the client doesn't consume html-json-css-etc.
You can return JSON from a controller action using the Json(object model) method on System.Web.Mvc.Controller.
for example
```
```
ActionResult MyAction() {
    return Json(new { success=false, for_lunch="mmm, chicken"});
}
```
```
That will return the json your webpage can consume.
So, that leaves the question - how does the browser call the MyAction for the json?
Several posts exist on this topic, and the first one i could find that did this was
this post
.
Hope that helps


Question:
I have a few model classes with basic one-to-many relationships.  For example, a book has many recipes, and each recipe has many ingredients:

class Book(models.Model):
    name = models.CharField(max_length=64)

class Recipe(models.Model):
    book = models.ForeignKey(Book)
    name = models.CharField(max_length=64)

class Ingredient(models.Model):
    text = models.CharField(max_length=128)
    recipe = models.ForeignKey(Recipe)

I'd like a flat list of all ingredients in all recipes from a particular book.  What's the best way to express this in Python?

If I was using LINQ, I might write something like this:

var allIngredients = from recipe in book.Recipes
                     from ingredient in recipe.Ingredients
                     select ingredient;

Answer:
To print each recipe and its ingredients:
```
```
mybook = Book.objects.get(name="Jason's Cookbook")
for recipe in mybook.recipe_set.all():
    print recipe.name
    for ingredient in recipe.ingredients:
        print ingredient.text
```
```
And if you just want to get a list of all ingredient objects:
```
```
mybook = Book.objects.get(name="Jason's Cookbook")
ingredient_list = []
for recipe in mybook.recipe_set.all():
    for ingredient in recipe.ingredients:
        ingredient_list.append(ingredient)
```
```
Documentation
.


Question:
I've explored python for several years, but now I'm slowly learning how to work with c.  Using the python documentation, I learned how to extend my python programs with some c, since this seemed like the logical way to start playing with it.  My question now is how to distribute a program like this.

I suppose the heart of my question is how to compile things.  I can do this easily on my own machine (gentoo), but a binary distribution like Ubuntu probably doesn't have a compiler available by default.  Plus, I have a few friends who are mac users.  My instinct says that I can't just compile with my own machine and then run it on another.  Anyone know what I can do, or some online resources for learning things like this?

Answer:
Please read up on distutils.  Specifically, the section on
Extension Modules
.
Making assumptions about compilers is bad policy; your instinct may not have all the facts.  You could do some marketplace survey -- ask what they can handle regarding source distribution of extension modules.
It's relatively easy to create the proper distutils
```
setup.py
```
and see who can run it and who can't.
Built binary distributions are pretty common.  Perhaps you can sign up some users will help create binary distributions -- with OS-native installers -- for some considerations.


Question:
When working with window handles, is it good enough to use the plain IntPtr or should I subclass SafeHandle?

Are there any significant pros/cons?

Thanks.

Answer:
That depends :)
If the handle is returned in such a way that you must eventually call a version of ::CloseHandle on them then you should always subclass SafeHandle.  SafeHandle makes the strongest guarantee possible in the .Net Framework that a handle will be freed.  Not freeing an IntPtr will lead to a resource leak.  Enough resource leaks will eventually lead to a program crash.
If the handle doesn't need to be freed then passing around IntPtr is sufficient.


Question:
I have a ComboBox bound to an ObservableCollection of decimals.  What is the correct way to apply our currency converter to the items?

Edit:

a) I have an existing currency converter that I must use
b) .NET 3.0

Do I need to template the items?

Answer:
Use
StringFormat
in the Binding expression like
```
```
<TextBox Text="{Binding Path=Value, StringFormat=Amount: {0:C}}"/>
```
```
See this
blog for more details.
A
ValueConverter
is another way - StringFormat doesnt work on .NET3.0 it needs WPF3.5 SP1.


Question: Where can I find either literature or video demonstration of unit testing applications using VB.NET? As a novice/hobbyist programmer I would like to build a solid foundation in developing applications using the unit testing methodology.

Answer:
If it helps any, you may want to learn C# if you plan on staying in the .NET world and ever plan to use .NET professionally.  I've answered why
here
.  Now, on to your question: O'Reilly and Associates had an
article on this very subject
recently (if by 2005 you mean recent, but for our purposes, we can call it recent).  You may also want to learn
Nunit
, which is a unit testing framework for .NET.
As far as Books:
Open Source .NET Development
- Covers Nunit.
eXtreme .NET: Introducing eXtreme Programming Techniques to .NET Developers
Test Driven Development in Microsoft.NET
That should get you started.  I don't know whether the code examples are in VB or C#, but if you have a
Safari online
subscription (which I highly recommend), you'll be able to browse these books without dropping money on them.


Question:
How do you convert a number to a string showing dollars and cents?

eg:
123.45    => '$123.45'
123.456   => '$123.46'
123       => '$123.00'
.13       => '$0.13'
.1        => '$0.10'
0         => '$0.00'

Answer:
In PHP and C++ you can use the printf() function
```
```
printf("$%01.2f", $money);
```
```


Question:
What are some of the ways you have implemented models in the Zend Framework?

I have seen the basic class User extends Zend_Db_Table_Abstract and then putting calls to that in your controllers:

$foo = new User;

$foo->fetchAll()

but what about more sophisticated uses? The Quickstart section of the documentation offers such an example but I still feel like I'm not getting a "best use" example for models in Zend Framework. Any interesting implementations out there?

EDIT: I should clarify (in response to CMS's comment)... I know about doing more complicated selects. I was interested in overall approaches to the Model concept and concrete examples of how others have implemented them (basically, the stuff the manual leaves out and the stuff that basic how-to's gloss over)

Answer:
You can do more complicated queries, check the
Advanced usage
section in the
```
Zend_Db_Table
```
manual page.
```
```
$select = $table->select();
$select->from($table,
              array('COUNT(reported_by) as `count`', 'reported_by'))
       ->where('bug_status = ?', 'NEW')
       ->group('reported_by');
```
```


Question:
I have a table like this:

<table>
    <tfoot>
        <tr><td>footer</td></tr>
    </tfoot>
    <tbody>
        <tr><td>Body 1</td></tr>
        <tr><td>Body 1</td></tr>
        <tr><td>Body 1</td></tr>
    </tbody>
    <tbody>
        <tr><td>Body 2</td></tr>
        <tr><td>Body 2</td></tr>
        <tr><td>Body 2</td></tr>
    </tbody>
    <tbody>
        <tr><td>Body 3</td></tr>
        <tr><td>Body 3</td></tr>
        <tr><td>Body 3</td></tr>
    </tbody>
</table>

I'd like to put some spacing between each tbody element, but padding and margin have no effect. Any ideas?

Answer:
Try this, if you don't mind not having borders.
```
```

footer

Body 1

Body 1

Body 1

Body 2

Body 2

Body 2

Body 3

Body 3

Body 3

```
```


Question:
I have a project that I have been working on for a while, just one of those little pet projects that I would like to one day release to open source.

Now I started the project about 12 months ago but I was only working on it lightly, I have just started to concentrate a lot more of my time on it(almost every night).

Because it is a framework like application I sometimes struggle with a sense of direction due to the fact I don't have anything driving my design decisions and I sometimes end up making features that are hard to use or even find.  I have been reading about how to do TDD and thought maybe this will help me with some of the problems that I am having.

So the question is do you think it's a good idea to start using TDD on a project that doesn't already use it.

EDIT: I have just added a bit to clarify what I mean by struggle with a "sense of direction", it properly wasn't the best thing to say without clarification.

Answer:
In my opinion, it's never too late to adopt a better practice - or to drop a worse one - so I'd say "Yes, you should start".
However ... (there's always a "but") ...
... one of the biggest gains of TDD is that it impacts on your design, encouraging you to keep reponsibilties separate, interactions clean and so on.
At this point in your project, you may find it difficult to get tests written for some aspects of your framework. Don't give up though, even if you can't test some areas, your quality will be the better for the areas you can test, and your skills will improve for the experience.


Question:
I have a JSF form that needs to upload a file via an icon click (i.e. without showing the textfield/browse button of the file upload component).

Is it possible to trigger the file-open dialog and uploading functionality of the upload component via some other component type?

Answer:
In my opinion, it's never too late to adopt a better practice - or to drop a worse one - so I'd say "Yes, you should start".
However ... (there's always a "but") ...
... one of the biggest gains of TDD is that it impacts on your design, encouraging you to keep reponsibilties separate, interactions clean and so on.
At this point in your project, you may find it difficult to get tests written for some aspects of your framework. Don't give up though, even if you can't test some areas, your quality will be the better for the areas you can test, and your skills will improve for the experience.


Question:
I have a winforms app and i want to keep track of every time a user clicks certain buttons, etc as well as other actions.  What is the best way for me to keep track of this information and then put it together so i can run metrics on most used features, etc.

This is a winforms app and I have users around the world.

Answer:
I'd try something like this:
```
```
// execute this method once all forms have been created
    public static void HookButtons()
    {
         foreach( Form f in Application.OpenForms )
         {
              EnumerateControls( f.Controls );
         }
    }

    public static void EnumerateControls( ICollection controls )
    {
        foreach( Control ctrl in controls )
        {
            if( ctrl.Controls.Count > 0 )
            {
                EnumerateControls( ctrl.Controls );
            }

            if( ctrl is ButtonBase )
            {
                ctrl.MouseClick +=new MouseEventHandler( ctrl_MouseClick );
            }
        }

    }

    static void ctrl_MouseClick( object sender, MouseEventArgs e )
    {
        ButtonBase clicked = ((ButtonBase)sender);

        // do something with the click information here
    }
```
```


Question: Is there an equivalant to Environment.NewLine in DotNet for a Tab character?

Answer:
NewLine is on the Environment class because the new line specification varies between platforms:
It's "\r\n" for non-Unix platforms and "\n" for Unix platforms. However tab is always "\t".


Question: I need to create an empty .mdb file, so that I can then run ADO commands on it (not ADO.NET). Is there a way to create an empty mdb using ADO?

Answer:
Here are some code snippets that work:
```
```
string sADOProvider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";

        ADOX.CatalogClass cat = new ADOX.CatalogClass();

        string sCreate = MainForm.sADOProvider + sFullPath;

        cat.Create(sCreate);

        // The point of this code is to unlock the access file after we
        // create it.   You can tell it is unlocked if the .ldb file disappears.
        System.Runtime.InteropServices.Marshal.ReleaseComObject(cat);
        cat = null;
        GC.Collect();
```
```


Question:
I am working on an application that will be used as an extensible framework for other applications.

One of the fundamental classes is called Node, and Nodes have Content. The SQL tables look like this:

TABLE Node ( NodeId int, .... etc )

TABLE NodeContentRelationship ( NodeId int, ContentType string, ContentId int)

It will be up to the developers extending the application to create their own content types.

Clearly this is bad from a relationship-database point of view as it is not possible to add a foreign key relationship to NodeContentRelationship.ContentId, even though it is a foreign key column.

However, the solution is quite simple and powerful so I am reluctant to change it.

What do you think - am I in for a world of pain down the track?

Answer:
Beware the
Inner Platform Effect
.
If you're trying to build an 'extensible framework' which allows developers to store data of different 'content types' and relate them to each other in a generic fashion, you may find that others have already
solved
this
problem
.


Question: As prescribed by Yahoo!, gzip'ng files would make your websites load faster. The problem? I don't know how :p

Answer:
http://www.webcodingtech.com/php/gzip-compression.php
Or if you have Apache, try
http://www.askapache.com/htaccess/apache-speed-compression.html
Some hosting services have an option in the control panel.  It's not always possible, though, so if you're having difficulty, post back with more details about your platform.


Question:
I'm dealing with an Oracle DBA at the moment, who has sent me some profiling he's done. One of the terms in his report is 'Buffer Gets', any idea what this actually means? My guess is bytes retrieved from a buffer, but I have no idea really. Here is some sample output:

  Buffer Gets    Executions  Gets per Exec  %Total Time (s)  Time (s) Hash Value
--------------- ------------ -------------- ------ -------- --------- ----------
    137,948,100       31,495        4,380.0   98.4  6980.57   6873.46 4212400674
Module: JDBC Thin Client
SELECT fieldOne, fieldTwo, fieldThree, fieldFour, fieldFive FROM TableExample
WHERE fieldOne = 'example'

It would also be handy to know what 'Gets per Exec' means, as I guess they are related? I'm a programmer, but not a DBA.

Answer:
Oracle storage is arranged into blocks of a given size (e.g. 8k).  Tables and indexes are made up of a series of blocks on the disk.  When these blocks are in memory they occupy a buffer.
When Oracle requires a block it does a
buffer get
.  First it checks to see if it already has the block it needs in memory.  If so, the in-memory version is used.  If it does not have the block in memory then it will read it from disk into memory.
So a buffer get represents the number of times Oracle had to access a block.  The reads could have been satisfied either from memory (the buffers) or have resulted in a physical IO.
Since physical IO is so expensive (compared to memory or CPU) one approach to tuning is to concentrate on reduction in buffer gets which is assumed will flow on to reduce physical IO.


Question:
In the application that I am working on, the logging facility makes use of sprintf to format the text that gets written to file. So, something like:

char buffer[512];
sprintf(buffer, ... );

This sometimes causes problems when the message that gets sent in becomes too big for the manually allocated buffer.

Is there a way to get sprintf behaviour without having to manually allocate memory like this?

EDIT: while sprintf is a C operation, I'm looking for C++ type solutions (if there are any!) for me to get this sort of behaviour...

Answer:
"the logging facility makes use of sprintf to format the text that gets written to file"
```
fprintf()
```
does not impose any size limit. If you can write the text directly to file, do so!
I assume there is some intermediate processing step, however. If you know how much space you need, you can use
```
malloc()
```
to allocate that much space.
One technique at times like these is to allocate a reasonable-size buffer (that will be large enough 99% of the time) and if it's not big enough, break the data into chunks that you process one by one.


Question:
When using call_user_func_array() I want to pass a parameter by reference.  How would I do this.  For example

function toBeCalled( &$parameter ) {
    //...Do Something...
}

$changingVar = 'passThis';
$parameters = array( $changingVar );
call_user_func_array( 'toBeCalled', $parameters );

Answer:
To pass by reference using
```
call_user_func_array()
```
, the parameter in the array must be a reference - it does not depend on the function definition whether or not it is passed by reference.  For example, this would work:
```
```
function toBeCalled( &$parameter ) {
    //...Do Something...
}

$changingVar = 'passThis';
$parameters = array( &$changingVar );
call_user_func_array( 'toBeCalled', $parameters );
```
```
See the notes on the
```
call_user_func_array()
```
function documentation
for more information.


Question:
Using google's Protocul Buffers, I have a service already written in Java which has its own data structures already. I'd like to use pb to delivering messages and I'm looking for a way to serialize the existing data structures that I have in Java to pb.
I can start by defining all the data structures in pb from scratch, which is probably the right way to go but I'm too lazy.
So, say I have a Person class in Java (or other supported languages) or a Plane class which has tens of attributes in it, is there a way to serialize that class to pb? Can I have a pb attribute of type Plane? (when Plane is not a pb, it's a Java class)

Answer:
No, you can't. Fields in protobuf messages are always the primitives (numbers, strings and byte arrays, basically), protobuf enums (which are generated as Java enums) or protobuf messages - and repeated versions of all of those, of course.
You could potentially write a tool which used reflection to create a .proto file from a Java class, but I suspect you'd find it quicker just to do it by hand. In particular, if you
did
use reflection you'd want to make sure that the fields were always generated with the same name, to maintain compatibility. One thing you
could
do is annotate the Java classes and write code to generate the .proto file based on those annotations - or even potentially serialize directly to proto format using the annotations. Personally I'd recommend creating the .proto file in
some
way rather than effectively rewriting the PB project - otherwise there's a significant risk of introducing bugs where there's already thoroughly tested code.
If you
do
create an annotation system, I'm sure Kenton Varda (and the rest of the PB community) would be interested in seeing it.


Question:
I have a very tricky situation (for my standards) in hand. I have a script that needs to read a script variable name from ConfigParser. For example, I need to read

self.post.id

from a .cfg file and use it as a variable in the script. How do I achieve this?

I suppose I was unclear in my query. The .cfg file looks something like:

[head]
test: me
some variable : self.post.id

This self.post.id is to be replaced at the run time, taking values from the script.

Answer:
test.ini:
```
```
[head]
var: self.post.id
```
```
python:
```
```
import ConfigParser

class Test:
  def __init__(self):
      self.post = TestPost(5)
  def getPost(self):
      config = ConfigParser.ConfigParser()
      config.read('/path/to/test.ini')
      newvar = config.get('head', 'var')
      print eval(newvar)

class TestPost:
  def __init__(self, id):
      self.id = id

test = Test()
test.getPost()   # prints 5
```
```


Question: I have a sharepoint event handler which I want to activate for a single list, not all the lists in the site. How do I go about this?

Answer:
Just that list or that list in each site ?
I have been testing the code that run when the event happens and I have used a
nice little tool
from u2u, which allows me to add or remove event handlers per list.
This MSDN article
is a nice primer.


Question:
How do I convert a string to the variable name in Python?

For example, if the program contains a object named self.post that contains a variable named, I want to do something like:

somefunction("self.post.id") = |Value of self.post.id|

Answer:
As referenced in Stack Overflow question
Inplace substitution from ConfigParser
, you're looking for
```
eval()
```
:
```
```
print eval('self.post.id') # Prints the value of self.post.id
```
```


Question:
I am a COM object written in ATL that is used from a C++ application, and I want to pass an array of BYTEs between the two.  My experience of COM/IDL so far is limited to passing simple types (BSTRs, LONGs, etc.).

Is there a relatively easy way to have the COM object pass an array to the caller?  For example, I want to pass a raw image (TIFF) instead of messing with temporary files.

Answer:
Check out using
safearrays
. Here's some example code:
The safearray is returned as a pointer to a VARIANT
```
```
[id(1), helpstring("LogCache")] HRESULT LogCache([out,retval] VARIANT* logCache);
```
```
Safearrays are pretty easy to use. Here's some example code which is a cache of the latest 1000 log messages of some application:
```
```
safearray_t<bstr_t> m_logCache;
   ...
   if (m_logCache.size() > 1000)
   {
       m_logCache.pop_back();
   }

   m_logCache.push_front(Msg.str(), 0);

    variant_t LogCache()
    {
        if (!m_logCache.is_empty())
        {
            variant_t cache(m_logCache);
            return cache;
        }
    }
```
```
Note that the syntax in your case is almost certainly going to be different since I'm using the
comet COM library
, but the ideas/concepts are the same.


Question:
When we write in a Javascript expression :

expression < <%=variableJsp%>

the double "<" seems to be a problem and the JSP is not interpreted ?

Is it a fault of the other servers that should not accept this type of expression ? Or WebSphere that bugs ?

Answer:
I find it generally a bad idea to inline javascript on jsp pages.Your problem is only one of the reasons to make javascript functions external.
Although I do not know websphere, this has happened to me on other containers.
If you insist on keeping it inline, you can probably use
```
```
expression < <%=variableJsp%>
```
```


Question:
Is there a way to specify the font size for a class to be, say, 70% of the inherited font size?

I have a general "button" class that sets up my buttons with the appropriate borders, background, etc. I use it in multiple places, including one where the font size is fairly small and another where the font size is quite large.

<div style="font-size: 26px;">
Push this: <input class="button" type="submit" value="Go">
</div>
<div style="font-size: 10px;">
Push this too: <input class="button" type="submit" value="Go">
</div>

In both instances I'd like the button font-size to be about 70% of the font size of the span or div the button is in.

Can I do this with pure CSS?

Answer:
Try:
```
```
font-size: 0.7em;
```
```
Here's some more information:
How to Size Text in CSS
at A List Apart


Question: The ListChanged event for an IBindingList fires a type ListChangedType.ItemDeleted when items are deleted, perhaps by a user deleting a row in a datagrid control bound to the list. The problem is that the NewIndex into the list is invalid in this event, it's been deleted, and the item that was deleted is not available. There should be an ItemDeleting event, but I doubt they will ever fix this.

Answer:
It's not really intended for that purpose.
```
NewIndex
```
is the index where the item was when it was deleted, and it's useful for bound controls to be able to locate their associated display item in their own lists and remove that.
What is the use case you want to enable with an
```
ItemDeleting
```
?


Question: I have a movie which is made up of a series of SWF files that read XML. Is there any way to burn it to a CD/DVD or at least convert it to a 'burnable' format such as AVI, MPEG, or ISO? Currently in order to burn it I have to so some funky screen capture stuff and recorded it to a DVD that way.

Answer:
Flash CS3 has a nifty way to export any swf (including those that use scripts) to video, but for some reason this is only available when exporting to .mov
Open up your animation in Flash, if you don't have a .fla available making a simple wrapper that loads your swf should work too. Then go File -> Export -> Export movie, and choose Quicktime. Set the various fiddly bits to your liking, and then Flash will step through your animation as fast as it can, saving you both the risk of dropped frames and having to wait for a 1 fps capture.


Question: In C#, what makes a field different from a property, and when should a field be used instead of a property?

Answer:
Properties expose fields.  Fields should (almost always) be kept private to a class and accessed via get and set properties.  Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.
```
```
public class MyClass
{
    // this is a field.  It is private to your class and stores the actual data.
    private string _myField;

    // this is a property. When accessed it uses the underlying field,
    // but only exposes the contract, which will not be affected by the underlying field
    public string MyProperty
    {
        get
        {
            return _myField;
        }
        set
        {
            _myField = value;
        }
    }

    // This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
    // used to generate a private field for you
    public int AnotherProperty { get; set; }
}
```
```
@Kent points out that Properties are not required to encapsulate fields, they could do a calculation on other fields, or serve other purposes.
@GSS points out that you can also do other logic, such as validation, when a property is accessed, another useful feature.


Question:
I have a method in an interface that I want to deprecate with portable C++.
When I Googled for this all I got was a Microsoft specific solution; #pragma deprecated and __declspec(deprecated).

A second prize solution would be to ifdef a MSVC and a GCC solution.

Answer:
In GCC you can declare your function with the attribute deprecated like this:
```
```
void myfunc() __attribute__ ((deprecated));
```
```
This will trigger a compile-time warning when that function is used in a .c file.
You can find more info under "Diagnostic pragmas" at
http://gcc.gnu.org/onlinedocs/gcc/Pragmas.html


Question:
I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.

I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like "_-.() ". What's the most elegant solution?

The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.

Answer:
This whitelist approach (ie, allowing only the chars present in valid_chars) will work if there aren't limits on the formatting of the files or combination of valid chars that are illegal (like ".."), for example, what you say would allow a filename named " . txt" which I think is not valid on Windows. As this is the most simple approach I'd try to remove whitespace from the valid_chars and prepend a known valid string in case of error, any other approach will have to know about what is allowed where to cope with
Windows file naming limitations
and thus be a lot more complex.
```
```
>>> import string
>>> valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
>>> valid_chars
'-_.() abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
>>> filename = "This Is a (valid) - filename%$&$ .txt"
>>> ''.join(c for c in filename if c in valid_chars)
'This Is a (valid) - filename .txt'
```
```


Question:
I have 3 projects in my solution that I want to deploy. Is there a nice and quick way of using Visual Studio's setup projects to deploy all three apps using one MSI and letting the user decide which apps he wants to install during the install process?

I have setup projects for the 3 individual apps, I also have an overarching setup project that has the output of those other three projects. Am I on the right track or is there a better way?

Answer:
I think you probably want merge modules. Accrding to MSDN:
A merge module is a standard feature of Microsoft Windows Installer that packages components together with any related files, resources, registry entries, and setup logic. You can use merge modules to install components that multiple applications share. You cannot install merge modules directly. You must merge them into deployment projects.
http://support.microsoft.com/kb/827025
In your case, each application would be a merge module and you would need to provide some UI to select which applications you would like to install. You could modify one of the default page templates to do that.


Question:
If you try to launch a .NET 3.5 application on a Windows computer which does not have this version of the .NET framework installed, you get a FileNotFoundException for some system assemblies (for example System.Core 3.5.0.0).

Is it possible to catch this exception and tell the user to upgrade their .NET framework or is it thrown too early to handle it?

Answer:
The simplest thing would just be to try it. (I don't have any non-3.5 machines to test it on, but I assume you do.)
Make your entry point a very simple one which just tries to load
```
System.Core.dll
```
and handles the exception appropriately. If it passes, move on to another class which can then use it. If it fails, give the appropriate error message and exit.
I
suspect
you don't need to have quite this level of isolation - so long as you don't have any fields which are of unavailable types, I wouldn't expect the assembly to be resolved until you first call a method which needs it. I'd have to consult CLR via C# to check. However, keeping it quite isolated would probably be safer - it avoids you accidentally introducing dependencies later. Heck, you could even have your "boot and check" type in a separate assembly which did nothing but launch another one if everything's okay.


Question:
A program written in Visual C/C++ 2005/2008 might not compile with another compiler such as GNU C/C++ or vice-versa. For example when trying to reuse code, which uses windows.h, written for a particular compiler with another, what are the differences to be aware of?

Is there any information about how to produce code which is compatible with either one compiler or another e.g. with either GC/C++ or MSVC/C++? What problems will attempting to do this cause?

What about other compilers, such as LCC and Digital Mars?

Answer:
Well this is a quite difficult question. Fact is that MSVC does not support the newest
C standard, about it's c++ compliance I can tell you anyything. Howerver "windows" C is understand by both MSVC and gcc you just can not hope for the other way. E.g if you use ANSI C99 features then you might have a hard time "porting" from gcc to MSVC.
But as  long as you try the way MSVC-> gcc you chances will be better. The only point you have to be aware of is the libraries. Most of the libraries on Windows are supposed to work with MSVC and so you need some extra tools to make them accessible to gcc also.
LCC is a quite older system,which AFAIKT does not support much from ANSI C99, it also needs tools from MSVC to work properly. LCC is "just " a compiler.
lcc-win32 is a C Development system striving to be ANSI C99 compliant. It comes along with linker,  IDE etc.
I can not tell about the state of Digital Mars implementation
Then there is also Pelles-C which is a fully fledged IDE also.
And we have hanging around OpenWatcom. Which once was quite a decent system but I can't tell how conformant it is.
All in all the "best" you can hope  for the easier way from MSVC -> other system but it will probably be much worse the other way round.
Regards
Friedrich


Question:
The problem is simple:

Using bash, I want to add a directory to my PYTHONPATH for ease of script execution. Unfortunately, the directory I want to use has a : in it. So I try each of the following

export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com:3344/
export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com\:3344/
export PYTHONPATH=${PYTHONPATH}:"/home/shane/mywebsite.com:3344/"

None of these work. Every time, the path is created as two separate directories on the path in python.
My question is, is it possible to do this for bash?
If so, what's the syntax required?

Answer:
There is only one you didn't try:
```
```
export PYTHONPATH=${PYTHONPATH}:"/home/shane/mywebsite.com\:3344/"
```
```
The problem is without the quotes, the escaping is interpreted directly, and converted into a literal ":" in the string.  But the ":" needs to be evaluated later.
```
```
$ echo "foo:"
foo:
$ echo \:foo
:foo
$ echo ":foo"
:foo
$ echo "\:foo"
\:foo
```
```
I can't guarantee this will fix your python-path problem, but it will get the \ literal into the string.


Question:
I have tried, 'PreviousPage', 'PreviousPage.IsCrossPagePostBack' 'Page.previousPage', page.title

It causes the client to stop rendering the page after this line.

simple example

protected void Page_Load(object sender, EventArgs e)
{
response.write("I can see this");
string test = PreviousPage.IsCrossPagePostBack.toString(); //Any page call Causes client rendering to freeze
response.write("But i cant see this");
System.Windows.Forms.MessageBox.Show("However i can see this,proving that the server is still running the code");
}

Anybody Please, any ideas?

Answer:
Have you checked PreviousPage for null?
From
msdn
:
The PreviousPage property is a null
  reference (Nothing in Visual Basic)
  when the user requests that page
  directly from the server.
Also -
```
MessageBox
```
in a web form,
not
a great idea... perhaps use the inbuilt
trace.axd


Question:
I'm talking about this:

If we have the letter 'A' which is 77 in decimal and 4D in Hex.
I am looking for the fastest way to get D.

I thought about two ways:

Given x is a byte.

x << 4; x >> 4

x %= 16

Any other ways? Which one is faster?

Answer:
Single AND operation can do it.
```
```
x = (x & 0x0F);
```
```


Question:
Are SQL Server timeouts (SELECT queries, in particular) logged in the ERRORLOG file?

Background is a customer with a web site having occasional "Request timeout" messages, looking to me assuming that the timeout is caused by a database timeout.  There are no timeout errors in the ERRORLOG in question.

Answer:
No. You will need to use SQL Profiler. A standard trace with the
Lock Timeout
event and
Deadlock Graph
events should do it.
Lock:Timeout Event Class
Deadlock Graph Event Class
Hardware aside (such as enough RAM and fast drives, and appropriate placement of Data and Log files on the appropriate RAID configurations) most timeouts are caused by not having a sufficently 'good' set of indexes for your workload.
Do you have index maintenance plans scheduled regularly?


Question:
Is this the best way to handle file moving in a windows service? we have many files that get matched and moved, but an end user may have the file opened at the time of moving.

This is what the code currently says:

Do While IO.File.Exists(OriginalFilePath)

    Try
        IO.File.Move(OriginalFilePath, BestMatchPath)
    Catch ex As IO.IOException
        Log(TraceLevel.Warning, "The file '{0}' was unable to be moved (probably opened by someone)", OriginalFilePath)
        Threading.Thread.Sleep(1000)
    End Try

Loop

Is there a better way to manage this? I have thought of threading it to allow the process to continue, but currently i am unsure if this is viable, as the rest of the process might need the files path to be accurate.

Answer:
No. You will need to use SQL Profiler. A standard trace with the
Lock Timeout
event and
Deadlock Graph
events should do it.
Lock:Timeout Event Class
Deadlock Graph Event Class
Hardware aside (such as enough RAM and fast drives, and appropriate placement of Data and Log files on the appropriate RAID configurations) most timeouts are caused by not having a sufficently 'good' set of indexes for your workload.
Do you have index maintenance plans scheduled regularly?


Question:
When I launch an ant script from Eclipse 3.4.x it prints the output to console until certain stage. After that it often hangs (wait forever). Last lines that I see at the screen (console) - partial output from my obfuscator.

Under Eclipse 3.3.2 everything works fine (the same project, workspace, settings, JVM etc.).

Does anybody have the same issue? Any thoughts how to fix it?

Answer:
One possible cause is that you are
running out of memory
Also try to run ant with the
```
-diagnostics
```
option.
You can check your
memory usage
and your
eclipse.ini
.
Another classic culprit is a
blocking access to a locked resource
(like an access to a file already being used by another process): try to close a many applications you can and relaunch ant.


Question:
I have this java code:

<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.2.6");

$("a#more").click(function() {

$("#info_box").show("blind", { direction: "vertical" }, 800);

});
</script>

And this link:

<a href="#" id="more">More Info...</a>

info_box is just a div with the properties:

width: 30%;
position: absolute;
left: 35%;
top: 250px;
background-color: #FFFFFF;
border: 2px solid #000000;
visibility: hidden;

How can this not be working, been trying to figure it out for 20 minutes.

Answer:
Are you sure you're calling the right function? According to the docs at
http://docs.jquery.com/Effects/show
the show function takes a speed as the first parameter, and a callback function as the second. Your
```
"blind"
```
and
```
{ direction: "vertical" }
```
are misplaced I think.
Also worth checking there's no conflict with another script e.g. mootools.


Question: Is there any way to find out if the user pressed the delete key or dot? It has the same keycode in FireFox.

Answer:
According to
Detecting keystrokes
, it is possible, provided that:
you search for the keyCode (
8
for delete) onkeydown/up, and
ignore both onkeypress and charCode (Especially if you consider the fact that IE does not fire keypressed event, only key up/down).


Question:
If you put up an NSAlert while your app is in the background your dock icon starts bouncing and keeps on bouncing until you switch back.

I find this annoying.

Does anyone know how disable that for a single app?

Answer:
Not that I'd recommend it, but there is a Haxie that may help:
Dock Detox
.
They allow you to intercept the bouncing and do other stuff, I think.
A quick google showed up:
```
```
- (void)cancelUserAttentionRequest:(int)request
```
```
But I really don't know if this will work for your purposes.


Question:
i'm currently experimenting using PixelShaders introduced with .net 3.5 sp1 to improve image processing performance. everything is much faster , but til yet i just had effects applied to some elements in my wpf forms, that i actually want to avoid.

we have a bunch of image processing functionality and i'd like to replace some othe the stuff piece by piece with pixel shaders to gain some performance.
is there a way to apply such a pixel shader to an ImageSource without having to display it?

Answer:
What is generally done in C++ / DirectX to achive this is:
Preparation (done once)
Create render target using CreateRenderTarget
Create off-screen surface using CreateOffscreenPlainSurface
Set render target surface using SetRenderTarget
Create any other input resources needed (Textures, Vertex Buffers ...)
Rendering (done multiple times)
Update input resources (textures, buffers) as needed
Render
Copy the contents of the render target into the off-screen surface via GetRenderTarget
Lock the off-screen surface and read its content on the CPU


Question:
I want to save a set of email addresses collected from a text field (separated by commas) into a single field in a table. I am trying to use serialize but I'm getting SerializationTypeMismatch error. How can I do this?

This is my model:

class Crew < ActiveRecord::Base

class Recipients < HashWithIndifferentAccess ; end

serialize :recipients, Recipients

end

Answer:
I would really reccomend that you parse (e.g. split on comma) the email list and put each in a row in a separate table (I assume you're talkin about a database table?). If you want to use the email addresses for something it's better to store them individually, and since you're talking about serialization I guess you've allready parsed the emails, and try to store an array or similar into a single field in a database. The "correct" normalized database way of doing this is to in your model wich you're currently trying to save the object, add a
```
has_many :emails
```
(or similar) and creat a new email table for each email.
One should allways have a very
good reason
for storing list type data in a blob, instead of using a proper associated table.


Question:
Many times I use 'mqsc' for create MQ queue manager from script files but I don't know how to generate script files.

Thanks

Answer:
There is a SupportPac that installs a program called "saveqmgr.exe".
Here's a link to the download of the Pac:
http://shrinkster.com/17kc
IBM seems to frequently reorganize its website, so the above link might not work if you check back here after a long while, but the SupportPac can be found easily by doing a search for "saveqmgr" on the Websphere MQ page.  Hope this helps!
IBM has this to say about the SupportPac:
Abstract
This SupportPac (saveqmgr) saves all the objects, such
  as queues, channels, etc, defined in a
  either local or remote queue manager
  to a file.
Download Description
This SupportPac interrogates the attributes
  of all the objects defined to a queue
  manager (either local or remote) and
  saves them to a file.
Possible Uses
The format of this file is suitable for use with runmqsc.
  It is therefore possible to use this
  SupportPac to save the definitions of
  objects known to a queue manager and
  subsequently recreate that queue
  manager.


Question:
I have a .net winforms app which has a few animation effects, fade ins and scroll animations etc.  These work fine however if I'm in a Remote Desktop Protocol session the animations start to grate.

Can someone suggest a way of determining whether or not an app is running across an RDP session so I can turn the effects off in this case?

Answer:
Use the
GetSystemMetrics()
function in the user32.dll.  Use
PInvoke
to call it.  The following is sample code provided by the first link.  The second link tells you how to invoke it in .NET.
```
```
BOOL IsRemoteSession(void){
      return GetSystemMetrics( SM_REMOTESESSION );
   }
```
```
Complete code:
```
```
[DllImport("User32.dll")]
static extern Boolean IsRemoteSession()
{
 return GetSystemMetrics ( SM_REMOTESESSION);
}
```
```
There's also the
```
SystemInformation.TerminalServerSession
```
Property, which determines whether or not the client is connected to a Terminal Server session.  The
code provided
by MSDN is extensive, so I won't duplicate it here.


Question:
I'm trying to find an editor (or some simple JavaScript - preferably jQuery) that will allow me to edit the contents of a textarea.

I don't want it to be rich text or WYSIWYG; I just want to be able to select a bit of text, click a button/link and have some simple HTML tags that I define put either side of the highlighted text. I also want to be able to insert empty tags at the cursor if no text is selected in the textarea. Essentially, what I'm looking for is similar to the Stack Overflow text editor, but for custom HTML, not Markdown.

What options are there that I could use?

Thanks in advance.

Answer:
Would something like
this
fit the bill? I think it just uses
```
document.selection
```
to identify where to insert the markup.


Question:
I've got a message contained in an byte[], encrypted with "RSA/ECB/PKCS1Padding". To decrypt it I create a Cipher c and initiate it with

c = Cipher.getInstance("RSA/ECB/PKCS1Padding");

Untill now I have only decrypted small messages, using the doFinal() method, returning an byte[] with the decrypted bytes.

c.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptetBytes = c.doFinal(encryptedBytes);

But in this case the data is bigger (approx 500 Bytes), and the doFinal()-method throws an exception (javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes). I guess I need to use the update()- method, but I can't figure out how to get it to work properly. How is this done?

Answer:
With RSA you can only encrypt/decrypt block with size up to your key length minus padding length. If you have data longer than your key maybe it is just merged in one array so you should split it into chunks with size of your key (128 bytes suggests 1024 key with no padding, I'm not sure if it's possible). Using update() is not the case here.
Simply, you have to know how this array was created.
Generally speaking, RSA shouldn't be used to encrypt large amount of data as it's quite time consuming. Should be used to encrypt key to symmetric cipher, like AES.
Take a look here:
https://www.owasp.org/index.php/Digital_Signature_Implementation_in_Java


Question:
I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.

What is the best way to control what urllib.urlopen returns?

Answer:
Probably the best way to handle this is to split up the code, so that logic that processes the page contents is split from the code that fetches the page.
Then pass an instance of the fetcher code into the processing logic, then you can easily replace it with a mock fetcher for the unit test.
e.g.
```
```
class Processor(oject):
    def __init__(self, fetcher):
        self.m_fetcher = fetcher

    def doProcessing(self):
        ## use self.m_fetcher to get page contents

class RealFetcher(object):
    def fetchPage(self, url):
        ## get real contents

class FakeFetcher(object):
    def fetchPage(self, url):
        ## Return whatever fake contents are required for this test
```
```


Question:
A number of business areas I work with use a folder structure to organise their Sharepoint housed documents (not ideal I know, but we're stuck with it).

I would like to use a web part page to present a number of views of their document libraries based on the subfolders that the documents appear in, but this is proving more difficult than I had thought.  Has anyone overcome this problem in the past?

Answer:
What kind of document library information do you want in the view?
How do you want the user to filter the view?
In general the most powerful way of creating views in sharepoint is with the data view web part.
http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx
You will need Microsoft Office SharePoint Designer.
You can present different views of you folders using the data view filter and sorting controls.
You can use web part connections to filter a dataview.
You can use any datasource linked to say a drop down to filter a dataview.
How to tie a dropdown list to a gridview in Sharepoint 2007?


Question:
In Oracle we can print output by dbms_output.put_line() but I don't know to do the same thing in DB2.

I currently use signal for printing some messages when I debug.

Answer:
What kind of document library information do you want in the view?
How do you want the user to filter the view?
In general the most powerful way of creating views in sharepoint is with the data view web part.
http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx
You will need Microsoft Office SharePoint Designer.
You can present different views of you folders using the data view filter and sorting controls.
You can use web part connections to filter a dataview.
You can use any datasource linked to say a drop down to filter a dataview.
How to tie a dropdown list to a gridview in Sharepoint 2007?


Question:
How do I execute the following shell command using the Python subprocess module?

echo "input data" | awk -f script.awk | sort > outfile.txt

The input data will come from a string, so I don't actually need echo.  I've got this far, can anyone explain how I get it to pipe through sort too?

p_awk = subprocess.Popen(["awk","-f","script.awk"],
                          stdin=subprocess.PIPE,
                          stdout=file("outfile.txt", "w"))
p_awk.communicate( "input data" )

UPDATE:  Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place!

Answer:
http://www.python.org/doc/2.5.2/lib/node535.html
covered this pretty well. Is there some part of this you didn't understand?
Your program would be pretty similar, but the second
```
Popen
```
would have stdout= to a file, and you wouldn't need the output of its
```
.communicate()
```
.


Question:
When connecting to a network share for which the current user (in my case, a network enabled service user) has no rights, name and password have to be provided.

I know how to do this with Win32 functions (the WNet* family from mpr.dll), but would like to do it with .Net (2.0) functionality.

What options are available?

Maybe some more information helps:

The use case is a windows service, not an Asp.Net application.

The service is running under an account which has no rights on the share.

The user account needed for the share is not known on the client side.

Client and server are not members of the same domain.

Answer:
You should be looking at adding a line like this:
```
```
<identity impersonate="true" userName="domain\user" password="****" />
```
```
Into your web.config.
More Information.


Question:
What's the best way to do it in .NET?
I always forget what I need to Dispose() (or wrap with using).

EDIT: after a long time using WebRequest, I found out about customizing WebClient. Much better.

Answer:
Here's what I use, it seems to work, but I don't know if it's the best way:
```
```
public string GetRequest(Uri uri, int timeoutMilliseconds)
{
    var request = System.Net.WebRequest.Create(uri);
    request.Timeout = timeoutMilliseconds;
    using (var response = request.GetResponse())
    using (var stream = response.GetResponseStream())
    using (var reader = new System.IO.StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}
```
```


Question:
I need to disable windows-update service from my installation. I already use vbscript to do some stuff so I would like to do it in vbscript.

My knowledge of vbscript (or any other script language) is very limited so...can anybody help me out with that? I'll really appreciate it!

Thanks.

Answer:
If you want to use VBScript, use WMI:
```
```
strComputer = "."  'could be any computer, not just the local one '
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colServiceList = objWMIService.ExecQuery _
("Select * from Win32_Service where Name = 'wuauserv'")

For Each objService in colServiceList
  objService.ChangeStartMode("Disabled")
Next
```
```
Look into
the documentation of the WMI Win32_Service Class
to find out what else might be doable.
Easier would be the use of
```
sc.exe
```
:
```
sc config wuauserv start=auto
```
Here is an excerpt of what
```
sc.exe
```
can do:
```
```
C:\>sc config
Modifies a service entry in the registry and Service Database.
SYNTAX:
sc <server> config [service name] <option1> <option2>...
CONFIG OPTIONS:
NOTE: The option name includes the equal sign.
 type= <own|share|interact|kernel|filesys|rec|adapt>
 start= <boot|system|auto|demand|disabled>
 error= <normal|severe|critical|ignore>
 binPath= <BinaryPathName>
 group= <LoadOrderGroup>
 tag= <yes|no>
 depend= <Dependencies(separated by / (forward slash))>
 obj= <AccountName|ObjectName>
 DisplayName= <display name>
 password= <password>
```
```


Question:
I have a List containing several keywords.
I foreach through them building my linq query with them like so (boiled down to remove the code noise):

List<string> keys = FillKeys()
foreach (string key in keys){
    q = q.Where(c => c.Company.Name.Contains(key));
}

When I now make my keys contain 2 keys that return results seperatly, but can never occure together (every item in q is either "xyz" or "123", never "123" AND "xyz"), I still get results. The resultset is then the same as the last string it got to.

I had a look at the linq query and it appears it creates the correct sql, but it replaces @p1 AND @p2 both by the same (last itterated) value.

What am I doing wrong?

Answer:
You're reusing the same variable (
```
key
```
) in your lambda expression.
See my article on
anonymous methods
for more details, and there are a number of related SO questions too:
LINQ to SQL bug (or very strange feature)...
Local variables with delegates
C# captured variable in a loop
C# gotcha answer
Building a LINQ query programmatically without local variables tricking me
The simple fix is to copy the variable first:
```
```
List<string> keys = FillKeys()
foreach (string key in keys){
    string copy = key;
    q = q.Where(c => c.Company.Name.Contains(copy));
}
```
```


Question:
I'm writing an applicationt hat was prototyped on MySQL and is now connecting to an Oracle database.

All I had to do to connect to the oracle database (having built up the table structure) was change the connection string.

What is the format to connect to a SQL Server DB on another machine?

I've read some tutorials which tell you to use the SQL Server JDBC adaptor but I'd rather configure the application so that it's database agnostic, and just have the connection string specify the protocol etc.

Any references I've seen which tell you how to use the bridge with SQL Server require the ODBC Data Source to be installed, this is less than ideal as my app may run on Linux or windows.

I'm not doing anything complicated just inserts.

Answer:
You should not use the JDBC-ODBC bridge in a production environment. It is much slower than other JDBC drivers and only necessary when a JDBC driver is not available.
SQL Server has a
JDBC driver
available from Microsoft. If you use it then you will get the required result.
With the ODBC bridge you have no choice but to install the ODBC driver.
This
article
describes the connection string you will need to use to connect to the SQL Server.


Question:
Any ideas on how I can acheive 'Hierarchical' gridview?
Basically I want when the user clicks on the '+', i "expand" and insert new rows without a full page post back.

Does this sound like a lot of AJAX stuff? Or should I read on ASP.NET MVC

Please point me in right direction

Answer:
You have two options I suppose:
You can render out those rows you want to insert, and the [+] shows them and hides them
You don't render them out, and they are sent to the browser via AJAX, and then inserted into the table.
I've done it both ways, and the more gridviewy way to do it is the first, in my opinion.  You can create a new templatefield for the [+]; define a child relationship name, and then  call
GetChildRows
(or an equivalent) on each row as you render, having those rows render hidden.


Question:
Given the following Delphil DLL declaration

function csd_HandleData(aBuf: PChar; aLen: integer): integer; stdcall;

what would be the VB6 declaration to use it?

I've tried a variety of declarations, e.g.

Declare Function csd_HandleData Lib "chsdet.dll" (ByVal aBuf As String, ByVal aLen As Integer)
Declare Function csd_HandleData Lib "chsdet.dll" (aBuf As Long, ByVal aLen As Integer)
Declare Function csd_HandleData Lib "chsdet.dll" (aBuf As Byte, ByVal aLen As Integer)

with the relevant code to suit the parameters, but nothing seems to work, i.e. the Delphi debugger says I have a too-largish value in aLen and a null string in aBuf.

I am working toward using a TypeLib to drive the connection, but was prototyping with Declares.

Answer:
try
```
```
Declare Function csd_HandleData Lib "chsdet.dll" (ByVal aBuf As String,
ByVal aLen As Integer) As Integer
```
```
Seems you forgot the return value.


Question:
I'm writing an application which has to be configurable to connect to Oracle, SQL Server and MySQL depending on client whim.

Up till now I'd been planning on using the JDBC-ODBC bridge and just connecting to the databases using different connection strings.

I'm told this is not very efficient.

Is there a pattern or best practice for connecting to multiple database systems? Or for selecting which driver to use?

Should I have it configurable? but include all three drivers or build three separate clients?

I'm not doing anything complex just pumping (inserting) data into the database from an event stream.

Answer:
If you need anything complex, Hibernate is a good choice.
otherwise, what I would do is store your connection details in a properties file (or some other form of configuration) - namely: driver classname, JDBC url, username and password.
Then, all you need to do is load up the connection details from your properties file and include the correct JAR file on your classpath and you're done.
You could use a library such as Commons-DBCP if you wanted it to be a little easier to configure but other than that it's all you need to do (provided your SQL statements work on every database, of course).


Question:
I am trying to have one one layer, and center images within. I.E., if I have 3 images and want 3 links beneath them, is there a way to do this without using a separate div tag for each link and image? To automatically make the links be centered under the images, and the images to be spaced evenly within a layer?

I was also wondering how I would make the div show behind standard html if that is possible. I.E. if I have some text and a div over the text, the div will default show over the text, when I would like it to be behind. Is this only possible by using another layer?

Answer:
Yes, you'll have to put a container element, such as a div, around each image and its caption to keep them together.
```
```

        caption caption

        more caption

--------
.pictureBox div {
    text-align: center;
    /* whatever width/height/positioning you want */
}
```
```
for the second part of the question, regarding putting it behind the other text, take a look at
CSS z-index
, though I think that only applies to absolutely positioned elements.


Question:
What is and how can it be used in C#.

Can you use the same concept in Python/Perl?

Answer:
A
partial type
(it doesn't have to be a class; structs and interfaces can be partial too) is basically a single type which has its code spread across multiple files.
The main use for this is to allow a code generator (e.g. a Visual Studio designer) to "own" one file, while hand-written code is put in another.
I've no idea whether Python/Perl have the same capabilities, I'm afraid.


Question:
I would like to get the path to the execution directory of a Windows Forms application. (That is, the directory in which the executable is located.)

Does anyone know of a built-in method in .NET to do this?

Answer:
In VB.NET
```
```
Dim directory as String = My.Application.Info.DirectoryPath
```
```
In C#
```
```
string directory = AppDomain.CurrentDomain.BaseDirectory;
```
```


Question:
A game that I play stores all of its data in a .DAT file. There has been some work done by people in examining the file. There are also some existing tools, but I'm not sure about their current state. I think it would be fun to poke around in the data myself, but I've never tried to examine a file, much less anything like this before.

Is there anything I should know about examining a file format for data extraction purposes before I dive headfirst into this?

EDIT: I would like very general tips, as examining file formats seems interesting. I would like to be able to take File X and learn how to approach the problem of learning about it.

Answer:
You'll definitely want a hex editor before you get too far.  It will let you see the raw data as numbers instead of as large empty blocks in whatever font notepad is using (or whatever text editor).
Try opening it in any archive extractors you have (i.e. zip, 7z, rar, gz, tar etc.) to see if it's just a renamed file format (.PK3 is something like that).
Look for headers of known file formats somewhere within the file, which will help you discover where certain parts of the data are stored (i.e. do a search for "IPNG" to find any (uncompressed) png files somewhere within).
If you do find where a certain piece of data is stored, take a note of its location and length, and see if you can find numbers equal to either of those values near the beginning of the file, which usually act as pointers to the actual data.
Some times you just have to guess, or intuit what a certain value means, and if you're wrong, well, keep moving.  There's not much you can do about it.
I have found that
http://www.wotsit.org
is particularly useful for known file type formats, for help finding headers within the .dat file.


Question:
Currently I have two MediaWikis, one a slightly older version than the other.  I want to merge the contents of both together, without eliminating duplicate pages.  So far the best option I can think of is to use a bot (like pywikipedia) to go through all the pages of one wiki, and try inserting them into the other, renaming duplicate pages.

This solution seems like it would take a while to accomplish though.  Is there a more pleasant way to do this that I'm just unaware of? I haven't worked with the MediaWiki database directly very much, so I'm not very comfortable messing with it without knowing what I'm doing.

Answer:
MediaWiki has
import
and
export
features, that you can use for moving the contents. It does merge histories of existing pages (see import link).
However, it does not handle conlicts of two different pages with the same name, so you'll have to handle moving the pages by yourself. As far as I can see in description of MediaWiki
page table
, you might be able to find and rename duplicate pages directly in SQL, but pywikipedia should work too (but you'll need to delete redirects that will result from "correct" page moves, otherwise they'll mess up with imported pages from the other wiki).


Question:
I have a website built in C#.NET that tends to produce a fairly steady stream of SQL timeouts from various user controls and I want to easily pop some code in to catch all unhandled exceptions and send them to something that can log them and display a friendly message to the user.

How do I, through minimal effort, catch all unhandled exceptions?

this question seems to say it's impossible, but that doesn't make sense to me (and it's about .NET 1.1 in windows apps):

Answer:
Do you mean handling it in all threads, including ones created by third-party code? Within "known" threads just catch
```
Exception
```
at the top of the stack.


Question: I am trying to write an installer (by creating a .vdproj) that will work on both Windows Vista and XP.  The only thing I am finding is that when I try to run it on Vista, the files that I include in the installer are installed with Read-only permissions for the Users groups.  This is a problem because the application needs to read/write from these files.  The only way I have been able to get it to work is to either "Run as Administrator" or actually change the permissions.  Does anyone know how to make these files be open to anyone to write?  Thanks.

Answer:
The Program Files folder and it's contents are read only for standard users.  This is by design, and you'll find that
this is the case on Windows XP as well.
It's just that on windows xp, so many people run with administrator rights all the time that you might get away with it.  If you ever want to distribute your app into a business environment, you'll soon find that   it won't work on XP there, either.
The solution is to NOT place files in the program's executable folder if standard users will need write access.  Put them in the Application Data folder instead.  For most xp machines, that will be here:
C:\Documents And Settings\All Users\Application Data\Your App
However, that won't always be the case and it's a little different on Vista anyway, so make sure you get that path via the mechanism provided by your programming environment.  In .Net, you can use the
```
Environment.GetFolderPath()
```
function.


Question:
The XML file I want to parse starts with  :

<!DOCTYPE plist PUBLIC "-//...//DTD PLIST 1.0//EN" "http://www.....dtd">

So when I start the SAX praser, it tries to access this DTD online, and I get a java.net.UnknownHostException.

I cannot modify the XML file before feeding it to the SAX parser

I have to run even with no internet connection

How can I change the SAX Parser behaviour so that it does not try to load the DTD ?
Thanks.

javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
factory.setValidating(false);

javax.xml.parsers.SAXParser parser = factory.newSAXParser();
parser.parse(xmlFile, handler);

Answer:
You can implement a custom
```
EntityResolver
```
which is what is used to lookup external entities during XML parsing.
```
```
org.xml.sax.EntityResolver customEntityResolver = new DummyEntityResolver();
javax.xml.parsers.SAXParser parser = factory.newSAXParser();
parser.getXMLReader().setEntityResolver(customEntityResolver);
parser.parse(xmlFile, handler);
```
```
And in your custom EntityResolver, just always return null. I think that should fix this problem.


Question:
I get the message that the namespace can't be found when I use the code below. Where does the AccessDeniedException live?

try { ... }
catch (SomeKindOfException ex)
{
MessageBox.Show(ex.Message);
}
catch (AccessDeniedException ex)
{
//Do something else
}

Thanks

Answer:
I don't think that's the exception you're looking for.  The only one with this name (that I can find) is in a Sharepoint namespace.  Try attaching the debugger and seeing exactly what the type of the thrown exception is.
The type of the exception is going to vary depending on your context.  So for example, if it's an "access denied" when trying to open a file, it could be a FileLoadException, or something similar.  If it's encountered because of Code Access Security,  it will be SecurityException.  And so on.


Question: We have very strange problem, one of our applications is continually querying server by using .net remoting, and every 100 seconds the application stops querying for a short duration and then resumes the operation. The problem is on a client and not on the server because applications actually queries several servers in the same time and stops receiving data from all of them in the same time.

Answer:
100 Seconds is a give away number as it's the default timeout for a webrequest in .Net.
I've seen in the past that the PSI (Project Server Interface within Microsoft Project) didn't override the timeout and so the default of 100 seconds was applied and would terminate anything talking to it for longer than that time.
Do you have access to all of the code and are you sure you have set timeouts where applicable so that any defaults are not being applied unbeknownst to you?


Question:
I'm sure there is a quick and easy way to calculate the sum of a column of values on Unix systems (using something like awk or xargs perhaps), but writing a shell script to parse the rows line by line is the only thing that comes to mind at the moment.

For example, what's the simplest way to modify the command below to compute and display the total for the SEGSZ column (70300)?

ipcs -mb | head -6
IPC status from /dev/kmem as of Mon Nov 17 08:58:17 2008
T         ID     KEY        MODE        OWNER     GROUP      SEGSZ
Shared Memory:
m          0 0x411c322e --rw-rw-rw-      root      root        348
m          1 0x4e0c0002 --rw-rw-rw-      root      root      61760
m          2 0x412013f5 --rw-rw-rw-      root      root       8192

Answer:
You could start by running the data through
```
cut
```
- which would at least trim the columns down.
You should then be able to pipe that into
```
grep
```
, stripping-out non-numerics.
Then ... well, then I'm not sure. It might be possible to pipe that to
```
bc
```
. If not, it could certainly be handed to a shell script to add each item.
If you used
```
tr
```
to change the newlines (
```
\n
```
) to spaces (
```
```
), and piped that through xargs into your script that loops until there are no more inputs, adding each one, you may have an answer.
So, something akin to the following:
```
```
cat <whatever> | cut -d'\t` -f7 | grep -v <appropriate-character-class> | tr '\n' ' ' | xargs script-that-adds-arguments
```
```
I may have the
```
cut
```
flags slightly wrong - but
```
man
```
is your friend :)


Question:
I have a .jar file that i've placed in my D:\Coldfusion8\wwwroot\web-inf\lib\ directory.  The file is abcdef.jar

This is my first time doing this, not sure what the path should be in my createObject().

<cfset abcObj = createObject("java","com.abcdef") />
<cfset result = acbObj.doStuff("123456") />

But when I run it, I get

Object Instantiation Exception.
Class not found: com.vp4jo_b

What am I missing in the path?

Answer:
Have you restarted the Coldfusion Service?
Even when in the class path, jars are only loaded at server start.
Info moved up from the comments:
Make sure the file is in the System class path, or in the one of the configured class paths of ColdFusion.
As for the class name parameter of
```
CreateObject()
```
: The class name starts within the jar. Open it like a .zip file and look at its structure. The dotted path mimics the folder structure, so if the Server still complains, you must be missing something in the dotted path.


Question:
Consider the following code in VB9:

Dim text = "Line1<br/>Line2"
Dim markup = <span><%= text %></span>.ToString

While I was hoping markup would end up being <span>Line1<br/>Line2</span>, it actually evaluates to <span>Line1&lt;br/&gt;Line2</span>.

Is there any way to get the value of the variable not to be HTML encoded?

P.S.: This is an oversimplified example of what I'm trying to do. I know this could be rewritten a number of ways to make it work, but the way my code is constructed, un-encoding the variable would be optimal. If that's not possible, then I'll go down a different road.

More detail: The "text" is coming from a database, where a user can enter free-form text, with carriage returns. The output is HTML, so somehow I need to get the value from the database and convert the carriage returns to line breaks.

Answer:
This behavior is "By Design."  When embedding a string expression inside an XML literal the value will be escaped to be a legal string value.
To get the behavior you are looking for you'll need to be embedding an XElement/XNode within an XML literal.  Take the following example.  It will correctly keep the
```
<br/>
```
tag as an XElement.
```
```
Dim text2 = Line
Line
Dim markup2 = <%= text2 %>.ToString
```
```
One way to achieve this is to fake an XElement.  To make the text a valid string, simply wrap it on both ends with a normal tag,
```
<a>
```
for example.  This is now a parsable XML fragment.  Once you have an XElement, it's easy to get the embedded behavior you are looking for
```
```
Dim text = "Line1
Line2"
Dim text2 = XElement.Parse("" + text + "")
Dim markup = <%= text2.Nodes %>.ToString
```
```


Question:
Could someone explain why this works in C#.NET 2.0:

    Nullable<DateTime> foo;
    if (true)
        foo = null;
    else
        foo = new DateTime(0);

...but this doesn't:

    Nullable<DateTime> foo;
    foo = true ? null : new DateTime(0);

The latter form gives me an compile error "Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime'."

Not that I can't use the former, but the second style is more consistent with the rest of my code.

Answer:
The compiler is telling you that it doesn't know how convert
```
null
```
into a
```
DateTime
```
.
The solution is simple:
```
```
DateTime? foo;
foo = true ? (DateTime?)null : new DateTime(0);
```
```
Note that
```
Nullable<DateTime>
```
can be written
```
DateTime?
```
which will save you a bunch of typing.


Question:
When using CDT I would like to have std::string show up in the 'variable' debug window with the string it contains. For instance if it is currently holding the word "history" I would like to see history in the debugger window labeled "variables".

I think that there is a general way to have it drill down into objects but I can't put my finger on it. Does anyone out there know how to do this?

This would also be useful for me to use when outputting just a single field from a complex object.

Thanks,
Bill

Answer:
Note that you
don't
want a general way of drilling down into objects; you want to pretty-print STL containers.
I think CDT delegates this to the debugger backend; i.e. it is up to your debugger (gdb, perhaps?) to inform CDT about the value of a variable and how it can be expanded.
Edit: I don't think that the GDB backend shipped with CDT has any support for "intelligent" display of STL containers. If you're really interested in this, I'd suggest that you contact the CDT development team at cdt-dev@eclipse.org.
Update/Edit: Please see other responses below for instructions on how to enable pretty printers in CDT.


Question:
In Perl

print "a" x 3;  # aaa

In C#

Console.WriteLine( ??? )

Answer:
It depends what you need... there is
```
new string('a',3)
```
for example.
For working with strings; you could just loop... not very interesting, but it'll work.
With 3.5, you could use
```
Enumerable.Repeat("a",3)
```
, but this gives you a sequence of strings, not a compound string.
If you are going to use this a lot, you could use a bespoke C# 3.0 extension method:
```
```
static void Main()
    {
        string foo = "foo";
        string bar = foo.Repeat(3);
    }
    // stuff this bit away in some class library somewhere...
    static string Repeat(this string value, int count)
    {
        if (count < 0) throw new ArgumentOutOfRangeException("count");
        if (string.IsNullOrEmpty(value)) return value; // GIGO
        if (count == 0) return "";
        StringBuilder sb = new StringBuilder(value.Length * count);
        for (int i = 0; i < count; i++)
        {
            sb.Append(value);
        }
        return sb.ToString();
    }
```
```


Question:
Being a Windows developer I'm currently working on my own project using LAMP. I understand what I need to know of PHP and MySQL, but Linux looks huge and it's not clear where to start and what is enough given my goals.
And my goals are to grasp general concepts, being able to deploy the project to a hosting provider and to be able to monitor the site's performance in order to spot problems, load issues, etc.

I know, the best solution is to get a Linux administrator to do that, but before I can do that I need to do it myself.

Answer:
You might consider, based on your introduction, a
WAMP
option (Windows Apache MySQL Python, Perl, and PHP).
Learning Linux isn't
hard
, but it's certainly not a short task, either. There're a lot of system administration tasks that carry over platform-to-platform, but the real answer to your question is to become at least a hobbyist Linux administrator, and then go from there.


Question:
We have 50+ Java batch processes that run at different times of the day.  They run on a Solaris box, and are started via cron.  Currently, the only way we only know if they succeed or fail is by an email generated at the end of each batch process.  We have a support team that monitors these emails.  Recently, we've had issues with emails not being received, even though the batches are running.  There must be a better way.

Without having to reinvent the wheel, are there any open source batch monitoring applications?

And a more general question, what is the best way to monitor batch processes?

Answer:
Is there currently some batch management system in-place?  Or are the jobs run through the OS scheduler? (ie, Windows
```
Schedule Tasks
```
or *nix
```
cron
```
)
Quartz
is an Open Source (Apache License) java-based job scheduler that has infrastructure in place for
listeners
that can be used for notification purposes, but there would be some code development involved.


Question:
I can't seem to figure out what I am doing wrong here. I publish my website to my server and when I try to run it I get the following exception:

Could not load the assembly 'App_Web_kh7-x3ka'. Make sure that it is compiled before accessing the page.

Has anyone else ever encountered this?

Answer:
A quick google for "Make sure that it is compiled before accessing the page."
led me to the following
http://www.velocityreviews.com/forums/t301533-could-not-load-assembly-make-sure-that-it-is-compiled-before-accessing-the-page.html
And the problem might be as described that the application pool / website is not set to the correct version of .NET
The following question has another solution as the last reply
http://forums.asp.net/t/1131537.aspx
From the looks up it it would seem your webserver is not properly configured, or that you are refering to a nonexistant/old dll


Question:
How could I setup a nice indice on cap:deploy?

I want the remote server to nice the cp commands like so:

nice -n 19 cp ...

Answer:
Using E4X syntax in ActionScript 3 I guess that would be something like:
```
```
report.prop5[0] = false;
```
```


Question: Is there a way to print out the diffs like they show when you open them with "gvim -d", with all the common code folded away and only the diffs showing in context?  I tried the print menu option, but it printed the entire file that I was currently "in", rather than printing the folded diffs.

Answer:
I dont think theres a way to get a side by side printout of the two files being diffed. But, you could use Vim's "Convert to HTML" tool on each of the two files being diffed and print those out separately. You could then stack them side by side to get the same effect.
Convert to HTML is kind of "pretty printing" - it saves all of the visual colour/syntax/fold  information.
```
```
:he convert-to-HTML
```
```


Question: Does any one know the best way to deploy a resource file to the App_GlobalResource folder of the web application when a feature is activated?

Answer:
Application resource files cannot be deployed via a feature unless you execute some code and start a SharePoint timer job that copies the files to the App_GlobalResources folder on each Web front-end server.
You should instead let the SharePoint solutions framework deploy the .RESX files to the App_GlobalResources folder on each server. You can specify application resource files as follows in the manifest.xml file of your WSP solution package:
```
```
<?xml version="1.0" encoding="utf-8"?>
<Solution SolutionId="{185E973C-3A10-4e2a-9E0F-DC14414551F9}"
          xmlns="http://schemas.microsoft.com/sharepoint/"
          DeploymentServerType="WebFrontEnd">

  <ApplicationResourceFiles>
    <ApplicationResourceFile Location="yourappname.resx"/>
    <ApplicationResourceFile Location="yourappname.en-US.resx"/>
  </ApplicationResourceFiles>

 ...
</Solution>
```
```
When you deploy the WSP solution package using STSADM or Central Administration, the SharePoint solutions framework will start a timer job that deploys these files to the App_GlobalResources folder of all the Web applications you decided to deploy the solution to.


Question:
How can I create a table that has its first row and first column both locked, as in Excel, when you activate 'freeze panes'?  I need the table to both scroll horizontally and vertically (a lot of solutions for this exist, but only allow vertical scrolling).

So, when you scroll down in the table, the first row will stay put, since it will have the column headings.  This may end up being in a thead, or it may not, whatever makes the solution easier.

When you scroll right, the first column stays put, since it holds the labels for the rows.

I'm pretty certain this is impossible with CSS alone, but can anyone point me toward a JavaScript solution?  It needs to work in all major browsers.

Answer:
How about a solution where you put the actual "data" of the table inside its own div, with
```
overflow: scroll;
```
? Then the browser will automatically create scrollbars for the portion of the "table" you do not want to lock, and you can put the "table header"/first row just above that
```
<div>
```
.
Not sure how that would work with scrolling horizontally though.


Question:
I am preparing a project proposal for a client who wants to publish video in his website. I need to define which video formats will be allowed, which video sizes, as well as the necessary tools for conversion and preparation.

I have no experience with embedding video in websites so which markup do I need to play video online?

Answer:
You could embed them using a flash player, like Youtube for example.
A quick way to do this is using some already made player, like the excellent
JW FLV Player
, free for non-commercial projects and very cheap for commercial ones.
It supports FLV and MP4 video files, you can convert your videos in this formats in a lot of ways, for example using
ffmpegx
.


Question: Let's say I want to create the alias %xed for %edit -x. How would I do it?

Answer:
Update:
The first response( below) does not accept parameters. So put this snippet at the end of the ipy_user_conf.py file ( it is in your home directory ).
```
```
def ed_xed(self,arg):
    ip = self.api
    return ip.magic.im_class.magic_edit(ip.IP," -x %s "%arg)

ip.expose_magic('xed',ed_xed)
```
```
Before update:
Does it has to be %magic?
You can use the macro and store magic to reproduce this behavior without the magic %.
```
```
In [5]: %edit -x
In [6]: macro xed 5
In [7]: store xed
In [8]: xed
```
```
for magic alias from the documentation ( %magic? ):
You can also define your own aliased
  names for magic functions. In your
  ipythonrc file, placing a line like:
execute
IPYTHON
.magic_pf =
IPYTHON
.magic_profile
will define %pf as a new name for
  %profile.
But I don't know how too add the parameter.


Question:
I'm writing code in Java, using the NetBeans IDE. I keep getting a couple of "Incompatible Type" errors. I declare a variable as String and then assign to it the value from a method that returns a String too. The error says that there was expected a type of "String" but instead found "..." where "..." the name of the method I call.

For example, this is a line that gives me the error:

incompatible types
found:     encode_monoalphabetic_engine
required:  java.lang.String

encoded = encode_monoalphabetic_engine(string);

Answer:
Perhaps you could post a more complete code snippet?
It looks like your method argument
```
string
```
isn't a
```
java.lang.String
```
?