Uncategorized

Useful Git Prompt

Here’s a snippet of bash script that I wrote to make my prompt tell me when I’m in a git repository and what branch I’m on.

And to my pleasant surprise, the PROMPT_COMMAND mechanism will respect color codes, so if you have your branch listings in git colorized, it will be reflected in your prompt.

function rfind
{
    dir=$PWD
    while [ ! -e $1 ]; do
        if [ $PWD == "/" ]; then
            command cd $dir
            return 1
        else
            command cd ..
        fi
    done

    rfdir=$PWD
    command cd $dir

    return 0
}

function git_dir
{
     typeset str
     rfdir=""
     rfind '.git'
     if [ $? -eq 0 ]; then
        str="{`git branch | grep '*' | cut -d ' ' -f 2`}"
        rfdir=`echo $rfdir | sed "s#$HOME#~#"`
     fi

    echo "$str"
}

function mkprompt
{
    typeset branch
    branch=`git_dir`
    PS1="${branch}$ "
}

PROMPT_COMMAND=mkprompt
export PROMPT_COMMAND
Uncategorized

More functional support in C++

Sutter just announced that C++0x will have support for lambdas and closures.

It looks from the N2550 report that these things are motivated by a desire for some syntactic sugar to make using STL algorithms easier (which is understandable), but I hope this will lead to more first-class support for the functional programming paradigm. It has long had support for function objects, but it would be difficult to write predominantly functional programs in C++. I hope it just got a little bit easier.

My question(s): will these lambdas be serializable? In Lisp, there are a couple of ways you could ship around a closure. Ultimately, if you really wanted to, you could express the lambda as a regular list, transmit it, and then call “compile” on it. Since C++ doesn’t have a built-in way to write and compile code from within the language itself, it will have to be somewhat different (or maybe it’s time to start writing a functor serializer for the boost library).

I am a huge C++ aficionado, and this news excites me. A comment over on news.yc captures my sentiments pretty well:

Lambda functions and closures in C++. E-gads man! Wasn’t the language complex enough already!

I have to say: I love it. C++ has always been my favorite language that I don’t program in. It’s like kung-fu for programmers. You can attack any problem. But most times we don’t need kung-fu.

There’s nothing like “getting in the zone” with a good C++ program. It’s a thing of beauty. And if you’re doing stuff that you have to use the tool, like writing drivers, low-level stuff, doing some “break the rules” programming, it’s the best there is. I wrote a shell extender for windows many years ago in C++. I got to change the desktop and file system to work the way I wanted it to. Very neat stuff.

The sad fact is that most of the time you can make more money writing something with a much higher level language. And you can make it faster and adapt to the market faster. So C++ is a tougher language to use for startups, in my opinion (although it is still my favorite)

Can you imagine the trouble you can get into with macros, lambda functions, and unsafe pointers? How about throwing i some operator overloading? It’s like a playground for nuclear weapons.

Uncategorized

New favorite quote

Charles Murray put it perfectly:

“A meaningful friendship does not consist of sharing backyard barbecues; a satisfying marriage does not consist of two people living together; a vibrant community is not created by yard sales. All of these relationships are given weight and consequence by the elemental events of life — birth, death, raising children, paying the rent, comforting the sad, joining together to do things that need getting done and (crucial point here) having responsibility for getting those things done. The welfare state says of too many important functions in life, “We’ll take care of that.” The natural human response is to say, “Okay, you do it.” And in this transfer of responsibility the welfare state has drained too much of the life from life.”

Uncategorized

The Programming and Management Blog » Most Influential Programmers Results

The Programming and Management Blog » Most Influential Programmers Results

Nick Halstead recently took a month-long poll over at his blog recently of what people consider the most influential programmers, and below is the result:

1st – Linus Torvalds

2nd – Alan turing

3rd – Dennis Ritchie

4th – Donald Knuth

5th – Rasmus Lerdorf

6th – John Carmack

7th – Bill Gates

8th – Richard Stallman

9th – Tim Berners-Lee

10th – Bjarne Stroustrup

I can’t say I think this list makes any sense at all. Firstly, while Linus is definitely influential, I think it’s a stretch to say he’s the most influential of all time. Rasmus Lerdorf, similarly created something interesting, but among the most influential of all time? Bill Gates’ influence is due more to his technical strategy and business acumen, not his programming.

His own top ten list is here:

  1. John Carmack
  2. Linus Torvalds
  3. Tim Berners-Lee
  4. Douglas Andrew Bel
  5. Dennis Ritchie
  6. Bram Cohen
  7. asmus Lerdorf, Andi Gutmans & Zeev Suraski
  8. Jez San
  9. Bjarne Stroustrup
  10. Richard Bartle & Roy Trubshaw

He cheated with all the “&”s. Of course, mine would look much different, I think. Remember – this is for all time. The criteria must be something other than simple fame, which seems to be the impetus for the poll-driven list. It also should be something other than riches. Influence that sprang from work as a programmer is the criteria. It might should even be two lists: influence over the world in general (or over multiple industries), and influence in the programming and software industry. Perhaps, put simply, the idea is people who have significantly changed the way we think or do things.

Anyway, here is my list. It is unorderd, as I just don’t know how I could possibly rank the individuals. They are from different times which posed different problems, had influence in different ways which has meant different things in modern times. One might be able to do very lose rankings, but a 1-10 ranking I think isn’t very sensible.

  • Richard Stallman
  • Guy Steele
  • Tim Berners-Lee
  • Brendan Eich
  • Larry Wall
  • Kernigan & Ritchie – OK, I’m cheating a little here too, because you really can’t separate these two in their achievements.
  • David Wheeler
  • Dan Bricklin
  • Bram Cohen
  • Donald Becker
  • Bjarne Stroustrup
  • James Gosling

Have a look at Wikipedia to see info about more programmers.

Uncategorized

Best Programming Language Advice

The demons *must* be ice-skating by now.  There was an almost wholly on-topic thread on /.

The original article was an “Ask Slashdot” regarding programming languages. Below are some of the more informed comments (or so I thought), along with some of my thoughts. My apologies for not having links. I started this post using a firefox blogging plugin, and I somehow didn’t get the links included.

Don’t waste time learning a lot of computer languages. Pick one or two, learn them well, learn their standard libraries, write programs in them, and read/maintain other people’s code.

This sounds reasonable to me, but I think there are some important caveats here. I think I’d pick more than one or two languages to be in your toolbox. My preference is to be proficient in languages that fall across the following categories: statically-typed languages, dynamically-typed languages, scripting languages, functional languages, procedural languages, and object-oriented languages. Of course, there could be plenty of overlap in exactly which languages you choose. For example, my language of choice whenever practical is the C++ programming language (not “C/C++”!). C++ is a multi-paradigm language; it obviously supports procedural and object-oriented programming, but it also provides support (to varying degrees) for functional programming and generic programming (via templates and — if you can hold your nose — the preprocessor). Of course, the realities of my education required that I also be proficient in Java and C.

That takes care of the statically-typed languages. I think dynamic languages (not necessarily including their standard libraries, if there is one) are easier to learn, so why limit yourself to one? If you know C, being able to create something useful in PHP is simply a matter of learning a little Apache HTTPD administration and being handy with the PHP API. I chose to learn a little Python because it’s very useful, but also because it has some neat features and is really hot right now (which means it is gaining traction among developers and people who create tools for it, which in turn make it that much easier to use). Python has really become one of the necessary packages for a reasonably complete OS install these days. If you’ll be doing a bunch of web applications, it may be worth your while to learn Ruby; if not, then Python will be a better general-purpose dynamic language, I think. Python is very practical. There are lots of other dynamic languages out there; among the more popular are Ruby, OCaml, Lisp (and it’s dialects, like Scheme and Elisp), but don’t think it’s necessarily worth your time to be proficient in a bunch of them. Pick one or two that meet your needs.

That leaves scripting languages. The two that have been most useful to me over a number of years, and not by a close margin, are the bourne shell and sed. Of course, that gives me away as a *nix geek. I don’t have anything against Windows; I just don’t do most of my development there (and I don’t think scripting tools are as ubiquitous). I think there are very few things you could do in some other scripting language that you couldn’t do comparably using ksh99 and sed.

Update: after re-reading this, I decided to add a blurb about Perl to hopefully stem the tide of emails and comments complaining that I didn’t mention it. Fine. Perl can do everything the Bourne shell and sed can combined, plus a whole, whole lot more. It’s a true statement. Perl has incredible utility, and it’s (somewhat) portable between *nix and Windows. I just haven’t had a lot of use for it because ksh99 (or bash, as is more common) and sed take less time to learn and are sufficient to meet my needs.

So here’s the point – after the realities of my education, professional environment, and personal preferences are all accounted for, the list of languages I’m reasonably proficient in (or at least comfortable with):

  • C
  • C++
  • Java
  • C#
  • Bourne shell
  • sed
  • Python
  • PHP
  • Common Lisp
  • Scheme

This, obviously, is more than one or two. I suppose an important thing to remember is that several of these for forced on me by circumstance, and several of them were simply inevitable (seriously…what programmers out there with more than a year or two of experience, including school, can’t write a little bit of C?), and the rest were personal choice.

Spend most of your time focusing on concepts that generalize to all programming.

And

Knowing about design patterns is useful in any language. The intricacies of C++ template programming are not. If I say “That’s a singleton”, people will know what I’m talking about whether the code is written in Ruby, C++, Java, or Cobol.

This is certainly good advice. I think design patters can be a double-edged sword; they provide a neat little box to think in, but they can also convey the useful experiences and proven idioms of legions of programmers. It’s also simply smart to be able to take what you know and apply it in a broad domain spectrum.

However, I think it’s very, very important to be really proficient in at least one language. Don’t let yourself be such a generalist that you can’t answer a few questions about at least one of your languages:

  • What are its strengths?
  • What are its weaknesses?
  • Does is support tail recursion?
  • What 5 things would you change in your favorite language?
  • If I were to create a new language that could only implement 5 features from your language, which would they be?
  • Which is the best compiler?
  • What can your language be practically used for?

Once or twice a year, spend some time learning about a language you don’t know. Try to understand how it’s different than the language you normally use, and more importantly why. Look at example code and code from open source projects and try to emulate their code with your code. For example, Ruby will let you open a file, read and process each line in a while loop, then close the file. But the “ruby way” of doing it is to pass a code block to the file’s “each_line” method. After you understand the syntax and the strengths of the new language, and the idioms used by the language, decide what you like, and what you don’t. Then figure out how you can apply the new things in the language you regularly use.

I like this very much, and I think it dovetails very nicely with my previous comments; doing a detailed compare-and-contrast between your most frequently-used language and a new one will help you answer the questions above, but it will also help you keep your toolbox stocked with the most useful tools for you.

More generally, languages should be treated just like essential tools are in any other profession (or craft, if you prefer). Mechanics have buildings filled with tools, each with their purpose. They have one pegboard or cabinet that contains a small set of tools that are used very frequently and those are the kind of tools that become like extensions of the mechanics’ own limbs. That’s how programming tools should be, including languages. Go ahead and get attached to one. It gives you a little personality, but don’t sell yourself short by thinking of languages as anything other than tools.

Uncategorized

Ok, I get it (or: Gtk+ is better than I thought).

In my last post, I kinda whined about the awkwardness of the Gtkmm API. At least, it seemed that way at the time. I toyed with libglade and Gtk+ for a while first and everything seemed very straightforward and easy.

Gtkmm and libglademm are different. They seemed awkward at first, but after further investigation, I like their designs much better, and the advantages presented by C++ seem obvious. One of my primary objections was that it didn’t seem that I could hook up the default signal handlers because they were made protected members of the widget classes. At the time, it seemed to me that the only way that the default signal handlers could be used at all was by deriving classes and overriding the handlers (which are virtual, by the way). I have since discovered that the default handlers are connected by default. Also, the “slotting” mechanism used for signals — whereby signal handlers can be chained together and all executed on a single event — is pretty nifty.

Speaking strictly of Gtkmm, this doesn’t seem so bad, but I was using glade to put my UI skeleton together, and I very much liked the idea of dynamically building your UI from an XML file at program startup, rather than coding all the tedium that goes along with UI development. I also prefer C++ to C whenever possible (actually, I prefer C++ to any other language whenever remotely appropriate), which is how I got here in the first place. Anyway, glade-2 — in my opinion — isn’t very good at dealing with “custom widgets”, which includes widgets that are derived from and substantially the same as the stock widgets. One caveat I should include here is that I haven’t really gone through this whole process with glade-3 yet. Maybe it’s better. I don’t know.

Offhand, I’d say one thing that could be better in glade-2 is if, once you placed some stock widget, you could edit the classname and let glade-2 assume that the user-entered classname is the name of a class that derives from the stock widget you originally placed. Then, maybe it could support all the properties of the original widget, but actually use your derived widget at runtime when the UI is built. This would be pretty much what I want, because thus far, the only use I have for writing custom widgets is to override the default signal handlers.

Uncategorized

Come On! Why must everything be derived?

I am trying to get some experience building graphical UIs using C++ after hours at work (and also to build a tool that would be useful there as well). I started looking into the various frameworks, and the truth is that there isn’t any magical silver bullet for C++. There is no Swing++, so to speak.

Anyway, I really like the idea of using the Glade tool to build the UI graphically and have it specified in an XML file which would then be read at runtime to construct the actual UI. I did a few toy examples in C to see how it’s done, and I was thoroughly impressed, especially with the signal autoconnect facility in libglade. Connecting callback functions is one of the many tedious things that really make it a chore to build a UI.

After doing that for a while, I thought I’d try the libglademm (and gtkmm/glibmm) libraries so I could benefit from the consistent API and proper object orientation and hierarchy for the various widgets. All very nice. If you want to create a custom widget, you don’t have to bend over backwards to do it; you just inherit from a stock widget and change as necessary, using the base class’ implementation where possible. Here’s what Debian’s Roger Leigh had to say about it:

The C++ code using Gtkmm is slightly more complex than the code using
Glade. However, the benefits of type and signal safety, encapsulation
of complexity and the ability to re-use code through the derivation of new
widgets make Gtkmm and libglademm an even better choice. Although it
is possible to write perfectly good code in C, Gtkmm gives the programmer
security through compiler type checking that plain GTK+ cannot offer. In
addition, improved code organisation is possible, because inheritance allows
encapsulation.

Then, after libglademm kindly constructs your widget objects for you, you just connect your signals. How hard can it be, right? After all, in libglade, all you have to do is this:

#include
#include

void some_signal_handler_func(GtkWidget *widget, gpointer user_data) {
/* do something useful here */
}

int main(int argc, char *argv[]) {
GladeXML *xml;

gtk_init(&argc, &argv);
glade_init();

/* load the interface */
xml = glade_xml_new("filename-for-interface", NULL);
/* connect the signals in the interface */
glade_xml_signal_autoconnect(xml);
/* start the event loop */
gtk_main();
return 0;
}

This is just a stock example from the libglade reference documentation, of course, but it illustrates nicely how much ugly crapwork you don’t have to do because glade does it for you. That ‘glade_xml_signal_autoconnect’ function is pure gold, buddy, let me tell you.

Anyway, I looked for something similar in libglademm, but there isn’t. There isn’t a Gnome::Glade::Xml::signal_autoconnect because, according to Leigh,

You need to do the connection “by hand” in your constructor, for
example. It’s not possible to connect to C++ object methods
automatically like you can with C functions.

It’s certainly not impossible. It’s especially challenging if you’re going for the most abstract form of portability, but who needs to do that? At any rate, that has no bearing on the fact that gtkmm expects you to derive every widget you use, if you want to use signals at all (and which widgets don’t fall into that category? GtkLabel maybe? Even then you sometimes want something to happen when you click a label). I am completely dismayed by this. Every object has a default signal handler…but it’s protected. What for? I just want to hook up whatever the default signal handlers are. If the defaults don’t do anything, then why aren’t they pure virtual? If they do something, then why can’t they just be exposed so I can avoid creating a new class for every widget I want to hook signals to?

The interface I’m working on has a top-level window with a number of nested widgets down to a pretty deep level (7 or 8 or so). Each level contains multiple widgets. If I want to hook signals to every one of them, everything I’ve read about it to date suggests that I’m going to have to derive tens of new classes, just so I can call their default signal handlers. How poor is that? The code and image size bloat are astonishing, and with all the big virtual tables that have to be constructed, the performance hit is surely unnecessarily monstrous.

*sigh*

Maybe someone who knows gtkmm on a much deeper level than me will comment here and set me straight. I’ll keep posting about this though, because despite its shortcomings, I don’t know that there is anything better for C++ out there right now. Nothing as portable as GTK+, anyway.

Uncategorized

Who’s a hose beast?

Ryan is disillusioned with C++.  The analogy of C++-as-a-person-whom-I’m-going-to-divorce is kinda lame, but his criticisms are typical.  I normally don’t get in blog wars like this, but for some reason, I’m feeling defensive tonight. 

  1. He complains about C++ that “You can’t decide who you are”. 

    What this means is that he thinks C++ behaves inconsistently.  Firstly, so does any other language that has more than one compiler.  Java may be an exception, but there aren’t many java VMs other than Sun’s – and even then, there are probably differences.  The C++ standard is clear about expected behavior in almost all conceivable scenarios, and it spells out where the behavior isn’t well-defined.  I think his complaint here ought to be with the “compiler friends” he hangs out with.  He could also find a portable compiler that tries to comply with the standards (such as gcc/mingw or the intel compiler, if he’s on x86.  VS2005 does a respectable job of implementing the standard, but then, it’s not portable in any sense.

  2. “Self-denial”? What the heck? 

    Yes, so C++ doesn’t have usable reflection capabilities.  That was an intentional design decision made to prevent the runtime overhead involved – remember, C++ was designed as a tool for creating high-performance software.  Languages and VMs that support real reflection are aren’t.  Repeat after me: C++ isn’t the tool you should use in a project that requires reflection.  Languages that support reflection aren’t the ones you should use in a project that require high performance.

  3. I honestly don’t understand his complaint that C++ doesn’t “know what strings are”. 

    He says he has to use a “null-terminated blah blah blah” – which you should never have to do in C++.  And what’s so bloated about std::string?  I find it to be quite nice, actually.  Non-standard third-party implementations need not apply.  std::string works just fine.

  4. C++ doesn’t know what arrays are?

    std::vector<int> anyone?  Also, if std::vector<std::vector<int> > doesn’t blow up your skirt, then typedef it.  Sheesh.

  5. Templates

    Where to start?  Firstly, C++ having templates is still more than Java can say.  Generics != templates.  The syntax is a little unseemly at first, but it’s an acquired taste – like beer.

  6. Dependency resolution.

    Firstly, header dependency resolution isn’t a characteristic of C++.  The pre-processor does that.  Secondly, if your code is so complicated that wrapping all your headers in
    #ifndef _BLAH_
    #define _BLAH_
    // definitions
    #endif

    doesn’t work for you, then your design is broken.  Don’t blame C++.

  7. Necessity of design patterns?

    Design patterns are just the outflow of a few decades worth of industrial experience.  People are starting to retire en masse, so they thought it might be a good idea to write some things down.  Why is that a bad idea, and what does that have anything to do with C++?  No language can obviate the benefits of having formal design patterns.  Not even our current rock-star, Ruby.

More generally, what I want say, and what many expert programmers will say until they’re blue in the face and what many other programmers simply won’t listen to is that languages are just tools.  They’re all designed for something, and that something isn’t always the same.  Actually, it usually isn’t.  Use a tool that’s appropriate for the job.  C++ happens to be designed for a very broad and general application domain.  That’s a large reason for why it’s so widely used.  I don’t know that I even know of any other languages that have such a large application domain.  Even Java, C#, and Lisp/Scheme aren’t as general-purpose as C++ is.  The point is use the tool appropriate for the job.  The fact that C++ is a combo compound mitre saw/router/nailgun doesn’t mean it should be used to paint a wall.  Likewise, you shouldn’t use a paintbrush to try and make furniture.  Ruby does not do everything Perl does with none of the downside.  Perl has its strengths, and Ruby has its.  Let it be at that.

Just to address Ryan’s specific comments: the reason certain languages are widely used and “safe” is because of their large application domain (and other reasons as well, many of which ultimately spring from this primary reason).  Businesses don’t want to invest in many niche tools when they can support good general tools for the same or less.

Also, I don’t necessarily disagree with his insistence that we shouldn’t be monolingual (picking up new programming languages should be something any good programmer can do quickly), but I also think that it’s good to be able to fall back on something as an expert. 

Powered by ScribeFire.

Uncategorized

ksh stuff

Below is a little code I use with ksh. The wt() function can only be expected to work in an X-term. The code sequences are different for other terminal emulators.

DIRSTACK=$PWD
function dirs {
  print $DIRSTACK
}

function pushd {
  dirname=$1
  cd ${dirname:?"missing directory name."}
  DIRSTACK="$PWD $DIRSTACK"
}

function popd {
  DIRSTACK=${DIRSTACK#* }
  top=${DIRSTACK%% *}
  cd $top
}

function rfind
{
  dir=$PWD
  while [ ! -e $1 ]; do
    if [ $PWD == "/" ]; then
      command cd $dir
      return 1
    else
      command cd ..
    fi
  done

  rfdir=$PWD
  command cd $dir

  return 0
}

function wt
{
  printf "ESC]0;${@/$HOME/'~'}^G"
}

function git_dir
{
  typeset str
  rfdir=""
  rfind '.git'
  if [ $? -eq 0  ]; then
    str="\{`git branch | grep '*' | cut -d ' ' -f 2`\}"
    wt "[${rfdir}${str}]"
  else
    wt "xterm"
  fi

  echo "$str"
}

function mkprompt
{
  typeset branch

  branch=`git_dir`
  PS1="${branch}$ "
}

function cd
{
  PS1="$ "
  command cd $@
  mkprompt
}
Uncategorized

More math, shift in blog direction

I’m planning to drive this blog in a slightly different direction. That is, I want to narrow down what I write about here to a few categories that interest me most, instead of shooting off in all directions with no depth in any of them. Of course, I still reserve the right to write about any topic at any time, but…

Anyhoo, the average reader should get what I’m saying.

In that vein, here’s a little bit more math geekery; Euler’s formula. This is not new in any way, or even something that isn’t blogged on often (it is, and by people who are far more knowledgeable, talented, and better at writing about math) and in true blog tradition, I’m swiping it wholesale from someone else. Go there to see a better explanation for all this.

[tex]e^{i\phi} = cos(\phi) + i sin(\phi)[/tex]

Let [tex]\phi = \pi[/tex], and you end up with

[tex]e^{i\pi} = – 1[/tex]

which leads to a striking equation that links together the most commonly used constants in mathematics:

[tex]e^{i\pi} + 1 = 0[/tex]

Interestingly, if you let [tex]\phi = \frac{\pi}{2}[/tex], then you get

[tex]e^{i\frac{\pi}{2}} = i[/tex]

Raising both sides to the power [tex]i[/tex], you get

[tex]e^{-\frac{\pi}{2}} = i^i[/tex]

Which can be calculated as [tex]i^i = 0.2078795763\cdots[/tex]