2012-04-23
Reasonable Contour Levels
import math
def generateContours(min_value, max_val, target):
value_range = max_val - min_value
x = int(round(3 * math.log10(value_range / target)))
if x % 3 == 1:
x = 2.5 * math.pow(10,math.floor(x / 3))
elif x % 3 == 2:
x = 5.0 * math.pow(10,math.floor(x / 3))
else:
x = math.pow(10, x / 3)
low = math.ceil(min_value / x) * x
return [low + (x * i)
for i in xrange(1+int(value_range / x))]
2012-04-03
Collapse paragraphs
#!/usr/bin/env python
# ignores witespace
# collapses paragraphs
import sys
for line in sys.stdin:
line = line.strip()
if len(line) == 0:
sys.stdout.write('\n\n')
else:
sys.stdout.write(line+' ')
2012-03-23
generate image files
#!/usr/bin/python import Image import numpy X = 1024 Y = 768 filename = '/tmp/x.png' ima = numpy.zeros((Y,X,4), dtype=numpy.uint8) ima[:,:,3] = 255 # make opaque Image.fromarray(ima,mode='RGBA').save(filename)
2012-03-16
colapsing multiple for loops
#!/usr/bin/env python
import glob, sys
def globlist(l):
return (j for i in l for j in glob.iglob(i))
for filename in globlist(sys.argv[1:]):
print filename
2012-02-23
makefiles
# Example (GNU) Makefile for a C++ project. # Assume there is a .h file for each .cxx executable_file_name = program cxxfiles = \ file_one.cxx \ file_two.cxx \ file_three.cxx \ file_four.cxx CXX = g++ CXXFLAGS = -g -Wall -std=c++0x objects := $(cxxfiles:.cxx=.o) headers := $(cxxfiles:.cxx=.h) ## If you use other extensions: # objects := $(cxxfiles:.cpp=.o) # objects := $(cxxfiles:.cc=.o) # headers := $(cxxfiles:.cxx=.hh) .PHONY : clean all all : $(executable_file_name) $(executable_file_name) : $(objects) $(CXX) $(CXXFLAGS) $^ -o $@ %.o: %.cxx $(headers) $(CXX) -c $(CXXFLAGS) $< -o $@ clean: rm -f -v $(objects)
# Example (GNU) Makefile for a Java project. # Constructs a JAR file with all of the classes. entrypointclass = Program jarfile = program.jar javafiles = \ file_one.java \ file_two.java \ file_three.java \ file_four.java JAVAC = javac JAVA = java JAR = jar RM = rm -f JCFLAGS = -Xlint -g JFLAGS = -enableassertions classes := $(javafiles:.java=.class) .PHONY : clean all run all: $(jarfile) run: $(jarfile) $(JAVA) $(JFLAGS) -jar $(jarfile) clean: $(RM) -v $(classes) $(jarfile): $(classes) $(JAR) cvfe $@ $(entrypointclass) $^ %.class : %.java $(JAVAC) $(JCFLAGS) $^
2012-02-01
rosetta stone
| Language | Null Pointer |
|---|---|
| C/C++ | NULL |
| Java | null |
| Python | None |
| Lisp | nill |
2012-01-17
PyQt QInputDialog.get*() wrappers
#!/usr/bin/env python
import PyQt4.QtGui
def getInt(title, label, mini=-2147483647, maxa=2147483647):
assert mini <= maxa
default = min(max(0, mini), maxa)
(ret, ok) = PyQt4.QtGui.QInputDialog.getInt(
PyQt4.QtGui.QWidget(), title, label, default, mini, maxa)
if not ok:
raise Exception('select error')
return ret
def getItem(title, label, items):
(ret, ok) = PyQt4.QtGui.QInputDialog.getItem(
PyQt4.QtGui.QWidget(), title, label, items)
if not ok:
raise Exception('select error')
return str(ret)
def getFloat(title, label, mini=-2147483647, maxa=2147483647,
default=None, decimals=1):
assert mini <= maxa
if default is None:
default = min(max(0, mini), maxa)
(ret, ok) = PyQt4.QtGui.QInputDialog.getDouble(
PyQt4.QtGui.QWidget(), title, label, default, mini, maxa, decimals)
if not ok:
raise Exception('select error')
return ret
def getItem(title, label, items):
(ret, ok) = PyQt4.QtGui.QInputDialog.getItem(
PyQt4.QtGui.QWidget(), title, label, items)
if not ok:
raise Exception('select error')
return str(ret)
def getText(title, label, default=''):
(ret, ok) = PyQt4.QtGui.QInputDialog.getText(
PyQt4.QtGui.QWidget(), title, label,
PyQt4.QtGui.QLineEdit.Normal, default)
if not ok:
raise Exception('select error')
return str(ret)
qApplication = PyQt4.QtGui.QApplication([])
print getItem('getItem()', 'select a color',
['red','orange','yellow','green','blue','violet'])
print getInt('getInt()', 'give me a number', 0, 100)
print getFloat('getFloat()', 'give me a number', 0.0, 1.0, None, 2)
print getText('getText()','give me some text','string')
2011-12-17
Java Makefiles
Here's a basic makefile for compiling Java programs. On most systems, you will only need to edit the first three lines.
classes = Prog.class AnotherClass.class entrypointclass = Prog jarfile = program.jar JAVAC = javac JAVA = java JAR = jar RM = rm -f JCFLAGS = -Xlint -g JFLAGS = -enableassertions .PHONY : clean all run all: $(jarfile) run: $(jarfile) $(JAVA) $(JFLAGS) -jar $(jarfile) clean: $(RM) -v *~ $(classes) $(jarfile): $(classes) $(JAR) cvfe $@ $(entrypointclass) $^ %.class : %.java $(JAVAC) $(JCFLAGS) $^
2011-12-06
One can start an executable with arguments inside GDB with a single bash command:
$ gdb EXECUTABLE <<< 'run ARG1 ARG2 ARG3'
2011-11-16
Quick linear regression script
#!/usr/bin/env python #sudo yum -y install scipy # input is space-deleimited (x y) pairs. import scipy import numpy import sys inp = [map(float, l.split()[0:2]) for l in sys.stdin] x = numpy.array([t[0] for t in inp]) y = numpy.array([t[1] for t in inp]) fit = scipy.polyfit(x,y,1) print 'y = (%f) x + (%f)' % tuple(fit)
power fit:
#!/usr/bin/env python
#sudo yum -y install scipy
# input is space-deleimited (x y) pairs.
import scipy
import numpy
import sys
import math
inp = [map(math.log, map(float, l.split()[0:2]))
for l in sys.stdin]
x = numpy.array([t[0] for t in inp])
y = numpy.array([t[1] for t in inp])
fit = scipy.polyfit(x,y,1)
print 'y = ({0[1]})e^({0[0]})'.format(tuple(fit))
2011-11-08
This script will snap your window to the left or right side of the screen in Linux: (SOURCE)
#!/bin/sh
## ${HOME}/bin/wmctrl-snap-edge
#DTPD#
WMCTRL="${HOME}/bin/wmctrl_`arch`"
#WMCTRL="/usr/bin/wmctrl"
test -x "/usr/bin/xdpyinfo" -a -x "$WMCTRL" || {
echo "error"; exit 1; }
WIDTH=`xdpyinfo | sed -n 's/ *dimensions: *\([0-9]*\)x.*/\1/p'`
HALF=$(($WIDTH / 2));
"$WMCTRL" -r :ACTIVE: -b add,maximized_vert;
if test "$1" = "left" ; then
"$WMCTRL" -r :ACTIVE: -e 0,0,0,$HALF,-1
elif test "$1" = "right" ; then
"$WMCTRL" -r :ACTIVE: -e 0,$HALF,0,$HALF,-1
fi
If you don't have wmctrl installed, you can apt-get it (Ubuntu):
sudo apt-get --yes install wmctrlOr compile it yourself:
sudo yum install libXmu-devel
cd /tmp
wget 'http://tomas.styblo.name/wmctrl/dist/wmctrl-1.07.tar.gz'
tar --extract --gzip --file "wmctrl-1.07.tar.gz"
cd wmctrl-1.07
./configure
make -j 4
mv wmctrl ${HOME}/bin/wmctrl_`arch`
The next step is to set up hotkeys. If you use Metacity like I do, then:
gconftool-2 --type string --set \
/apps/metacity/global_keybindings/run_command_6 \
'<Ctrl><Alt>Page_Up'
gconftool-2 --type string --set \
/apps/metacity/keybinding_commands/command_6 \
"${HOME}/bin/wmctrl-snap-edge left"
gconftool-2 --type string --set \
/apps/metacity/global_keybindings/run_command_7 \
'<Ctrl><Alt>Page_Down'
gconftool-2 --type string --set \
/apps/metacity/keybinding_commands/command_7 \
"${HOME}/bin/wmctrl-snap-edge right"
2011-11-03
#!/bin/sh # Restart X11 under Ubuntu. # #DTPD# test `id -u` = "0" || exec sudo "$0" exec /usr/sbin/service gdm restart
2011-10-14
(defun next-good-buffer () "HWC" (interactive)
(next-buffer)
(while (and (not (string= (buffer-name) "*scratch*"))
(equal (buffer-file-name) nil))
(next-buffer)))
(defun previous-good-buffer () "HWC" (interactive)
(previous-buffer)
(while (and (not (string= (buffer-name) "*scratch*"))
(equal (buffer-file-name) nil))
(previous-buffer)))
(global-set-key [(control next)] 'next-good-buffer)
(global-set-key [(control prior)] 'previous-good-buffer)
(global-set-key [(control tab)] 'next-good-buffer)
(global-set-key [(control shift tab)] 'previous-good-buffer)
(global-set-key [(control iso-lefttab)] 'next-good-buffer)
(global-set-key [(control shift iso-lefttab)] 'previous-good-buffer)
2011-09-29
.emacs look and feel
;_____________________________________________________________________
;
; Look And Feel
;_____________________________________________________________________
(setq inhibit-startup-screen 't)
(tool-bar-mode nil)
(menu-bar-mode nil)
(set-scroll-bar-mode 'right)
(when window-system
(add-to-list 'default-frame-alist '(background-color . "black"))
(add-to-list 'default-frame-alist '(foreground-color . "white"))
(add-to-list 'default-frame-alist '(background-mode . dark))
(custom-set-faces '(default ((t
(:height 110 :family "DejaVu Sans Mono"))))))
;_____________________________________________________________________
;
; Keyboard Bindings
;_____________________________________________________________________
(setq x-select-enable-primary t)
(setq x-select-enable-clipboard t)
(cua-mode)
(global-unset-key (kbd "M-z"))
(global-set-key (kbd "M-z") 'suspend-emacs)
(global-set-key (kbd "C-h") 'backward-delete-char-untabify)
(global-set-key [(control s)] 'save-buffer)
(global-set-key [(control f)] 'isearch-forward)
(define-key isearch-mode-map [(control f)] 'isearch-repeat-forward)
2011-09-10
One can make a hostname alias for SSH and SCP by adding to the the SSH config file:
## ~/.ssh/config Host cs HostName = login.cs.unc.edu User = hal
2011-08-18
make -j
Update: Russ reccomends 2N threads.
#!/bin/sh
## {$HOME}/bin/makej
renice 1 $$ > /dev/null
N_CPUS=`grep processor /proc/cpuinfo | wc -l`
N_THRDS=`expr ${N_CPUS:-1} "*" 2`
exec /usr/bin/make -j "$N_THRDS" "$@"
2011-08-08
#!/bin/sh N_CPUS=`grep processor /proc/cpuinfo | wc -l` exec /usr/bin/make -j "$N_CPUS" "$@"
2011-07-18
yet another emacs function
(defun diary () (interactive)
(let ((ddir "d:/")
(year (format-time-string "%Y"))
(ymd (format-time-string "%Y-%m-%d"))
(ymdt (format-time-string "%Y-%m-%d %H:%M:%S %z")))
(make-directory (concat ddir year ) 't)
(find-file (concat ddir year "/" ymd ".txt"))
(goto-char (point-max)) (newline)
(insert ymdt) (newline) (newline)))
2011-07-15
stopwatch
#!/usr/bin/python
"""Stopwatch program.
Hit 'Enter' to save a time.
Hit 'Ctrl-c' to stop the script
"""
from datetime import datetime, date, time
import time, sys
start = datetime.now()
print __doc__
try:
while True:
time.sleep(0.071)
sys.stdout.write('\b'*22)
sys.stdout.write(str(datetime.now() - start))
sys.stdout.flush()
except KeyboardInterrupt:
sys.stdout.write('\n\n')
2011-06-16
diagnose
I'm only using one out of four processor cores for this batch job. Why is my computer slowing down? Ohhh. Memory leak. That's easy to remedy.
2011-06-05
out of town
I'll be at MSU the next two weeks.
2011-06-03
sync
One beautiful thing about git is that I can clone my own clone of someone else's repository. That way I can easilly keep my laptop in sync with my workstation. Neat.
2011-05-27
reduce
In high-school chemistry, you learn that the ideal gas law is
These letters are drilled into my head, but I realised yesterday that I am losing my intuitive understanding of the relation. The physics version of it is
where N is now a dimensionless number and k is comes from the definition of T. Let ρ be our number density and the relation simplifies to
Pressure is density times temperature.
In the heterogeneous CS Unix environment, I may be executing emacs from a console as “emacs -nw” or from an icon on the desktop. Some computers will have the emacs-color-theme package installed, others won't. So in my .emacs file, I put the following lines:
;; from .emacs ...
(setq emacs-style-file "~/.emacs-style")
(when
(and window-system
(require 'color-theme nil t)
(file-readable-p emacs-style-file))
(progn
(load emacs-style-file)
(my-color-theme)))
2011-05-17
After two weeks, I've finally produced a proof of concept. Not an important program, and it's not finished, but I feel like I've made something.
2011-05-12
GNU tar for win32 can't actually fork a process for gzip. What century is it? Here's my fix:
@echo off REM untargz.bat :AGAIN if "%1" == "" goto END gzip -d -c < "%1" | tar -xv shift goto AGAIN :END
2011-05-06
Big ice cubes melt more slowly than small ones. Are your ice cubes big enough?
2011-05-05
Just becasue Samba and AFS allow you to open multi-gigabyte data files as if they were local, you still should not. Even if you have a nice 100 Mbit/sec direct connection. Unless the software in question knows to expect these sort of shenanigans.
Work/School email:
hal
AT
cs.unc.edu
Personal email:
halcanary
AT
gmail.com
HWC