Question:
Does anyone use Accurev for Source Control Management? We are switching (eventually) from StarTeam to Accurev.

My initial impression is that the GUI tool is severely lacking, however the underlying engine, and the branches as streams concept is incredible.

The biggest difficulty we are facing is assessing our own DIY tools that interfaced with starteam, and either replacing them with DIY new tools, or finding and purchasing appropriate replacements.

Additionally, is anyone using the AccuWork component for Issue management? Starteam had a very nice change request system, and AccuWork does not come close to matching it. We are evaluating either using Accuwork, or buying a 3rd party package such as JIRA.

Opinions?

Answer:
At a previous employer we reviewed Accurev and Plastic SCM. At the end of the day, I was not impressed with Accurev's interface, or the so-called "streams". We went with Plastic, and nobody complained.
@Jonathan
The streams are interesting,but I don't see how any version control can magically avoid collisions when two people touch the same code in the same file. Accurev's model was intriguing, but at the end of the day, nice clean branching and merging with a drop dead easy interface made Plastic the choice for us. Plastic's timeline view (I forget the actual name), showing the branch/merge/check-in history made it very simple to review the history of the project from a bird's eye view.


Question:
In my code behind I wire up my events like so:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    btnUpdateUser.Click += btnUpateUserClick;
}

I've done it this way because that's what I've seen in examples.

Does the base.OnInit() method need to be called?

Will it be implicitly be called?

Is it better to call it at the beginning of the method or at the end?

What would be an example where confusion over the base method can get you in trouble?

Answer:
In this case, if you don't call the base OnInit, then the Init even will not fire.
In general, it is best practice to ALWAYS call the base method, unless you specifically know that you do not want the base behaviour to occur.
Whether its called at the start or the end depends on how you want things to work. In a case like this, where you are using an override instead of hooking up an event handler, calling it at the start of the method makes more sense. That way, your code will run after any handlers, which makes it more emulate a "normal" event handler.


Question:
I'd like to use a database to store i18n key/value pairs so we can modify / reload the i18n data at runtime. Has anyone done this? Or does anyone have an idea of how to implement this? I've read several threads on this, but I haven't seen a workable solution.

I'm specifically refering to something that would work with the jstl tags such as

<fmt:setlocale>
<fmt:bundle>
<fmt:setBundle>
<fmt:message>

I think this will involve extending ResourceBundle, but when I tried this I ran into problems that had to do with the way the jstl tags get the resource bundle.

Answer:
Are you just asking how to store UTF-8/16 characters in a DB? in mysql it's just a matter of making sure you build with UTF8 support and setting that as the default, or specifying it at the column or table level. I've done this in oracle and mysql before. Create a table and cut and paste some i18n data into it and see what happens... you might be set already..
or am I completely missing your point?
edit:
to be more explicit... I usually implement a three column table... language, key, value... where "value" contains potentially foreign language words or phrases... "language" contains some language key and "key" is an english key (i.e. login.error.password.dup)... language and key are indexed...
I've then built interfaces on a structure like this that shows each key with all its translations (values)... it can get fancy and include audit trails and "dirty" markers and all the other stuff you need to enable translators and data entry folk to make use of it..
Edit 2:
Now that you added the info about the JSTL tags, I understand a bit more... I've never done that myself.. but I found this old info on
theserverside
...
```
```
HttpSession session = .. [get hold of the session]
ResourceBundle bundle = new PropertyResourceBundle(toInputStream(myOwnProperties)) [toInputStream just stores the properties into an inputstream]
Locale locale = .. [get hold of the locale]
javax.servlet.jsp.jstl.core.Config.set(session, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle ,locale));
```
```


Question:
I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.

For example:

original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])

Is there a builtin function that does that?

Answer:
```
zip
```
is its own inverse! Provided you use the special * operator.
```
```
>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
```
```
The way this works is by calling
```
zip
```
with the arguments:
```
```
zip(('a', 1), ('b', 2), ('c', 3), ('d', 4))
```
```
… except the arguments are passed to
```
zip
```
directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big.


Question:
I've heard rumors that PHP is planning on introducing a "goto" command. What is it supposed to be doing?

I've tried searching a bit, but haven't found anything awfully descriptive. I understand that it won't be a "GOTO 10"-like command...

Answer:
Granted, I am not a PHP programmer, and I don't know what PHP's exact implementation of GOTO will look like, but here is my understanding of GOTO:
GOTO is just a more explicit flow control statement like any other. Let's say you have some nested loops and you only need to find one thing. You can put in a conditional statement (or several) and when conditions are met properly, you can use a GOTO statement to get out of all the loops, (instead of having a 'break' statement at each level of nesting with a conditional statement for each. And yes, I believe the traditional implementation is to have named labels that the GOTO statement can jump to by name. You can do something like this:
```
```
for(...) {
    for (...) {
        for (...) {
        // some code
        if (x) GOTO outside;
        }
    }
}
:outside
```
```
This is a simpler (and more efficient) implementation than without GOTO statements. The equivalent would be:
```
```
for(...) {
    for (...) {
        for (...) {
            // some code
            if (x) break;
        }
        if(x) break;
    }
    if(x) break;
}
```
```
In the second case (which is common practice) there are three conditional statements, which is obviously slower than just having one. So, for optimization/simplification reasons, you might want to use GOTO statements in tightly nested loops.


Question: How can I request a random row (or as close to truly random as is possible) in pure SQL?

Answer:
I don't know how efficient this is, but I've used it before:
```
```
SELECT TOP 1 * FROM MyTable ORDER BY newid()
```
```
Because GUIDs are pretty random, the ordering means you get a random row.


Question:
I have a datalist with a OnDeleteCommand="Delete_Command".

I want the delete a record with multiple primary Keys but I do not know how to access it from the Delete_Command event.

If I use DataKeyField I'm limited to only one key.
Any workarounds for this?

Answer:
You can access all of the keys:
```
```
gridView.DataKeys[rowNum][dataKeyName]
```
```
where rowNum is e.RowIndex from the gridView_RowDeleting event handler, and dataKeyName is the key you want to get:
```
```
<asp:GridView ID="gridView" runat="server" DataKeyNames="userid, id1, id2, id3" OnRowDeleting="gridView_RowDeleting">

protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    gridView.DataKeys[e.RowIndex]["userid"]...
    gridView.DataKeys[e.RowIndex]["id1"]...
    gridView.DataKeys[e.RowIndex]["id2"]...
    gridView.DataKeys[e.RowIndex]["id3"]...
}
```
```


Question:
How can I create this file in a directory in windows 2003 SP2:

.hgignore

I get error: You must type a file name.

Answer:
That's a "feature" of Windows Explorer. Try to create your files from a command line (or from a batch/program you wrote) and it should work fine. Try this from a dos prompt:
```
```
echo Hello there! > .hgignore
```
```


Question:
I have a standard HTML image tag with an image in it, 100 by 100 pixels in size. I want people to be able to click the image and for that to pass the X and Y that they click into a function.

The coordinates need to be relative to the image top and left.

Answer:
I think you're talking about:
```
```
<input id="info" type="image">
```
```
When submitted, there are form values for the x and y coordinate based on the input element id (
```
info.x
```
and
```
info.y
```
in this case).
http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.4.1


Question: How can I check file permissions, without having to run operating system specific command via passthru() or exec()?

Answer:
What do you want to do by checking file permissions?
When writing secure code, it's almost always incorrect to "check, then do" anything.  The reason is that between the checking whether you can do something and actually doing it, the state of the system could change such that doing it would have a different result.
For example, if you check whether a file exists before writing one, don't check whether you wrote the file successfully (or don't check in a detailed-enough fashion), and then later depend on the contents of the file you wrote, you could actually be reading a file written by an attacker.
So instead of checking file permissions, just do whatever it was you were going to do if the permissions check succeeded, and handle errors gracefully.


Question:
I was reading the example chapter from the book by Ayende and on the website of the Boo language I saw a reference to the Specter BDD Framework.

I am wondering if anybody is using it in their project, how that works out and if there are more examples and/or suggested readings.

Just in case you are wondering, I'm a C# developer and so I plan to use it in a C#/.NET environment.

A few year later visiting this question. I think we can safely assume Specflow and some others like NSpec became the tools we are using.

Answer:
Create one Message table, containing a unique MessageId and the various properties you need to store for a message.
```
```
Table: Message
Fields: Id, TimeReceived, MessageDetails, WhateverElse...
```
```
Create two link tables - QuoteMessage and JobMessage. These will just contain two fields each, foreign keys to the Quote/Job and the Message.
```
```
Table: QuoteMessage
Fields: QuoteId, MessageId

Table: JobMessage
Fields: JobId, MessageId
```
```
In this way you have defined the data properties of a Message in one place only (making it easy to extend, and to query across all messages), but you also have the referential integrity linking Quotes and Jobs to any number of messages. Indeed, both a Quote and Job could be linked to the
same
message (I'm not sure if that is appropriate to your business model, but at least the data model gives you the option).


Question:
I have an Interface called IStep that can do some computation (See "Execution in the Kingdom of Nouns"). At runtime, I want to select the appropriate implementation by class name.

// use like this:
IStep step = GetStep(sName);

Answer:
If the implementation has a parameterless constructor, you can do this using the System.Activator class. You will need to specify the assembly name in addition to the class name:
```
```
IStep step = System.Activator.CreateInstance(sAssemblyName, sClassName).Unwrap() as IStep;
```
```
http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx


Question:
To grab the inode of a file in PHP, you can use this:

$fs = stat($file);
echo $fs['ino'];

The problem with this is EVERYWHERE says it's slow and you should avoid it.  So the question becomes what's the fast(er) way to do it?

Answer:
You could use
```
fileinode()
```
but you should run benchmarks if you think it is slow.


Question:
I'm leading a project where we'll be recording metrics data. I'd like to retain the data for years. However, I'd also like to keep the primary table from becoming bloated with data that, while necessary for long term trending, isn't required for short term reporting.

What is the best strategy for handling this situation? Simply archive the old data to another table? Or "roll it up" via some consolidation of the data itself (and then store it off to a different table)? Or something else entirely?

Additional info: we are using SQL Server 2005.

Answer: Either of those options are excellent, but it really depends on the problem domain. For things like cash balances or statistical data, I think that rolling up records and consolidating them is the best way, you can then move the rolled up records into a parallel archive table, keying them in such a way that you can "unroll" if necessary. This keeps your primary data table clean and quick, but allows you to retain the extra data for auditing or whatever. The key question is, how do you implement the "roll-up" process. Either automatically, via a trigger or server side process, or by user intervention at the application level?


Question:
What would be the best way to have a list of items with a checkbox each in Java Swing?

I.e. a JList with items that have some text and a checkbox each?

Answer:
I'd probably be looking to use a
JTable
rather than a
JList
and since the default rendering of a checkbox is rather ugly, I'd probably be looking to drop in a custom
TableModel
,
CellRenderer
and
CellEditor
to represent a boolean value. Of course, I would imagine this has been done a bajillion times already. Sun has
good examples
.


Question:
I have a huge web app that is having issues with memory leak in IE 6.

Fixing a memory leak in a 5 line code sample that demonstrates the problem is easy.

But if I have a very huge application, where should a start from?

Answer:
Check out
Drip
.  That usually takes the guesswork out of IE memory leaks.
If for some reason Drip doesn't find it, take a close look at any JavaScript code that works with events.  That is almost always the source of any significant memory leak in a browser.
Destroying a DOM element with handlers attached to it, without removing those handlers first, will prevent the memory associated with those handlers from being recovered.


Question: By default each row of a Gridview maps to each row in a datatable or dataset attached to its datasource. But what if I want to display these rows in multiple columns. For example if it has 10 rows, 5 rows each should be displayed in 2 columns side by side. Also can I do this with the Infragistics grid. Is this possible?

Answer:
You can use a
```
DataList
```
control instead. It has a
```
RepeatColumns
```
property that you can define the number of columns you want to display.
In .NET Framework 3.5, there is an even better solution, the
```
ListView
```
control. You can find further information about how to use the ListView control
here
.


Question:
I just wonder what options there are to properly measure/profile/optimize ASP.net 2.0 Web Parts, especially the ones for Sharepoint 2007?

As Web Parts are a layer on another layer of technology, getting resource usage, open handles and stuff only for the web part seems to be a bit difficult.

Does anyone know some good tools or practices for profiling and optimizing web parts?

Answer: I have found seperating out all the business logic in to a seperate DLL that is easily unit testable has been the easiest method for me.  But to be honest there is really no good way that I have found, besides what I have just mentioned.  The same has been true for me with Facebook applications recently.  I think this is common for any application that runs inside of another platform.  Especially when performance and testing where never a goal when the platform developers started to build the system.


Question:
I've been trying to understand how Ruby blocks work, and to do that I've been trying to implement them in C.

One easy way to implement closures is to pass a void* to the enclosing stack to the closure/function but Ruby blocks also seem to handle returns and break statements from the scope that uses the block.

loop do
  break i if (i >= 4000)
  i *= 2
end

I think one of the closures proposals for Java works like this also.

So, how would you implement Ruby-blocks/Java-closures in C?

Answer:
The concept of closures requires the concept of contexts. C's context is based on the stack and the registers of the CPU, so to create a block/closure, you need to be able to manipulate the stack pointer in a correct (and reentrant) way, and store/restore registers as needed.
The way this is done by interpreters or virtual machines is to have a
```
context
```
structure or something similar, and not use the stack and registers directly. This structure keeps track of a stack and optionally some registers, if you're designing a register based VM. At least, that's the simplest way to do it (though slightly less performant than actually mapping things correctly).


Question:
If you have two versions of the same report (.rpt) and you want to establish what the exact differences are, what is the best way to go about this? I've seen some commercial tools to do this, but I'm not too interested in forking out cash for something that should be relatively straight forward. Can I hook into the Crystal API and simply list all of the properties of every field or something? Please someone tell me that there's an Open Source project somewhere that does this... @:-)

@Kogus, wouldn't diffing the outputs as text hide any formatting differences?

@ladoucep, I don't seem to be able to export the report without data.

Answer:
One helpful technique is to output both versions of the report to plain text, then diff those outputs.
You could write something using the crystal report component to describe every property of the report, like you described.  Then  you could output
that
to text, and diff
those
.  I'm not aware of any open source tool that does it for you, but it would not be terribly hard to write it.
@question in the post:
Diffing the outputs would only show formatting changes if the
relative
positions had changed.  For example, if i had this:
before:
First name, last name, addresss
after:
Last Name, First Name, Address
Then that would show up as a difference.
But if I had just bumped the address column over a few pixels, or changed it from plain text to bold, then you are right, that would not show up.


Question:
What is the best way to manage a list of windows (keeping them in order) to be able to promote the next window to the top-level when the current top-level window is closed.

This is for a web application, so we're using jQuery Javascript.

We'd talked through a few simplistic solutions, such as using an array and just treating [0] index as the top-most window.

I'm wondering if there's any potentially more efficient or useful alternative to what we had brainstormed.

Answer:
One helpful technique is to output both versions of the report to plain text, then diff those outputs.
You could write something using the crystal report component to describe every property of the report, like you described.  Then  you could output
that
to text, and diff
those
.  I'm not aware of any open source tool that does it for you, but it would not be terribly hard to write it.
@question in the post:
Diffing the outputs would only show formatting changes if the
relative
positions had changed.  For example, if i had this:
before:
First name, last name, addresss
after:
Last Name, First Name, Address
Then that would show up as a difference.
But if I had just bumped the address column over a few pixels, or changed it from plain text to bold, then you are right, that would not show up.


Question:
I'm currently looking at the Python framework Django for future db-based web apps as well as for a port of some apps currently written in PHP. One of the nastier issues during my last years was keeping track of database schema changes and deploying these changes to productive systems. I haven't dared asking for being able to undo them too, but of course for testing and debugging that would be a great feature. From other questions here (such as this one or this one), I can see that I'm not alone and that this is not a trivial problem. Also, I found many inspirations in the answers there.

Now, as Django seems to be very powerful, does it have any tools to help with the above? Maybe it's even in their docs and I missed it?

Answer:
Last time I checked (version 0.97), syncdb will be able to add tables to sync your DB schema with your models.py file, but it cannot:
Rename or add a column on a populated DB. You need to do that by hand.
Refactorize your model (like split a table into two) and repopulate your DB accordingly.
It might be possible though to write a Django script to make the migration by playing with the two different
managers
, but that might take ages if your DB is large.


Question:
Thinking about getting into .net technology project management

I've had plenty of experience with PHP projects: I'm aware of most of the existing frameworks and libraries, and I've written specs and case studies based on this knowledge.

What should I know about .net?
Which top resources would you recommend me to know so I can rapidly learn and later stay up to date on the technology?

Edit (8.24.08): The answers I got so far essentially discuss being a good PM. Thanks, but this is not what I meant. Any .net essentials would be appreciated.

Answer:
Start with the basics before you get to the higher level stuff like web services (though that is important too). The most important things you need to learn, as a project manager, are the things you're going to be questioning your underlings about later. For example, my PM (also a PHP guy) has absolutely no knowledge of garbage collection and its implications, which makes it incredibly difficult for me to explain to him why our .NET Windows service appears to be taking 80MB of RAM.
Remember, you are not the one who needs to know everything. You should be issuing overarching directives, and let the people with the expertise sort out the details. That said, study up on the technicals a bit so that they can communicate effectively with you.
Edit (8/24/08):You should know something about the underlying technicals; not necessarily all .NET stuff either (garbage collection, .config files, pipes and services if you're running services adjacent to your project's main focus, stuff like that). Higher-reaching concepts would probably include WPF (maybe Silverlight as well), LINQ (or your ORM of choice), as well as the Vista bridge and related bridging code if your project includes desktop apps at all. Those three things seem to be the focus for this round of .NET. Something else that's very important to have at least a passing knowledge of is the ways that .NET code can/must interoperate with native code: P/Invoke, Runtime Callable Wrapping and COM Callable Wrapping. There are still a lot of native things that don't have a .NET equivalent.
As for resources, I'd highly recommend MSDN Magazine. They tend to preview upcoming technologies and tools well before average developers will ever see them.


Question:
What languages and tools do you consider a youngster starting out in programming should use in the modern era?

Lots of us started with proprietary Basics and they didn't do all of us long term harm :) but given the experiences you have had since then and your knowledge of the domain now are there better options?

There are related queries to this one such as "Best ways to teach a beginner to program?" and "One piece of advice" about starting adults programming both of which I submitted answers to but children might require a different tool.

Disclosure:  it's bloody hard choosing a 'correct' answer to a question like this so who ever has the best score in a few days will get the 'best answer' mark from me based on the communities choice.

Answer:
I recently saw a presentation about
GreenFoot
(a java based learning environment for children). It looked awesome. If I would have kids, I would give it a try
Link to the presentation
It is a very playful environment, where you could start with very basic methods. The kids learn thinking in an object oriented way (you cannot instantiate an animal, but you can instantiate a cat). And the better they get, the more of Java you can uncover for/with them.


Question:
I've recently taken up learning some C# and wrote a Yahtzee clone.  My next step (now that the game logic is in place and functioning correctly) is to integrate some method of keeping stats across all the games played.

My question is this, how should I go about storing this information?  My first thought would be to use a database and I have a feeling that's the answer I'll get... if that's the case, can you point me to a good resource for creating and accessing a database from a C# application?

Storing in an XML file actually makes more sense to me, but I thought if I suggested that I'd get torn apart ;).  I'm used to building web applications and for those, text files are generally frowned upon.

So, going with an XML file, what classes should I be looking at that would allow for easy manipulation?

Answer:
A database may be overkill - have you thought about just storing the scores in a file?
If you decide to go with a database, you might consider
SQLite
, which you can distribute just like a file. There's an open source .NET provider -
System.Data.SQLite
- that includes everything you need to get started.
Accessing and reading from a database in .NET is quite easy - take a look at
this question
for sample code.


Question: What's the easiest, tersest, and most flexible method or library for parsing Python command line arguments?

Answer:
Use
```
optparse
```
which comes with the standard library. For example:
```
```
#!/usr/bin/env python
import optparse

def main():
  p = optparse.OptionParser()
  p.add_option('--person', '-p', default="world")
  options, arguments = p.parse_args()
  print 'Hello %s' % options.person

if __name__ == '__main__':
  main()
```
```
Source:
Using Python to create UNIX command line tools
However as of Python 2.7 optparse is deprecated, see:
Why use argparse rather than optparse?


Question:
This line in YUI's Reset CSS is causing trouble for me:

address,caption,cite,code,dfn,em,strong,th,var {
    font-style: normal;
    font-weight: normal;
}

It makes my em not italic and my strong not bold. Which is okay. I know how to override that in my own stylesheet.

strong, b
{
  font-weight: bold;
}

em, i
{
  font-style: italic;
}

The problem comes in when I have text that's both em and strong.

<strong>This is bold, <em>and this is italic, but not bold</em></strong>

My rule for strong makes it bold, but YUI's rule for em makes it normal again. How do I fix that?

Answer:
If your strong declaration comes after YUI's yours should override it. You can force it like this:
```
```
strong, b, strong *, b * { font-weight: bold; }
em, i, em *, i * { font-style: italic; }
```
```
If you still support IE7 you'll need to add
```
!important
```
.
```
```
strong, b, strong *, b * { font-weight: bold !important; }
em, i, em *, i * { font-style: italic !important; }
```
```
This works - see for yourself:
```
```
/*YUI styles*/
address,caption,cite,code,dfn,em,strong,th,var {
  font-style: normal;
  font-weight: normal;
}
/*End YUI styles =*/

strong, b, strong *, b * {
  font-weight: bold;
}

em, i, em *, i * {
  font-style: italic;
}
```
```
```
```
Bold - Italic - Bold and Italic
```
```


Question:
I'm working on a projects which involves a lot of database writes, I'd say (70% inserts and 30% reads).  This ratio would also include updates which I consider to be one read and one write.  The reads can be dirty (e.g. I don't need 100% accurate information at the time of read).

The task in question will be doing over 1 million database transactions an hour.

I've read a bunch of stuff on the web about the differences between MyISAM and InnoDB, and MyISAM seems like the obvious choice to me for the particular database/tables that I'll be using for this task.  From what I seem to be reading, InnoDB is good if transactions are needed since row level locking is supported.

Does anybody have any experience with this type of load (or higher)?  Is MyISAM the way to go?

Answer:
I'm not a database expert, and I do not speak from experience. However:
MyISAM tables use table-level locking
. Based on your traffic estimates, you have close to 200 writes per second. With MyISAM,
only one of these could be in progress at any time
. You have to make sure that your hardware can keep up with these transaction to avoid being overrun, i.e., a single query can take no more than 5ms.
That suggests to me you would need a storage engine which supports row-level locking, i.e., InnoDB.
On the other hand, it should be fairly trivial to write a few simple scripts to simulate the load with each storage engine, then compare the results.


Question:
Is there an easy way in C# to create Ordinals for a number? For example:

1 returns 1st

2 returns 2nd

3 returns 3rd

...etc

Can this be done through String.Format() or are there any functions available to do this?

Answer:
You'll have to roll your own. From the top of my head:
```
```
public static string Ordinal(this int number)
{
  var work = number.ToString();
  if ((number % 100) == 11 || (number % 100) == 12 || (number % 100) == 13)
    return work + "th";
  switch (number % 10)
  {
    case 1: work += "st"; break;
    case 2: work += "nd"; break;
    case 3: work += "rd"; break;
    default: work += "th"; break;
  }
  return work;
}
```
```
You can then do
```
```
Console.WriteLine(432.Ordinal());
```
```
Edited for 11/12/13 exceptions. I DID say from the top of my head  :-)
Edited for 1011 -- others have fixed this already, just want to make sure others don't grab this incorrect version.


Question: Anyone have any good urls for templates or diagram examples in Visio 2007 to be used in software architecture?

Answer:
There should be templates already included in Visio 2007 for software architecture but you might want to check out
Visio 2007 templates
.


Question:
I'm packaging up a .NET 2.0 based web app for deployment through a Windows Installer based package.  Our app uses Report Viewer 2008 and I'm including the Microsoft Report Viewer Redistributable 2008 installer.  When I check the download page for Report Viewer 2008, it lists .NET 3.5 as a requirement.

Is having .Net 3.5 installed really needed Report Viewer 2008?  We targeted .Net 2.0 for our app, there isn't anything in our code that would use the 3.0 or 3.5 Frameworks.

We are in the middle of testing and everything seems to be working with out 3.5, but I don't want to miss an edge condition and cause an error for a customer because he was missing a prerequisite run time package.

Answer: Keep in mind that MSFT might be requiring the 3.5 Framework so they can write against it in future updates/releases, which might place your app in an unsupported (by MSFT) state.


Question:
I'm trying to develop specialized audio player for windows mobile devices (Professional ones). And I've ran into the problem an once.

There no compressed audio APIs on WM or I was unable to found house in documentation. Yes there are WM6 Sound API but it cannot even pause playback or seek to specified position. There are allways Windows Media Player on WM device but I've not found it APIs documentation.

So the question is:

Is there simple way to play, pause, forward, rewind, getting playback position and getting audio file length on compressed audio of several popular formats? Any library? platform APIs? Anything?

Answer:
This might be of no help at all, but the (very good) podcast player
BeyondPod
has a built in player, based on Windows Media Player, and it's open source - so you could have a look at what API they are using.
Obviously if they've written their own custom player, you wont be able to just copy it if you're writing a commercial app. But you could use it for API documentation if they're just calling through to some Media Player API.


Question: I have a large text template which needs tokenized sections replaced by other text. The tokens look something like this: ##USERNAME##.  My first instinct is just to use String.Replace(), but is there a better, more efficient way or is Replace() already optimized for this?

Answer:
System.Text.RegularExpressions.Regex.Replace()
is what you seek - IF your tokens are odd enough that you need a regex to find them.
Some kind soul did some performance testing
, and between Regex.Replace(), String.Replace(), and StringBuilder.Replace(), String.Replace() actually came out on top.


Question:
I have something like this:

barProgress.BeginAnimation(RangeBase.ValueProperty, new DoubleAnimation(
    barProgress.Value, dNextProgressValue,
    new Duration(TimeSpan.FromSeconds(dDuration)));

Now, how would you stop that animation (the DoubleAnimation)? The reason I want to do this, is because I would like to start new animations (this seems to work, but it's hard to tell) and eventually stop the last animation...

Answer:
To stop it, call
```
BeginAnimation
```
again with the second argument set to
```
null
```
.


Question: I've found out how to convert errors into exceptions, and I display them nicely if they aren't caught, but I don't know how to log them in a useful way. Simply writing them to a file won't be useful, will it? And would you risk accessing a database, when you don't know what caused the exception yet?

Answer:
You could use
set_error_handler
to set a custom exception to log your errors. I'd personally consider storing them in the database as the default Exception handler's backtrace can provide information on what caused it - this of course won't be possible if the database handler triggered the exception however.
You could also use
error_log
to log your errors. It has a choice of message destinations including:
Quoted from
error_log
PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log  configuration directive is set to. This is the default option.
Sent by email to the address in the destination  parameter. This is the only message type where the fourth parameter, extra_headers is used.
Appended to the file destination . A newline is not automatically added to the end of the message  string.
Edit: Does markdown have a noparse tag for underscores?


Question: What are attributes in .NET, what are they good for, and how do I create my own attributes?

Answer:
An attribute is a class that contains some bit of functionality that you can apply to objects in your code. To create one, create a class that inherits from System.Attribute.
As for what they're good for... there are almost limitless uses for them.
http://www.codeproject.com/KB/cs/dotnetattributes.aspx


Question:
I'm a complete Xcode/Objective-C/Cocoa newbie but I'm learning fast and really starting to enjoy getting to grips with a new language, platform and paradigm.

One thing is though, having been using Visual Studio with R# for so long I've kind of been spoiled with the coding tools such as refactorings and completion etc and as far as I can tell Xcode has some fairly limited built in support for this stuff.

On that note, does anyone know if any add-ins or whatever are available for the Xcode environment which add coding helpers such as automatically generating implementation skeletons from a class interface definition etc?

I suspect there aren't but I suppose it can't help to ask.

Answer:
Xcode has refactoring for C and Objective-C built in.  Just select what you'd like to refactor, choose "Refactor..." from either the menu bar or the contextual menu, and you'll get a window including the available refactorings and a preview area.
Xcode doesn't currently have a public plug-in API; if there are specific types of plug-ins you'd like Apple to enable, file enhancement requests in the
Bug Reporter
.  That way Apple can count and track such requests.
However, there are third-party tools like
Accessorizer
and
```
mogenerator
```
(the latest release is
```
mogenerator 1.10
```
) that you can use to make various development tasks faster.  Accessorizer helps you create accessor methods for your classes, while
```
mogenerator
```
does more advanced code generation for Core Data managed object classes that are modeled using Xcode's modeling tools.


Question:
I'd like to take some RTF input and clean it to remove all RTF formatting except \ul \b \i to paste it into Word with minor format information.

The command used to paste into Word will be something like:
oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) (with some RTF text already in the Clipboard)

{\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Courier New;}}
{\colortbl ;\red255\green255\blue140;}
\viewkind4\uc1\pard\highlight1\lang3084\f0\fs18 The company is a global leader in responsible tourism and was \ul the first major hotel chain in North America\ulnone  to embrace environmental stewardship within its daily operations\highlight0\par

Do you have any idea on how I can clean up the RTF safely with some regular expressions or something? I am using VB.NET to do the processing but any .NET language sample will do.

Answer:
You can strip out the tags with regular expressions.  Just make sure that your expressions will not filter tags that were actually text.  If the text had "\b" in the body of text, it would appear as \b in the RTF stream.   In other words, you would match on "\b" but not "\b".
You could probably take a short cut and filter out the header RTF tags.  Look for the first occurrence of "\viewkind4" in the input.  Then read ahead to the first space character.  You would remove all of the characters from the start of the text up to and including that space character.  That would strip out the RTF header information (fonts, colors, etc).


Question:
Are there any automatic methods for trimming a path string in .NET?

For example:

C:\Documents and Settings\nick\My Documents\Tests\demo data\demo data.emx

becomes

C:\Documents...\demo data.emx

It would be particularly cool if this were built into the Label class, and I seem to recall it is--can't find it though!

Answer:
What you are thinking on the label is that it will put ... if it is longer than the width (not set to auto size), but that would be
```
```
c:\Documents and Settings\nick\My Doc...
```
```
If there is support, it would probably be on the Path class in System.IO


Question:
I have been using Eclipse as an IDE for a short amount of time (about 3 months of full use) and almost every day I learn about some shortcut or feature that I had absolutely no idea about.  For instance, just today I learned that Ctrl+3 was the shortcut for a Quick Access window.

I was wondering what your most useful/favorite Eclipse features are.  With the IDE being so big, it would be helpful to learn about the more commonly used parts of the program.

Answer:
Ctrl
-
Alt
(
up
/
down
)  Copy selected line(s) above or below current line.
Alt
(
up
/
down
)  Move current (or multiple selected) lines up or down
Ctrl
-
Shift
-
R
Bring up the resource window, start typing to find class/resource
Ctrl
-
O
Bring up all methods and fields for the current class. Hitting it again will bring up all methods and fields for current class and super classes.
Ctrl
-
/
or
Ctrl
-
Alt
-
C
Comment single or multiple lines with //
Ctrl
-
Shift
-
/
Comment selected lines with /* */
Ctrl
-
.
Take you to the next error or warning line


Question:
I'm trying to bind a list of custom objects to a WPF Image like this:

<Image>
    <Image.Source>
        <BitmapImage UriSource="{Binding Path=ImagePath}" />
    </Image.Source>
</Image>

But it doesn't work. This is the error I'm getting:

"Property 'UriSource' or property 'StreamSource' must be set."

What am I missing?

Answer:
You need to have an implementation of
IValueConverter
interface that converts the uri into an image.  Your Convert implementation of IValueConverter will look something like this:
```
```
BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(value as string);
image.EndInit();

return image;
```
```
Then you will need to use the converter in your binding:
```
```
<Image>
    <Image.Source>
        <BitmapImage UriSource="{Binding Path=ImagePath, Converter=...}" />
    </Image.Source>
</Image>
```
```


Question: I'm interested in doing comparisons between the date string and the MySQL timestamp. However, I'm not seeing an easy conversion. Am I overlooking something obvious?

Answer:
Converting from timestamp to format:
```
```
date('Y-m-d', $timestamp);
```
```
Converting from formatted to timestamp:
```
```
mktime(0, 0, 0, $month, $day, $year, $is_dst);
```
```
See
date
and
mktime
for further documentation.
When it comes to storing it's up to you whether to use the MySQL DATE format for stroing as a formatted date; as an integer for storing as a UNIX timestamp; or you can use MySQL's TIMESTAMP format which converts a numeric timestamp into a readable format.
Check the MySQL Doc
for TIMESTAMP info.


Question:
I've seen this all over the place:

Download here!  SHA1 =
  8e1ed2ce9e7e473d38a9dc7824a384a9ac34d7d0

What does it mean? How does a hash come into play as far as downloads and... What use can I make of it? Is this a legacy item where you used to have to verify some checksum after you downloaded the whole file?

Answer:
It's a security measure.  It allows you to verify that the file you just downloaded is the one that the author posted to the site.  Note that using hashes from the same website you're getting the files from is not especially secure.  Often a good place to get them from is a mailing list announcement where a PGP-signed email contains the link to the file and the hash.
Since this answer has been ranked so highly compared to the others for some reason, I'm editing it to add the other major reason mentioned first by the other authors below, which is to verify the integrity of the file after transferring it over the network.
So:
Security - verify that the file that you downloaded was the one the author originally published
Integrity - verify that the file wasn't damaged during transmission over the network.


Question:
AOP is an interesting programming paradigm in my opinion. However, there haven't been discussions about it yet here on stackoverflow (at least I couldn't find them). What do you think about it in general? Do you use AOP in your projects? Or do you think it's rather a niche technology that won't be around for a long time or won't make it into the mainstream (like OOP did, at least in theory ;))?

If you do use AOP then please let us know which tools you use as well. Thanks!

Answer:
We used aspectJ in one of my big projects for quite some time.  The project was made up of several web services, each with several functions, which was the front end for a complicated document processing/querying system.  Somewhere around 75k lines of code.  We used aspects for two relatively minor pieces of functionality.
First was tracing application flow.  We created an aspect that ran before and after each function call to print out "entered 'function'" and "exited 'function'".  With the function selector thing (pointcut maybe?  I don't remember the right name) we were able to use this as a debugging tool, selecting only functions that we wanted to trace at a given time.  This was a really nice use for aspects in our project.
The second thing we did was application specific metrics.  We put aspects around our web service methods to capture timing, object information, etc. and dump the results in a database.  This was nice because we could capture this information, but still keep all of that capture code separate from the "real" code that did the work.
I've read about some nice solutions that aspects can bring to the table, but I'm still not convinced that they can really do anything that you couldn't do (maybe better) with "normal" technology.  For example, I couldn't think of any major feature or functionality that any of our projects needed that couldn't be done just as easily without aspects - where I've found aspects useful are the kind of minor things that I've mentioned.


Question:
Other than self.class.send :method, args..., of course.  I'd like to make a rather complex method available at both the class and instance level without duplicating the code.

UPDATE:

@Jonathan Branam: that was my assumption, but I wanted to make sure nobody else had found a way around.  Visibility in Ruby is very different from that in Java.  You're also quite right that private doesn't work on class methods, though this will declare a private class method:

class Foo
  class <<self
    private
    def bar
      puts 'bar'
    end
  end
end

Foo.bar
# => NoMethodError: private method 'bar' called for Foo:Class

Answer:
Unless I'm misunderstanding, don't you just need something like this:
```
```
class Foo
    private
    def Foo.bar
        # Complex logic goes here
        puts "hi"
    end

    public
    def bar
        Foo.bar
    end
end
```
```
Of course you could change the second definition to use your self.class.send approach if you wanted to avoid hardcoding the class name...


Question: What is the difference in ASP/VBScript between Int() and CInt()?

Answer:
Int()
The Int function returns the integer part of a specified number.
CInt()
The CInt function converts an expression to type Integer.
And the best answer comes from
MSDN
CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.


Question:
I want to test the behavior of a certain piece of .NET code in partial trust environments.  What's the fastest way to set this up?  Feel free to assume that I (and other readers) are total CAS noobs.

@Nick: Thanks for the reply.  Alas, the tool in question is explicitly for unmanaged code.  I didn't say "managed" in my question, and should not have assumed that people would infer it from the ".NET" tag.

Answer:
Use the
Microsoft Application Verifier
.
AppVerifier helps to determine:
When the application is using APIs correctly:
      (Unsafe TerminateThread APIs., Correct use of Thread Local Storage (TLS) APIs.,          o Correct use of virtual space manipulations (for example, VirtualAlloc, MapViewOfFile).
Whether the application is hiding access violations using structured exception handling.
Whether the application is attempting to use invalid handles.
Whether there are memory corruptions or issues in the heap.
Whether the application runs out of memory under low resources.
Whether the correct usage of critical sections is occurring.
Whether an application running in an administrative environment will run well in an environment with less privilege.
Whether there are potential problems when the application is running as a limited user.
Whether there are uninitialized variables in future function calls in a thread's context.


Question:
I've tried several things already,

std::stringstream m;
m.empty();
m.clear();

both of which don't work.

Answer:
```
```
m.str("");
```
```
seems to work.


Question:
I've seen binary trees and binary searching mentioned in several books I've read lately, but as I'm still at the beginning of my studies in Computer Science, I've yet to take a class that's really dealt with algorithms and data structures in a serious way.

I've checked around the typical sources (Wikipedia, Google) and most descriptions of the usefulness and implementation of (in particular) Red-Black trees have come off as dense and difficult to understand. I'm sure for someone with the necessary background, it makes perfect sense, but at the moment it reads like a foreign language almost.

So what makes binary trees useful in some of the common tasks you find yourself doing while programming? Beyond that, which trees do you prefer to use (please include a sample implementation) and why?

Answer:
Red Black trees are good for creating well-balanced trees. The major problem with binary search trees is that you can make them unbalanced very easily. Imagine your first number is a 15. Then all the numbers after that are increasingly smaller than 15. You'll have a tree that is very heavy on the left side and has nothing on the right side.
Red Black trees solve that by forcing your tree to be balanced whenever you insert or delete. It accomplishes this through a series of rotations between ancestor nodes and child nodes. The algorithm is actually pretty straightforward, although it is a bit long. I'd suggest picking up the CLRS (Cormen, Lieserson, Rivest and Stein) textbook, "Introduction to Algorithms" and reading up on RB Trees.
The implementation is also not really so short so it's probably not really best to include it here. Nevertheless, trees are used
extensively
for high performance apps that need access to lots of data. They provide a very efficient way of finding nodes, with a relatively small overhead of insertion/deletion. Again, I'd suggest looking at CLRS to read up on how they're used.
While BSTs may not be used explicitly - one example of the use of trees in general are in almost every single modern RDBMS. Similarly, your file system is almost certainly represented as some sort of tree structure, and files are likewise indexed that way. Trees power Google. Trees power just about every website on the internet.


Question:
In what situation would it be more appropriate for me to use a bitset (STL container) to manage a set of flags rather than having them declared as a number of separate (bool) variables?

Will I get a significant performance gain if I used a bitset for 50 flags rather than using 50 separate bool variables?

Answer:
Well, 50 bools as a bitset will take 7 bytes, while 50 bools as bools will take 50 bytes.  These days that's not really a big deal, so using bools is probably fine.
However, one place a bitset might be useful is if you need to pass those bools around a lot, especially if you need to return the set from a function.  Using a bitset you have less data that has to be moved around on the stack for returns.  Then again, you could just use refs instead and have even less data to pass around. :)


Question:
I have a byte array in memory, read from a file.  I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation. What I would like is something like this:

byte[] largeBytes = [1,2,3,4,5,6,7,8,9];
byte[] smallPortion;
smallPortion = split(largeBytes, 3);

smallPortion would equal 1,2,3,4

largeBytes would equal 5,6,7,8,9

Answer:
You can't. What you might want is keep a starting point and number of items; in essence, build iterators. If this is C++, you can just use
```
std::vector<int>
```
and use the built-in ones.
In C#, I'd build a small iterator class that holds start index, count and implements
```
IEnumerable<>
```
.


Question:
Why should I or shouldn't I use dirty reads:

set transaction isolation level read uncommitted

in SQL Server?

Answer:
Generally when you need to do a sizeable (or frequent) queries to busy tables, where read committed would possibly be blocked by locks from uncommited transactions, but ONLY when you can live with inaccurate data.
As an example, on a gaming web site I worked on recently there was a summary display of some stats about recent games, this was all based on dirty reads, it was more important for us to include then exclude the transactional data not yet committed (we knew anyway that few, if any, transactions would be backed out), we felt that on average the data would be more accurate that way.


Question:
I'm working on a DCOM application with the server and client on two machines, both of which are running WinXP with Service Pack 2. On both machines, I'm logged in with the same username and password.

When the client on one machine calls CoCreateInstanceEx, asking the other machine to start up the server application, it returns E_ACCESSDENIED.

I tried going into the server app's component properties in dcomcnfg and giving full permisions to everyone for everything, but that didn't help.

What do I need to do to allow this call to succeed?

Update: When the server app is running on a Windows 2000 box, I do not get this error; CoCreateInstanceEx returns S_OK.

Answer:
Three things to check:
1) Go back to dcomcnfg and make try making sure that not just the access security but also the "launch permissions" section contains the appropriate security users or groups.
2) Ensure that the Authentication Level is set to something else other than "None"
3) Also check that the location on disk that the component is located is actually accessible to the account configured in the security permissions you set.
EDIT:
One more: Are you calling CoInitialiseSecurity() first too? That rings a bell!
EDIT2:
Based on your update: Try dropping the firewalls completely on both XP machines and see if that makes a difference. You may need to let DCOM through explicitly.


Question:
I'd like to be able to track file read/writes of specific program invocations.  No information about the actual transactions is required, just the file names involved.

Is there a cross platform solution to this?

What are various platform specific methods?

On Linux I know there's strace/ptrace (if there are faster methods that'd be good too).
I think on mac os there's ktrace.

What about Windows?

Also, it would be amazing if it would be possible to block (stall out) file accesses until some later time.

Thanks!

Answer:
On Windows you can use the command line tool
Handle
or the GUI version
Process Explorer
to see which files a given process has open.
If you're looking for a get this information in your own program you can use the
IFS kit
from Microsoft to write a file system filter. The file system filter will show all file system operation for all process. File system filters are used in AV software to scan files before they are open or to scan newly created files.


Question:
I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column that's comma separated (sounds crazy but could work). I've even heard someone recommend a sparse matrix, but then how do the tag names grow gracefully?

Am I missing a best practice for tags?

Answer:
Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, with foreign keys set running on a proper database, should work well and scale properly.
```
```
Table: Item
Columns: ItemID, Title, Content

Table: Tag
Columns: TagID, Title

Table: ItemTag
Columns: ItemID, TagID
```
```


Question:
Some things look strange to me:

What is the distinction between 0.0.0.0, 127.0.0.1, and [::]?

How should each part of the foreign address be read (part1:part2)?

What does a state Time_Wait, Close_Wait mean?

etc.

Could someone give a quick overview of how to interpret these results?

Answer:
0.0.0.0 usually refers to stuff listening on all interfaces.
127.0.0.1 = localhost (only your local interface)
I'm not sure about [::]
TIME_WAIT means both sides have agreed to close and TCP
must now wait a prescribed time before taking the connection
down.
CLOSE_WAIT means the remote system has finished sending
and your system has yet to say it's finished.


Question:
I need to script the creation of app pools and websites on IIS 6.0. I have been able to create these using adsutil.vbs and iisweb.vbs, but don't know how to set the version of ASP.NET for the sites I have just created to 2.0.50727.0.

Ideally I would like to adsutil.vbs to update the metabase. How do I do this?

Answer:
I found the following script
posted
on Diablo Pup's blog.  It uses ADSI automation.
```
```
'******************************************************************************************
' Name: SetASPDotNetVersion
' Description: Set the script mappings for the specified ASP.NET version
' Inputs: objIIS, strNewVersion
'******************************************************************************************
Sub SetASPDotNetVersion(objIIS, strNewVersion)
 Dim i, ScriptMaps, arrVersions(2), thisVersion, thisScriptMap
 Dim strSearchText, strReplaceText

 Select Case Trim(LCase(strNewVersion))
  Case "1.1"
   strReplaceText = "v1.1.4322"
  Case "2.0"
   strReplaceText = "v2.0.50727"
  Case Else
   wscript.echo "WARNING: Non-supported ASP.NET version specified!"
   Exit Sub
 End Select

 ScriptMaps = objIIS.ScriptMaps
 arrVersions(0) = "v1.1.4322"
 arrVersions(1) = "v2.0.50727"
 'Loop through all three potential old values
 For Each thisVersion in arrVersions
  'Loop through all the mappings
  For thisScriptMap = LBound(ScriptMaps) to UBound(ScriptMaps)
   'Replace the old with the new
   ScriptMaps(thisScriptMap) = Replace(ScriptMaps(thisScriptMap), thisVersion, strReplaceText)
  Next
 Next

 objIIS.ScriptMaps = ScriptMaps
 objIIS.SetInfo
 wscript.echo "<-------Set ASP.NET version to " & strNewVersion & " successfully.------->"
End Sub
```
```


Question:
Today I was working on a tab navigation for a webpage. I tried the Sliding Doors approach which worked fine. Then I realized that I must include an option to delete a tab (usually a small X in the right corner of each tab).

I wanted to use a nested anchor, which didn't work because it is not allowed. Then I saw the tab- navigation at Pageflakes, which was actually working (including nested hyperlinks). Why?

Answer:
They must be doing some really crazy stuff with JavaScript to get it to work (notice how neither the parent nor the nested anchor tags have a name or href attribute - all functionality is done through the class name and JS).
Here is what the html looks like:
```
```

Click & Type Page Name

  X

```
```


Question:
I'm designing a database table and asking myself this question: How long should the firstname field be?

Does anyone have a list of reasonable lengths for the most common fields, such as first name, last name, and email address?

Answer:
Just looking though my email archives, there are a number of pretty long "first" names (of course what is meant by first is variable by culture).  One example is Krishnamurthy - which is 13 letters long.  A good guess might be 20 to 25 letters based on this.  Email should be
much
longer since you might have firstname.lastname@somedomain.com.  Also, gmail and some other mail programs allow you to use firstname.lastname+sometag@somedomain.com where "sometag" is anything you want to put there so that you can use it to sort incoming emails.  I frequently run into web forms that don't allow me to put in my full email address without considering any tags.   So, if you need a fixed email field maybe something like  25.25+15@20.3 in characters for a total of 90 characters (if I did my math right!).


Question:
How can I determine all of the assemblies that my .NET desktop application has loaded?  I'd like to put them in the about box so I can query customers over the phone to determine what version of XYZ they have on their PC.

It would be nice to see both managed and unmanaged assemblies.  I realize the list will get long but I plan to slap an incremental search on it.

Answer:
Looks like
```
AppDomain.CurrentDomain.GetAssemblies();
```
will do the trick :)


Question:
When I try to create a SQL Server Login by saying

CREATE LOGIN [ourdomain\SQLAccessGroup] FROM WINDOWS;

I get this error

The server principal 'ourdomain\SQLAccessGroup' already exists.

However, when I try this code

DROP LOGIN [ourdomain\SQLAccessGroup]

I get this error

Cannot drop the login 'ourdomain\SQLAccessGroup', because it does not exist or you do not have permission.

The user that I am executing this code as is a sysadmin.  Additionally, the user ourdomain\SQLAccessGroup does not show up in this query

select * from sys.server_principals

Does anyone have any ideas?

Answer:
We are still struggling to understand the
HOW
of this issue, but it seems that [ourdomain\SQLAccessGroup] was aliased by a consultant to a different user name (this is part of an MS CRM installation).  We finally were able to use some logic and some good old SID comparisons to determine who was playing the imposter game.
Our hint came when I tried to add the login as a user to the database (since it supposedly already existed) and got this error:
```
```
The login already has an account under a different user name.
```
```
So, I started to examine each DB user and was able to figure out the culprit.  I eventually tracked it down and was able to rename the user and login so that the CRM install would work.  I wonder if I can bill them $165.00 an hour for my time... :-)


Question:
When I'm working with DataBound controls in ASP.NET 2.0 such as a Repeater, I know the fastest way to retrieve a property of a bound object (instead of using Reflection with the Eval() function) is to cast the DataItem object to the type it is and then use that object natively, like the following:

<%#((MyType)Container.DataItem).PropertyOfMyType%>

The problem is, if this type is in a namespace (which is the case 99.99% of the time) then this single statement because a lot longer due to the fact that the ASP page has no concept of class scope so all of my types need to be fully qualified.

<%#((RootNamespace.SubNamespace1.SubNamspace2.SubNamespace3.MyType)Container.DataItem).PropertyOfMyType%>

Is there any kind of using directive or some equivalent I could place somewhere in an ASP.NET page so I don't need to use the full namespace every time?

Answer:
I believe you can add something like:
```
```
<%@ Import Namespace="RootNamespace.SubNamespace1" %>
```
```
At the top of the page.


Question:
I'm tired of being in the middle of typing something, having a pop-up with a question appear, and hitting enter before reading it... (it also happens with some windows that are not pop-ups)

Do you know if there's some setting I could touch for this not to happen?

Answer:
I believe you can add something like:
```
```
<%@ Import Namespace="RootNamespace.SubNamespace1" %>
```
```
At the top of the page.


Question: What's the most efficient way to concatenate strings?

Answer:
The most efficient is to use StringBuilder, like so:
```
```
StringBuilder sb = new StringBuilder();
sb.Append("string1");
sb.Append("string2");
...etc...
String strResult = sb.ToString();
```
```
@jonezy: String.Concat is fine if you have a couple of small things. But if you're concatenating megabytes of data, your program will likely tank.


Question:
What's the easiest way to profile a PHP script?

I'd love tacking something on that shows me a dump of all function calls and how long they took but I'm also OK with putting something around specific functions.

I tried experimenting with the microtime function:

$then = microtime();
myFunc();
$now = microtime();

echo sprintf("Elapsed:  %f", $now-$then);

but that sometimes gives me negative results.  Plus it's a lot of trouble to sprinkle that all over my code.

Answer:
I like to use phpDebug for profiling.
http://phpdebug.sourceforge.net/www/index.html
It outputs all time / memory usage for any SQL used as well as all the included files. Obviously, it works best on code that's abstracted.
For function and class profiling I'll just use
```
microtime()
```
+
```
get_memory_usage()
```
+
```
get_peak_memory_usage()
```
.


Question:
I've got a System.Generic.Collections.List(Of MyCustomClass) type object.

Given integer varaibles pagesize and pagenumber, how can I query only any single page of MyCustomClass objects?

Answer:
If you have your linq-query that contains all the rows you want to display, this code can be used:
```
```
var pageNum = 3;
var pageSize = 20;
query = query.Skip((pageNum - 1) * pageSize).Take(pageSize);
```
```
You can also make an extension method on the object to be able to write
```
```
query.Page(2,50)
```
```
to get the first 50 records of page 2. If that is want you want, the information is on the
solid code blog.


Question: I'm currently trying out db4o (the java version) and I pretty much like what I see. But I cannot help wondering how it does perform in a real live (web-)environment. Does anyone have any experiences (good or bad) to share about running db4o?

Answer:
We run DB40 .NET version in a large client/server project.
Our experiences is that you can potentially get much better performance than typical relational databases.
However, you really have to tweak your objects to get this kind of performance. For example, if you've got a list containing a lot of objects, DB4O activation of these lists is slow. There are a number of ways to get around this problem, for example, by inverting the relationship.
Another pain is activation. When you retrieve or delete an object from DB4O, by default it will activate the whole object tree. For example, loading a Foo will load Foo.Bar.Baz.Bat, etc until there's nothing left to load. While this is nice from a programming standpoint, performance will slow down the more nesting in your objects. To improve performance, you can tell DB4O how many levels deep to activate. This is time-consuming to do if you've got a lot of objects.
Another area of pain was text searching. DB4O's text searching is far, far slower than SQL full text indexing. (They'll tell you this outright on their site.) The good news is, it's easy to setup a text searching engine on top of DB4O. On our project, we've hooked up Lucene.NET to index the text fields we want.
Some APIs don't seem to work, such as the GetField APIs useful in applying database upgrades. (For example, you've renamed a property and you want to upgrade your existing objects in the database, you need to use these "reflection" APIs to find objects in the database. Other APIs, such as the [Index] attribute don't work in the stable 6.4 version, and you must instead specify indexes using the Configure().Index("someField"), which is not strongly typed.
We've witnessed performance degrade the larger your database. We have a 1GB database right now and things are still fast, but not nearly as fast as when we started with a tiny database.
We've found another issue where Db4O.GetByID will close the database if the ID doesn't exist anymore in the database.
We've found the Native Query syntax (the most natural, language-integrated syntax for queries) is far, far slower than the less-friendly SODA queries. So instead of typing:
```
```
// C# syntax for "Find all MyFoos with Bar == 23".
// (Note the Java syntax is more verbose using the Predicate class.)
IList<MyFoo> results = db4o.Query<MyFoo>(input => input.Bar == 23);
```
```
Instead of that nice query code, you have to an ugly SODA query which is string-based and not strongly-typed.
For .NET folks, they've recently introduced a LINQ-to-DB4O provider, which provides for the best syntax yet. However, it's yet to be seen whether performance will be up-to-par with the ugly SODA queries.
DB4O support has been decent: we've talked to them on the phone a number of times and have received helpful info. Their user forums are next to worthless, however, almost all questions go unanswered. Their JIRA bug tracker receives a lot of attention, so if you've got a nagging bug, file it on JIRA on it often will get fixed. (We've had 2 bugs that have been fixed, and another one that got patched in a half-assed way.)
If all this hasn't scared you off, let me say that we're very happy with DB4O, despite the problems we've encountered. The performance we've got has blown away some O/RM frameworks we tried. I recommend it.
update July 2015
Keep in mind, this answer was written back in 2008. While I appreciate the upvotes, the world has changed since then, and this information may not be as reliable as it was when it was written.


Question:
I've got a System.Generic.Collections.List(Of MyCustomClass) type object.

Given integer varaibles pagesize and pagenumber, how can I collect only any single page of MyCustomClass objects?

This is what I've got.  How can I improve it?

'my given collection and paging parameters
Dim AllOfMyCustomClassObjects As System.Collections.Generic.List(Of MyCustomClass) = GIVEN
Dim pagesize As Integer = GIVEN
Dim pagenumber As Integer = GIVEN

'collect current page objects
Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass)
Dim objcount As Integer = 1
For Each obj As MyCustomClass In AllOfMyCustomClassObjects
If objcount > pagesize * (pagenumber - 1) And count <= pagesize * pagenumber Then
    PageObjects.Add(obj)
End If
objcount = objcount + 1
Next

'find total page count
Dim totalpages As Integer = CInt(Math.Floor(objcount / pagesize))
If objcount Mod pagesize > 0 Then
totalpages = totalpages + 1
End If

Answer:
You use GetRange on your IEnuramble implementing collection:
```
```
List<int> lolInts = new List<int>();

for (int i = 0; i <= 100; i++)
{
    lolInts.Add(i);
}

List<int> page1 = lolInts.GetRange(0, 49);
List<int> page2 = lilInts.GetRange(50, 100);
```
```
I trust you can figure out how to use GetRange to grab an individual page from here.


Question: What is the best method for comparing IEEE floats and doubles for equality?  I have heard of several methods, but I wanted to see what the community thought.

Answer:
The best approach I think is to compare
ULPs
.
```
```
bool is_nan(float f)
{
    return (*reinterpret_cast<unsigned __int32*>(&f) & 0x7f800000) == 0x7f800000 && (*reinterpret_cast<unsigned __int32*>(&f) & 0x007fffff) != 0;
}

bool is_finite(float f)
{
    return (*reinterpret_cast<unsigned __int32*>(&f) & 0x7f800000) != 0x7f800000;
}

// if this symbol is defined, NaNs are never equal to anything (as is normal in IEEE floating point)
// if this symbol is not defined, NaNs are hugely different from regular numbers, but might be equal to each other
#define UNEQUAL_NANS 1
// if this symbol is defined, infinites are never equal to finite numbers (as they're unimaginably greater)
// if this symbol is not defined, infinities are 1 ULP away from +/- FLT_MAX
#define INFINITE_INFINITIES 1

// test whether two IEEE floats are within a specified number of representable values of each other
// This depends on the fact that IEEE floats are properly ordered when treated as signed magnitude integers
bool equal_float(float lhs, float rhs, unsigned __int32 max_ulp_difference)
{
#ifdef UNEQUAL_NANS
    if(is_nan(lhs) || is_nan(rhs))
    {
        return false;
    }
#endif
#ifdef INFINITE_INFINITIES
    if((is_finite(lhs) && !is_finite(rhs)) || (!is_finite(lhs) && is_finite(rhs)))
    {
        return false;
    }
#endif
    signed __int32 left(*reinterpret_cast<signed __int32*>(&lhs));
    // transform signed magnitude ints into 2s complement signed ints
    if(left < 0)
    {
        left = 0x80000000 - left;
    }
    signed __int32 right(*reinterpret_cast<signed __int32*>(&rhs));
    // transform signed magnitude ints into 2s complement signed ints
    if(right < 0)
    {
        right = 0x80000000 - right;
    }
    if(static_cast<unsigned __int32>(std::abs(left - right)) <= max_ulp_difference)
    {
        return true;
    }
    return false;
}
```
```
A similar technique can be used for doubles.  The trick is to convert the floats so that they're ordered (as if integers) and then just see how different they are.
I have no idea why this damn thing is screwing up my underscores.  Edit: Oh, perhaps that is just an artefact of the preview.  That's OK then.


Question:
Which C#/.NET Dependency Injection frameworks are worth looking into?
And what can you say about their complexity and speed.

Answer:
Ninject is great. It seems really fast, but I haven't done any comparisons. I know Nate, the author, did some comparisons between Ninject and other DI frameworks and is looking for more ways to improve the speed of Ninject.
I've heard lots of people I respect say good things about StructureMap and CastleWindsor. Those, in my mind, are the big three to look at right now.


Question:
I'm running Apache on Linux within VMWare.

One of the PHP pages I'm requesting does a sleep(), and I find that if I attempt to request a second page whilst the first page is sleep()'ing, the second page hangs, waiting for the sleep() from the first page to finish.

Has anyone else seen this behaviour?

I know that PHP isn't multi-threaded, but this seems like gross mishandling of the CPU.

Edit: I should've mentioned that the CPU usage doesn't spike. What I mean by CPU "hogging" is that no other PHP page seems able to use the CPU whilst the page is sleep()'ing.

Answer:
Are you actually seeing the CPU go to 100% or just that no other pages are being served? How many apache-instances are you runnning? Are they all stopping when you run sleep() in of of the threads?
PHP's sleep() function essentially runs through an idle loop for n seconds. It doesn't release any memory, but it should not increase CPU load significantly.


Question:
What is the difference between the following types of endianness?

byte (8b) invariant big and little endianness

half-word (16b) invariant big and little endianness

word (32b) invariant big and little endianness

double-word (64b) invariant big and little endianness

Are there other types/variations?

Answer:
the basic concept is the ordering of bits:
```
```
1010 0011
```
```
in little-endian is the same as
```
```
0011 1010
```
```
in big-endian (and vice-versa).
You'll notice the order changes by grouping, not by individual bit.  I don't know of a system, for example, where
```
```
1100 0101
```
```
would be the "other-endian" version of the first version.


Question: How do I go about specifying and using an ENUM in a Django model?

Answer:
From the
Django documentation
:
```
```
MAYBECHOICE = (
    ('y', 'Yes'),
    ('n', 'No'),
    ('u', 'Unknown'),
)
```
```
And you define a charfield in your model :
```
```
married = models.CharField(max_length=1, choices=MAYBECHOICE)
```
```
You can do the same with integer fields if you don't like to have letters
in your db.
In that case, rewrite your choices:
```
```
MAYBECHOICE = (
    (0, 'Yes'),
    (1, 'No'),
    (2, 'Unknown'),
)
```
```


Question: I know Hostmonster allows Python. Has anyone successfully run Django on there? Any problems?

Answer:
Well, if it support Python, you might be able to run Django using a FastCGI setup, as described here:
FastCGI Docs
. If it supports mod_python (which I guess it's what you mean), then sure, you can install it using the steps listed here:
ModPython docs


Question:
#if SYMBOL
  //code
#endif

what values does C# predefine for use?

Answer:
Depends on what /define compiler options you use.
```
Visual Studio
```
puts the
```
DEBUG
```
symbol in there for you via the project settings, but you could create any ones that you want.


Question:
SQL Experts,

Is there an efficient way to group runs of data together using SQL?

Or is it going to be more efficient to process the data in code.

For example if I have the following data:

ID|Name
01|Harry Johns
02|Adam Taylor
03|John Smith
04|John Smith
05|Bill Manning
06|John Smith

I need to display this:

Harry Johns
Adam Taylor
John Smith (2)
Bill Manning
John Smith

@Matt: Sorry I had trouble formatting the data using an embedded html table it worked in the preview but not in the final display.

Answer:
For this particular case, all you need to do is group by the name and ask for the count, like this:
```
```
select Name, count(*)
from MyTable
group by Name
```
```
That'll get you the count for each name as a second column.
You can get it all as one column by concatenating like this:
```
```
select Name + ' (' + cast(count(*) as varchar) + ')'
from MyTable
group by Name
```
```


Question:
I've spent a good amount of time coming up with solution to this problem, so in the spirit of this post, I'm posting it here, since I think it might be useful to others.

If anyone has a better script, or anything to add, please post it.

Edit: Yes guys, I know how to do it in Management Studio - but I needed to be able to do it from within another application.

Answer:
Here's the script that I came up with. It handles Identity columns, default values, and primary keys. It does not handle foreign keys, indexes, triggers, or any other clever stuff. It works on SQLServer 2000, 2005 and 2008.
```
```
declare @schema varchar(100), @table varchar(100)
set @schema = 'dbo' -- set schema name here
set @table = 'MyTable' -- set table name here
declare @sql table(s varchar(1000), id int identity)

-- create statement
insert into  @sql(s) values ('create table [' + @table + '] (')

-- column list
insert into @sql(s)
select
    '  ['+column_name+'] ' +
    data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
    case when exists (
        select id from syscolumns
        where object_name(id)=@table
        and name=column_name
        and columnproperty(id,name,'IsIdentity') = 1
    ) then
        'IDENTITY(' +
        cast(ident_seed(@table) as varchar) + ',' +
        cast(ident_incr(@table) as varchar) + ')'
    else ''
    end + ' ' +
    ( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' +
    coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','

 from INFORMATION_SCHEMA.COLUMNS where table_name = @table AND table_schema = @schema
 order by ordinal_position

-- primary key
declare @pkname varchar(100)
select @pkname = constraint_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where table_name = @table and constraint_type='PRIMARY KEY'

if ( @pkname is not null ) begin
    insert into @sql(s) values('  PRIMARY KEY (')
    insert into @sql(s)
        select '   ['+COLUMN_NAME+'],' from INFORMATION_SCHEMA.KEY_COLUMN_USAGE
        where constraint_name = @pkname
        order by ordinal_position
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
    insert into @sql(s) values ('  )')
end
else begin
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
end

-- closing bracket
insert into @sql(s) values( ')' )

-- result!
select s from @sql order by id
```
```


Question:
I want to know what a "virtual base class" is and what it means.

Let me show an example:

class Foo
{
public:
    void DoSomething() { /* ... */ }
};

class Bar : public virtual Foo
{
public:
    void DoSpecific() { /* ... */ }
};

Answer:
It means a call to a virtual function will be forwarded to the "right" class.
C++
FAQ Lite
FTW.
In short, it is often used in multiple-inheritance scenarios, where a "diamond" hierarchy is formed.  Virtual inheritance will then break the ambiguity created in the bottom class, when you call function in that class and the function needs to be resolved to either class D1 or D2 above that bottom class.  See the
FAQ item
for a diagram and details.
It is also used in
sister delegation
, a powerful feature (though not for the faint of heart).  See
this
FAQ.
Also see Item 40 in Effective C++ 3rd edition (43 in 2nd edition).


Question:
I ended up writing a quick little script for this in Python, but I was wondering if there was a utility you could feed text into which would prepend each line with some text -- in my specific case, a timestamp.  Ideally, the use would be something like:

cat somefile.txt | prepend-timestamp

(Before you answer sed, I tried this:

cat somefile.txt | sed "s/^/`date`/"

But that only evaluates the date command once when sed is executed, so the same timestamp is incorrectly prepended to each line.)

Answer:
How about this?
```
```
cat somefile.txt | perl -pne 'print scalar(localtime()), " ";'
```
```
Judging from your desire to get live timestamps, maybe you want to do live updating on a log file or something?  Maybe
```
```
tail -f /path/to/log | perl -pne 'print scalar(localtime()), " ";' > /path/to/log-with-timestamps
```
```


Question: I'm not clear on the differences between the "current" version of Ruby (1.8) and the "new" version (1.9). Is there an "easy" or a "simple" explanation of the differences and why it is so different?

Answer:
Sam Ruby has a
cool slideshow that outline the differences
.
In the interest of bringing this information inline for easier reference, and in case the link goes dead in the abstract future, here's an overview of Sam's slides. The slideshow is less overwhelming to review, but having it all laid out in a list like this is also helpful.
Ruby 1.9 - Major Features
Performance
Threads/Fibers
Encoding/Unicode
gems is (mostly) built-in now
if statements do not introduce scope in Ruby.
What's changed?
Single character strings.
Ruby 1.9
```
```
irb(main):001:0> ?c
=> "c"
```
```
Ruby 1.8.6
```
```
irb(main):001:0> ?c
=> 99
```
```
String index.
Ruby 1.9
```
```
irb(main):001:0> "cat"[1]
=> "a"
```
```
Ruby 1.8.6
```
```
irb(main):001:0> "cat"[1]
=> 97
```
```
{"a","b"} No Longer Supported
Ruby 1.9
```
```
irb(main):002:0> {1,2}
SyntaxError: (irb):2: syntax error, unexpected ',', expecting tASSOC
```
```
Ruby 1.8.6
```
```
irb(main):001:0> {1,2}
=> {1=>2}
```
```
Action:
Convert to {1 => 2}
```
Array.to_s
```
Now Contains Punctuation
Ruby 1.9
```
```
irb(main):001:0> [1,2,3].to_s
=> "[1, 2, 3]"
```
```
Ruby 1.8.6
```
```
irb(main):001:0> [1,2,3].to_s
=> "123"
```
```
Action:
Use .join instead
Colon No Longer Valid In When Statements
Ruby 1.9
```
```
irb(main):001:0> case 'a'; when /\w/: puts 'word'; end
SyntaxError: (irb):1: syntax error, unexpected ':',
expecting keyword_then or ',' or ';' or '\n'
```
```
Ruby 1.8.6
```
```
irb(main):001:0> case 'a'; when /\w/: puts 'word'; end
word
```
```
Action:
Use semicolon, then, or newline
Block Variables Now Shadow Local Variables
Ruby 1.9
```
```
irb(main):001:0> i=0; [1,2,3].each {|i|}; i
=> 0
irb(main):002:0> i=0; for i in [1,2,3]; end; i
=> 3
```
```
Ruby 1.8.6
```
```
irb(main):001:0> i=0; [1,2,3].each {|i|}; i
=> 3
```
```
```
Hash.index
```
Deprecated
Ruby 1.9
```
```
irb(main):001:0> {1=>2}.index(2)
(irb):18: warning: Hash#index is deprecated; use Hash#key
=> 1
irb(main):002:0> {1=>2}.key(2)
=> 1
```
```
Ruby 1.8.6
```
```
irb(main):001:0> {1=>2}.index(2)
=> 1
```
```
Action:
Use Hash.key
```
Fixnum.to_sym
```
Now Gone
Ruby 1.9
```
```
irb(main):001:0> 5.to_sym
NoMethodError: undefined method 'to_sym' for 5:Fixnum
```
```
Ruby 1.8.6
```
```
irb(main):001:0> 5.to_sym
=> nil
```
```
(Cont'd) Ruby 1.9
```
```
# Find an argument value by name or index.
def [](index)
  lookup(index.to_sym)
end
```
```
svn.ruby-lang.org/repos/ruby/trunk/lib/rake.rb
Hash Keys Now Unordered
Ruby 1.9
```
```
irb(main):001:0> {:a=>"a", :c=>"c", :b=>"b"}
=> {:a=>"a", :c=>"c", :b=>"b"}
```
```
Ruby 1.8.6
```
```
irb(main):001:0> {:a=>"a", :c=>"c", :b=>"b"}
=> {:a=>"a", :b=>"b", :c=>"c"}
```
```
Order is insertion order
Stricter Unicode Regular Expressions
Ruby 1.9
```
```
irb(main):001:0> /\x80/u
SyntaxError: (irb):2: invalid multibyte escape: /\x80/
```
```
Ruby 1.8.6
```
```
irb(main):001:0> /\x80/u
=> /\x80/u
```
```
```
tr
```
and
```
Regexp
```
Now Understand Unicode
Ruby 1.9
```
```
unicode(string).tr(CP1252_DIFFERENCES, UNICODE_EQUIVALENT).
  gsub(INVALID_XML_CHAR, REPLACEMENT_CHAR).
  gsub(XML_PREDEFINED) {|c| PREDEFINED[c.ord]}
```
```
```
pack
```
and
```
unpack
```
Ruby 1.8.6
```
```
def xchr(escape=true)
  n = XChar::CP1252[self] || self
  case n when *XChar::VALID
    XChar::PREDEFINED[n] or
      (n>128 ? n.chr : (escape ? "&##{n};" : [n].pack('U*')))
  else
    Builder::XChar::REPLACEMENT_CHAR
  end
end
unpack('U*').map {|n| n.xchr(escape)}.join
```
```
```
BasicObject
```
More Brutal Than
```
BlankSlate
```
Ruby 1.9
```
```
irb(main):001:0> class C < BasicObject; def f; Math::PI; end; end; C.new.f
NameError: uninitialized constant C::Math
```
```
Ruby 1.8.6
```
```
irb(main):001:0> require 'blankslate'
=> true
irb(main):002:0> class C < BlankSlate; def f; Math::PI; end; end; C.new.f
=> 3.14159265358979
```
```
Action:
Use ::Math::PI
Delegation Changes
Ruby 1.9
```
```
irb(main):002:0> class C < SimpleDelegator; end
=> nil
irb(main):003:0> C.new('').class
=> String
```
```
Ruby 1.8.6
```
```
irb(main):002:0> class C < SimpleDelegator; end
=> nil
irb(main):003:0> C.new('').class
=> C
irb(main):004:0>
```
```
Defect 17700
Use of $KCODE Produces Warnings
Ruby 1.9
```
```
irb(main):004:1> $KCODE = 'UTF8'
(irb):4: warning: variable $KCODE is no longer effective; ignored
=> "UTF8"
```
```
Ruby 1.8.6
```
```
irb(main):001:0> $KCODE = 'UTF8'
=> "UTF8"
```
```
```
instance_methods
```
Now an Array of Symbols
Ruby 1.9
```
```
irb(main):001:0> {}.methods.sort.last
=> :zip
```
```
Ruby 1.8.6
```
```
irb(main):001:0> {}.methods.sort.last
=> "zip"
```
```
Action:
Replace instance_methods.include? with method_defined?
Source File Encoding
Basic
```
```
# coding: utf-8
```
```
Emacs
```
```
# -*- encoding: utf-8 -*-
```
```
Shebang
```
```
#!/usr/local/rubybook/bin/ruby
# encoding: utf-8
```
```
Real Threading
Race Conditions
Implicit Ordering Assumptions
Test Code
What's New?
Alternate Syntax for Symbol as Hash Keys
Ruby 1.9
```
```
{a: b}

redirect_to action: show
```
```
Ruby 1.8.6
```
```
{:a => b}

redirect_to :action => show
```
```
Block Local Variables
Ruby 1.9
```
```
[1,2].each {|value; t| t=value*value}
```
```
Inject Methods
Ruby 1.9
```
```
[1,2].inject(:+)
```
```
Ruby 1.8.6
```
```
[1,2].inject {|a,b| a+b}
```
```
```
to_enum
```
Ruby 1.9
```
```
short_enum = [1, 2, 3].to_enum
long_enum = ('a'..'z').to_enum
loop do
  puts "#{short_enum.next} #{long_enum.next}"
end
```
```
No block? Enum!
Ruby 1.9
```
```
e = [1,2,3].each
```
```
Lambda Shorthand
Ruby 1.9
```
```
p = -> a,b,c {a+b+c}
puts p.(1,2,3)
puts p[1,2,3]
```
```
Ruby 1.8.6
```
```
p = lambda {|a,b,c| a+b+c}
puts p.call(1,2,3)
```
```
Complex Numbers
Ruby 1.9
```
```
Complex(3,4) == 3 + 4.im
```
```
Decimal Is Still Not The Default
Ruby 1.9
```
```
irb(main):001:0> 1.2-1.1
=> 0.0999999999999999
```
```
Regex “Properties”
Ruby 1.9
```
```
/\p{Space}/
```
```
Ruby 1.8.6
```
```
/[:space:]/
```
```
Splat in Middle
Ruby 1.9
```
```
def foo(first, *middle, last)

(->a, *b, c {p a-c}).(*5.downto(1))
```
```
Fibers
Ruby 1.9
```
```
f = Fiber.new do
  a,b = 0,1
  Fiber.yield a
  Fiber.yield b
  loop do
    a,b = b,a+b
    Fiber.yield b
  end
end
10.times {puts f.resume}
```
```
Break Values
Ruby 1.9
```
```
match =
   while line = gets
     next if line =~ /^#/
     break line if line.find('ruby')
   end
```
```
“Nested” Methods
Ruby 1.9
```
```
def toggle
  def toggle
    "subsequent times"
  end
  "first time"
end
```
```
HTH!


Question:
What is the difference between using angle brackets and quotes in an include directive?

#include <filename>

#include "filename"

Answer:
What differs is the locations in which the preprocessor searches for the file to be included.
```
#include <filename>
```
The preprocessor searches in an implementation-defined manner, normally in directories pre-designated by the compiler/IDE. This method is normally used to include header files for the C standard library and other header files associated with the target platform.
```
#include "filename"
```
The preprocessor also searches in an implementation-defined manner, but one that is normally used to include programmer-defined header files and typically includes same directory as the file containing the directive (unless an absolute path is given).
For GCC, a more complete description is available in the GCC
documentation on search paths
.


Question:
I have a product which has been traditionally shipped as an MSI file.  It is deployed through some sort of SMS push to thousands of desktops by our various clients.  The software we use to create these installers is getting long in the tooth and we are looking to replace it.  We have already standardized on InstallAnywhere for most of our products as we support many operating systems.  Unfortunately InstallAnywhere cannot produce MSI files.

I am wondering if it is required that SMS use MSI files or if it can handle other installer types (.exe).  If not, are there any open source programmes for creating MSI files?

Answer:
If you want to create
```
MSI
```
files, try
WiX: Windows Installer XML (WiX) toolset
.
It's an addon to Visual Studio 2005 and 2008, is open-source, and Microsoft developed.  You can use XML to specify and create MSI files.  There is a
wealth
of
resources
available on it, and
```
WiX 3.0
```
is, although in beta, is very complete.
Also, note that you don't have to start from scratch, you can decompile an existing MSI using the WiX
```
Dark
```
utility, modify the XML in any way you like, and then recompile it into an MSI.


Question:
Is there a simple way in .NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL:

http://www.mywebsite.com:80/pages/page1.aspx

I need to return:

http://www.mywebsite.com:80

I know I can use Request.Url.AbsoluteUri to get the complete URL, and I know I can use Request.Url.Authority to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string.

Any suggestions?

Answer:
Request.Url will return you the
Uri
of the request.  Once you have that, you can retrieve pretty much anything you want.  To get the protocol, call the
Scheme
property.
Sample:
```
```
Uri url = Request.Url;
string protocol = url.Scheme;
```
```
Hope this helps.


Question:
The following C++ code uses a ifstream object to read integers from a text file (which has one number per line) until it hits EOF. Why does it read the integer on the last line twice? How to fix this?

Code:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream iFile("input.txt");    // input.txt has integers, one per line

    while (!iFile.eof())
    {
        int x;
        iFile >> x;
        cerr << x << endl;
    }

    return 0;
}

input.txt:

10
20
30

Output:

10
20
30
30

Note: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).

Answer:
Just follow closely the chain of events.
Grab 10
Grab 20
Grab 30
Grab EOF
Look at the second-to-last iteration.  You grabbed 30, then carried on to check for EOF.  You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line).  Therefore you carry on to the next iteration.  x is still 30 from previous iteration.  Now you read from the stream and you get EOF.  x remains 30 and the ios::eofbit is raised.  You output to stderr x (which is 30, just like in the previous iteration).  Next you check for EOF in the loop condition, and this time you're out of the loop.
Try this:
```
```
while (true) {
    int x;
    iFile >> x;
    if( iFile.eof() ) break;
    cerr << x << endl;
}
```
```
By the way, there is another bug in your code.  Did you ever try to run it on an empty file?  The behaviour you get is for the exact same reason.


Question:
There may be more than one way to ask this question, so here's a desciption of the problem. I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work. Practically this works fine, I just now have a different branch as my main development branch. I'm wondering how I could change things around so I'm working on master again but it doesn't have my junk work and said work is on a different branch.

Some ways this could be asked/solved:
How do I rename my master branch to something else and then rename something else to master?
How do I back up master and then cause all commits I've backed up past to be on a different branch?

Thanks for all the (quick) answers! They're all good.

Answer:
This is relatively easy:
```
```
git checkout -b fake_master master # fake_master now points to the same commit as master
git branch -D master               # get rid of incorrect master
git checkout -b master real_master # master now points to your actual master
git checkout master                # optional -- switch on to your master branch
```
```


Question:
I'm trying to reteach myself some long forgotten math skills. This is part of a much larger project to effectively "teach myself software development" from the ground up (the details are here if you're interested in helping out).

My biggest stumbling block so far has been math - how can I learn about algorithms and asymptotic notation without it??

What I'm looking for is some sort of "dependency tree" showing what I need to know. Is calculus required before discrete? What do I need to know before calculus (read: components to the general "pre-calculus" topic)? What can I cut out to fast track the project ("what can I go back for later")?

Thank!

Answer:
Here's how my school did it:
```
```
base:
    algebra
    trigonometry
    analytic geometry

track 1                       track 2               track 3
    calc 1                       linear algebra        statistics
    calc 2                       discrete math 1
    calc 3 (multivariable)       discrete math 2
    differential equations
```
```
The base courses were a prerequisite for everything, the tracks were independent and taken in order.
So to answer your specific question, only algebra is needed for discrete.  If you want to fast track, do one of these:
```
```
algebra, discrete
algebra, linear algebra, discrete (if you want to cover matrices first)
```
```
HTH...  It about killed me when I returned to school and took these, but I'm a much better programmer for it.  Good Luck!


Question:
I'm working on a web application that needs to prints silently -- that is without user involvement.  What's the best way to accomplish this?  It doesn't like it can be done with strictly with Javascript, nor Flash and/or AIR.  The closest I've seen involves a Java applet.

I can understand why it would a Bad Idea for just any website to be able to do this.  This specific instance is for an internal application, and it's perfectly acceptable if the user needs to add the URL to a trusted site list, install an addon, etc.

Answer:
I have to be honest, I am kinda thinking out loud here.. But could it not be done with  an applet or some sort (be it Java or whatever) that is given trusted permissions (such as that within the Intranet zone) or something?
May be worth investigating what permissions can be given to each zone?
Following a Google, I think you definately have a challenge, so far most of the articles I have seen involve printing to
printers connected to the server
.
If its internal, would it be possible to route printing from the server to department/user printers or something?


Question: Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception.  Thoughts on a postcard please.

Answer:
Well, I don't see any difference between catching a general exception or a specific one, except that when having multiple catch blocks, you can react differently depending on what the exception is.
In conclusion, you will catch both
```
IOException
```
and
```
NullPointerException
```
with a generic
```
Exception
```
, but the way your program should react is probably different.


Question:
>>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334

time.mktime should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day?

Answer:
```
```
mktime(...)
    mktime(tuple) -> floating point number

    Convert a time tuple in local time to seconds since the Epoch.
```
```
local time... fancy that.
The time tuple:
```
```
The other representation is a tuple of 9 integers giving local time.
The tuple items are:
  year (four digits, e.g. 1998)
  month (1-12)
  day (1-31)
  hours (0-23)
  minutes (0-59)
  seconds (0-59)
  weekday (0-6, Monday is 0)
  Julian day (day in the year, 1-366)
  DST (Daylight Savings Time) flag (-1, 0 or 1)
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.
```
```
Incidentally, we seem to be 6 hours apart:
```
```
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233356400.0
>>> (1233378000.0 - 1233356400)/(60*60)
6.0
```
```


Question:
Could somebody please do a rundown of how to programmatically encrypt a config-file in .NET, preferably in C#.

What I would like to do is do some kind of check on an application's startup to see if a section is unprotected, and if it is, then encrypt it. This for both settings and connection-strings.

Also if anyone could list the types of encryption-providers and what is the difference between them.

I don't know if the code for doing this in a normal WinForms-application is transparent to doing this in ASP.NET.

Answer:
There is a good article from 4 guys about
Encrypting Configuration Information in ASP.NET 2.0 Applications
Hope this helps


Question:
Anti aliasing cannot be turned off in WPF. But I want to remove the blurred look of WPF fonts when they are small.

One possibility would be to use a .net 2.0 component. This looks like it would lose the transparency capability and Blend support. Never tried it though.

Anyone has a solution for this? Any drawbacks from it?

Thank you

Answer:
Have you tried putting a
WindowsFormsHost
control on a WPF window/control? That will allow WPF to render a WinForms control.
UPDATE November 2012
: This question and answer is 4 years old.
Text rendering has since improved in WPF
. Please don't put WinForms controls in WPF apps; that was a hackish way to fix font rendering. It's no longer needed.