rulururu

post Interesting way of swapping variables

March 12th, 2008

Filed under: C++ — Kai @ 7:10 am

I found an interesting way of swapping two variables.

Normally I’d just use one of these functions:

void swap(int* i, int* j)
{ 
    int t=*i;
    *i=*j;
    *j=t;
}

or the xor (bitwise) way:

void xorSwap(int* i, int* j)
{
    *i ^= *j;
    *j ^= *i;
    *i ^= *j;
}

Instead of this you also could swap this kinda tricky way:

void swap_vars(int* i, int* j)
{ 
    *j=*i+*j-(*i=*j);
}

For the solution no temporary varbiables are getting used.
It also can be used for any data types and this is more efficient than the normal methods. Additionally it would be thinkable to implement it as a template function.

This little one liner is cute and all, but it is unreadable. So if you use it, you need to add a couple lines of comments saying what it does (not just “swap integers” as that will be assumed to be an out of date comment) which makes the effort of programming greater than using a temp variable.

post string::size_type and unsigned integer

March 11th, 2008

Filed under: C++ — Kai @ 7:26 pm

The C++ std::string class provides string::size_type as an integer datatype large enough to represent any possible string size.

The ‘find’ member function returns the location of the first occurrence of a substring or character in a string. This return value is an integer (whose type is string::size_type). If the substring or character is not found, it needs some value to return that signals this fact.

std::string::size_type std::string::find
                          (char c, std::string::size_type pos ) const;

The maximum value of an int is 2,147,483,647.

Meaning that if a line won’t hold more than 2,147,483,647 characters - which in normal cases never do - then you don’t have to bother declaring string::size_type, you can just declare an integer, which is more simple.

You’d also keep in mind that in theory, you don’t have any knowledge about string::size_type, it could be a 16-bit integer, a 32-bit integer or a 64-bit integer. The only thing a size_type is guaranteed to be is an unsigned integral type.

Even declaring an int for keeping the return value of a function that returns an string::size_type you get a warning because correct thing to do is to always use the string::size_type. That is guaranteed to always work when using C++ STL.

By the way I found this in GCC source code:

#undef SIZE_TYPE
#define SIZE_TYPE "unsigned int"

post XML the LINQ way

March 11th, 2008

Filed under: .NET — Kai @ 6:51 pm

In former posts I often wrote something about LINQ (Language Integrated Query, pronounced “link”) especially when writing about advantages of .NET 3.0.

Today I’d like to give you some really usefull snippets you can use with LINQ when accessing an xml file.

First of all I’ve got to show you the xml file I refer to. It’s just a small document that holds some information about music albums.

<?xml version="1.0" encoding="utf-8" ?>
<Albums>
  <Album>
    <Artist>Black Sabbath</Artist>
    <Title>Seventh Star</Title>
    <Date>2/20/1986</Date>
  </Album>
  <Album>
    <Artist>Judas Priest</Artist>
    <Title>Jugulator</Title>
    <Date>3/24/1997</Date>
  </Album>
</Albums>

Reading xml with LINQ can be archieved in the twinkling of an eye.

At first I create some anonymous objects with the properties, Artist, Title, and Date.

XDocument xmlDoc = XDocument.Load("albums.xml");
 
var albums = from album in xmlDoc.Descendants("Album")
                select new
                {
                  Artist = tutorial.Element("Artist").Value,
                  Title = tutorial.Element("Title").Value,
                  Date = tutorial.Element("Date").Value,
                };

The result (albums) is an IEnumerable collection filled with anonymous objects. It can simply be accessed that way:

foreach(var album in albums)
{
   MessageBox.Show(album.Title.ToString());
   MessageBox.Show(album.Date.Subtract(DateTime.Now()).ToString().Format ("Y"));
}

For not using anonymous types all the time a better solution is to create a typed list.

List<artist> albums = (from album in xmlDoc.Descendants("Album")
   select new album
   {
     Artist = album.Element("Artist").Value,
     Title = album.Element("Title").Value,
     Date = DateTime.Parse(album.Element("Date").Value),
   }).ToList<album>();

This is pretty clear and can be extend easily.

I also would be possible to constrict the select. If the list should just contain every album with artist’s name being something “black” just type:

List<artist> albums = (from album in xmlDoc.Descendants("Album")
   where artist.Element("Artist").Value.Contains("Black")
   select new album
   {
     ...
   }).ToList<album>();

Also distinct, group by, order by and some others operations can be done that way.
To filter the result you can design really complex statements using LINQ.

Creation of an xml file is easy as well. The XDocument and XElement types have a load and a parse method for creating.

The first thing to do is creating a document:

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XComment("All my albums"),
 
    //... new xElements
)

This is an anonymously typed data structure:

var albums = new[]
{
   new {Artist = "Iron Maiden", Title = "Flight Of Icarus", ID = 3},
   new {Artist = "Iron Maiden", Title = "Running Free", ID = 1},
   new {Artist = "In Flames", Title = "The Mirror's Truth", ID = 4},
};

When creating the xml out of this, it will be additionally done with proper order (notice that the ID is not in proper sequence). For better demonstration how the data can be filtered I, to simplify matters, added an identification number to each album.

XElement albums = new XElement("albums",
                        from a in albums
                        orderby a.ID //descending 
                        select new XElement("Album",
                            new XElement("Artist", a.Artist),
                            new XElement("Title", a.Title),
                            new XAttribute("ID", a.ID)
                            )
                        );

Notice the difference between XElement and XAttribute:

Element:

<Artist>Iron Maiden</Artist>

Attribute:

<ID = "2"></ID>

or

<ID = "2" />

When you’d rather use elements and when using attributes is recommented is described here:

[IBM] Principles of XML design: When to use elements versus attributes

At least you shouldn’t forget to save the file to streams.

doc.Save(@"C:\albums.xml");

I don’t wanted to tell you all about LINQ, it’s more likely to show how incredibly powerful LINQ is. This covers even a small portion of it. LINQ can be used for databases just as easily as it was used here on XML. As you can see, the LINQ project is extremely ambitious and this blog entry has just scratched the surface.

post PowerShell for admins

March 10th, 2008

Filed under: .NET — Kai @ 5:57 pm

Windows PowerShell is a new command-line shell and task-based scripting technology that provides comprehensive control and automation of system administration tasks.

However, I became more dissatisfied with the native Windows command shell. I learned to program the UNIX shell (bash to be specific) a bit and found it to be way more advanced than the Windows shell.

Aesthetically, PowerShell doesn’t look too different from most existing shell scripting clients. In fact, on a superficial level you could probably be fooled into thinking that it is exactly the same as either bash or cmd. PowerShell, however has a very powerful underlying structure that ties in neatly with the registry, the .NET Framework and (more obviously) the file system.

I think the text shell is the preferred way to do system administration for most people who have to take care of a system.

Let’s have a closer look:

PowerShell is available for Windows XP, 2003 Server and Vista.

  • Download .Net 2.0 Framework
  • Download PowerShell
  • Unzip the downloads and run their respective setup. I used all the defaults.

Type “Powershell -?” and you’ll see the command line parameters you can use to start PowerShell. There are a couple that are interesting here.

Using PowerShell is a bit different than any other command shell I have used. It is centered around the concept of cmdlets (command lets), which are commands that manipulate objects to perform a single task.
Every command in PowerShell returns a collection of objects. These objects can be manipulated in the exact same way as if you were using an object-oriented language. The ls/dir command creates a collection of file objects which can have any .NET function performed upon them from within the shell.

When you’d like to use a command with a pipe you can do it this way:

PowerShell -NoProfile -NonInteractive -Command "Get-Process *ss |sort handles"

This PowerShell syntax is obviously more verbose but it is also more powerful.
Also consider using the “-confirm” parameter to test configurations before execution for certain commands.

Killing Task the easy way with Powershell instead of Task Manager. For example we attemp to kill Winamp.

get-process wina*

Once the Process ID has been identified, you can kill the errant process by entering:

stop-process -id 2792

That way is also possible:

get-process wina* | stop-process

Windows PowerShell includes an untyped scripting language which can implement complex operations using cmdlets imperatively. The scripting language supports variables, functions, branching (if-then-else), loops (while, do, for, and foreach), and error handling, as well as integration with .NET. Variables in PowerShell scripts have names that start with $; they can be assigned any value, including the output of cmdlets. While the language is untyped, internally the variables are stored with their types, which can be either primitive types or objects.

Microsoft’s PowerShell is a solid step forward in script-language design.

There’s a whole bunch of scripts available on the internet, some are just one line others are really complex - there are limits set on your creativity.

Also remote adminstration via ssh can be done more enhanced. Just use freeSSHd server and log in with Putty (ssh client):

$PowerShell/v1.0/powershell.exe -Command -

Another alternative solution for a better windows shell is win-bash which is based on nt_bash which was an early bash port for windows nt started by Mountain Math Software some years ago. As far as I know, the nt_bash port project stopped in alpha status and has been never finished.

Download Windows PowerShell 1.0: [link]
You can also have a look at the preview release of Version 2.0 from November 6, 2007.

Win-bash project on sourceforce: [link]

post RobotTurK: Disaster Emergency Video system

March 5th, 2008

Filed under: Internet, WPF — Kai @ 7:24 pm

I found an article that’s worth reading on msdn blogs. It looks more funny than it probably should.

At first I got to tell you what Microsoft Robotics Studio is.

The Microsoft Robotics Studio is a Windows-based environment for robot control and simulation. It is aimed at academic, hobbyist, and commercial developers and handles a wide variety of robot hardware.

RoboTurk employs Unmanned Aerial Vehicles (UAV) equipped with cameras that are capable of steaming live video of disaster struck areas to any number of ground command stations. The helicopter carries onboard an eBox compute-unit that runs Microsoft Robotics Studio, allowing the robot to execute specific command issued by ground statation or to auto-fly or safely land. The ground stations utilizes Windows Server 2008 Media Services that capture, process and streams video.

Helicopter

Other illustrations in the post are not less fun. Have a look:

RobotTurK: Disaster Emergency Video system on Microsoft Robotics Studio Blog

By the way, for developers it might be interesting to know that for streaming Silverlight, which is the web part of WPF, is used.

post An alternative implementation of Trim() for STL

March 5th, 2008

Filed under: C++ — Kai @ 6:00 pm

The C-STL - string.h does provide many functions which are often needed when working with strings.
However, the well-known trim operation is not implemented.

As you probably know is trim or sometimes called strip a common string manipulation function which removes leading and trailing whitespace from a string.

There is no standard trim function in C or C++. Most of the available string libraries for C contain code which implements trimming, or functions that significantly ease an efficient implementation. The function has also often been called EatWhitespace in some, non-standard C libraries.

The open source C++ library Boost has several trim variants. One is:

#include <boost/algorithm/string/trim.hpp>
 
trimmed = boost::algorithm::trim_copy(''string'');

MFC provides a Trim() (which makes problems with VC6) and TrimLeft() / TrimRight() as well.

If you simply need a trim function and not a whole library to be included you can use this.

std::string trim(const std::string& s,const std::string& drop = " ")
{
 std::string::size_type first = s.find_first_not_of( drop );
 std::string::size_type last  = s.find_last_not_of( drop );
 
 if( first == std::string::npos || last == std::string::npos ) return std::string( "" );
   return s.substr( first, last - first + 1 );
}

In addition to string.hI have one more solution for you if you’re being willed using std::string (which doesn’t make much sense in most cases).

Remove whitespaces on the right side:

char* trim_right(char* szSource)
{
  char* pszEOS = 0;
 
  // Set pointer to character before terminating NULL
  pszEOS = szSource + strlen( szSource ) - 1;
 
  // iterate backwards until non ' ' is found
  while( (pszEOS >= szSource) && (*pszEOS == ' ') )
    *pszEOS-- = '\0';
  return szSource;
}

Cut off the left side:

char* trim_left(char* szSource)
{
  char* pszBOS = 0;
 
  pszBOS = szSource;
 
   // iterate backwards until non ' ' is found
   while(*pszBOS == ' ')
    *pszBOS++;
 
  return pszBOS;
}

Trim both sides:

char* trim(char *szSource)
{
  return trim_left( trim_right( trim_left(szSource) ) );
}

You also can use it with std::string when converting the std::string with c_str() method.

Trim function is very useful together with substring.

ruldrurd
« Previous PageNext Page »
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)