Voder-Vocoder

The Log of Hal Canary

Navigation: Home | THE LOG | Log Archives | Resume | Contact Info | Public Key | SSL | Math Applets | Site Map | WP Backend | RSS2 | Atom

Archive for the “Computers & Code” Category

« Previous Entries

dynamic arrays

About ten years ago, I wrote a C++ program to print out all the prime numbers less than a given number using trial division. I recently went back and looked at the program and realized how little I knew at the time. Even though my first CS class covered object-oriented programming in C++, we never really talked the about simply using the new keyword on arrays to make use of dynamic arrays. The topic was covered in my second CS class, which I took three years later.

int *array;
int array_size = 128;
array = new int[array_size];

/* do somthing to fill the array */

int *temparray = new int[(array_size * 2)];
for (int i = 0; i < array_size; i++)
    temparray[i] = array[i];
array_size = array_size * 2;
delete [] array;
array = temparray;

In the last few years, I have realized that for the simplest progrmas, C is often more efficient and straightforward than C++. In C, the code looks exactly the same, except that new is replaced by malloc() and delete is replaced by free().

int *array;
int *temparray;
int array_size = 128;
int i;
array = malloc(array_size * sizeof(*array));

/* do somthing to fill the array */

temparray = malloc(array_size * 2 * sizeof(*temparray));
for (i = 0; i < array_size; i++)
    temparray[i] = array[i];
array_size = (array_size * 2);
free(array);
array = temparray;

Hal Canary | Computers & Code | 2010-03-17 09:00:38 UTC
Permanent Link | No Comments

algorithms matter

This example of why the right algorithm matters comes directly from my textbook. Here's the C implementation:

Bad:

#include <stdio.h>
#include <stdlib.h>
long int fib(long int n) {
  if (n==0)
    return 1;
  if (n==1)
    return 1;
  return fib(n-1) + fib(n-2);
}
int main(int argc, char *argv[]) {
  if (argc <= 1) {
    fprintf(stderr, "argument?\n\n");
    exit(1);
  }
  long int n = atol(argv[1]);
  printf("f(%li) = %li\n",n,fib(n));
  return 0;
}

Good:

#include <stdio.h>
#include <stdlib.h>
long int fib(long int n) {
  long a=1, b=1, c;
  int i;
  for (i = 1;i < n; i++){
    c = a + b; a = b; b = c;
  }
  return b;
}
int main(int argc, char *argv[]) {
  if (argc <= 1) {
    fprintf(stderr, "argument?\n\n");
    exit(1);
  }
  long int n = atol(argv[1]);
  printf("f(%li) = %li\n",n,fib(n));
  return 0;
}

Output:

$ time ./fib2 38 ; time ./fib1 38
f(38) = 63245986

real	0m0.002s
user	0m0.000s
sys	0m0.004s
f(38) = 63245986

real	0m1.492s
user	0m1.428s
sys	0m0.004s

And you can show how nicely the good algorithm scales up by pulling out a bigint library, like Java's BigInteger:

public class fib3 {
  public static String fib(int n) {
    java.math.BigInteger a,b,c;
    int i;
    a = b = java.math.BigInteger.ONE;
    for (i = 1;i < n; i++) {
      c = a.add(b); a = b; b = c;
    }
    return b.toString();
  }
  public static void main(String[] args) {
    if (args.length < 1) {
      System.err.println("argument?");
      System.exit(1);
    }
    int n = Integer.parseInt(args[0]);
    System.out.print("f(" +
      Integer.toString(n) + ") = ");
    System.out.println(fib(n));
  }
}

Hal Canary | Computers & Code | 2010-03-11 18:48:25 UTC
Permanent Link | No Comments

fullscreen without distractions

Step 1. Set a hotkey to make applications run full-screened in Gnome:

gconftool-2 --type string --set \
  /apps/metacity/window_keybindings/toggle_fullscreen \
  '<Ctrl><Alt>f'

Step 2. Run your text editor and terminal window fullscreen.

Step 3. Code without distractions.

Hal Canary | Computers & Code | 2010-02-27 20:23:17 UTC
Permanent Link | No Comments

private static String itoa(int i)

I like Java's verbosity; it is consistant and clear. But sometimes you want succinct things.

/** "Returns a String object representing the specified integer." */
private static String itoa(int i){
	return Integer.toString(i);
}
/** "Returns a String object representing this Integer's value." */
private static String itoa(Integer i){
	return i.toString();
}

Also, I realized I had been using assert statements without -enableassertions for the last month, which did me very little good. A good habit, I suppose.


ALSO:

private static void printl(String s) {
	System.out.println(s);
}
private static void error(String s) {
	System.err.println(s);
}

Hal Canary | Computers & Code | 2010-02-21 11:19:27 UTC
Permanent Link | Comments Off

Mplayer and Gnome's screensaver.

#!/bin/sh
#DTPD
gnome-screensaver-command --inhibit &
INHIBIT_PID=$!
mplayer -dvd-device /dev/scd0 -ontop \
	-fs dvdnav:// -nocache 2> /dev/null
kill $INHIBIT_PID

This is how to use gnome-screensaver's inhibit command with a video player such as mplayer.

Hal Canary | Computers & Code | 2010-02-17 21:05:06 UTC
Permanent Link | Comments Off

time-wasting methods.

/* verbose java masturbation: */
public class Foo {
  private int foobar;
  public void setFoobar(int value) {
    foobar = value;
  }
  public int getFoobar(){
    return foobar;
  }
}
/* much less annoying: */
public class Foo {
  public int foobar;
}

Hal Canary | Computers & Code | 2010-01-17 22:23:38 UTC
Permanent Link | Comments Off

Printing a text file

Printing a text file is one of those basic things you never think about. Unless you are me. I like to play with the variables and make that printout look good.

#!/bin/sh
# Print a UTF-8 document to the default printer
# Written by Hal Canary 2009-12-23.
#DTPD# Dedicated to the Public Domain.

# Configurable Options
font="Monospace 11"
#font="Serif 11"
#font="Sans 11"
paper="letter"
b_margin=0.25
t_margin=0.25
r_margin=0.25
l_margin=0.75

# convert inches to PostScript points
b_margin=`echo "( $b_margin * 72 ) / 1" | bc`
t_margin=`echo "( $t_margin * 72 ) / 1" | bc`
r_margin=`echo "( $r_margin * 72 ) / 1" | bc`
l_margin=`echo "( $l_margin * 72 ) / 1" | bc`

exec paps --font="$font" \
  --paper="$paper" \
  --bottom-margin=$b_margin \
  --top-margin=$t_margin \
  --right-margin=$r_margin \
  --left-margin=$l_margin \
  "$@" | lpr
#EOF#

Hal Canary | Computers & Code | 2010-01-07 13:22:40 UTC
Permanent Link | Comments Off

Email Advice:

I've spent a lot of time writing email the past few weeks, so this is on my mind.

1) Keep your work email separate from personal. People change jobs, your friends shouldn't lose track of you because of this.

2) Don't use the email account that comes with your ISP subscription. The next time you move or change ISP you will be forced to get a new email account. Combined with (1), this leaves two options: pay for a hosted email solution, maybe with a personal domain-name, or use one of the free email providers. I suggest Google's gmail.com, which offers IMAP connection so that you can check you mail using your favorite email client (Mozilla Thunderbird, Apple's Mail.app, Novell Evolution, Microsoft Outlook, Novell GroupWise, et cetera) as well as on the web.

3) Configure your email client to send plain-text email by default. This usually produces much smaller message sizes and can easily be read by the most email clients.

4) When replying to a email, delete most of the quoted message, leaving only enough to give your reply context. At the very least, delete the signature.

5) If you are not replying to something in a previous message, don't hit reply; instead, compose a new message. This makes a new thread in clients that organize mails into threads.

6) Don't top post.

7) If you are going to compose your message in a word processor before sending it, copy-and-paste it into the email's body instead of sending an attachment.

8) If you must send an attachment, use an open file format.

9) This is one I am very guilty of. If you don't have time to compose a proper reply to an email that requires a reply, you should shoot off a quick acknowledgement message.

10) If you are at all technically savvy, go ahead and install GnuPG (if your system didn't already have it) and configure your email client to make use of it to sign your emails.

Hal Canary | Computers & Code, Life | 2009-09-27 22:08:01 UTC
Permanent Link | Comments Off

software for ubuntu

If you are a LTS user like me and stuck on Hardy Heron, sometimes packages are availible that have the newest shiniest thing prepackaged for you. Emacs 23 can be installed with a simple

sudo apt-get install emacs-snapshot-gtk

and then I wrote a little script to launch emacs with my favorite font:

#!/bin/sh
exec emacs-snapshot \
  -fn "Monospace-11" "$@" 

* * *

Another bleeding-edge thing to check out is Google Chrome's native Linux edition. Go get it from this page.

Hal Canary | Computers & Code | 2009-09-27 22:01:37 UTC
Permanent Link | Comments Off

Command-line Package Tools

Command-line package commands for Debian and Ubuntu-type systems that you should know:

apt-get update
resynchronize the package index files
apt-get dist-upgrade
install the newest versions of all packages currently installed and handle changing dependencies
apt-get install PKG
install a package and figure out dependancies
apt-get remove PKG
remove a package
apt-get clean
clear out the local repository of retrieved package files
apt-cache showpkg PKG
displays information about the package
apt-cache search REGEX
search all available package lists for a regex pattern
dpkg-query --list PATTERN
list installed packages matching given pattern
dpkg-query --status PKG
report the status of specified package
dpkg-query --listfiles PKG
list files installed to your system from a package
dpkg-query --search FILENAME
search for a filename from installed packages

Hal Canary | Computers & Code | 2009-09-26 18:54:45 UTC
Permanent Link | Comments Off

ssh-show-key-fingerprint

#!/bin/sh
## ~/bin/ssh-show-key-fingerprint
## Prints out SSHD Key Fingerprints
## Written 2004-2009 Hal Canary
## Dedicated ott he Public Domain.
test "$#" -eq 0 && \
  exec "$0" /etc/ssh/ssh_host_*_key.pub
for file in "$@" ; do
  ( cd `dirname "$file"`;
    /usr/bin/ssh-keygen -l \
      -f  `basename "$file"`; )
done

What to do with this info? first of all, print out the fingerprints and put them in your wallet.

Here's another thing I do:

ssh-show-key-fingerprint | \
  sudo tee -a /etc/issue.ssh > /dev/null
echo 'Banner /etc/issue.ssh' | \
  sudo tee -a /etc/ssh/sshd_config > /dev/null

This, of course, is in no way a secure way to check your fingerprint, since it is just as vulnerable to a man-in-the-middle attack. But it works as a backup plan.

And some legal theories say you should insert these additional lines into your /ets/issue.ssh file:

 UNAUTHORIZED ACCESS PROHIBITED.

 USE OF THIS SYSTEM BY ANY USER, AUTHORIZED OR UNAUTHORIZED,
 CONSTITUTES CONSENT TO THIS MONITORING, INTERCEPTION,
 RECORDING, READING, COPYING, or CAPTURING and DISCLOSURE
 by SYSTEM OWNER.

Hal Canary | Computers & Code | 2009-09-26 13:01:31 UTC
Permanent Link | Comments Off

MakeBookmarksFile

#!/usr/bin/env python
# MakeBookmarksFile - convert a text file containing
# URLs into a HTMl file with clickable links.
#
# Copyright 2008 Hal Canary
#
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and
# associated documentation files (the 'Software'), to
# deal in the Software without restriction, including
# without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom
# the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice
# shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF
# ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
# EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import sys,re
fi = sys.stdin
fo = sys.stdout
s=fi.readline().strip()
## The first line of the input is a title.
head='<!DOCTYPE html PUBLIC \
"-//W3C//DTD HTML 4.01//EN" \
"http://www.w3.org/TR/html4/strict.dtd">\n\
<html><head>\n<meta http-equiv="Content-Type" \
content="text/html; charset=utf-8">\n\
<title>%s</title>\n</head><body><div>\n\
<h1>%s</h1>\n'
fo.write(head % (s,s))
for line in fi:
  s=line.strip()
  if (s == "") :
    continue
  ## convert & to &amp; and so on.
  s=re.sub('&','&amp;',s)
  s=re.sub('<','&lt;',s)
  s=re.sub('>','&gt;',s)
  s=re.sub('"','&quot;',s)
  fo.write("<a href=\"%s\">%s</a><br>\n" % (s,s))
fo.write('</div></body></html>\n')

Hal Canary | Computers & Code | 2009-09-24 12:51:50 UTC
Permanent Link | Comments Off

« Previous Entries

Copyright 1997-2007 by Hal Canary.
mailto: h3 at halcanary dot org
xmpp:halcanary@jabber.org
aim:halwcanary
http://halcanary.org