q:
I am making a site that publishes articles in issues each month. It is straightforward, and I think using a Markdown editor (like the WMD one here in Stack Overflow) would be perfect.

However, they do need the ability to have images right-aligned in a given paragraph.

I can't see a way to do that with the current system - is it possible?

[A]
You can embed HTML in Markdown, so you can do something like this:
```
```
<img style="float: right;" src="whatever.jpg">

Continue markdown text...
```
```


q:
If I have a type defined as a set of an enumerated type, it's easy to create an empty set with [], but how do I create a full set?

EDIT:  Yeah, the obvious solution is to use a for loop.  That's also a really bad solution if there's another way. Does anyone know of a way that'll work in constant time?

[A]
Per Barry's suggestion:
```
```
FillChar(VarSet, SizeOf(VarSet), $FF);
```
```

s: huggingface

c: devops

d: intermediate


q:
I keep seeing references to the visitor pattern in blogs but I've got to admit, I just don't get it.  I read the wikipedia article for the pattern and I understand its mechanics but I'm still confused as to when I'd use it.

As someone who just recently really got the decorator pattern and is now seeing uses for it absolutely everywhere I'd like to be able to really understand intuitively this seemingly handy pattern as well.

[A]
The reason for your confusion is probably that the Visitor is a fatal misnomer. Many (prominent
1
!) programmers have stumbled over this problem. What it actually does is implement
double dispatching
in languages that don't support it natively (most of them don't).
1)
My favourite example is Scott Meyers, acclaimed author of “Effective C++”, who called this one of his
most important C++ aha! moments
ever
.


q:
So far, I've only been passing javascript strings to my web methods, which get parsed, usually as Guids. but now i have a method that accepts an IList... on the client, i build this array of objects and then attempt to pass it like:

$.ajax({
  type: 'POST',
  url: 'personalization.aspx/SetPersonalization',
  data: "{'backerEntries':" + backerEntries + "}",
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  success: postcardManager.SetPersonalizationComplete
});

The post:

{'backerEntries':[object Object],[object Object],[object Object]}

The error response:

Invalid JSON primitive: object.

For some reason, jquery doesn't seem to convert my array into a json string? Any ideas why? I tried putting [] around the backerEntries, and {}, as well as {[]} just in sheer desperation. Am I missing something obvious here?

[A]
The data you are passing you are trying to pass it as a string already.  If you want jQuery to transform it leave the whole thing as an object, e.g.
```
```
data:{backerEntries: backerEntries }
```
```
Assuming of course backerEntries is an array.  jQuery should transform this and will append it to the querystring as that is its default behaviour.  Your current code is relying on default JavaScript behaviour which won't by default convert an array into its string representation.


q:
Hoping some of you TinyXML++ people can help me out. Really, since you recomended to me before I think you owe me ;)

I have the following code:

   //ticpp::Iterator< ticpp::Element > child( "SetPiece" );
    ticpp::Iterator< ticpp::Node > child("SetPiece");
    GLuint lc_SPieces = 0;
    for(child = child.begin( this ); child != child.end(); child++ )
    {
        lc_SPieces++;
    }

If I use the top declaration for child I get the error:

Unhandled exception at 0x7c812aeb in
  Drawing.exe: Microsoft C++ exception:
  __non_rtti_object @ 0x0012f7b4.

And I get it in dbgheap.c at this line:

pvBlk = _heap_alloc_dbg(nSize, nBlockUse, szFileName, nLine);

What's weird is it works with Node, and I know that there are elements in there(I checked using the TinyXML iteration methods).

Has anyone run into this before?

[A]
just poking in the dark, i don't know tinyxml, but it seems that a dynamic_cast went wrong.
If you dynamic_cast<> a pointer, you get a NULL-pointer on failure. However, if you cast to a reference type, there is no concept of a NULL-reference, so the runtime throws this  exception (or bad_type).
MSDN on dynamic_cast, and why it can go wrong
The line you pasted for the exception to occur does not help to clear up the situation, since it identifies the symptom rather than the cause.
Try to identify the cast that went wrong, you should be able to find it if you walk up the stack and find the last method in tinyxml libs or headers. Then you can decide whether tinyxml is worng, or you just applied it the wrong way.
good luck!


q:
It's easy to get the value of a key from a .NET generic Dictionary:

Dictionary<int, string> greek = new Dictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
string secondGreek = greek[2];  // Beta

But trying to get the keys given a value is not as straightforward because there could be multiple keys:

int[] betaKeys = greek.WhatDoIPutHere("Beta");  // expecting single 2

[A]
revised: okay to have some kind of find you would need something other than dictionary, since if you think about it dictionary are one way keys.  that is, the values might not be unique
that said it looks like you're using c#3.0 so you might not have to resort to looping and could use something like:
```
```
var key = (from k in yourDictionary where string.Compare(k.Value, "yourValue", true)  == 0 select k.Key).FirstOrDefault();
```
```


q:
There's not a lot to add to the subject really.

I am after a free task board/ burndown reporting tool for Windows.

[A]
Well, without knowing more about your situation, I have to
highly
recommend a wall of index cards and a handdrawn chart on flip chart paper. Works much better than any software in the standard situation.
If you really have to use software, there is none that I could recommend unreservedly, let alone a free one. You might want to keep in mind that some of the commercial ones are free for open source or academic projects, too. Which one's right for you will depend, besides other things, on how much you want it to define your process.


q:
I'm trying to make a page in php that takes rows from a database, displays them, and then give the viewer a chance to upvote or downvote a specific entry. Here is a snippet:

echo("<form action=\"vote.php\" method=\"post\"> \n");
echo("<INPUT type=\"hidden\" name=\"idnum\" value=\"".$row[0]."\">");
echo("<INPUT type=\"submit\" name=\"up\" value=\"Upvote.\">  \n");
echo("<INPUT type=\"submit\" name=\"down\" value=\"Downvote\"> ");
echo("<form/>\n");

The problem is when I hit a submit button, the value for idnum that gets sent is based on the one farthest down it seems. So my questions is, when a submit button is pressed, are the values for all inputs on a page sent?

[A]
Your form is not closed properly. Use
```
</form>
```
instead of
```
<form/>
```
.


q:
I would like to create an HTML table with row colors changing based on position and content.  But instead of alternating every row, I'd like to be able to group rows together, so that I can have some XML like this:

<itemlist>
   <item group="0">Conent...blah blah</item>
   <item group="0">Content...who cares</item>
   <item group="1">Content</item>
   <item group="2">Content</item>
   <item group="2">Content</item>
</itemlist>

And all of the items with group=0 are one color, and items with group=1 are another, and group=2 are either toggled back to the first color, or are their own color.

All I can seem to find out there is ways to alternate every row, but I can't seem to "get it" when it comes to actually using the node data to help me make the decision.

[A]
The first two groups are simple as you can parse them based on their group number.
To handle group 2, consider using the
preceding
function to get a list of proir notes, and use
count
to determine how many there are. You can can then alternate values based on whether the count is even or odd.


q:
I seem to remember being able to print out (or locate) the specific switches that each -O<num> option turns on.  Can you remind?

Thanks!

[A]
You may also try the good ol' manual
```
```
$ man gcc
```
```
at the subsection "Options That Control Optimization".


q:
I would like to know if it is possible to determine if a function parameter with a default value was passed in Python.
For example, how does dict.pop work?

>>> {}.pop('test')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'pop(): dictionary is empty'
>>> {}.pop('test',None)
>>> {}.pop('test',3)
3
>>> {}.pop('test',NotImplemented)
NotImplemented

How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C?

Thanks

[A]
You can do it like this:
```
```
def isdefarg(*args):
    if len(args) > 0:
        print len(args), "arguments"
    else:
        print "no arguments"

isdefarg()
isdefarg(None)
isdefarg(5, 7)
```
```
See the Python documentation on
calls
for full information.


q:
Does anyone have any suggestions (or a regular expression) for parsing the HTTP Accept header?

I am trying to do some content-type negotiation in ASP.NET MVC. There doesn't seem to be a built in way (which is fine, because there are a lot of schools of thought here), but the parsing is not entirely trivial and I would rather not re-invent the wheel if someone has already done it well and is willing to share.

[A]
The
RFC
is quite complex. If the regex where to follow these rules to the letter, it would become several lines long.
If you already have the Accept-header, and ignore the quotes and the parameters, you could do something like this to match each pair:
```
```
/([^()<>@,;:\\"\/[\]?={} \t]+)\/([^()<>@,;:\\"\/[\]?={} \t]+)/
```
```
```
*
```
is included in the character class, so it does not need any special case in the regex.


q:
As the title describes, what are the different doctypes available and what do they mean? I notice that the layout looks a little different in IE7 when I switch from

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

to

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Are there any others and what are the effects or ramifications?

Thanks!

[A]
Here is the official explanation of the various DTD's from the W3C:
http://www.w3.org/QA/2002/04/valid-dtd-list.html
You might also find the following beneficial:
http://www.freedivs.com/tutorials/Choosing%20a%20DOCTYPE/


q:
I used the method

$("#dvTheatres a").hover(function (){
        $(this).css("text-decoration", "underline");
    },function(){
        $(this).css("text-decoration", "none");
    }
);

Is there a more elegant method?(single line)

[A]
Why not just use CSS?
```
```
#dvTheatres a {
    text-decoration: none;
}

#dvTheatres a:hover {
    text-decoration: underline;
}
```
```


q: I would like to construct a query that displays all the results in a table, but is offset by 5 from the start of the table. As far as I can tell, MySQL's LIMIT requires a limit as well as an offset. Is there any way to do this?

[A]
As you mentioned it LIMIT is required, so you need to use the biggest limit possible, which is 18446744073709551615 (maximum of unsigned BIGINT)
```
```
SELECT * FROM somewhere LIMIT 18446744073709551610 OFFSET 5
```
```


q:
I'm interested to know what are the "must have" JSP tag libraries apart from JSTL. All I've found so far are

ccc - for accessing static constants in JSP (without scriptlet)

displaytag - for generating sophisticated HTML tables that includes data paging, grouping, sorting, exporting etc.

What other indispensible tag libs are out there?

[A]
I use displaytag, and have been quite happy with it. The only other tag library I use is the one that comes with the Stripes Action Framework.
But my truly indispensable Tag library is the one we wrote.
At the office we must have over 50 of them by now for our internal framework.
The key behind them, though, is that they're JSP 2.0 Tag Files rather than class JSP Tags written in Java. Tag files are powerful and very easy to use.
Where classic JSP tag discouraged tag development because it was so difficult, Tag Files encourage it to where it's trivial for refactoring JSP pages now.
I think Tag Files and JSTL turned JSP as a page markup technology from mediocre to one of the best out there.


q:
I'm using autotools to build a shared object.

Using pkglib_LTLIBRARIES in my Makefile.am causes a libtest.la AND libtest.so to be built.

I only want it to build/install libtest.so.

Is this possible?

[A]
The details of generating libraries varies widely from platform to platform. For example, on OS X, your library would be called libtest.dylib rather then libtest.so. libtool is part of the autotools suite, and its job is to abstract away all the messy platform dependent details. To do this, it creates a high-level, platform independent description of the library. This is is the libtest.la file you are seeing. libtools uses this platform independent description of the library to put together the final native library.
If you are using the autotools I don't think you are going to be able to avoid generating libtest.la. I suppose you could hack your local libtool shell script to remove it at completion, but you'd just have to generate it again the next time you ran make.
I found the
GNU documentation on libtool
somewhat opaque. Here is a
less opaque but kind of dated description
.


q:
I've heard that it's possible with extension methods, but I can't quite figure it out myself. I'd like to see a specific example if possible.

Thanks!

[A]
It really depends on what you mean by "mixin" - everyone seems to have a slightly different idea. The kind of mixin I'd
like
to see (but which isn't available in C#) is making implementation-through-composition simple:
```
```
public class Mixin : ISomeInterface
{
    private SomeImplementation impl implements ISomeInterface;

    public void OneMethod()
    {
        // Specialise just this method
    }
}
```
```
The compiler would implement ISomeInterface just by proxying every member to "impl" unless there was another implementation in the class directly.
None of this is possible at the moment though :)


q:
I'm a newbie at networking.  I understand the concept of multicast, but was wondering if it's reliable on the open/public internet?

It seems like sort of an edge case that different backbones or ISPs might intentionally break to reduce router load or generally segment the network for practical high-use applications.

Is my fear reasonable?

P.S. Follow-up question here:
Best tutorial for application multicasting?

[A]
IP multicast in the internet doesn't really work. From the
Wikipedia article
:
For both these reasons, and also
  reasons of economics, IP Multicast is
  not in general use in the commercial
  Internet.
People who desire to participate in the global IP multicast need to attach themselves to the MBONE. The Wikipedia article points out that application-level multicast infrastructures do work, e.g. IRC.


q:
Which sql data type should we use for number bases primary key:

int

bigint

numeric

float

[A]
Generally,
```
int
```
.
```
bigint
```
if you think you'll have more rows than there are atoms in the universe.
```
uniqueidentifier
```
is useful if you need
globally
unique keys (keys that are guaranteed to be unique across all tables in your schema, maybe even universally unique (I don't remember))
The other two I wouldn't use they're not integral types (they have fractions, which just don't make a lot of sense as keys)


q:
I am having some trouble manipulating images using CodeIgniter 1.7.  With the following code, the image is uploaded correctly. Alas, instead of a new image being made, and then modified; the existing image is modified. Any help?

//Upload image first
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|bmp';

$this->load->library('upload', $config);
$this->upload->do_upload();

//Now fix the image
$picloc = $this->upload->data();
$picloc = $picloc['file_name'];

$thumbnail = "thumb_".$picloc;

$imagemanip['image_library'] = 'gd2';
$imagemanip['source_image'] = './uploads/'.$picloc;
$imagemanip['new_img'] = './uploads/'.$thumbnail;
$imagemanip['maintain_ratio'] = TRUE;
$imagemanip['width'] = 250;
$imagemanip['height'] = 250;

$this->load->library('image_lib', $imagemanip);

$this->image_lib->resize();

[A]
The problem is simple, you have a typo in the line:
```
```
$imagemanip['new_img'] = './uploads/'.$thumbnail;
```
```
The the index should be "new_image", not "new_img", so the line becomes..
```
```
$imagemanip['new_image'] = './uploads/'.$thumbnail;
```
```


q:
What is the best way to store a large number of data points?

For example temperature values which are measured every minute over lots of locations?

SQL databases with one row per data points doesn't seem very efficient.

[A]
I would like to know why you reckon it to be "not efficient". Probably you need to explain your data model and schema to give a better context of the scenario.
Storing multiple data points into a single row, when they are not related to each other, and should indeed stand on their own, is not a good approach. Meshing together will result in very counter-intuitive and quirky query statements to pull out the correct data points you need for a given scenario.
We have done work in a power station before, collecting data from various systems and metering equipment a wide variety of gas and electrical parameters that need to be monitored and aggregated. They can come in every 3-5 minutes to 30-60 minutes depending on the type of parameters. These naturally results in millions of records per month.
The key is indexing the tables properly so that their physical order is tied to sequence in which the records came in. (Clustered index)  New pages and extents are created and filled sequentially by incoming data. This should prevent massive page splits and reshuffling.


q:
I am working on a PHP application that intends to ease company workflow and project management, let's say something like Basecamp and GoPlan.

I am not sure on what the best approach is, database-wise. Should I use a single database and add client-specific columns to each of the tables, or should I create a database for each new client? An important factor is automation: I want it to be dead simple to create a new client (and perhaps opening the possibility to signing up for yourself).

Possible cons I can think of using one database:

Lack of extensibility

Security problems (although bugs shouldn't be there in the first place)

What are your thoughts on this? Do you have any ideas what solution the above companies are most likely to have chosen?

[A]
For multitenancy, performance will typically increase the more resources you manage to share across tenants, see
http://en.wikipedia.org/wiki/Multitenancy
So if you can, go with the single database. I agree that security problems would only occur due to bugs, as you can implement all access control in the application. In some databases, you can still use the database access control by careful use of views (so that each authenticated user gets a different view).
There are ways to provide extensibility also. For example, you could create a single table with extension attributes (keyed by tenant, base record, and extension attribute id). Or you can create per-tenant extension tables, so that each tenant has his own extension schema.


q:
While using Vim (at home and at work), I often find myself doing similar things repeatedly. For example, I may turn a bunch of CSV text into a series of SQL inserts. I've been using Vim for years, but only recently have I tried to seriously think about how I could improve my productivity while using it.

My question is.. Is there a good way (or right way) to store commonly used commands or command sequences? And how is the best way to execute them? It would be nice to be able to use the same script on a live session and also over the command line against some file.

I'm hoping that I can store them in a .vim file so that I can hand them to coworkers (who are not as proficient with vim) for them to use.

[A]
You can store your common task macros in .vim files, like
this
for example, and then you can load them with the command
:so file.vim
Here
you can find a bunch of useful macros, also I recommend you to learn well the useful
q
macro recording
command, it's very very powerful...
The macros created with the
q
command are stored in a register, qq stores the macro in the q register, so when you end the recording you can simply paste the macro, with
"qp
and save it, later you can load it by simply yanking the macro into a register i.e.:
"qY
, the macros are only text and remember you can use any register instead of q. There is a Vim Script for storing
q
macros:
marvim : Macro Persistent Storage and Shareable Repository for VIM
Also take a look to the
Vim Scripting Language
.


q: How can I count operations in C++? I'd like to analyze code in a better way than just timing it since the time is often rounded to 0 millisec.

[A] If you are timing code, it's worth running it a lot of times in a loop to avoid the effect of the timer resolution. So you might run the thing you're timing 10,000 times and measure the amount of time it takes to run all the iterations. It will probably only take a few seconds to run and you'll get better timing data.


q: How do I enable assembly bind failure logging (Fusion) in .NET?

[A]
Set the following registry value:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion!EnableLog] (DWORD) to 1
To disable, set to 0 or delete the value.
[edit ]:Save the following text to a file, e.g FusionEnableLog.reg, in
Windows Registry Editor Format:
```
```
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion]
"EnableLog"=dword:00000001
```
```
Then run the file from windows explorer and ignore the warning about possible damage.


q:
So I've got a Ruby method like this:

def something(variable, &block)
  ....
end

And I want to call it like this:

something 'hello' { do_it }

Except that isn't working for me, I'm getting a syntax error. If I do this instead, it works:

something 'hello' do
  do_it
end

Except there I'm kind of missing the nice look of it being on one line.

I can see why this is happening, as it could look like it's a hash being passed as a second variable, but without a comma in between the variables...but I assume that there must be a way to deal with this that I'm missing. Is there?

[A]
If you want "def something" to to accept a block, you need to yield data to that block. For example:
```
```
#to uppercase string
def something(my_input)
 yield my_input.upcase
end

# => "HELLO WORLD"
something("hello world") { |i| puts i}
```
```


q: I'm new to the VxWorks Environment are there any good sources of information out there?

[A]
If your budget allows it, I would recommend taking one of the courses offered by WindRiver.  My company brought in one of their trainers to teach a class on-site and it was excellent.  They provided hands-on programming activities and a lot of information.  If you are new to the concepts of real-time or embedded programming, they provided the necessary background information, and even if you were already familiar with these (as I was), there was plenty of useful training specific to VxWorks and Workbench.  I believe they also organize their own courses, in addition to coming to companies.
Course Schedule


q: I'm new to the VxWorks environment, I'm wondering what C and C++ compilers are available for use with VxWorks?

[A]
As far as i know Tornado VxWorks IDE using gcc toolchain.
Any way i suggest to use the compiler provided by WindRiver (which i believe their version
of gcc)  to avoid compatibility problems.
It's probably worth to menation the VxWorks version you having in mind.
I guess gcc version will be depend on VxWorks version and probably on target platform.


q:
In a web application I am developing, I wish to implement wiki-style edits (where each and every edit is saved, can be compared, and users can rollback edits easily).

What is a good way of implementing this without re-inventing the wheel too much?

Thank you in advance.

[A]
I believe you're really seeking a
Content Management System
(CMS), of which a Wiki is a specialization (IMHO).
Googling '
CMS Open Source
' brings as its top hit:
Open Source CMS
, try before you install
Joomla
Drupal
Wordpress
And a
lot
of other information.
Commercially, I really like Atlassian's
Confluence
.  Wiki like markup, editing history, easily attach documents and now supporting editing in Word, Excel & Powerpoint.


q:
I have the following line:

"14:48 say;0ed673079715c343281355c2a1fde843;2;laka;hello ;)"

I parse this by using a simple regexp:

if($line =~ /(\d+:\d+)\ssay;(.*);(.*);(.*);(.*)/) {
    my($ts, $hash, $pid, $handle, $quote) = ($1, $2, $3, $4, $5);
}

But the ; at the end messes things up and I don't know why. Shouldn't the greedy operator handle "everything"?

[A]
Try making the first 3
```
(.*)
```
ungreedy
```
(.*?)
```


q: I've been writing a lot recently about Parallel computing and programming and I do notice that there are a lot of patterns that come up when it comes to parallel computing. Noting that Microsoft already has released a library along with the Microsoft Visual C++ 2010 Community Technical Preview (named Parallel Patterns Library) I'm wondering what are the common parallel programming patterns you have been using and encountering that may be worth remembering? Do you have any idioms you follow and patterns that you seem to keep popping up as you write parallel programs with C++?

[A]
First you have to chose between shared-memory computing, and shared-nothing computing. Shared memory is easier, but doesn't scale that well - you will use shared-nothing if you either
a) have a cluster, rather than a multiprocessor system, or
b) if you have many CPUs (say, > 60), and a high degree of non-uniform memory
For shared-memory, the common solution is to use threads; they are easy to understand as a concept, and easy to use in the API (but difficult to debug).
For shared-nothing, you use some kind of messaging. In high-performance computing, MPI is established as the messaging middleware.
You then also need to design an architecture for the parallel activities. The most common approach (again because it's easy to understand) is the farmer-worker-pattern (a.k.a. master-slave).


q: I am trying to insert an image (jpg) in to a word document and the Selection.InlineShapes.AddPicture does not seem to be supported by win32old or I am doing something wrong.  Has anyone had any luck inserting images.

[A]
Running on WinXP, Ruby 1.8.6, Word 2002/XP SP3, I recorded macros and translated them, as far as I could understand them, into this:
```
```
require 'win32ole'

begin
  word = WIN32OLE::new('Word.Application')   # create winole Object
  doc = word.Documents.Add
  word.Selection.InlineShapes.AddPicture "C:\\pictures\\some_picture.jpg", false, true
  word.ChangeFileOpenDirectory "C:\\docs\\"
  doc.SaveAs "doc_with_pic.doc"
  word.Quit
rescue Exception => e
  puts e
  word.Quit
ensure
  word.Quit unless word.nil?
end
```
```
It seems to work. Any use?


q:
I want to make an MVC route for a list of news, which can be served in several formats.

news -> (X)HTML

news.rss -> RSS

news.atom -> ATOM

Is it possible to do this (the more general "optional extension" situation crops up in several places in my planned design) with one route? Or do I need to make two routes like this:

routes.MapRoute("News-ImplicitFormat",
                "news",
                new { controller = "News", action = "Browse", format = "" });

routes.MapRoute("News-ExplicitFormat",
                "news.{format}"
                new { controller = "News", action = "Browse" });

It seems like it would be useful to have the routing system support something like:

routes.MapRoute("News",
                "news(.{format})?",
                new { controller = "News", action = "Browse" });

[A]
I made a method to support adding pairs like this as follows:
```
```
public static void MapRouteWithOptionalFormat(this RouteCollection routes,
                                              string name,
                                              string url,
                                              object defaults)
{
    Route implicitRoute = routes.MapRoute(name + "-ImplicitFormat",
                                          url,
                                          defaults);
    implicitRoute.Defaults.Add("format", string.Empty);

    Route explicitRoute = routes.MapRoute(name + "-ExplicitFormat",
                                          url + ".{format}",
                                          defaults);
}
```
```


q: For a requirement i was asked to export information into a custom entity that was created in MS CRM 4.0. I am trying to do this programmatically and I have not found a single code that actually accomplishes this. I wrote code to check if a certain value for a field exists in the entity but creating a new entity seems to be a little bit of puzzle for me. Any help on this would be appreciated.

[A]
This is my experience when I had a similar requirement in MS CRM 3.0. I started using the CRM sdk to import data but found it was not easy.
Then I ended up using
Scribe adapter for CRM
. It is not free but will easily solve your problem for importing to custom entities. Will post some links on that. need to go through some old bookmarks.
Not sure if this feature exist out of the box for CRM 4.0.


q:
I'm writing an iOS app with a table view inside a tab view. In my UITableViewController, I implemented -tableView:didSelectRowAtIndexPath:, but when I select a row at runtime, the method isn't being called.  The table view is being populated though, so I know that other tableView methods in my controller are being called.

Does anyone have any ideas what I may have screwed up to make this happen?

[A]
It sounds like perhaps the class is not the
```
UITableViewDelegate
```
for that table view, though
```
UITableViewController
```
is supposed to set that automatically.
Any chance you reset the delegate to some other class?


q:
Returning to WinForms in VS2008 after a long time.. Tinkering with a OOD problem in VS2008 Express Edition.

I need some controls to be "display only" widgets. The user should not be able to change the value of these controls... the widgets are updated by a periodic update tick event. I vaguely remember there being a ReadOnly property that you could set to have this behavior... can't find it now.

The Enabled property set to false: grays out the control content. I want the control to look normal.
The Locked property set to false: seems to be protecting the user from accidentally distorting the control in the Visual Form Designer.

What am I missing?

[A]
For some typical winforms controls:
http://jquiz.wordpress.com/2007/05/29/c-winforms-readonly-controls/
This is also a good tip to preserve the appearance:
```
```
Color clr = textBox1.BackColor;
    textBox1.ReadOnly = true;
    textBox1.BackColor = clr;
```
```


q:
I'm struggling with Test::Unit.  When I think of unit tests, I think of one simple test per file.  But in Ruby's framework, I must instead write:

class MyTest < Test::Unit::TestCase
   def setup
   end

   def test_1
   end

   def test_1
   end
end

But setup and teardown run for every invocation of a test_* method.  This is exactly what I don't want.  Rather, I want a setup method that runs just once for the whole class.  But I can't seem to write my own initialize() without breaking TestCase's initialize.

Is that possible?  Or am I making this hopelessly complicated?

[A]
That's how it's supposed to work!
Each test should be completely isolated from the rest, so the
```
setup
```
and
```
tear_down
```
methods are executed once for every test-case. There are cases, however, when you might want more control over the execution flow. Then you can group the test-cases in
suites
.
In your case you could write something like the following:
```
```
require 'test/unit'
require 'test/unit/ui/console/testrunner'

class TestDecorator < Test::Unit::TestSuite

  def initialize(test_case_class)
    super
    self << test_case_class.suite
  end

  def run(result, &progress_block)
    setup_suite
    begin
      super(result, &progress_block)
    ensure
      tear_down_suite
    end
  end

end

class MyTestCase < Test::Unit::TestCase

  def test_1
    puts "test_1"
    assert_equal(1, 1)
  end

  def test_2
    puts "test_2"
    assert_equal(2, 2)
  end

end

class MySuite < TestDecorator

  def setup_suite
    puts "setup_suite"
  end

  def tear_down_suite
    puts "tear_down_suite"
  end

end

Test::Unit::UI::Console::TestRunner.run(MySuite.new(MyTestCase))
```
```
The
```
TestDecorator
```
defines a special suite which provides a
```
setup
```
and
```
tear_down
```
method which run only once before and after the running of the set of test-cases it contains.
The drawback of this is that you need to tell
Test::Unit
how to run the tests in the unit. In the event your unit contains many test-cases and you need a decorator for only one of them you'll need something like this:
```
```
require 'test/unit'
require 'test/unit/ui/console/testrunner'

class TestDecorator < Test::Unit::TestSuite

  def initialize(test_case_class)
    super
    self << test_case_class.suite
  end

  def run(result, &progress_block)
    setup_suite
    begin
      super(result, &progress_block)
    ensure
      tear_down_suite
    end
  end

end

class MyTestCase < Test::Unit::TestCase

  def test_1
    puts "test_1"
    assert_equal(1, 1)
  end

  def test_2
    puts "test_2"
    assert_equal(2, 2)
  end

end

class MySuite < TestDecorator

  def setup_suite
    puts "setup_suite"
  end

  def tear_down_suite
    puts "tear_down_suite"
  end

end

class AnotherTestCase < Test::Unit::TestCase

  def test_a
    puts "test_a"
    assert_equal("a", "a")
  end

end

class Tests

  def self.suite
    suite = Test::Unit::TestSuite.new
    suite << MySuite.new(MyTestCase)
    suite << AnotherTestCase.suite
    suite
  end

end

Test::Unit::UI::Console::TestRunner.run(Tests.suite)
```
```
The
Test::Unit
documentation
documentation provides a good explanation on how suites work.


q:
Is std::string size() a O(1) operation?

The implementation of STL I'm using is the one built into VC++

[A]
```
```
size_type __CLR_OR_THIS_CALL size() const

{   // return length of sequence

    return (_Mysize);

}
```
```
So it eventually might be like this, but you can never be sure.


q:
I'm using a std::map (VC++ implementation) and it's a little slow for lookups via the map's find method.

The key type is std::string.

Can I increase the performance of this std::map lookup via a custom key compare override for the map? For example, maybe std::string < compare doesn't take into consideration a simple string::size() compare before comparing its data?

Any other ideas to speed up the compare?

In my situation the map will always contain < 15 elements, but it is being queried non stop and performance is critical.   Maybe there is a better data structure that I can use that would be faster?

Update: The map contains file paths.

Update2: The map's elements are changing often.

[A]
The first thing is to try using a hash_map if that's possible - you are right that the standard string compare doesn't first check for size (since it compares lexicographically), but writing your own map code is something you'd be better off avoiding. From your question it sounds like you do not need to iterate over ranges; in that case map doesn't have anything hash_map doesn't.
It also depends on what sort of keys you have in your map. Are they typically very long? Also what does "a little slow" mean? If you have not profiled the code it's quite possible that it's a different part taking time.
Update: Hmm, the bottleneck in your program is a map::find, but the map always has less than 15 elements. This makes me suspect that the profile was somehow misleading, because a find on a map this small should not be slow, at all. In fact, a map::find should be so fast, just the overhead of profiling could be more than the find call itself. I have to ask again, are you sure this is really the bottleneck in your program? You say the strings are paths, but you're not doing any sort of OS calls, file system access, disk access in this loop? Any of those should be orders of magnitude slower than a map::find on a small map. Really any way of getting a string should be slower than the map::find.


q:
What is the right way to perform some static finallization?

There is no static destructor. The AppDomain.DomainUnload event is not raised in the default domain. The AppDomain.ProcessExit event shares the total time of the three seconds (default settings) between all event handlers, so it's not really usable.

[A]
Basically, you can't. Design your way around it to the fullest extent possible.
Don't forget that a program can
always
terminate abruptly anyway - someone pulling out the power being the obvious example. So anything you do has to be "best effort" - in which case I'd certainly
hope
that
```
AppDomain.ProcessExit
```
would be good enough.
What do you need to do, in your particular case?


q: Before few days I was at some IT conference here in Belgrade. On Agenda was a topic about MySql, and clustering in MySql, and the guys from MySql said  that they have the best solution for cluster split brain problem, does anyone know something about this, is this true or just a marketing trick?

[A]
MySQL Cluster requires at least 3 systems which allows it have one of the nodes be an arbitrator for dealing with split brain scenarios.  Two of the systems can run data nodes/mysqld nodes and the third needs to run the management node (which is normally the arbitrator by default, however SQL nodes can also operate as them).
In the event of a split brain setup (ie. the two data nodes can no longer talk to each other, but they are still running), then they will realize it and ask the arbitrator to decide which node is allowed to continue to running.  If a node can not talk to the arbitrator then it will shutdown.  From all of the nodes the arbitrator can talk to it will pick a node to continue to running and tell the other(s) to shutdown.
The arbitrator is normally the management node, but can also be data nodes.  If the arbitrator fails, then the cluster can elect a new one.  However, it can't do this during arbitration, so if both a data node and arbitrator fail at once, the third node will shutdown.
Of course, it gets a bit more complex when you have multiple node groups, but the same basic ideas apply in those cases as well.
You can read more about this at in the
MySQL Cluster FAQ
.


q:
I've recently become aware that there's a distinction between IP multicasting (which apparently doesn't work that well on the public internet) and application multicasting (which is apparently used in IRC and PSYC, per http://en.wikipedia.org/wiki/Multicast).

Is there a good tutorial on implementing application-level multicasting?

I thought the whole point of multicast was to reduce bandwidth for common network segments, so it's hard for me to understand what application-level multicast does.

[A]
The purpose of IP level multicasting is to reduce bandwidth for common network segments where many users wish to receive the same traffic.   It's usually limited to one particular subnet and an IP router won't propagate the multicast beyond the subnet.   This is done for scalability reasons - it wouldn't be a good idea to allow one host to originate multicast packets which are propagated to every IP address on the internet.
There are different ways to think of "application level" multicasting.   One approach is to build a multicast tree using the host computers participating in the multicast.   Dijkstra's algorithm could be used to do this (Wikipedia has a reasonable description of this).   However, maintaining the list of participating computers - and keeping the tree up to date - can be a fair amount of work if hosts are joining and leaving the network at a substantial rate.   And you probably don't have a good estimate of hop cost available at the application level.
Another approach you should review is the flooding algorithm used in the Gnutella network's query routing protocol.     (Wikipedia also has a good description of this.)   This approach alleviates the need to build a multicast tree, but it has the downside of generating more network traffic.  In fact, a LOT more network traffic, as the traffic grows with the square of the number of nodes, i.e. O(n**2).


q:
When I try to commit the first revision to my git repository (git commit) from Cygwin, I'm getting an error in gvim which says "Unable to open swap file for "foo\.git\COMMIT_EDITMSG" [New Directory]. I think it might be some sort of permission problem, but I've tried removing the read-only flag from the folder, as well as recursively adjusting the owner (using the windows property tab, not chown under Cygwin) to be the account I'm running under, without any luck. If I change the default editor to notepad, I get "The system cannot find the file specified", even though the file (COMMIT_EDITMSG) does exist and even contains:

# Please enter the commit message for your changes.
# (Comment lines starting with '#' will not be included)
# etc...

How can I troubleshoot this problem further?

[A]
Unable to open swap file for "foo\.git\COMMIT_EDITMSG" [New Directory].
Looks like the
```
git commit
```
is passing the file path as a Windows path, not a POSIX path. note the
```
\
```
in the message.
```
gvim
```
is going to try to open `foo.gitCOMMIT_EDITMSG", which doesn't exist.
I don't use
```
git
```
, but I imagine it uses an environment var similar to
```
SVN_EDITOR
```
.  You may need to wrap the editing session with a small script that uses
```
cygpath
```
to change the file path from Windows to Posix separators.
```
```
#!/bin/bash
gvim "$(cygpath --unix "${1}")"
```
```
Caveat Emptor, untested.


q:
Wizards can kick-start features. They can also obfuscate your code, and are anti-YAGNI.

On balance, do you think Wizards are more useful or more harmful?

[A]
They're there for a reason - to try and make your life easier.
They can be useful and save you 5 or 10 minutes of typing.  Of course it's best to read and make sure you understand what they've written for you.
If you use them without understanding, then they could be considered harmful in the fact that they're letting you get away with not learning something you should probably know, but on balance I think they're a good thing.


q:
I understand that creating too many threads in an application isn't being what you might call a "good neighbour" to other running processes, since cpu and memory resources are consumed even if these threads are in an efficient sleeping state.

What I'm interested in is this: How much memory (win32 platform) is being consumed by a sleeping thread?

Theoretically, I'd assume somewhere in the region of 1mb (since this is the default stack size), but I'm pretty sure it's less than this, but I'm not sure why.

Any help on this will be appreciated.

(The reason I'm asking is that I'm considering introducing a thread-pool, and I'd like to understand how much memory I can save by creating a pool of 5 threads, compared to 20 manually created threads)

[A]
I think you'd have a hard time detecting any impact of making this kind of a change to working code - 20 threads down to 5. And then add on the added complexity (and overhead) of managing the thread pool. Maybe worth considering on an embedded system, but Win32?
And you can set the stack size to whatever you want.


q:
I'm using jQuery to wire up some mouseover effects on elements that are inside an UpdatePanel. The events are bound in $(document).ready . For example:

$(function() {
    $('div._Foo').bind("mouseover", function(e) {
        // Do something exciting
    });
});

Of course, this works fine the first time the page is loaded, but when the UpdatePanel does a partial page update, it's not run and the mouseover effects don't work any more inside the UpdatePanel.

What's the recommended approach for wiring stuff up in jQuery not only on the first page load, but every time an UpdatePanel fires a partial page update? Should I be using the ASP.NET ajax lifecycle instead of $(document).ready?

[A]
I would use one of the following approaches:
Encapsulate the event binding in a function and run it every time you update the page. You can always contain the event binding to specific elements so as not to bind events multiple times to the same elements.
Use the
livequery
plug-in, which basically performs method one for you auto-magically. Your preference may vary depending on the amount of control you want to have on the event binding.


q:
I use the :e and :w commands to edit and to write a file. I am not sure if there is "close" command to close the current file without leaving Vim?

I know that the :q command can be used to close a file, but if it is the last file, Vim is closed as well; Actually on Mac OS MacVim does quit. Only the Vim window is closed and I could use Control-N to open a blank Vim window again. I would like Vim to remain open with a blank screen.

[A]
If you've saved the last file already, then
```
:enew
```
is your friend (
```
:enew!
```
if you don't want to save the last file). Note that the original file will still be in your buffer list (the one accessible via
```
:ls
```
).


q:
Let's say I have a char* str = "0123456789" and I want to cut the first and the last three letters and print just the middle, what is the simplest, and safest, way of doing it?

Now the trick: The portion to cut and the portion to print are of variable size, so I could have a very long char*, or a very small one.

[A]
You can use
```
printf()
```
, and a special format string:
```
```
char *str = "0123456789";
printf("%.6s\n", str + 1);
```
```
The precision in the
```
%s
```
conversion specifier specifies the maximum number of characters to print.  You can use a variable to specify the precision at runtime as well:
```
```
int length = 6;
char *str = "0123456789";
printf("%.*s\n", length, str + 1);
```
```
In this example, the * is used to indicate that the next argument (
```
length
```
) will contain the precision for the
```
%s
```
conversion, the corresponding argument must be an
```
int
```
.
Pointer arithmetic can be used to specify the starting position as I did above.
[EDIT]
One more point, if your string is shorter than your precision specifier, less characters will be printed, for example:
```
```
int length = 10;
char *str = "0123456789";
printf("%.*s\n", length, str + 5);
```
```
Will print "
```
56789
```
".  If you always want to print a certain number of characters, specify both a minimum field width and a precision:
```
```
printf("%10.10s\n", str + 5);
```
```
or
```
```
printf("%*.*s\n", length, length, str + 5);
```
```
which will print:
```
```
"     56789"
```
```
You can use the minus sign to left-justify the output in the field:
```
```
printf("%-10.10s\n", str + 5);
```
```
Finally, the minimum field width and the precision can be different, i.e.
```
```
printf("%8.5s\n", str);
```
```
will print at most 5 characters right-justified in an 8 character field.


q: I read all over the place about how Spring encourages you to use interfaces in your code. I don't see it. There is no notion of interface in your spring xml configuration. What part of Spring actually encourages you to use interfaces (other than the docs)?

[A]
You may probably want to try using it for yourself to be better able to see this, it may not be clear from the docs how Spring encourages interface use.
Here are a couple of examples:
Say you're writing a class that needs to read from a resource (e.g., file) that may be referenced in several ways (e.g., in classpath, absolute file path, as a URL etc). You'd want to define a
```
org.springframework.core.io.Resource
```
(interface) property on your class. Then in your Spring configuration file, you simply select the actual implementation class (e.g.,
```
org.springframework.core.io.ClassPathResource
```
,
```
org.springframework.core.io.FileSystemResource
```
,
```
org.springframework.core.io.UrlResource
```
etc). Spring is basically functioning as an extremely generic factory.
If you want to take advantage of Spring's AOP integration (for adding transaction interceptors for instance), you'll pretty much need to define interfaces. You define the interception points in your Spring configuration file, and Spring generates a proxy for you, based on your interface.
These are examples I personally have experience with. I'm sure there are much more out there.


q:
I have a windows service connecting to a SqlServer database on the local box.  This works fine most all the time.  At a large customer, however, the database connectivity gets corrupted for some rare and unknown reason.  When this happens, calls to DbDataAdapter.Fill return a DataSet with a different number of columns than in the select command passed in (validated by trace logs showing the sql expected, and the number of columns returned).  For the first few errored DataSets it appears the adapter instance is returning results from the previous query.  This is happening even though the adapter objects are unique instances, and the connection/adapter creation calls are thread protected (as DbProviderFactory is not thread safe).

Has anyone experience this or something similar?  Does anyone know what could cause this?  At this moment in time, I'm having a hard time thinking up new ideas for a cause of this.

[A]
The following should work in your .bash_profile or .bashrc
```
```
case $TERM in
xterm-color)
export PS1='\[\e]0;\W\007\]\[\e[34;1m\]\W\[\e[0m\]\$ '
;;
*)
export PS1='\W\$ '
;;
esac
```
```


q: What tools do you know, other than those in Visual Studio, to analyze performance bottlenecks in a Windows CE/Mobile application? I'm looking for something like AQTime for CE/Mobile, to profile C/C++ applications compiled to native code.

[A]
If you're doing .NET CF development, check out the
Power Toys for .NET CF 3.5
for utilities that can help you pinpoint bottlenecks, especially memory-related ones.


q:
In C++ I'd like to do something like:

int n = get_int_from_user();

char* matrix = new char[n][n];

matrix[0][0] = 'c';
//...
matrix[n][n] = 'a';

delete [][] matrix;

but of course this doesn't work.  What is the best way to do something similar?  I've seen some solutions to this but they seem pretty messy.

[A]
For a true two dimensional array:
```
```
int n = get_int_from_user();

char** matrix = new char*[n];
for (int i = 0; i < n; i++) {
    matrix[i] = new char[n];
}

// Operations on matrix.

for (int i = 0; i < n; i++) {
    delete [] matrix[i];
}
delete matrix;
```
```
Just off the top of my head. Mistakes, no doubt. However, other people have posted a more elegant approach, I think.


q:
I have a class that defines a CallRate type. I need to add the ability to create multiple instances of my class by reading the data from a file.

I added a static method to my class CallRate that returns a List<CallRate>. Is it ok for a class to generate new instances of itself by calling one of its own constructors? It works, I just wonder if it's the proper thing to do.

List<CallRates> cr = CallRates.ProcessCallsFile(file);

[A]
It is perfectly fine to get object(s) of its own from the static method.
e.g.
One of the dot net libraries does the same thing as you did,
```
```
XmlReadrer reader = XmlReader.Create(filepathString);
```
```


q:
For my Django app I have Events, Ratings, and Users. Ratings are related to Events and Users through a foreign keys.  When displaying a list of Events I want to filter the ratings of the Event by a user_id so I know if an event has been rated by the user.

If I do:

event_list = Event.objects.filter(rating__user=request.user.id)

(request.user.id gives the user_id of the current logged in user) ...then I only get the events that are rated by the user and not the entire list of events.

What I need can be generated through the custom SQL:

SELECT *
FROM `events_event`
LEFT OUTER JOIN (
  SELECT *
  FROM `events_rating`
  WHERE user_id = ##
  ) AS temp
ON events_event.id = temp.user_id

Is there an easier way so I don't have to use custom SQL?

[A]
To make best use of Django, you have to avoid trying to do joins.
A "left outer join" is actually a list of objects with optional relationships.
It's simply a list of Events,
```
Event.objects.all()
```
.  Some Event objects have a rating, some don't.
You get the list of Events in your view.  You handle the optional relationships in your template.
```
```
{% for e in event_list %}
    {{ e }}
    {% if e.rating_set.all %}{{ e.rating_set }}{% endif %}
{% endfor %}
```
```
is a jumping-off point.


q:
I'm trying to find some info on the best and most common RESTful url actions.

for example, what url do you use for displaying the details of an item, for editing the item, updating, etc.

/question/show/<whatever>
/question/edit/<whatever>
/question/update/<whatever> (this is the post back url)
/question/list   (lists the questions)

hmm. thanks to anyone helping out :)

[A]
Assuming
```
/questions/10
```
is a valid question then the method is used to interact with it.
POST to add to it
PUT to create or replace it
GET to view/query it
and DELETE to well.. delete it.
The url doesn't change.


q:
In some my project I notice that during executing unit tests under VSTS2008 its VSTestHost's memory consuming grows. As I have very many tests in my solution it leads to OutOfMemroyException eventually.
That looks very strange for me as I was sure that MSTest creates a new AppDomain for each unit test. Otherwise how would it reset static fields?
But if AppDomain is being created for each test than memory shouldn't leak. But it does.

So the question is: Should VS create AppDomain for each test class or not? If yes than how can I check that it does it.
I tried tracing through ProcessExpolorer and Performance snap-in. A value of "Total appdomain unloaded" is always 0 during test run.

[A]
I don't think the unit test engine creates a new AppDomain for each test.  Since creating an AppDomain is a relatively expensive operation, doing so for each test would slow down execution of unit tests considerably!
Visual Studio 2008 uses a seperate executable called vstesthost.exe to run unit tests.  VS communicates with vstesthost.exe (how it does this I don't know) to tell it what tests to run.  vstesthost.exe returns the execution results to VS which displays those results.
If you are getting OutOfMemoryExceptions when running your unit tests I would say that's a strong indicator that your code under test is actually not cleaning things up.  Are you sure that you aren't retaining handles to unmanaged objects/memory?  I would recommend running your unit tests under a Performance Analysis (you can do that by finding the unit test under the "Test View", right-clicking on it, and selecting "Create Performance Session").  This might shed some light at least on your object allocations.


q: In a prior question, I asked about using xbuild to compile a solution file, only to be told it doesn't work for that.  NAnt seems a little out of date.  What other options are there?  I need something that supports dependencies across multiple projects.

[A]
I'm not sure there's only one correct build system to use. :-)
I know that the Mono team uses make to build MonoDevelop and that MonoDevelop uses make under the covers to build projects created by MonoDevelop (
http://tirania.org/blog//texts/md-build.html
).
That said, there's also xBuild (
http://www.mono-project.com/Microsoft.Build
) which is an MSBuild compatible build engine created by the mono team.  That might actually be the best tool as it would allow you to build your projects under Microsoft's .NET platform in addition to Mono.  This link (
http://go-mono.com/forums/#nabble-td15680662
) talks about MD moving towards MSBuild also.


q: I'm using Visual Studio 2008 to develop ASP.NET applications. Currently I'm debugging with running on IIS. I would like to switch to the development web server (Cassini) for debugging, so that I can use features like edit and continue. The reason that I'm not, is because the development web server only starts up when you are in debug mode. Is there any way to keep it running all the time, and just have Visual Studio attach to the existing server process like it does with IIS?

[A]
Once started, the built-in web server continues executing even when you stop debugging, as long as your VS2008 project is still open.  Just start up the debugger when you want to start debugging again.  I typically have another browser window open and interact with the built-in web server from there instead of the browser window that it opens so I can keep working with the application in the same state even after turning off the debugger (which closes the opened browser window).
I'm running VS2008 on Windows XP SP3.


q:
I have a C/C++ application and I need to create a X509 pem certificate containing both a public and private key.  The certificate can be self signed, or unsigned, doesn't matter.

I want to do this inside an app, not from command line.

What OpenSSL functions will do this for me?  Any sample code is a bonus!

[A]
Any chance of doing this via a
```
system
```
call from within your app?  Several good reasons for doing this:
Licensing:  Calling the
```
openssl
```
executable arguably separates it from your application and may provide certain advantages.
Disclaimer: consult a lawyer on this.
Documentation:  OpenSSL comes with
phenomenal
command-line documentation that greatly simplifies a potentially complicated tool.
Testability:  you can exercise OpenSSL from the command line until you understand exactly how to create your certs.  There are a
lot
of options; expect to spend about a day on this until you get all the details right.  After that, it's trivial to incorporate the command into your app.
If you choose to use the API, check the
```
openssl-dev
```
developers' list on www.openssl.org.
Good luck!


q:
When I make a query, I often wonder about this:

Is it better to add extra field(s) to
the table, or just get the values and
calculate in your server side
language?

For example, table Student contains Student.score field. I want to get the grades.

Do I get the score and make a bunch of
if/else/switch for the grades?

Do I waste space by adding a field just to store
something that is dependent on another
field?

The former is annoying to do everytime you need the grades.
The latter scares me when I think of space usage. If I have as small as 10,000 records then I've already wasted 10,000 fields!

Which is the most efficient method, considering non-trivial tables and medium to big database size?

If it matters lets use PHP as the server side language.

[A]
Your data persistence layer should generally not store calculated values that are subject to frequent change. To do so creates the risk of allowing stagnant data to persist within the data store and then affect the business layer which will in turn affect everything else.
Generally speaking you always want to produce calculated values at run-time.
However, I wouldn't worry about a single additional field within the database when determining the best way to address any design issue. Hard drive space is both cheap and plentiful. :-)


q: Is there a fool-proof way to pull out all the risks involved in a project? And does it differ depending on the type of projects your working on (ie: website, client/server...)?

[A]
Definitely no fool-proof way. Whole books have been written on the topic. And speaking of books, I recommend this one:
Software Project Survival Guide by Steve McConnell (I know, crappy image)
alt text http://ecx.images-amazon.com/images/I/41X9bGinoNL._SL500_BO2,204,203,200_AA219_PIsitb-sticker-dp-arrow,TopRight,-24,-23_SH20_OU01_.jpg


q: Is there anything similar to an indexOf function in the NSString objects?

[A]
Use
```
-[NSString rangeOfString:]
```
:
```
```
- (NSRange)rangeOfString:(NSString *)aString;
```
```
Finds and returns the range of the first occurrence of a given string within the receiver.


q: I'm trying to go deep into Dictionary ADT and Skip List for Java. My textbook doesn't cover a lot about this and whatever it has covered is very complicated. Which is the best online site to get more information on Dictionary ADT and Skip List for Java. I'm looking for the one which talks visually and gives a lot of examples.

[A]
Since it sounds like you're in an algorithms class, I would separate the implementation of a dictionary and a skip list from what is provided by the Java API. At this point, it's more important that you understand the concept of what these abstract data types are, because they can be implemented in any language (C#, PHP, Scheme, Brainfuck, etc.)
Your instructor will probably want you to: first, define the interface or contract for a dictionary (or a skip list), and then figure out its implementation. If you're programming in Java, use JUnit to verify the correctness of your algorithms. If you're programming in some other language, look for any xUnit API.
Look in
NIST's Dictionary of Algorithms and Data Structures
as a secondary resource to your textbook to understand what these things mean. Probably the best algorithm book in Java is Sedgewick's, and its main distinctive is its pedagogical use of applets. Since the sample code is not written in idiomatic Java, I wouldn't look there for industrial-strength implementations of the algorithms. After all, you're supposed to do the work yourself, not use someone else's collections API.
Oh, btw, Java 6 has two implementations of skip lists:
```
ConcurrentSkipListSet
```
and
```
ConcurrentSkipListMap
```
. And the interface of a dictionary data structure in Java is
```
Map
```
.


q:
I recently came across the data structure known as a skip list. It seems to have very similar behavior to a binary search tree.

Why would you ever want to use a skip list over a binary search tree?

[A]
From the
Wikipedia
article you quoted:
Θ(n) operations, which force us to visit every node in ascending order (such as printing the entire list) provide the opportunity to perform a behind-the-scenes derandomization of the level structure of the skip-list in an optimal way, bringing the skip list to O(log n) search time. [...]
  A skip list, upon which we have not
  recently performed [any such] Θ(n) operations,
does not
  provide the same absolute worst-case
  performance guarantees as more
  traditional balanced tree data
  structures
, because it is always
  possible (though with very low
  probability) that the coin-flips used
  to build the skip list will produce a
  badly balanced structure
EDIT: so it's a trade-off: Skip Lists use less memory at the risk that they might degenerate into an unbalanced tree.


q:
Anyone know if there is already a validator for "type" strings?

I want to make sure that the type attributes in my custom config are one of the following:

type="TopNamespace.SubNameSpace.ContainingClass, MyAssembly"
type="TopNamespace.SubNameSpace.ContainingClass, MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089"

Writing one is easy enough, I just don't want to reinvent the wheel.

[A]
You'll get an error with resharper's Global Error Analysis if it can't find the namespace or class, but that's not always helpful if your referencing a plugin.
probably the simpliest thing is to put your code to load the app domain in a try catch block.
if the dll is in the bin it will be loaded on startup but it won't throw an error until you use it so if you just new up an instance of ContainingClass. You could pull the namespaces from the config and then try and use each class.


q: Short of using a profiler, is there any way inside a running program to detect first chance exceptions?  Ideally, I would like to record more detailed state information that is not available once the catch block has taken over the final exception.

[A]
I think the only way you can get that information in .NET is using a Debugger.
Otherwise, you'll have to develop a solution yourself for saving the state of a stackframe and having a special way to log exceptions. You'd basically be doing the same things that a memory profiler does, keep track of the instances that are created.  This would be a huge performance hit though unless you limit the amount of information you are logging.
A better solution would be to use the Trace and Assert capabilities in the System.Diagnostics namespace to selectively trace the program state, or to use a logging facility (log4net, EnterpriseLibrary, NLog, roll your own simple one) to dump thread / stack / variable information as you go.
In any case, adding all this extra information is a big overhead.
EDIT: I got news of this project in my feed:
NTrace
.  It looks like it will fit a little more of what you're trying to do.


q:
I have seen samples of closure from - What is a 'Closure'?

Can anyone provide simple example of when to use closure?

Specifically, scenarios in which closure makes sense?

Lets assume that the language doesn't have closure support, how would one still achieve similar thing?

Not to offend anyone, please post code samples in a language like c#, python, javascript, ruby etc.
I am sorry, I do not understand functional languages yet.

[A]
Typically, if one doesn't have closures, one must define a class to carry with it the equivalent of the closure's environment, and pass it around.
For example, in a language like Lisp, one can define a function that returns a function (with a closed-over environment) to add some predefined amount to its argument thusly:
```
```
(defun make-adder (how-much)
  (lambda (x)
    (+ x how-much)))
```
```
and use it like this:
```
```
cl-user(2): (make-adder 5)
#<Interpreted Closure (:internal make-adder) @ #x10009ef272>
cl-user(3): (funcall * 3)     ; calls the function you just made with the argument '3'.
8
```
```
In a language without closures, you would do something like this:
```
```
public class Adder {
  private int howMuch;

  public Adder(int h) {
    howMuch = h;
  }

  public int doAdd(int x) {
    return x + howMuch;
  }
}
```
```
and then use it like this:
```
```
Adder addFive = new Adder(5);
int addedFive = addFive.doAdd(3);
// addedFive is now 8.
```
```
The closure implicitly carries its environment with it; you seamlessly refer to that environment from inside the executing part (the lambda). Without closures you must make that environment explicit.
That should explain to you when you would use closures:
all the time
. Most instances where a class is instantiated to carry with it some state from another part of the computation and apply it elsewhere are elegantly replaced by closures in languages which support them.
One can implement an object system with closures.


q:
I'm trying to set up a loop where an animation runs a certain number of times, and a function is run before each iteration of the animation.  The timing ends up being off, though -- it runs the callback n times, then runs the animation n times. For example:

for (var i=0;i<3;i++) {
  console.log(i);
  $('#blerg').animate({top:'+=50px'},75,'linear', function(){log('animated')});
}

outputs

0
1
2
animated
animated
animated

I ran into this problem with scriptaculous before I switched to jquery, and discovered a "beforeSetup" animation callback.  Is there a jquery equivalent?

[A]
The animation is asynchronous. So the loops runs through pretty quickly, starting off three animations and outputting 1, 2 and 3. After a while the animations complete and output animated x 3. That would explain your output.
How about some recursion?
```
```
do_animation(max_runs, total_runs) {
   log();
   if (total_runs < max_runs) {
       $(foo).animate(..., do_animation(max_runs, ++total_runs));
    }
}
```
```
do_animation(3, 0);
Give that a try and let me know how it runs.


q:
I want to see how long a function takes to run. What's the easiest way to do this in PLT-Scheme? Ideally I'd want to be able to do something like this:

> (define (loopy times)
  (if (zero? times)
      0
      (loopy (sub1 times))))
> (loopy 5000000)
0                      ;(after about a second)
> (timed (loopy 5000000))
Took: 0.93 seconds
0
>

It doesn't matter if I'd have to use some other syntax like (timed loopy 5000000) or (timed '(loopy 5000000)), or if it returns the time taken in a cons or something.

[A]
Found it...
From the
online documentation
:
```
(time-apply proc arg-list)
```
invokes the procedure proc with the arguments in arg-list. Four values are returned: a list containing the result(s) of applying proc, the number of milliseconds of CPU time required to obtain this result, the number of ``real'' milliseconds required for the result, and the number of milliseconds of CPU time (included in the first result) spent on garbage collection.
Example usage:
```
```
> (time-apply loopy '(5000000))
(0)
621
887
0
```
```


q: What is a view in Oracle?

[A]
A
View in Oracle
and in other database systems is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used. For example, if we frequently issue the following query
```
```
SELECT customerid, customername FROM customers WHERE countryid='US';
```
```
To create a view use the
CREATE VIEW command
as seen in this example
```
```
CREATE VIEW view_uscustomers
AS
SELECT customerid, customername FROM customers WHERE countryid='US';
```
```
This command creates a new view called view_uscustomers. Note that this command does not result in anything being actually stored in the database at all except for a data dictionary entry that defines this view. This means that every time you query this view, Oracle has to go out and execute the view and query the database data. We can query the view like this:
```
```
SELECT * FROM view_uscustomers WHERE customerid BETWEEN 100 AND 200;
```
```
And Oracle will transform the query into this:
```
```
SELECT *
FROM (select customerid, customername from customers WHERE countryid='US')
WHERE customerid BETWEEN 100 AND 200
```
```
Benefits of using Views
Commonality of code being used. Since a view is based on one common set of SQL, this means that when it is called it’s less likely to require parsing.
Security. Views have long been used to hide the tables that actually contain the data you are querying. Also, views can be used to restrict the columns that a given user has access to.
Predicate pushing
You can find advanced topics in this article about "
How to Create and Manage Views in Oracle
."


q:
In most versions of windows, you can get to the menu by pressing the F10 key, thus avoiding having to use the mouse.  This behaviour does not appear to be present in Windows Mobile 5.0, but is desirable as the device I am using will be more keyboard than touch screen driven.

Is there a way of programmatically activating and using the menu on Windows Mobile 5.0, under C++ using either MFC or Windows API calls.  I have tried setting the focus of the CFrameWnd and CCeCommandBar classes to no avail.

[A]
After a number of attempts, the following appears to work;
```
```
void CMyFrame::OnFocusMenu()
{
  PostMessage(WM_SYSCOMMAND,SC_KEYMENU,0);
}
```
```
FWIW, none of the following did, where m_wndCommandBar is the CCeCommandBar toolbar containing the menu;
```
```
::SetActiveWindow(m_wndCommandBar.m_hWnd);
m_wndCommandBar.PostMessage(WM_ACTIVATE,WA_ACTIVE,0);
m_wndCommandBar.PostMessage(WM_LBUTTONDOWN,0,0);
m_wndCommandBar.PostMessage(WM_LBUTTONUP,0,0);
m_wndCommandBar.OnActivate(WA_ACTIVE, NULL, FALSE);
m_wndCommandBar.SetFocus();
```
```


q:
We are using Subversion. We would like to

1. search across all commit messages ?
2. monitor the commits on certain important files ?
3. identify files that are never/rarely used ?
4. identify files that are most frequently changed ?
5. identify files that most developers have accessed ?
6. identify files that have been committed together many number of times ?

The usage of these data could be to weed out messages like these, to refactor code and clean up the project of unused files.

Please suggest tools to achieve the same..

EDIT: We run SVN on Windows 2003.

[A]
What platform are you using?  On linux, a quick shell script using
```
sed
```
should do the trick.


q:
In C++, is it safe to extend scope via a reference?

In code, what I mean is:

MyCLass& function badIdea()
{
    MyClass obj1;
    ...
    return obj1;
}

[A]
Please clarify what you do mean.
Assuming you intend to do this:
```
```
int * p = NULL;
{
  int y = 22;
  p = &y;
}
*p = 77; // BOOM!
```
```
Then no, absolutely not, scope does not get extended by having a reference.
You may want to look at smart pointers, e.g. from boost libraries:
clickety


q:
I have a regular expression to match a persons name.

So far I have ^([a-zA-Z\'\s]+)$ but id like to add a check to allow for a maximum of 4 spaces. How do I amend it to do this?

Edit: what i meant was 4 spaces anywhere in the string

[A]
Screw the regex.
Using a regex here seems to be creating a problem for a solution instead of just solving a problem.
This task should be 'easy' for even a novice programmer, and the novel idea of regex has polluted our minds!.
```
```
1: Get Input
2: Trim White Space
3: If this makes sence, trim out any 'bad' characters.
4: Use the "split" utility provided by your language to break it into words
5: Return the first 5 Words.
```
```
ROCKET SCIENCE.
replies
what do you mean screw the regex? your obviously a VB programmer.
  Regex is the most efficient way to work with strings. Learn them.
No. Php, toyed a bit with ruby, now going manically into perl.
There are some thing ( like this case ) where the regex based alternative is computationally and logically exponentially overly complex for the task.
I've parse entire php source files with regex, I'm not exactly a novice in their use.
But there are many cases, such as this, where you're employing a logging company to prune your rose bush.
I could do all steps 2 to 5 with regex of course, but they would be simple and atomic regex, with no weird backtracking syntax or potential for recursive searching.
The steps 1 to 5 I list above have a known scope, known range of input, and there's no ambiguity to how it functions. As to your regex, the fact you have to get contributions of others to write something so simple is proving the point.
I see somebody marked my post as offensive, I am somewhat unhappy I can't mark this fact as offensive to me. ;)
Proof Of Pudding:
```
```
sub getNames{
    my @args = @_;
    my $text = shift @args;
    my $num  = shift @args;

    # Trim Whitespace from Head/End
    $text =~ s/^\s*//;
    $text =~ s/\s*$//;

    # Trim Bad Characters (??)
    $text =~ s/[^a-zA-Z\'\s]//g;

    # Tokenise By Space
    my @words = split( /\s+/, $text );

    #return 0..n
    return @words[ 0 .. $num - 1 ];
} ## end sub getNames

print join ",", getNames " Hello world     this is a    good test", 5;
>> Hello,world,this,is,a
```
```
If there is anything ambiguous to anybody how that works, I'll be glad to explain it to them. Noted that I'm still doing it with regexps. Other languages I would have used their native "trim" functions provided where possible.
Bollocks -->
I first tried this approach. This is your brain on regex. Kids, don't do regex.
This might be a good start
```
```
/([^\s]+
    (\s[^\s]+
      (\s[^\s]+
        (\s[^\s]+
          (\s[^\s]+|)
         |)
       |)
    |)
  )/
```
```
( Linebroken for clarity )
```
```
/([^\s]+(\s[^\s]+(\s[^\s]+(\s[^\s]+|)|)|))/
```
```
( Actual )
I've used
```
[^\s]+
```
here instead of your A-Z combo for succintness, but the point is here the nested optional groups
ie:
```
```
(Hello( this( is( example))))
(Hello( this( is( example( two)))))
(Hello( this( is( better( example))))) three
(Hello( this( is()))))
(Hello( this()))
(Hello())
```
```
( Note: this, while being convoluted, has the benefit that it will match each name into its own group )
If you want readable code:
```
```
$word = '[^\s]+';
  $regex = "/($word(\s$word(\s$word(\s$word(\s$word|)|)|)|)|)/";
```
```
( it anchors around the  (capture|)  mantra of "get this, or get nothing" )


q:
The situation is somewhat like-

var someVar = some_other_function();
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

The problem is that the value of someVar is not visible inside the listener function of the addEventListener, where it is probably being treated as a new variable.

[A]
There is absolutely nothing wrong with the code you've written. Both
```
some_function
```
and
```
someVar
```
should be accessible, in case they were available in the context where anonymous
```
```
function() { some_function(someVar); }
```
```
was created.
Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same
```
someVar
```
variable next to the call to
```
addEventListener
```
)
```
```
var someVar;
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);
```
```


q:
I have extensively used Prototype before and it helped us add considerable interactivity to our web applications. However we are looking at making the move to use jQuery in order to standardize on something better supported in Visual Studio.

I understand that we can use the jQuery.noConflict to run it alongside Prototype, but we would like to avoid having users need to download both libraries to use our website.

So, is there a good resource that can help us move old scripts from Prototype to jQuery?

[A]
I can't really help you too much with your question, other than to say that I haven't heard of any such tool, and that I'd be really surprised if one actually existed.
While I think jQuery is a great library, and that you're right to be wanting to only use one library, just remember that the cost of you changing over all your scripts is going to be many many hours of work. The cost of your users downloading an extra 30kb of scripts is going to be roughly 0.3 seconds. Perhaps try to slowly phase out Prototype and only refactor your existing pages when a) you have to, or b) if you've got nothing better to do.


q:
A few days ago, I asked why its not possible to store binary data, such as a jpg file into a string variable.

Most of the answers I got said that string is used for textual information such as what I'm writing now.

What is considered textual data though? Bytes of a certain nature represent a jpg file and those bytes could be represented by character byte values...I think. So when we say strings are for textual information, is there some sort of range or list of characters that aren't stored?

Sorry if the question sounds silly. Just trying to 'get it'

[A]
Depends on the language. For example in Python string types (str) are really byte arrays, so they can indeed be used for binary data.
In C the NULL byte is used for string termination, so a sting cannot be used for arbitrary binary data, since binary data could contain null bytes.
In C# a string is an array of chars, and since a char is basically an alias for 16bit int, you can probably get away with storing arbitrary binary data in a string. You might get errors when you try to display the string (because some values might not actually correspond to a legal unicode character), and some operations like case conversions will probably fail in strange ways.
In short it might be possible in some langauges to store arbitrary binary data in strings, but they are not designed for this use, and you may run into all kinds of unforseen trouble. Most languages have a byte-array type for storing arbitrary binary data.


q:
A common pattern in C++ is to create a class that wraps a lock - the lock is either implicitly taken when object is created, or taken explicitly afterwards. When object goes out of scope, dtor automatically releases the lock.
Is it possible to do this in C#? As far as I understand there are no guarantees on when dtor in C# will run after object goes out of scope.

Clarification:
Any lock in general, spinlock, ReaderWriterLock, whatever.
Calling Dispose myself defeats the purpose of the pattern - to have the lock released as soon as we exit scope - no matter if we called return in the middle, threw exception or whatnot.
Also, as far as I understand using will still only queue object for GC, not destroy it immediately...

[A]
It's true that you don't know exactly when the dtor is going to run... but, if you implement the IDisposable interface, and then use either a 'using' block or call 'Dispose()' yourself, you will have a place to put your code.
Question: When you say "lock", do you mean a thread lock so that only one thread at a time can use the object? As in:
```
```
lock (_myLockKey) { ... }
```
```
Please clarify.


q: How do you create non scrolling div that looks like the MS Office 2007 ribbon on a web page without two sets of scroll bars. One for the window and one for the div.

[A]
Use a fixed position
```
<div>
```
element, that has 100% width and a high
```
z-index
```
.
You'll also want to ensure that that the start of your scrolling content isn't obscured by the fixed
```
<div>
```
, until you start scrolling down, by putting this in another
```
<div>
```
and positioning this appropriately.
```
```

        HEader content goes here

        Main content goes here

```
```
Note the the height of the first
```
<div>
```
, and the top margin of the second, will need to be adjusted to suit your needs.
P.S. This doesn't work in IE7, for some reason, but it's a good starting point, and I'm sure that you can work out some variation on this theme, that works in the way that you want it to.


q:
In RoR,how to validate a Chinese or a Japanese word for a posting form with utf8 code.

In GBK code, it uses [\u4e00-\u9fa5]+ to validate Chinese words.
In Php, it uses /^[\x{4e00}-\x{9fa5}]+$/u for utf-8 pages.

[A]
Ruby 1.8 has poor support for UTF-8 strings. You need to write the bytes individually in the regular expression, rather then the full code:
```
```
>> "acentuação".scan(/\xC3\xA7/)
=> ["ç"]
```
```
To match the range you specified the expression will become a bit complicated:
```
```
/([\x4E-\x9E][\x00-\xFF])|(\x9F[\x00-\xA5])/  # (untested)
```
```
That will be improved in Ruby 1.9
, though.
Edit:
As noted in the comments, the unicode characters \u4E00-\u9FA5 only map to the expression above in the UTF16-BE encoding. The UTF8 encoding is likely different. So you need to analyze the mapping carefully and see if you can come up with a byte-matching expression for Ruby 1.8.


q:
What, if any, is the performance difference between the following two loops?

for (Object o: objectArrayList) {
    o.DoSomething();
}

and

for (int i=0; i<objectArrayList.size(); i++) {
    objectArrayList.get(i).DoSomething();
}

[A]
From Item 46 in
Effective Java
by Joshua Bloch :
The for-each loop, introduced in
  release 1.5, gets rid of the clutter
  and the opportunity for error by
  hiding the iterator or index variable
  completely. The resulting idiom
  applies equally to collections and
  arrays:
```
```
// The preferred idiom for iterating over collections and arrays
for (Element e : elements) {
    doSomething(e);
}
```
```
When you see the colon (:), read it as
  “in.” Thus, the loop above reads as
  “for each element e in elements.” Note
  that there is no performance penalty
  for using the for-each loop, even for
  arrays. In fact, it may offer a slight
  performance advantage over an ordinary
  for loop in some circumstances, as it
  computes the limit of the array index
  only once. While you can do this by
  hand (Item 45), programmers don’t
  always do so.


q:
How do i backup a SQL database using PHP.

Is there a vendor agnostic way to do this that conforms to ANSI SQL?

If not maybe you can list how to do it for each of the database vendors?

[A]
Every database system comes with some program for dumping its contents.
PostgreSQL:
```
pg_dump
```
MySQL:
```
mysqldump
```
...
You can simply call that program from PHP using
```
system()
```
or
```
shell_exec()
```
.
For example, if you use PostgreSQL with enabled
Ident authentication
and want to dump the Database
```
test
```
directly as SQL text to the browser, it's as simple as:
```
```
<?php
header('Content-type: text/plain');
system('pg_dump test');
?>
```
```
When using MySQL with database user and password stored into
```
~/.my.cnf
```
, it is also very simple:
```
```
<?php
header('Content-type: text/plain');
system('mysqldump test');
?>
```
```
However,
don't do this:
```
```
<?php
header('Content-type: text/plain');
system('mysqldump -utestuser -p
testpassword
test');
?>
```
```
because transmitting a password as command line argument is
very insecure
.


q:
I'm using BizUnit to unit-tests my Biztalk orchestrations, but some orchestrations consume a WebService,and testing these seems more like integration testing than unit testing.

I'm familiar with using a mocking framework to mock the generated proxy objects, in order to test a web service from a Windows Forms application, but I would like to be able to do it in a more integrated way in a request-response port?

How would you approach this problem?

[A]
This is a very interesting question that I still haven't seen a good generic answer to. Some people suggest using SoapUI but I haven't had time to actually test that yet.
This page
might be interesting on that.
Another way might be to somehow wrap the WebDev.WebHost.dll and use that ... Phil Hakkck discusses that in
this post
.
It's also be discussed before on SO
here
.
Please let us know if you find another solution to this!


q:
Does anyone have a recommendation about web service security architecture in Java (preferably under JBoss)?  Any recommended reading?

I want to expose a fairly rich web service to the world but the data are sensitive and it requires authentication from the current client (Flex), accessed via RPC.  I definitely do not want any server-side session state.

What's the best way to go about implementing security through web services in Java/JBoss and where can I read about it?

[A]
For web services security in JBoss, I would start by reading
8.4 WS-Security
of the
JBossWS User Guide
.


q: In the C language, using keyboard interrupt, how can I display an alternate key from what the user typed? E.g., when I press 'Q' on the keyboard, then the screen should display 'A'.

[A]
We need a little more information about Your environment.
As far as I understand Your question, You want to replace the
keyboard interrupt handler with Your own in this way:
Save the entry address of the original keyboard handler.
Install Your own that calls the original and manipulates the keycode value.
However, on most modern operating systems it is much easier to define and install a new keyboard layout.


q:
Is there a way of getting the websites absolute URL (http://www.domain.com/) using Java? because I've googled a bit but I only come across with having to make 2 or 3 classes to create that function =/

Update:

The thing is I am trying to create a crawler that will give me some information and among that I'd like to get the URL of the webpage it's getting the information from. I'm developing this in JAVA and what I meant to say was that I was wondering if there was some getUrl(); or any method like that to get me the Url, because I know it can be done but I've only done it writing a whole other class to retrieve the url and then inherit it and use it further...hope it made it clearer

[A]
The question is not really clear, but I'll make the assumption that you are trying to get the path from within a Servlet.
```
```
String realPath = getServletConfig().getServletContext().getRealPath(relativePath);
```
```


q:
I'm new to PHP and before I waste a lot of time doing things the hard way, I wanted to find out if there are shortcuts/techniques to creating PHP web forms apps.  All this app will do is display web forms with data from 1 or more tables.  In addition to displaying data, the user must be able to update the form and add new data to the forms.  I know how to to do all this by manually writing all the PHP/HTML code.  But I'm looking for anything that can save me time.

Unfortunately, I can't use any of the fancy PHP libraries such as CakePHP for this.   I'm restricted to using the core PHP framework, Oracle for the database and the OCI library for Oracle access.

Given these constraints, what the easiest way to support CRUD operations in a basic PHP forms app?  Are there code generators or other tools that can help?

[A]
Unfortunately, I can't use any of the fancy PHP libraries such as CakePHP for this. I'm restricted to using the core PHP framework,
Most PHP frameworks are written in PHP. So you wouldn't have to install anything to use them.
That said, forms are rather non-trivial. Treating a form as a separate component only works to some extend. Because of that, many frameworks have forms deeply integrated into them, and not as a standalone component.
You could take a peek at Zend Framework's (now known as
Laminas
)
Form component
. It's fairly self-sufficient and feature-rich.


q:
Is there a way to persist an enum to the DB using NHibernate? That is have a table of both the code and the name of each value in the enum.

I want to keep the enum without an entity, but still have a foreign key (the int representation of the enum) from all other referencing entities to the enum's table.

[A]
An easy but not so beautiful solution:
Create an integer field with and set the mapping in the mapping file to the field.
Create a public property that uses the integer field.
```
```
private int myField;
public virtual MyEnum MyProperty
{
   get { return (MyEnum)myField; }
   set { myField = value; }
}
```
```


q: I want to do this using the Math.Round function

[A]
Try this:
```
```
twoDec = Math.Round(val, 2)
```
```


q:
I have been searching for recent performance benchmarks that compare L2S and EF and couldnt find any that tested calling stored procedures using the released version of EF. So, I ran some of my own tests and found some interesting results.

Do these results look right? Should I be testing it in a different way?

One instance of the context, one call of the sproc:
(dead link)

One instance of the context, multiple calls of the same sproc:
(dead link)

Multiple instances of the context, multiple calls of the same sproc:
(dead link)

[A]
I think you should test it in a somewhat different way, in order to distinguish
startup costs vs. execution costs
.  The Entity Framework, in particular, has substantial
startup costs resulting from the need to compile database views
(although you can do this in advance).  Likewise, LINQ has a notion of a
compiled query
, which would be appropriate if executing a query multiple times.
For many applications, query execution costs will be more important than startup costs.  For some, the opposite may be true.  Since the performance characteristics of these are different, I think it's important to distinguish them.  In particular, averaging startup costs into the average cost of a query executed repeatedly is misleading.


q:
Writing something like this using the loki library,

typedef Functor<void> BitButtonPushHandler;

throws a compiler error, but this works

typedef Functor<void,TYPELIST_1(Matrix3D*)> Perspective;

Functor.h:530: error: '((Loki::FunctorHandler, int>*)this)->Loki::FunctorHandler, int>::f_' cannot be used as a function
  Functor.h:530: error: return-statement with a value, in function returning 'void'

Anyone familiar with this library know how to get the first line working?

[A]
Looking at the source code, the Functor template definition is as follows:
```
```
template <typename R = void, class TList = NullType,
        template<class, class> class ThreadingModel = LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL>
    class Functor{...};
```
```
As commented below, there are no template typedefs allowed, so all types (or accept all defaults) need to be specified.
You can just define as follows and let the defaults do the work:
```
```
typedef Functor<> BitButtonPushHandler;
```
```
This compiles for me with a small test Functor class (not the actual Loki one), and I can use the typedef successfully.


q:
Say you have a string, but you don't know what it contains. And you want to replace all occurences of a particular word or part of a word with a formatted version of the same word.
For example, I have a string that contains "lorem ipsum" and i want to replace the entire word that contains "lo" with "lorem can" so that the end result would be "lorem can ipsum"
but if I put the string "loreal ipsum" through the same function, the result would now be "loreal can ipsum".
Thanks

[A]
```
$str = preg_replace('/lo(\w*)/', 'lo$1 can', $str);
```
This replaces "lo" plus any word characters with "lo" + the other characters + " can"
It will also replace "lo" with "lo can" - if you don't want this, change
```
\w*
```
to
```
\w+
```


q:
I understand that using the "===" compares type, so running the following code results in "not equal" because it's comparing a number type to a string type.

var a = 20;
var b = "20";
    if (a === b) {
        alert("They are equal");
    } else {
        alert("They are not equal");
}

But I dont understand how using the "==" to compare only the value results in the "They are equal" message.

var a = 20;
var b = "20";
    if (a == b) {
        alert("They are equal");
    } else {
        alert("They are not equal");
}

How are the values equal? Isn't the string "20" stored as the ASCII characters 50 and 48 (0110010 and 0110000 in binary) and 20 stored as the actual binary number 0010100?

EDIT: Thanks everyone! I think all the responses are great and have helped me understand this much better.

[A]
The
```
==
```
operator compares only the values of the variables. If the types are different, a conversion is operated. So the number 20 is converted to the string "20" and the result is compared.
The
```
===
```
operator compares not only the values, but also the types, so no cast is operated. In this case
```
"20" !== 20
```


q:
I have a JavaScript snippet that runs very well on Firefox and Safari, but refuses to run on IE:

var drop= function(id)
{
   if(document.getElementById("select1").value == "Ficha de pediatria"){
    top.location.href = "print.jsp?id="+id+"&type=2";
   }
   else if(document.getElementById("select1").value == "Ficha normal"){
        top.location.href = "print.jsp?id="+id+"&type=1";
   }
}

<select id="select1" name="select1" onChange="drop(id);return false;">
<option>Imprimir:</option>
<option>Ficha de pediatria</option>
<option>Ficha normal</option>
</select>

I trimed this as it had more JSP code but it' remained the same. Anyone got any idea why it's not running on IE?

[A]
[EDIT]  Sorry.  I introduced an error with my first post by not carefully looking at how you are constructing your url.  I shouldn't have removed the
```
id
```
parameter.  I've updated the code and it should work now.
Try this instead:
```
```
function drop(ctl,id)
{
   var value = ctl.options[ctl.selectedIndex].value;

   if(value == "Ficha de pediatria"){
       window.top.location.href = "print.jsp?id="+id+"&type=2";
   }
   else if (value == "Ficha normal"){
       window.top.location.href = "print.jsp?id="+id+"&type=1";
   }
}

<select id="select1" name="select1" onChange="drop(this,id);return false;">
<option>Imprimir:</option>
<option>Ficha de pediatria</option>
<option>Ficha normal</option>
</select>
```
```
[EDIT] A bit of explanation...
I think the issue is how it is accessing the DOM.  I don't think that IE has a value property on a select.  I think you have to get at it via the selected option.  Also, I'm not sure that there is a top property in the global namespace, but you should be able to get at it via
```
window.top
```
to set the location.  Finally, I made a slight improvement in that by specifying
```
this
```
as the argument, you can skip the element lookup and reference it directly from the control passed as the argument.


q: How do I clear the cin buffer in C++?

[A]
The following should work:
```
```
cin.flush();
```
```
On some systems it's not available and then you can use:
```
```
cin.ignore(INT_MAX);
```
```


q:
Given the following table, how does one calculate the hourly mode, or value with the highest frequency by hour?

CREATE TABLE Values
(
    ValueID int NOT NULL,
    Value int NOT NULL,
    LogTime datetime NOT NULL
)

So far, I've come up with the following query.

SELECT count(*) AS Frequency,
DatePart(yy, LogTime) as [Year],
DatePart(mm, LogTime) as [Month],
DatePart(dd, LogTime) as [Day],
DatePart(hh, LogTime) as [Hour]
FROM Values
GROUP BY
Value,
DatePart(yy, LogTime),
DatePart(mm, LogTime),
DatePart(dd, LogTime),
DatePart(hh, LogTime)

However, this yields the frequency of each distinct value by hour. How do I add a constraint to only return the value with the maximum frequency by hour?

Thanks

[A]
Nest the aggregates...
```
```
SELECT
    MAX(Frequency) AS [Mode],
    [Year],[Month],[Day],[Hour]
FROM
    (SELECT
         COUNT(*) AS Frequency,
         DatePart(yy, LogTime) as [Year],
         DatePart(mm, LogTime) as [Month],
         DatePart(dd, LogTime) as [Day],
         DatePart(hh, LogTime) as [Hour]
    FROM
         Values
    GROUP BY
         Value,
         DatePart(yy, LogTime),
         DatePart(mm, LogTime),
         DatePart(dd, LogTime),
         DatePart(hh, LogTime)
    ) foo
GROUP By
    [Year],[Month],[Day],[Hour]
```
```