Advanced File Handling with Streams in C++

From time to time, I will not use streams, as I sometimes prefer the console output, although, as you may know already, that also is handled like a file, so every trick that works on the console IO will compile and run just as well on files. For this article, a minimal knowledge of STL containers and iterators and how they work is necessary.

I won’t promise that I’m going to present every little trick, but I will try to show and discuss a few interesting ones. The stream part already forms a pretty strong basis for programming for anyone, but as you will see, once we combine it with some algorithms (found inside the <algorithm> header) it will be even simpler to use, and offer more.

First, let me point out that, as with any stream, the manipulators will work also with the files. If you have not heard about them in general, or how you should handle/use them, please search for my articles covering it. I dedicated two separate articles to the topic, and both of them have appeared (if not, then they are queued) here on the Developer Shed Network.

Printing from Containers

Probably from the first day that you started learning the C++ language, you’ve heard that you should start using the STL library, as it offers great containers. If you initially started with the C programming classes and you like arrays, I urge you also to get used to the vector container at least.

Often, you have a collection of types in a vector and you want to print them to the console (or a file) separated by a space, or every item in new line. Writing this can be done in just a line:

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

int main()

{

std::vector<int> numbers;

numbers.push_back(97);

numbers.push_back(98);

numbers.push_back(99);

copy(numbers.begin(), numbers.end(), ostream_iterator<char>(cout, “…n”));

return 1;

}

We use the copy algorithm; it copies from our container to the stream. The real strength of this design is the ostream_class and its parameters. The class returns an iterator that will point out where to print the content between the first two iterators of the copy. In addition, the ostream_iterator class is highly customizable, with inputs like output format, where to put it, and what delimiter will be used between the members.

The template argument must be one for which the insertion operator is declared. As long as all of this is completed, you can call this method even for your own custom class, as the operator<< will be used to copy the streams from the container to the output stream. The result in the upper case looks impressive; we just converted the int values into their ASCI chars.

a…

b…

c…

Press any key to continue . . .

Reading Inside a Container

You can use the same trick in the other direction (input), since it’s just as easy. Let us suppose you have the input waiting for input in a predefined way. For example, we will try with a sequence of int types. Now we will copy in the other direction, so we need to indicate from where to copy, and to where. The first two members are the istream_iterator that will delimit the borders. When we pass a class to it, it will return an iterator to its start, and no parameter will just point to the end of file.

The last argument is a little more interesting. Under normal conditions, whenever you make a copy, you make sure that the target is large enough to hold the incoming stream of data. This is achieved by calling the destination resize() function, but in the case of this iterator type, this process is simplified by calling the push_back() method on the destination iterator. Hence, a vector can handle any size as long as you have enough physical and virtual memory available.

#include <iostream>

#include <vector>

#include <algorithm>

#include <fstream>

using namespace std;

int main()

{

vector<int> numbers;

ifstream in;

in.open(“In.txt”);

if (!in)

{

return 0; // terminate program, nothing more to do

}

copy( istream_iterator<int>(in), istream_iterator<int>(), back_insert_iterator<vector<int>>(numbers));

copy(numbers.begin(), numbers.end(), ostream_iterator<char>(cout, “…n”));

return 1;

}

The input file contained the following:

97 98 122 100 101A 12

With the output:

a…

b…

z…

d…

e…

Press any key to continue . . .

The rule stands. If you have defined a special class, and if you define the extraction function (operator >>) for it, you will be able to call it for this kind of input. For each member, the extraction function will be called to resolve the input. Naturally, you need to call the iterator creations to those kinds of template arguments.

Writing to Two Streams

Often, you may need to stream your data into two places at the same time. A perfect situation similar to this is when you need to dump the screen’s content to an output file. Therefore, whatever will be printed to the screen will be contained by a file as well. To resolve this, you always need to create another stream, and later call an insertion process for both the console and the file.

This is counterproductive. Besides, you might forget one step and then struggle due to a strange inconsistency. The perfect solution is to create a stream type to which we can bind both of them. Deriving from the ostream class is not a good idea, as this offers no virtual over-writable functions.

Doing the same thing at the streambuffer class is possible, as I have described in my article called Extending the Basic Streams in C++”. Feel free to search for it here on the network if you are interested in learning about this approach in more detail about this approach. However, there is a much simpler way to do it.

#include <iostream>

#include <fstream>

#include <iomanip>

using namespace std;

template<typename charType,

typename twinCharTraits = std::char_traits<charType> >

struct basic_TwinStream : basic_ostream<charType,twinCharTraits>

{

//define our new basic type

typedef basic_ostream<charType,twinCharTraits> TwinType;

 

// constructor -> we initialize the two stream references

// construct this by using as buffer for the stream the // buffer of the first

basic_TwinStream(std::ostream& os_1, std::ostream& os_2)

: TwinType(os_1.rdbuf()), m_os_1(os_1), m_os_2(os_2)

{ }

// declare the insertion operator, this will be called on // both of them

template<typename T>

basic_TwinStream& operator<<(const T& t)

{

m_os_1 << t;

m_os_2 << t;

return *this;

}

// a insertion operator for the manipulators

basic_TwinStream& operator<<

(TwinType& (__cdecl *manip)(TwinType& ))

{

m_os_1 << manip;

m_os_2 << manip;

return *this;

}

private:

std::ostream& m_os_1;

std::ostream& m_os_2;

};

typedef basic_TwinStream<char> TwinStream;

typedef basic_TwinStream<wchar_t > WTwinStream;

int main()

{

ofstream out(“OutIn.txt”);

TwinStream oneTwinStream(cout, out);

oneTwinStream <<left << setw(25) << setfill(‘@’)

<< “Yeti is from north” << endl;

}

The key observation here was to detect that, for a stream, the most-used function is the insertion operator. If we can create a class where we simply overwrite, we are close to a perfect situation. However, another detail must be considered. What if we want to use the manipulators to format our output? Implementing in this fashion is necessary, as we will lack any other functions.

Before we venture further, let us see the result. Here are the outputs first, straight from the console and followed by the output into the OutIn text file:

Yeti is from north@@@@@@@

Press any key to continue . . .

Yeti is from north@@@@@@@

As you can see, we will be losing the side of available functions to call. In fact, all that we can do is call the insertion operator on both types and manipulators. Calling more advanced functions, like the unsetf() or setf(), is on the list of things to be implemented, and I will leave this task to the reader. The fact that the other functions are missing is a good thing, as the user cannot use some of them that make no sense in this context.

Serialize Your Class into Streams in C++

So you started learning to code in C++. You know how to create a class, learned the golden rule that a “deconstructor” will always exist, and have decided that it’s time to learn about streams. What a great tool to use if you know what it is all about.

I assume you know how to use streams for writing some data to a file and not only to the console. If this statement is false in your case, I advise you to read some of my other articles on this topic, published here on the Developer Shed Network. Once you understand that, then handling the serialization of objects with just a few lines will become manageable.

However, there is a problem. When you try to pass to the stream, your very own and custom class (with its own internal members) the compiler just puts out an error that this is an invalid move. The reason for this issue is that the streams are compatible by default only with the default types known by C++. If all this is true in your case, you are in the right place, as here I will show you how to resolve it.

This process, known also as insertion and extraction in streams, is an easy and practical way to resolve serialization. In the world of C++, I/O tasks are completed through the iostream library, which is an object-oriented class library that makes use of multiple and virtual inheritance. This is provided inside the “iostream” library as a component of C++.

Why Should You Make Your Class Compatible with Streams?

Making your class compatible with the streaming function is in reality a straightforward task. You simply output anything that you need inside an overload of the insertion/extraction operator. Let me present  the advantage of implementing a streaming process first.

I have constructed a simple class that represents a car inside a database. As with any car at this level, it will have a unique ID and a name:

class car

{

public:

car(){};

car(string carType, int ID)

{m_carType = carType; m_ID = ID;}

virtual ~car() {};

string getName(){return m_carType;}

int getID(){return m_ID;}

void setCar(string carN)

{ m_carType = carN;}

private:

string m_carType;

int m_ID;

};

How do we serialize this object easily? We might just use the Iostream library of C++. Now I will present my examples in the cout (the console stream), but this can be generalized to any kind of stream.

Michael, for instance, assumes that he as a programmer is more interested in the ID, so apply a print like this:

car A(1, “Ford”);

cout << A.getID() << ‘t’ << A.getName();

Later, Joe enters the picture, and he believes that, for the user interface, the name is more important. So he decides to push the ID into the background the ID, and inverts the printing order:

car B(1, “Ford”);

cout << B.getName()<< ‘t’ <<B.getID();

Now imagine doing this inside a serialization program. Each time Joe tries to read in the data written by Michael (or vice versa), most probably undefined behavior will occur, because an inconsistency of the two serializations exists. Converting the name to a number and the number to a name is not a good idea at all.

Now all of this, placed inside of a single main function, may look trivial, but imagine this is inside a large application — one that has tens of thousands of lines. Things will be much harder to synchronize once a group of programmers start working on this program, not just you.

Besides, explicitly writing down every time how the members of the class should be printed is a time consuming activity — one that will extend the length of the code you need to spend looking over the code, and increase the number of places where errors can occur. We should be able to directly apply the insertion/extraction operator to our class, and write all this just once in an obvious place for maintenance purposes.

The iostream members will accept any basic build types like char*, int, string, and so forth. All we have to do is make our class a basic build type as well, and we will accomplish this by defining the operator overload for it. Proceed to the next page to see how to do so.

The Insertion

The insertion operation is completed by the >> operator. It is a smart move from the designing team to overload the bitwise shift operator for types where you cannot do this, indeed where this does not make any sense. Reusability is once again scheduled.

The first task we need to do is define the function of the operator overload like this:

ostream& operator<< (ostream& out, const car& per);

This is overloading the operator << (in fact it defines the operator) for types where, on the left side of the operator is an ostream, and on the right side a car type. The const assures the input class that through this process the data of the “per” will not change, and the reference passing of the argument is for performance purposes, as we avoid creating a new object and copying the data from the input inside it.

Now all we need to do is perform the insertion of the class inside the function into the ostream. Nevertheless, here we have a small design issue. We need to access all of the data in the “car” class inside the function, as we might or might not have functions that guarantee access to its private or protected members.

Here for instance we have the getName() and getID() public methods for this, but designing a class that will not divulge a member that we still want to serialize is surely an achievable task. Besides calling, a function can decrease the performance of your program. We need to make sure that we have access to all of the members of the class, so the road we need to pass on is the friend keyword.

friend ostream& operator<< (ostream& out, const car& per);

Applying the upper declaration of the function inside the car class will point out to the compiler that this function is a friend with the class and guarantee access to all non-public members/functions, just as if those were public. Now we can define the function outside the class in the following manner:

ostream& operator<< (ostream& out, const car& per)

{

out << per.m_carType << ‘t’;

out << per.m_ID << endl;

return out;

}

Inside the function, we just pass each build in type C into the stream, and you might want to make sure that the members are separated by some white spaces (or else you will see a long sequence of chars in your streams). Also, make sure to call a flush at the end of your streaming (here the endl has encapsulated that option); otherwise, they might just be pushed into the buffer and, in the end, not displayed properly.

The Extraction

The insertion assumes that we take the same passes, with just a couple of differences. The direction of the operator changes; now you need to overload the operator >>. You need to declare/define the function for an ifstream type.

As long as you know how the input will look, your task is trivial. For example, for the upper class, I know that the order is name followed by the ID number, and all this is separated by white spaces (the newline and the tab). So I just read it in, maintaining the order of the output.

So declare the friend function inside the class:

friend istream& operator>> (istream& out, car& per);

Define the function as follows:

istream& operator>> (istream& in, car& per)

{

in >> per.m_carType;

in >> per.m_ID;

return in;

}

Here let’s point out that the input argument of the class is no longer const, as we will modify its members with the input data. Returning the stream (here and at the insertion process) is required so that we can maintain the chain affect of the insertion/extraction process like this:

cin << “Yeti” << endl ;

Now that we have this entire task completed, let us see it in action:

// first construct a few items from the upper

car A(“Ford”, 1);

car B(“Toyota”, 2);

// create a ofstream into what will print it

ofstream output(“OutIn.txt”);

 

output << A <<B; // this will print all to the first person

output.close();

// create a ifstream for now to read in

car C,D;

ifstream input(“OutIn.txt”);

input >> C >> D;

 

cout << C <<D << endl;

input.close();

The output result is exactly what we were looking for:

Ford 1

Toyota 2

Press any key to continue . . .

Following the convention within the stream and taking the steps outlined above, instead of writing a function like writeToStream, will make your code easier to read. Now we have a centerpiece that we can easily maintain and make sure there is no conflict is between the input and the output.

Our type is now included between the basic build types, so if we want another class that encapsulates our car class inside its insertion and extraction function, we don’t need to serialize our object anymore; just call the operator on it, as we’ve already done here.

However, if you want to serialize your own data throughout your files in a system that has a more complicated build, I strongly recommend that you take a look at Boost’s serialization classes. They offer you this support in a simple, efficient, and portable way.

General Stream Manipulation in C++

If you’ve programmed in C already and used the “scanf” function, you already know what I am talking about here. Writing a float value on the screen with two digits of precision after the decimal point is done on the fly. A strong library such as C++ must have something similar implemented.

Once you’ve gone through this article, you will see that even more. You can go as far as to create your own formatters/manipulators, but that will be the subject of a different article, so stay tuned for that one.

For now, let’s see what we have implemented. Manipulators are functions that are applied with the insertion operator << in the case of output streams. They are declared in the <iostream>, <ios> or the <iomanip> header, depending on the area they are covering.

Eventually manipulators modify a couple of flags that define the behavior of the stream, defined all the way up in the ios_base class. Nevertheless, before we apply any of them, we should first grasp the knowledge of how we can reset all that we have modified.

The “flags” member function of each stream is overloaded in two ways. First, one takes no parameters and returns the current format state. The return type is a defined type inside the stream class, namely “fmtflags.” I will present my examples on the cin and cout stream connected to the console window, but they will work on any stream class. Each time you want to save it, just act as follows:

#include <iostream>

using namespace std;

int main ()

{

ostream::fmtflags basicFlag = cout.flags();

// Do manipulations on the stream // (1)

ostream::fmtflags usedFlag = cout.flags(basicFlag);

// Apply new formatting flags

cout.flags(usedFlag); // recall the format used at (1)

// Print what you want with the first collection

cout.flags(basicFlag); // reset the console stream flags

return 0;

}

This first example I’ve extended a little so you can see the header I use, and that I also added the std namespace to the global namespace, as I’m a bit too lazy to write the “std::” keyword in front of each function used.

Now we have saved in the “basicFlag” variable, in matter of effect, the current format setting applied to the cout stream. The second overload of the flags function will handle the set process. It will also return the current collection of flag settings inside the stream and set the new collection that you gave as input.

As you may expect, you do not necessarily need to save the usedFlag before the change. You could also just call it as we did in the end. We set the new settings, in fact the basic settings, saved at the start.

As far as the library where you’ll find them, most of the manipulators are found inside the iostream header; however, the ones taking an argument also will have their place in the “iomanip” header, so make sure to include that as well, once you use one of them on your stream.

All of the flag changes can be resolved with the rdstate() and setstate() member functions of streams, but this is harder to read and manage. Manipulators provide a more elegant solution, so I recommend using them; however, be aware that when using these, the changes are permanent (except one that confirms the rule :P, but we will talk about that also).

If you set a flag, it will stay until you explicitly modify it. The cin/cout streams are a prime example of this, as most programmers would like to have them working in a default mode. So in those situations where you use modifiers, make sure you delimit the modifications with a state save and a restore.

If you thought that there were already too many ways available to modify them, let me say to you that the flag sets can be done with the setf() function also, and unsetf() will turn off a flag. As in the example below; do not think about what it does, just observe the method:

cout.setf( ios_base::dec );

cout.unsetf( ios_base::dec );

In fact, the “setf” has an overload that takes two parameters, where the second is the flags that are to be turned off. This trick can save you a couple of lines when you want to turn some flags on/off at the same time.

Numeric Systems and Bool Values

In this section we will talk about how you can change the numeric system in which you display a number, but first I’ll show you a little trick for telling the cout stream to write the bool values in a more common language. Surely every programmer will know that zero is false and anything else true, but why not make that obvious to anyone?

For this, there are the boolaplha/noboolaplha flags:

cout << boolalpha<< false << ” and ” << true << noboolalpha << endl;

cout << false << ” and ” << true << endl;

false and true

0 and 1

Press any key to continue . . .

First, we printed in the more sophisticated way with the flag on. The second line (actually the third in the code snippet) is how they will get the default settings. From this you could already point out the permanent state of the flags. As noted at the end of first line, we changed the flag back to the default behavior; the noboolalpha is set on by default.

In addition, here we should cover the endl manipulator that puts in a new line and flushes the stream. You may also put just a zero char in the console if you apply the ends manipulator. Note the empty space in the example below before the “Press” word.

char a= ‘a’;

cout << a << ends;

a Press any key to continue . . .

Now how about number systems? We all know that by default, we work in the decimal number system, but sometimes we may want to express/print the number in a different one. The octal and hexadecimal systems are used near the decimal one, so only for these the basic stream manipulators offer support. For others you may write your own one.

int a = 100;

cout << oct << a << endl ;

cout << dec << a << endl;

cout << hex << a << endl;

cout << setbase(9) << a << endl;

cout << showbase<< endl;

cout << oct << a << endl ;

cout << dec << a << endl;

cout << hex << a << endl;

144

100

64

100

0144

100

0x64

Press any key to continue . . .

In the example above, I have already explained everything, but let’s go through it once again for the sake of detail. For setting a specific number in you system, you apply the corresponding manipulator to the stream: the oct stays for the octal number system, the dec for the decimal and the hex for the hexadecimal.

You can also set base explicitly though the setbase() manipulator (be warned; as this requires an argument as input, you need to include the iomanip), but calling it on anything other than 8, 10, or 16 is considered invalid input, and the decimal default will be forced. Now all that remains is learning how we tell the system in which that the number on the screen is displayed.

In order to accomplish this, the so-called showbase manipulator was made. It will display nothing in front of number if it is a decimal, add a “0” if it is in the octal system and a “0X” if the hexadecimal number system is the rule. By default, this is off.

Float Formatting

Formatting float numbers is a little more interesting, as you can change the precision of the display, the notation of the display, and even the decimal display for float values that turn out to have some whole part at a level. All of it is condensed in the lines below.

double i = 3.165; //(1)

cout << i << endl; //(2)

cout <<showpoint<< i << endl; //(3)

int old = cout.precision(2); //(4)

 

cout << i << endl; //(5)

cout << scientific << i << endl; //(6)

cout << uppercase<< i <<endl; //(7)

cout << fixed << setw(8) << right << i << endl; //(8)

cout << setw(8) << internal ; //(9)

cout << setfill(‘@’) << showpos << i << endl; //(10)

 

cout << setfill(‘#’) << showpos << -i << endl; //(11)

cout.precision(old); //(12)

3.165

3.16500

3.2

3.17e+000

3.17E+000

3.17

+@@@3.17

-3.17

Press any key to continue . . .

In the first line we just print out the number as we should—nothing devilish. In the third row of the code snippet we apply the showpoint manipulator that tells the stream what prints the zeros after the decimal points. The opposite of this is on by default, the noshowpoint manipulator.

We can set the precision of the output with the precision function of the stream. This function will return the old one, so we can restore it in the end (line 12). However, be aware that this will be the count of all numbers that will be printed, even the ones prior to the decimal point.

Here I cannot stress enough that C++ will NOT truncate the number when it converts from a larger precision to a smaller one. Instead, it will round the number, so be aware of this. Line 5 in the code and line 3 in the output demonstrate my point.

Then again there it is the scientific flag. This will display the number in a scientific manner. However, this has some additional effects. This means that the precision functions no longer set the precision for the number. Now only the after-the-decimal-point function will be applied.

Whether or not to apply the scientific mode is resolved automatically by the stream after making an evaluation of the number. If it is very large or small, the scientific view will be better for readability, so it will print it out in that fashion. Nevertheless, you can request the scientific mode with the manipulator mentioned above. If you want your output to be easy to read, better leave it on the default behavior.

If you want to print a char uppercase (also, for hexadecimal values, the X), just apply the uppercase manipulator or the nouppercase if you want the default behavior. The fixed manipulator will get the precision behavior from the scientific mode into the default settings. So just apply that to the numbers after the decimal point.

Then we have the ordering options. You have a right manipulator and a default one, left. This will make sense with the setw function. This will point out to the stream that you want that your output take n position (what you specify as an argument to the setw) on the screen.

The stream will take the output, and if it is smaller than what you specified, align it as required and fill the remaining chars as you want. By default, this character is the space, but you can modify it as I did with the setfill(‘#’) manipulator.

Here we must point out that setw is the exception function that I was talking about earlier. The setw function is special, and only affects the following first output (or input, as I will show in the last section). That is why the last line ended up printing just the number.

Other manipulators used here are the internal one, that will tell the stream to order the sign to the left and the number to the right. Then there is the showpos one, that just forces it to print the positive sign on the  screen (or inside a file).

You may ask how we turn off the fixed effects, as I have not mentioned a counterpart. The answer is that we must unset all the settings for the floatfield (all that apply for a float number) with the following method:

cout.unsetf(ostream::floatfield);

// note: or we can write a manipulator to do the same but //that will be explained in a future article

Preparing For Programming Contests

This is the second part of the four-part series article I began here on Dev Articles. The first one also appeared here and tried to elucidate the mystery of why we should bother even to participate in something like this. If you failed to catch it when it originally appeared, you are free to search for it in my profile or by its title: Programming Contests: Why Bother?

As I told you at the end of the previous article, today we are going to focus on how you should prepare and act when participating in a programming contest: before, during, and after it. For a start, let us speak about what to do before.

We can divide the “training camp” that you should go through before the contest in the following parts: theory, mentality, global, simulation, experience sharing, and at the place. These sections will make sure that you’ve put in 90 percent of the effort and investment that is required to be successful at this. The remaining 10 percent is composed of your intuitiveness and (why not recognize it?) pure luck.

Remember that as important as it is to prepare for a contest, it is just as important to not overload your brain. It is advisable to totally relax for about a week before a greater challenge; just enjoy life and recharge your batteries.

You’ll need to understand high-level theories for the contest; that’s the theory element I mentioned above. Most of the time, if you rely only on what your teachers teach you in high school or even at the college/university level, you will easily find yourself facing issues that you cannot solve. This will be mainly because you don’t know a special technique, which seemed extreme and useless within the material for an average student…and therefore, it was not included.

In order to be entirely ready for a contest, you need to read a couple of books that endeavor to cover the algorithms of a field in detail. These are written most of the time by ex-Olympians, people who themselves faced these issues and are explaining and elaborating their own experience.

There are dozens of these kinds of books; nevertheless, there are a couple of them that have earned the title of classics. One that has earned the title of “The Bible of Algorithms” for its value is the appropriately titled Introduction to Algorithms by the trio of Cormen, Leiserson, and Rivest.

The other is Donald E. Knuth’s The Art of Computer Programming; it is highly polished and quite heavy. Other interesting books include The Algorithm Design Manual by Steven Skiena, Programming Challenges: The Programming Contest Training Manual by Steven Skiena and Miguel Revilla, Algorithms by Robert Sedgewick and Computational Geometry: An Introduction by Michael Ian Shamos and Franco P. Preparata (from which you can read an excerpt here ).

Of course, there are more books, which may be worth your attention; however, these are the most popular of them. Then again, the Internet can serve as the most elaborate way to obtain information; sites like the USACO Training Gate and the ACM’s site also have a large database with problems and their solutions. Now let us move forward by focusing on the mentality required.

Before the programming contest

Prior to each contest, many people set up roadblocks for themselves with false ideas and mindsets. I would like to talk about them here so you can get them out of your head before you compete.

The one always invoked is “I am not prepared enough.” Well, the truth is that most of the time, this indeed has some basis. Yet you should not sit back and give up; on a harder contest; the problems may require something more than just pure knowledge, intuition and luck. Go at it with an optimistic and relaxed approach.

Still, do not exaggerate; experience will tell you how much preparation and studying you should do beforehand. Remember that even if all goes wrong, you will still obtain valuable experience for the future. With this, we come to the second false idea: that someone else who is participating is better than you, and that you, therefore, will have no chance.

Wrong. All of you will have the same environment during the contest. S/he may have a better chance, but nothing is done until it is done. Moreover, as I explained before, the experience is one of the main attributes/traits that helps when competing. You can only accumulate this if you go and compete, right?

Another false thought is that you should not start a problem just because it is too hard. You know it is easier to win in a contest where the problems are easy, as solving them requires less effort. The true challenge is to do the same on a contest where the problems are very hard.

Here you may not come up with a perfect solution, just an approach that can solve a part of the tests. This alone can be enough, though, to obtain the desired place. Still, you cannot be sure that you will be number one, as someone may just solve it. If no one makes the maximum score on a contest, it does not mean that none of the participants were prepared enough.

With this, we came to the final mental block. A few contests last for more than a day of competition. If for some reason, you make too few points on the first day, do not say that you have no chance in the future. A good second day can bring home for you the desired place. Remember that the set of problems in contests are hard most of the time, and the points obtained by contestants are rarely close to the maximum. Even winning half of the points can turn out to be sufficient.

Now we can continue to the global preparation session. This involves simply tracking your progress and making it systematic. It is advisable to maintain a list of what algorithms are coming up most of the time, how you implement them, and what problems they can solve.

Plan your approach toward every little detail of the contest. If you know what you want to do and how you imagine doing it, you have already a higher chance to actually do it when you need to. Here enters quite a lot like time managing and tracking your progress, so you know your weak points.

The next part is the simulation. If you want to react better at the contest, the best way to accommodate the situation is to simulate it. Find out the point system, and the structures of the contest in which you are going to participate, and test yourself; then, analyze your comportment.

One of the best ways to do this is to use the many Internet sites that offer a set of problems and accept and test your solution. Do this just as you would at the contest — no breaks or pauses for time, and so on. If you do not act in this way, you will only trick yourself. Ultimately, observe your mistakes and correct them. We all learn best from our own mistakes, so do not fear them.

Experience sharing is also crucial. As I said before, the best knowledge comes from experience. It is advisable to learn from others also, so if you can, take problems to your professors or people who have already participated in the contest. Sometimes there are organized collective sessions; make sure you go to these, as they increase the level of understanding of all contestants.

Finally, the night just before the contest, you should make sure to sleep enough and to be present at the contest in time, with all of the required accessories (like a pen, paper and so on). Moreover, you should also, of course, maintain a mindset that will let you treat the entire contest seamlessly, with little or no effort.

During the contest

Of course, being ready at the time you are at the contest is even more important than being prepared enough. When you get the problems, make sure you read them all and get a general idea of what you need to do. During the first few minutes, do not even touch the computer; just imagine how you would solve the issue and check it out on paper to see if it works.

In addition, this is the time to clarify any questions you may have related to the problems. Form the questions so the answer can be a clear yes or no; otherwise, you may get a “No Comment” answer. If this happens, it means you may need to reformulate the question or simply that what you asked is already included in the problem. So re-read it.

Make sure you plan your algorithm according to the input limits. This can drastically change the difficulty of a problem. For instance, if N<200, an algorithm with a complexity of N^3 will run in a reasonable time, but the situation changes when this is around 2000. Take into account every little detail.

It is recommended that you start with the easiest problem, or if you cannot choose one like this, start with the one that seems most familiar or accessible for you. Make a game plan and stick to it. This means you’ll need to allocate a specific time for each of the problems and try to complete them in that time. If you terminate one earlier, you can modify your time for the others.

Start searching for possible solutions and find the best of them, but not necessarily from the point of view of efficiency. Rather, find one that has the best complexity/implementation time ratio. Remember that you are asked to solve the problem in a given time, not to find the best possible solution. As always, do not exaggerate and lose more time on searching for a better, easier-to-implement solution if this search takes more than the time to implement a complex algorithm.

Always implement the shortest solution between the ones that have the best complexity. Once you start implementing the algorithm, there are a couple of methods that will increase your writing speed and most important, shorten your debugging/testing time. Let us go over them.

It is an unwritten rule of contests, (unless it is explicitly specified in the problem) that the input data is always correct. Compilation settings do affect the execution time of the application. So do not be amazed if, at the contest, your program runs more slowly than at home.

Choose to write code that is simple and structured. In competitions, many prefer to write more C stylish code as it is more secure and offers fewer places to go wrong. If you have an option, do not use pointers, because debugging them can turn out to be troublesome. This also goes for the use of templates. Operations with real numbers are less accurate than in the “real” world, and slower, so avoid them as well.

Learn to write your programs in a modular form. This will let you debug your programs more easily and make sure that you can follow what you are writing effortlessly. Do not overstate! Remember that calling a function takes extra time. It is best to minimize the number of calls.

Use variables that will tell their purpose within their name. Guess what? A variable can contain more than two characters. Nevertheless, do not waste too much time with this; stay under the 10 character barrier. If you write in a way that will make your code more readable, even after a year, you will make your own life easier. For this purpose, coding standards were invented. If you want to find out more about this, make sure you read my article here. You can skip the comment part at time-pressed contests.

Save and test your application often. You do not want to get in the situation of having a well-made program teamed up with a power surge, equaling an unsolved problem. Nobody will believe that you actually made the program and it was good. Also, testing often can save you precious time in the later debugging process. The catch is to test at every major step. For instance, if the input needs to be sorted, test it, so you do not fail at this “milestone.”

Sometimes, more of the input data stream is put inside a single file. If this is the case, take extra care, because if your program hangs up at one problem, you will lose the points for all of them. Also, make sure you flush the output stream after each one of the resolved sub-solutions, as you may get some points for the problems for which your program ran successfully.

Your code needs to be short and optimized. How to make this happen will be the subject of the next two parts of this article series. Now I will give you some advice about the debugging part.

Everyone would like to write perfect code on the first try; however, experience tells us that this happens too rarely, so eventually, you will arrive at this task. Always make at least four tests to determine if your algorithm is a correct one (a more advisable number is 7-8, though).

The test given on the paper has little significance. This is given most of the time more to confuse the contestant than help him/her. In addition, these never contain those special cases for which you will lose points. So invent tests yourself and run them on this. If one fails, run your program gradually and see where something goes wrong.

If you find the mistake, you may reload the earlier executed test to make sure you have not modified it so that it will now fail. If the time allocated for the problem passes, bring up a version that works at least partially and continue on to the next problems. Do not waste too much time debugging a single program!

When you manage to finish, if you have additional time and the initial algorithm turns out to be too slow, you may try to search for a new one. In this case, keep a back-up file of the original, so if everything goes wrong, you can still present the original solution.

After the contest and closing thoughts

Sometimes you may finish before your time is up. This happens normally only on the easier contests; nevertheless, if this does occur, do not come out of it yet. Make sure that each one of your programs runs with no errors, and invent more test numbers.

Sometimes you may even write a test generator and a solution checker, as the same are tested later on by a commission. Before you finish, make sure you did everything to get the best result.

This is the time for you to evaluate yourself, so when the results are published, you can contest it if you feel that you earned more. At some competitions, the evaluations are made in front of the contestant. This is the perfect time for you to observe your mistakes, if you made any, and learn from them.

Now you earn experience. Talk with the other contestants. See how they approached problems that you could not resolve, or if they did it in a more elegant fashion than you did. Find out what mistakes they made, also, so you can learn from them.

Now we are done. We went through all of the stages of a contest. Make sure you join us next week when I will be presenting for you a couple of methods that let you write code in a short and optimized way. Thank you for your patience in reading this article.

Easy and Efficient Programming for Contests

A few of the tricks I will present here are not always the best approach, so use them only when you really need to. For instance, if you are creating a complex application that is being co-developed by a large team, it is a good idea to make everything as clear as possible, rather than inserting complicated code that may drive the others crazy. Nevertheless, at a programming contest, it would come handy.

Most of the tips I will share are the result of years of experience at programming contests or bright thoughts from more inspired people. I invented none of these examples, but I tried them out in my own code snippets, and they work like a charm, creating code that is both simple and fast.

Therefore, I will point out the initial source of these ideas, so make sure to give him all the credit. In this article, most of the ideas came from Alexandru Mosoi. Additionally, note that this is an article series about programming contests. In these, I try to answer questions like what they are and why you should participate in them. Finally, I also present a collection of useful tricks that will help you finish out in front.

If you missed the first two parts, you could find them at my profile under the names of “Programming Contests: Why Bother?” and “Preparing for a Programming Contest.” Now, as I promised you in the previous articles, let us get on with this.

How to write code

The problem with most beginners is that they do not realize the importance of clean and visible code. Most people say that this only puts extra effort into the equation and complicates your life for no reason. They will only see how wrong they are when they start to lose competitions for this. The sooner you comprehend this, the better.

One of the crucial things to learn is how to use the language to create code that is both readable and “followable.” By this, I mean that you need to write your code so you can instantly tell at every single point what you are doing. Of course, many things can be done in a multitude of ways; however, you want something clean and simple, so in the event of a bug, you can detect it in a short period.

One of the ways to achieve this is to make use of functions. Use them to structure your code in sub-segments according to tasks. Each piece of a function should nevertheless fit inside a screen; therefore, they should be around 30-50 lines long and not longer. The golden rule is that the complexity of the function (to write/ understand) is in inverse proportion with its length.

Prefer, as long as it is an option, solutions that are simpler, and fewer bugs can occur inside them. Therefore, use C instead of C++ as long as you can. This way, you will create a more reliable program that also will turn out to be faster most of the time.

Sure, C++ offers a couple of ways to resolve elegantly some traditional problems; however, these will show their muscles inside larger and more complex programs. When we are talking about contest programming, C will do so many things faster.

I myself programmed a couple of algorithms in C++ just to observe that the college’s code in C runs significantly faster. For instance, sorting a vector of ints with std::sort is slower than using an array of ints and sorting it with the qsort.

Additionally, “cin” “cout” and “cerr” slow down the application significantly. The bottom line is, if you have an option, do not use STL and C++. When you break down your code into smaller functions, you may use the inline keyword so you will not lose speed due to the function call.

This will tell the compiler at compile time to take this and insert 1:1 to where the function is called (if the function is smaller, and this will not make a significant change to the size of the exe), or just place that in cache of the CPU at run time. However, the cache has a limit, so do not declare all of them in this way, because this will mean none of them is inline.

Make sure you use the const and static keywords also. If a parameter for a function is passed down that should not be modified, use the const keyword. This will save you a lot of time for eventual debugging, because something still changed it. It is a good idea to use the uppercase letters for more important variables, so they will draw your attention and make you concentrate on them more.

Macros, arrays and memory

Avoid using macros for functions. You can lose points for a simple construction as follows:

#define MAX (a, b) ((a) < (b)? (b) : (a))

 

int query(int a, int b)

{

int k, l, r;

int result = 0;

 

result = MAX(k, query(l, r));

….

return result;

}

Observe that sometimes, the MAX is called twice; it’s best to avoid this situation during a contest. Instead, use a function declared as inline:

inline int MAX(int a, int b)

{

if(a > b)

return a;

return b;

}

Most of the time at a contest, the input and output of the program is a file. From this, you can already conclude that you need to use a lot of fscanf and fprintf. However, there is a solution for this. You can bind both of the files to the standard input and output with the function freopen (for newer compilers this has been declared deprecated and there exists a secure version of it).

freopen(“in.txt”, “r”, stdin);

freopen(“out.txt”, “w”, stdout);

This is easy, and from now on, you can read and print all of your files using the scanf and prinft functions, making your life easier and your code a little simpler. Every now and then, you may want to use arrays with negative indexing.

Everyone who is familiar with the Pascal language knows that this was possible with it. Nevertheless, creating arrays in this way is not an option in C/C++, however we can trick the system using the following macro definition.

int A[201];

#define A (A + 100)

Now you have an array that you can “index” from -100 to 100. In addition, it is advisable to use the “++i” operator instead of “i++”; executing the first will be faster. As for the second, a local variable will be created to calculate the new value for “i.” Creating variables this small (int) is not a big task, but it is still an additional task. The situation changes when you use STL and use the operator for iterators. In that case, do not ever use the second construction, as that will lead to a slow execution of your program.

For infinite values, I recommend that you use either one of the following:

#define INFINITY 0X3F

or

#define INFINITY INT_MAX/2

This will be most of the time large enough for the input files and INFINITY plus INFINITY will remain positive and fit inside the int. For setting default values for an array use the memset function.

int array_1[100];

int* array_2;

int length_2;

 

// allocate place using malloc for array_2

 

memset( array_1, 0XFF, sizeof(array_1)); // -1 at every place

memset( array_1, 0X3F, sizeof(array_2)*length_2);// INFINITY

When you want to compare two strings where you know their length, it is faster to use memcmp than strcmp. Do the following:

memcmp(string_1, string_2, MIN(length_1, length_2)+1);

Reading the first character after the white space can be done with the following construction of the scanf:

scanf(“ %c”, &character);

As a final thought for this page, you should remember that the program that generates the input data and the one that solves the problems should be two separate items.

Exploiting the language’s strengths

Now we already know that every language has its strengths and weaknesses. As for the C/C++ world, it is a known truth that bitwise operations are much faster than the usual ones known from math classes. Here I will present a method that uses this knowledge to work approximately four times faster than the ones presented in manuals.

The original idea came from Mihai Patrascu, and we are talking about binary search. This type of search will find an item inside a sorted array, taking advantage of the fact that the array is sorted. It will always split the array into two, determine in which part of it is our value, and repeat for that section the upper algorithm until it finds it. The algorithm I will present here will follow this idea, however, by comparing the values directly it will start to determine bit by bit the queried value:

#include “stdio.h”

#include “stdlib.h”

 

int length;

int *array;

 

int binary_search(int value)

{

int i, step;

for (step = 1; step < length; step <<= 1);

for (i = 0; step; step >>= 1)

if (i + step < length && array[i + step] <= value)

i += step;

return i;

}

During the first step it determines how many moves it needs to make, or in more common language, calculates log 2 length. In the second step, it takes the route back and adjusts “i” until it finds the element.

For now, we will take a break so you can digest what I’ve presented here so far. I leave you with the promise that next week I will finish up this series of articles with the fourth part.

New API Platform for HTML5

As for the reasoning behind the API platform’s launch, AT&T’s chief marketing officer David Christopher used the AT&T Developer Summit at the Consumer Electronics Show in Las Vegas to say that it was done to address fragmentation issues.  App developers typically have the tedious task of rewriting native applications for Android devices, BlackBerrys, iPhones, and Windows Phones.  By creating HTML5 apps, the process is simplified, as users of different devices can access them via browsers, all while maintaining the look and feel of native apps.  Christopher’s stance was strengthened by a statistic provided by Strategy Analytics, which projects 85 percent of smartphones to have HTML5-capable browsers by 2016.

AT&T’s new platform also comes with other appealing features in addition to its set of APIs, including technology that will optimize an app’s performance and functionality based on a specific smartphone’s detected capabilities.  Developers can also employ in-app purchases that will appear on a customer’s AT&T bill.  Use of the APIs is available for a fee of $99, which covers registration.  API hosting takes place on cloud services such as Microsoft’s Azure and Heroku.

To further its dedication to HTML5, AT&T announced plans to open an HTML5 app store later this year.  Android and iPhone owners will have the first crack at the store, but the company said other devices would gain access to the store at a later date.  The store is expected to carry a layout similar to a magazine, rather than the typical app store design that lists apps in categories.

Juniper Research, a firm that specializes in research and analysis for clients in the hi-tech communications sector worldwide, recently released a report offering details and projections on the mobile gaming market from 2011 to 2016.  Highlighting the report’s findings is a projection of mobile in-game purchase revenue, hitting the $4.8 billion mark in 2016.

Mobile in-game purchase revenue amounted to $2.1 billion in 2011.  While that is impressive, it pales in comparison to the $4.8 billion projection for 2016.  Juniper feels the jump in revenue will be driven by a few different factors.  First, the sharp increase in smartphone adoption by consumers is a major factor that should boost in-game sales.  Smartphones offering increased performance, design, and functionality are hitting shelves at a rapid pace, and consumers are snatching them up equally as fast.  The more smartphones you have in consumers’ hands, the more exposure, and opportunities for sales to occur.

Another major factor driving in-game purchase popularity is what is described as the “freemium” model.  This model essentially offers a product, such as a game in this case, as a free download.  If a user wishes to access any of the advanced features, they must pay a premium to do so.

The model is less risky for consumers and allows developers to offer a taste of their product at the same time.  As more consumers gain a comfort level with the freemium model, downloads should increase, as should eventual in-game purchases.  Juniper lists games in the Social and Casual genres as the ones that will account for the majority of mobile games downloads, since their audience will likely demand gameplay that is more immersive in nature.

The final factor behind the in-game purchase boom is developer adoption of the freemium model.  Free games often garner more downloads than their pay-per-download counterparts, which provides developers with a wider audience.  Piracy is also reduced with free games since they can be initially downloaded at no cost.

If a user wants to make an in-game purchase at a later date, it must be done through the developer’s server.  Charlotte Miller, the author of the Juniper report, described the appeal of the freemium model to developers:

Juniper’s report also offered other projections for the mobile gaming market.  It projects mobile games revenue on feature phones to be cut in half over the next five years.  Juniper sees tablets as a major player in the realm of mobile gaming as well, with the devices accounting for at least a third of mobile games revenues by the time 2016 rolls around.

The Top HTML5 Audio Players

HTML5 has certainly made a name for itself and has managed to overshadow the previously ubiquitous technology known as Flash.  While you usually hear about HTML5’s impressive capabilities when it comes to video, it has solid audio capabilities as well.  To show you how those capabilities have been put to use, this article will list some of the top HTML5 audio players around.  As you search on your own, you will likely find more audio players, but this list will give you a sneak peek as to what is out there.

MediaElement.js

MediaElement.js offers both audio and video playing capability via pure HTML and CSS.  The player addresses compatibility issues intelligently by employing custom Flash and Silverlight players that emulate the HTML5 MediaElement API on older browsers.  This is an essential feature of the player, as it eliminates any worries you may have when it comes to users with different browsing preferences.

Moving on, MediaElement.js offers extensive customization.  The player is fully skinnable and supports such useful bells and whistles as Ambilight, the <track> element, and full-screen video to give visitors a more enjoyable audio and video experience.  The player can be extended even further with a YouTube API for Flash and HTML5, auto-translation powered by Google Translate, and much more.  Simply put, you will be hard-pressed to find a free HTML5 audio and video player that supplies as much functionality in an easy to use format as MediaElement.js does.

jPlayer

Although our primary focus of this list is HTML5 audio players, jPlayer gives you the best of both worlds, as it allows you to integrate both audio and video into your Web pages with ease.  Just how easy is it to use?  If time is of the essence, you can leverage the power of jPlayer within just minutes.  Should you have any questions, the player comes with extensive documentation and a guide to help you get started.  There is also a sizeable community that you can rely on for your jPlayer needs.

Constructed with the MooTools JavaScript framework and HTML5, jPlayer’s long list of features should appeal to anyone in need of an HTML5 audio player.  Coming in at only 8KB, jPlayer is as lightweight as it is powerful.  One of its most impressive features is its platform support across Windows OSX, iOS, Android, and BlackBerry, as well as such browsers as Internet Explorer, Chrome, Firefox, Opera, and Safari.  jPlayer can be easily extended, works with several plugins across different platforms, and offers no licensing restrictions thanks to its status as a free open source project.  You can also customize jPlayer to fit your needs with a little HTML and CSS.

Audio.js is an HTML5 audio player that is very simplistic in nature.  Do not let its simplicity fool you, however, as it is highly functional and easy to use.  Categorized as a drop-in JavaScript library, Audio.js employs the native HTML5 <audio> tag as its bread and butter.  It also transitions to an invisible Flash player to emulate the <audio> tag when necessary.If you are looking for customization, Audio.js offers that through CSS styling.  As for compatibility, the player has been tested and verified to work across multiple platforms such as Android, iOS, Chrome, Firefox, Internet Explorer, Opera, and Safari.

Speakker

Described by its creators as a cross-browser audio solution featuring HTML5, Speakker is a wisely named audio player that comes with a boatload of features.  The player is very easy to setup via some lines of JavaScript and a bit of CSS.  From there, you have plenty of options as how you want to implement Speakker.

Among the characteristics you can tweak with Speakker include the player’s color themes, dimensions, and buttons.  You can opt for buttons that match light color schemes, or those that go with dark color schemes.  Want to make the player informational in nature?  You can do so by including links to artist information, as well as ones that are related to social media.  Speakker can use Flash as a fall back and also works across the major browsers to ensure compatibility for different users.  As a bonus, the creators of Speakker will supposedly release a new Nano version of the player that packs a ton of functionality and style in a compressed visual package.

HTML5 Audio Player Bookmarklet

This is a very nifty tool that gives you the power to play linked audio files on any Web page.  As long as that page has links to downloadable audio files, you can use the HTML5 Audio Player Bookmarklet to play those files with ease.  This offers a nice alternative to visitors who want to stream an audio file and saves them the hassle of having to download it to their computer.  One example of a site where the bookmarklet would come in handy is with Dropbox.

Zen HTML5 Audio Player

Out of all of the HTML5 audio players in this list, Zen is by far the most basic.  Regardless, its style is unique, so it is at least worth a look.  Powered by jPlayer and styled with CSS3, Zen gives you a demo of a simple HTML5 audio player that plays a single song.

Conclusion

Well, there you have it.  This concludes our list of the top HTML5 audio players.  As mentioned earlier, you will definitely find more audio players worth checking out if you peruse the Web on your own.  Hopefully, this list served to whet your appetite when it comes to the new and exciting world of HTML5.  If you know of any HTML5 audio players worth mentioning, list them in the comments section so that others can take a closer look.  Remember to check back with us for additional articles on HTML5 and much more in the future.HTML5 is making waves through the tech world, and this article will detail some of the best HTML5 audio players that are currently available on the Web.

HTML5: Not for Phone Apps?

The latest version of Hypertext Markup Language offers rich functionality without requiring the assistance of third-party plug-ins. This capability should make it perfect for generic web applications that work on any mobile platform. The reality falls short of this ideal.The problem is that mobile applications built with HTML5 do not offer the same level of performance as applications built for a specific platform. This explains why Facebook CEO Mark Zuckerberg stated publicly that his company’s attempt to create HTML 5 apps instead of native apps for mobile platforms for the social site was the firm’s biggest mistake.

Unfortunately, this leaves many developers in a bad position when trying to build an all-inclusive web-based mobile app. There’s Apple’s iPhone, Droid phones, Samsung’s Galaxy, and others. If you want an app that runs well on all three platforms, will you need to build your application three times, once for each platform? And if so, what does that say about the future of HTML5?

Serene Chan, industry analyst for ICT, the Asia Pacific at Frost & Sullivan sees a reason to be hopeful. She recently told ZDNet that it was too early to decide whether HTML5 was a success or failure. “Just because Facebook [says it] will go back to native apps is not indicative that HTML 5 is doing badly. The Facebook app contains HTML 5 in areas where the company wants flexibility in making modifications quickly,” she noted.

Still, phone apps do not seem to be the way forward for HTML 5. According to Vishal Jain, mobile services analyst at 451 Research, “Feature phones and HTML 5 do not go hand in hand.” Still, its usage could grow in other areas where its performance won’t compare unfavorably with what is already available, such as graphics rendering, Web services protocol, and server-side programming. Jain explains this by pointing out that HTML 5 is a combination of technologies that can be deployed in isolation. So while applications built-in HTML 5 appear to deliver poor performances when compared to those built natively, the markup language is versatile enough to be used for many other tasks.

Why does HTML 5 apparently work so poorly for mobile apps? According to Jain, the latest features of the language need a better-performing chipset than one typically finds in feature phones; an improved chipset would raise the price of the device. It’s easy to imagine the reaction from manufacturers and consumers to higher prices, especially since a properly-supported HTML 5 app won’t feel very different from a native app to the user of a feature phone. Besides, users of feature phones do not typically use many apps, so to developers, there seems to be little point in creating HTML 5 apps for this market.

Still, a number of companies are trying to improve HTML 5’s performance and enhance its spread. Mozilla, for example, is using HTML 5 in the design of its own mobile operating system for smartphones; its applications will, of course, be built in HTML 5. Plans call for Mozilla’s Firefox OS to run on cheap handsets in markets where Apple iOS and Google Android-based smartphones are beyond the budget of most users. This move could be good for the future of HTML 5.

There are some, though, who seem to think HTML 5 should look to HTML’s past to achieve a solid future. One comment left on the ZDNet article mentioned above stated bluntly that “HTML should be left for content, not functionality. That’s what it was designed for before the dropout-boys came along and turned it into a mess.” What the comment writer seems not to see is that the nature of the content itself has changed; it’s much more interactive. Yes, you still see plenty of examples of simple text on a page (such as this article) or static images, but attracting visitors now means giving them something to do: a game to play, a quiz to take, a calculator to use, videos to click on, and so forth. The line between content and “functionality” is no longer as clear-cut as it used to be – and it will continue to blur. This is why HTML 5, or something very like it, will gradually see greater adoption in the months and years to come.

Google Releases Stable Dart Version, JavaScript Rival

After more than a year of work, Google finally released the first stable version of Dart, the scripting language it hopes will take the place of JavaScript. Though the search giant also unveiled plenty of other goodies to go along with Dart, the company faces an uphill battle for the language’s adoption.What kind of inducements does Google offer for those interested in creating web-based applications in Dart? For starters, there’s Dartium, a Chromium-based browser that includes the Dart virtual machine (DVM). Programmers can use it to test Dart web applications directly, without compiling to JavaScript until they need to test them on other browsers. Keep in mind that Dartium is a technical preview, and users are warned right at the top of the download page not to use Dartium as their primary browser.

So what do you do when you’re ready to run your Dart app on a browser without a DVM? The Dart project also offers the Dart2JS compiler to take care of this issue. It lets users convert Dart software into JavaScript so browser that doesn’t boast a DVM can run it. And if you’re not sure how to start writing that Dart app you’ve been dreaming of, you can check out some pre-built code. Let’s not forget the Dart editor that Google and the Dart project thoughtfully provide.

This stable version of Dart makes some serious improvements on previous versions. The language’s developers paid attention to copious feedback and “plow[ed] through thousands of bug reports and feature requests from the web community,” according to Lars Bak, a software engineer working on the project. For example, he noted that the Dart Virtual Machine now outperforms even V8, the JavaScript engine in Chrome, on some Octane tests. Octane is a browser benchmark for JavaScript created by Google and released back in August.

With JavaScript’s long history and ubiquitous usage, Dart needs to be able to interact with it. One new addition to Dart is the js.dart library that “allows Dart code running in the browser to manipulate JavaScript running on the same page.” In this way, the Dart code can interact with third-party JavaScript libraries.

If you’re interested in rolling up your sleeves and seeing what you can do with Dart, you may want to check out the new language specification. Those of you who have already used Dart to one degree or another and just want to see what’s been added will want to look at the language changes. But some of you might be wondering why you should use Dart when JavaScript still dominates and neither Microsoft nor Mozilla care to support it?

I don’t have a good answer to that – and unless Google does, Dart may die a quick death. In Google’s opinion, however, JavaScript is broken to the point that continuing fixes, such as those employed through the EcmaScript standards process, won’t save it. And never mind projects like CoffeeScript that let developers create their apps in a more polished language before converting it back into JavaScript! Apparently, we need something better, according to Google, and Dart is it.

Still, Dart has its supporters, such as Mike Eberhart, who notes that it might become his primary development language. “I am absolutely thrilled with the productivity improvements I am seeing when developing with Dart (instead of JavaScript)!” he wrote in his blog. He believes the language’s real potential lies in business applications, “where the browser-choice can be 100% guaranteed to include Chrome (if it remains the only browser to include Dart support).” If Dart makes developing such applications more efficient and less costly and is as easy for JavaScript developers to learn as Eberhart claims, he may have a point. At the very least, Google makes it easy for you to find out for yourself.

Add New Website Features to Please Users

You may be surprised by the number of features you can add to your website that improves its usability. Some greatly affect a site’s look and feel, while others add small but friendly “touches” that make it seem more personal. With CSS3, HTML5, JavaScript, and jQuery, you can easily experiment with some of the ideas I’ll be discussing in this article.Chris Lake writing for Econsultancy describes these as “experiential web design trends” because they directly affect a user’s website experience. The idea behind these features is to encourage user interaction and certain behaviors. Not all of them will be appropriate for all websites, of course.

One useful feature is sticky navigation or sticky content. This is an item that stays in the same fixed position when the user scrolls down the page. It’s mainstream enough that I hardly notice when websites do this; when I do notice it, my first thought is “of course that navigation is right there where I left it!” If you want to encourage users to share your content, you can put social sharing buttons (for Twitter, Facebook, etc.) in fixed positions, not just navigation. Or you could make sure your “related articles” box is sticky to encourage visitors to read more content.

Some websites have become so popular that their style has escaped out into the wider web, to be copied in many different places. Or maybe the style itself is so versatile that it shows up everywhere. Take grid layouts for images, for example. You’ll find them on Pinterest, Etsy, eBay, and even Lady Gaga’s website. Such layouts let users take a lot in at a glance, without forcing them to give more weight to any one thing. They’re worth considering for your e-commerce website.

You should also consider inline form validation and auto-saving of forms for your website. Lake notes that this feature will boost form completion rates, and expects to see more of it in the future. And it doesn’t have to be fancy or complicated. “Show a little green tick icon (or similar) when all is okay. Or a red cross if things go awry.” Twitter’s form not only offers both of these when you fill out your form but explains the problem on lines that received a red X. Knowing WHY a particular line threw back an error will do a lot to decrease user frustration!

Lake characterizes another little feature that you can add to your website as “persuasive content.” I think of it as providing a sense of urgency. For example, Expedia does this when you’re checking out a hotel by telling you how many other people are looking at that hotel. Amazon does it by telling you that you can get a particular item tomorrow morning if you order by a certain time – and includes a ticking clock countdown to emphasize the point. I’m sure you can come up with other ways to create a sense of urgency around converting that are more specific to your business.

Of course, creating a sense of urgency isn’t the only way you can gently tweak your visitor’s feelings. Better still, you can do it in ways that make them smile and don’t leave them feeling manipulated – because it’s small but obvious. Lake uses the example of White Stuff’s checkout basket cartoon on its shopping cart page. It sits there with a little frown until you put something in it; then it smiles. Or take Google Maps’ StreetView icon; when he’s exploring Hawaii for you, he carries a surfboard!

You can even play with your visitors’ emotions AND build in useful functionality. Photojojo features a little “do not pull” lever on its pages; when you click on it, the lever turns red, and a hand with a long arm comes down and pulls the page up. What a cool way to scroll! And what a sneaky way to encourage a particular behavior.

Lake lists many more features you can use to enhance your visitors’ experience of your website. Consider them carefully and be sure to test them. A touch of whimsy might not be appropriate for the website of a professional accounting firm, for example, but it might be just the thing for a hydroponics farm trying to foster a down-home feeling. You might find that features you initially reject can be adapted to suit your needs perfectly, when you apply a little thought, some creativity, and the right approach. Good luck!