Our Craft

Making it better

replace_all for C++

Posted by danielmeyer on November 6, 2009

I’m always surprised by some of the basic functionality C++’s standard library lacks.    This week’s: a function to replace all occurrences within string x of string a with string b.  Of course it can be done, it’s just unwieldy given only the standard library facilities.

That’s why I’m so thankful for the Boost libraries.  Looks like <boost/algorithm/string/replace.hpp>’s replace_all() or replace_all_copy() would do the trick!

Posted in Technical Stuff | Tagged: | Leave a Comment »

Is it an assigment or a copy construct?

Posted by danielmeyer on October 27, 2009

Suppose we have the following code:

myclass a;
myclass b = a;

Does the  second line invoke b’s default constructor and then the assignment operator?  Wouldn’t it be more efficient to rewrite it like this:

myclass b(a);

Actually, though, the first and second versions are equivalent: both result in a single copy constructor call; neither one uses the assignment operator.

Let’s try an example to demonstrate this.

#include <iostream>

class myclass
{
private:
    std::string innards;
public:
    myclass& operator=(const myclass& c);
    myclass(const myclass& c);
    myclass();
    ~myclass();
};

myclass& myclass::operator=(const myclass& c)
{
    std::cout << "myclass::operator=\n";
    if(&c != this)
    {
        innards = c.innards;
    }
    return *this;
}

myclass::myclass(const myclass& c)
 : innards(c.innards)
{
    std::cout << "myclass::myclass(const myclass& c)\n";
}

myclass::myclass()
{
    std::cout << "myclass::myclass()\n";
}

myclass::~myclass()
{
    std::cout << "myclass::~myclass()\n";
}

int main(void)
{
    myclass a;
    myclass b = a;
    return 0;
}

The output is:

myclass::myclass()
myclass::myclass(const myclass& c)
myclass::~myclass()
myclass::~myclass()

A default construct, a copy construct, and two destructs.

Posted in Technical Stuff | Tagged: | Leave a Comment »

4040404

Posted by danielmeyer on October 24, 2009

40404

I thought this was funny: the other day I browsed to a nonexistent URL at a website, and because that page was not found it redirected me to 404.html …which also was not found.  So I ended up getting a 404 Not Found error on 404.html.  Cool!

Posted in Fun, Technical Stuff | Leave a Comment »

Simple GUI with Python and TKinter

Posted by danielmeyer on October 22, 2009

It would be nice to have a way to build quick-n-dirty GUIs so I can GUI-enable tools when that makes sense… but I’ve always just had a mental block about “going to that length”.

Yesterday though, I was flipping through Python in a Nutshell and I saw a GUI example there (p. 329) that was so simple I typed it in and tried it out :

import sys, Tkinter
Tkinter.Label(text="Welcome!").pack()
Tkinter.Button(text="Exit", command=sys.exit).pack()
Tkinter.mainloop()

That yields a simple little dialog:

hellotk-1

…that can be resized:

hellotk-2

I need to try some more of this!

Posted in Technical Stuff | Tagged: , , | Leave a Comment »

Defining your C++ template in a .cpp file

Posted by danielmeyer on October 21, 2009

Normally all your C++ template classes are implemented in their header files, and when we  tried to move the definition of a template class out to a .cpp file, the compiler complained.  I thought I remembered reading in Stroustrup’s The C++ Programming Language of  a keyword  that could help with this very issue, last time I was doing C++ programming.  A little digging turned up the name of the keyword: export (TC++PL §9.2.3).  However, it’s currently not a good option (also see the beginning of the discussion).

So, back into the header it goes.  :)

Posted in Technical Stuff | Tagged: , | Leave a Comment »

playcd

Posted by danielmeyer on October 21, 2009

Here is a simple CD player/pauser written in Python:

# Playcd.py - Play or pause an audio CD
# Author: Daniel S. Meyer
# Version 0.1
#
# Usage: python playcd.py
# (On Windows you can create a shortcut whose target is for example
# C:\installs\python\python.exe c:\bin\playcd.py , and place it on
# your Windows desktop.  Then you can assign a shortcut key (say,
# Ctrl+Alt+P) to that shortcut.  Now you can play and pause your
# CD by pressing the key combination.)
#
# TODOs:
# - When saving the state, also save the list
#   of tracks (or at least the number of tracks) so
#   we can detect if the CD is changed and not "resume"
#   in the middle of a different CD.
# - Add options for next/previous tracks
# - Detect if a track is an audio track before attempting to play it
# - Support playing a device other than the first one
# 

import pygame,os

def get_state_file_name():
    return os.environ['TEMP']+'/playcd-state.tmp'

pygame.cdrom.init()
cd0 = pygame.cdrom.CD(0)
cd0.init()
if cd0.get_busy():
    # Currently playing: pause it
    cd0.pause()

    # Save our state for later resume
    cdstate = open(get_state_file_name(),'w')
    cdstate.write(str(cd0.get_current()[0]) + '\n') # current track
    cdstate.write(str(cd0.get_current()[1])) # position within track
    cdstate.close()
else:
    # Not currently playing: try to resume from saved state
    try:
      cdstate = open(get_state_file_name(), 'r')
      curtrack = int(cdstate.readline())
      pos = float(cdstate.readline())
      cdstate.close()
      os.remove(get_state_file_name())
    except:
      # If anything goes wrong restoring our state,
      # just start playing at the beginning
      curtrack = 0
      pos = 0

    cd0.play(curtrack,pos,None)

    # Work around bug where only first track plays
    cd0.pause()
    cd0.resume()

cd0.quit()
pygame.cdrom.quit()

I set up the shortcut and shortcut key as described in the comments. Now I can play or pause an audio CD by pressing Ctrl+P.

(‘Course, I could have avoided this whole issue by getting a multimedia keyboard that has play and pause buttons on it… but then how would I learn Python? ;)

Posted in Technical Stuff | Tagged: | Leave a Comment »

Codesample CSS style

Posted by danielmeyer on October 20, 2009

When I have source code or want to demonstrate typing at the console, I’d like to show that highlighted in a certain way. I know precious little CSS, but here’s the pinnacle of my current achievement: the code sample box:

int x = 5;
++x;

To accomplish this, I first define the codesample style*:

<style>
.codesample {border:thin solid gray; padding-left:3em; font-family:Courier,monospace;
             background-color:#eeeeee; color:black;}
</style>

When I want to make use of this style, I just use a <pre> tag with a class of codesample:

<pre class="codesample">
int x = 5;
++x;
</pre>

…which yields the look featured at the top.

Next step: Right now I redefine the codesample style in each internal blog post.  As an alternative, there are a couple of ways to specify an external style sheet…maybe I’ll eventually set that up in SharePoint and have each post that needs it just point to that.

*(Here on WordPress I’ve purchased the custom CSS upgrade and I just put the .codesample part in the custom CSS area of the blog site admin; but for a SharePoint blog post I would do as above, putting the <style> tag in the body of the post**.)

**The <style> element is supposed to be in the <head> of an HTML document, not the <body>… possibly you can get at the <head> and do this more properly – I just don’t know how a the moment.

Posted in Technical Stuff | Tagged: | Leave a Comment »

Link getter

Posted by danielmeyer on October 20, 2009

As I learn Python, I’m writing some little helper scripts.  Here’s the latest, a script that prints all the .mp3 links referenced by a page (or pages) to standard output:

# mp3s.py
#
# Purpose: display all .mp3 links in the pages
#   pointed to by the given URLs
#
# Usage: python mp3s.py url [url2 [url3...]]
#
# Author: Daniel Meyer
# Date: Oct 20, 2009
import sys
import urllib2
from HTMLParser import HTMLParser

class LinkFinder(HTMLParser):
  def __init__(self):
    HTMLParser.__init__(self)
    self.links = []

  def handle_starttag(self, tag, attrs):
    if tag == 'a':
      for attr, value in attrs:
        if attr == 'href':
          self.links.append(value)

for url in sys.argv[1:] :
  page = urllib2.urlopen(url)
  linkFinder = LinkFinder()
  linkFinder.feed(page.read())
  linkFinder.close()

  for link in linkFinder.links:
    if link.find('.mp3') != -1:
      print link

Notice lines 15-17, which were required to initialize the links data member (since while still calling the base class constructor.

I’ve found this type of thing helpful when preparing to download conference audio where there are several individual mp3 links – I can then pipe the output through xargs to wget to download ‘em:

python mp3s.py http://www.t4g.org/conference/t4g-2006/ | xargs wget

Posted in Technical Stuff | Tagged: | Leave a Comment »

When’s the payoff?

Posted by danielmeyer on October 15, 2009

I put my home mortgage in an Excel spreadsheet so I could run scenarios:  if we pay $200 extra per month, how long is it till payoff?  What if we do $300 extra per month?  No  extra per month?  Each time I changed the pay-extra amount though, I’d have to scroll down to see what month the payoff would be.

Finding the row

First I needed to somehow search the “Balance” column for the first cell whose value was zero.  This was accomplished with the following function:

=MATCH(0,B:B,0)

Explanation of the parameters:

  1. 0 – the value we’re looking for
  2. B:B – the column we’re searching
  3. 0 – the match type (we need match type 0 because the other search types require that the values be in ascending order but our balance values are in descending order (the same reason we can’t use LOOKUP or VLOOKUP))

This formula gives a value like 117 (the first row where there’s a zero balance).  Now we need to turn that into a date…

Displaying the payoff date

For this we’ll use the INDIRECT function, which takes a cell address as a string.  In my spreadsheet, the balance amounts are in column B and the month/year dates are beside them in column A, so if the row were 117, the formula for showing the month would be =INDIRECT(“A117″) .  Of course, if we knew it was in cell A117, we’d just use A117 instead of INDIRECT(“A117″), but we can’t hardcode the row – we need to get it from the match calculation.  The address of the cell containing our payoff date, then, is:

"A"&MATCH(0,B:B,0)

Final formula

Putting it all together, here is the formula we’ll put near the top of the spreadsheet so that we can quickly see the payoff date as we change the amount of extra paid:

=INDIRECT("A"&MATCH(0,B:B,0))

(Thanks to Aladin for his post to the MrExcel message board, which got me started toward this solution.)

Posted in Technical Stuff | Tagged: , | Leave a Comment »

Gears & sprockets

Posted by danielmeyer on October 13, 2009

no-longer-slipping

My beloved three-speed bicycle had three problems, one after the other.

First, the rear tire went flat.

After I fixed that, the chain would  skip gears (or at least it felt that way).

After I fixed that, something was slipping, such that when I pedaled hard, some of the effort was lost to just making the rear gear spin.  This made for mushy pedaling.

I can hear the clamoring begin to rise: “Throw the old thing away already!  Get a new one!”

Now, now… this is my legacy system and it meets my requirements.  :)  I just want to write down what I did for the latter two fixes, since I think I’ve experienced these same issues in the past and forgot:

Skipping Gears Fix

Why was the chain skipping gears?  I never could see it happening, but I do know that increasing the tension of the chain (by loosening the rear axle and moving it backward) fixed that issue.

Mushy Pedaling Fix

Why was the pedaling mushy?  When I fixed the slipping gears problem, I moved the serrated washers (these might give the idea) on the rear axle from the inner side of the metal frame to the outer side.  I don’t remember why I did this, but it seems to have enabled the mushy slippage.  I moved the serrated washers back to the inner side of the frame (working to maintain chain tension!) and the mushiness evaporated.

No unit tests… a lot of moving parts… you start to get scared to change anything… hmm!

Posted in Uncategorized | Tagged: | Leave a Comment »