Erich Schubert: Documenting fat-jar licenses
What is the appropriate way to document the individual licenses of a fat jar (a jar archive that includes the program along with all its dependencies)?
rsync is often used to back up systems,
with options such as:
-a --archive-H --hard-links-A --acls-X --xattrs--numeric-ids
By default, rsync uses literal UIDs
and GIDs if it can find matches in both the source and the
destination.
That is, if you have users jacquouille
(1002) on your source system Reblochon, and a user jacquouille (1005) on your destination system
Neufch tel, rsync will map them: files with an UID of 1002 will be
backed up with an UID of 1005.
This may or may not be wanted, but anyway you must be aware of it.
For instance, if you have to restore Reblochon's home directories and do that by
attaching a new drive locally to Neufch tel,
you will end with mixed up UIDs.
This option --numeric-ids forces rsync to use numeric IDs instead of trying
to map them. It is notably needed for backups of jailed systems (BSD
jails, OpenVZ, VServer, lxc ) which appear to have bogus IDs when seen from
their host system because they have their own ID maps.
--fake-super
When you back up a full system or anything that requires keeping file
ownership or device information, you need to have root privileges on the
destination system. Without them, rsync would be
unable to correctly chown() the destination
files.
This option --fake-super offers a way to
back up privileged information without requiring root privileges. It works by
adding special extended attributes such as user.rsync.%stat containing al this information. Of
course, it still requires a destination file system that supports extended
attributes.
This provides a good way to push system backups without weakening your
security by opening a root access on you destination system. For instance, I
personally use it with rsyncd running as an unprivileged user.
Here s the general process.
First, well in advance of the move, crank the TTL on the domains way down. This way, old IPs won t be cached for very long once the system moves.
Next, start rsyncing data from the old machine to the new. Do not yet shut down daemons on the old. Shut down as much as you can on the new. You ll want to focus on static data, such as /home. /usr is a good candidate as well. /var if you are selective databases may be a good candidate, or may not. The idea is to seed the destination with data so that when we do the real rsync, most of the data will be there; it will have to tidy things up after daemons are stopped, and update some things, but the bulk of the work should be done.
Next, start preparing some exclude lists for the final rsync, which will copy an entire machine to the other. You will likely want to exclude files such as /etc/fstab, /etc/network/interfaces, /etc/resolv.conf, /etc/hosts, /etc/default/grub, /sys/*, /proc/*, /dev/*, and the like. I used rsync -v -P -a -H -A -X -S numeric-ids delete-after.
Now, start editing config files for the new IP, but do it on the old server (these will be synced over to the new one). Start with the bind config files, and touch anything else that needs it maybe Apache configs, whatever.
Next, get ready to do the final sync. In an ideal environment, we d just shut both machines down to single-user mode, but that s not going to quite cut it here. Use ps and shut down all daemons except sshd and udev on the destination. Yes, including even syslog. This is to prevent anything actively accessing the disk during the rsync, and also to prevent any issues with clients accessing server daemons that aren t ready yet.
Now, on the source machine, reload bind. This will start answering DNS queries with the new machine s IP, and should also propagate the changes to your secondary DNS. Next, kill off all the daemons on the source machine, except for ssh and bind. You might want to set /etc/nologin to prevent regular users from logging in on ssh, if you have them. Now rsync things over to the new machine. Do any final tweaking over there (merging in /etc/hosts maybe, dealing with the udev rules.d persistent net thing, etc.). Reboot the new server and you should be up and running.
Much of my academic research involves statistics and crunching through
big datasets. To do this, I use computer clusters like Amazon's
EC2 and a cluster at the Harvard MIT Data Center. I will
frequently kick of a job to run overnight on the full HMDC cluster of
~100 computers. Some of my friends do so nearly every night on similar
clusters. Like many researchers and engineers, it costs me nothing to
kick off a big job. That said, computers consume a lot of energy so I
did a little back-of-the-envelope calculation to figure out what the
cost in terms of resources might add up to.
An overnight job that uses a 100 computer cluster might use 800
computer-hours. Although power efficiency varies hugely between
computers, most statistical analysis is CPU intensive and should come
close to maximizing power consumption. According to a few sources
[e.g., 1 2 3], 200 watts might be a conservative estimate
of much a modern multi-CPU server will draw under high load and won't
include other costs like cooling. Using this estimate, the overnight
job on 100 machines would easily use 160 kilowatt hours (kWh) of
energy.
In Massachusetts, most of our power comes from coal. This page
suggests that an efficient coal plant will generate 2,460 kWh for each
ton of coal. That means that one overnight job would use 59 kg (130
lbs) of coal. In the process, you would also create 153 kg (338 lb)
of CO2 and a bit under half a kilogram (about 1 lb) of nitrogen oxides
and sulfur dioxide each. It's a very rough estimate but it certainly
generates some pressure to make sure the research counts!
Of course, I've written some free software that runs on many thousands
of computers and servers. How many tons of coal are burnt to support
laziness or a lack of optimization in my software? What is the coal
cost of choosing to write a program in a less efficient, but easier to
write, higher-level programming languages like Python or Ruby instead
of writing a more efficient version in C?
# Add a system group for Skype addgroup --system skype # Override permissions of skype (assuming Debian package!) dpkg-statoverride --update --add root skype 2755 which skype
iptables -I OUTPUT -p tcp -m owner --gid-owner skype \
-m multiport ! --dports 80,443 -j REJECT
iptables -I OUTPUT -p udp -m owner --gid-owner skype -j REJECT
They allow outgoing connections by Skype only on ports 80 and 443, which
supposedly do not trigger the firewall (in fact, this filter is recommended
by our network administration for Skype).which I've put just after the conntrack default module, as 05_skype.py""" Skype restriction to avoid firewall block. Raw iptables commands. """ iptables(Firewall.output, "-p tcp -m owner --gid-owner skype -m multiport ! --dports 80,443 -j %s" % Firewall.reject) iptables(Firewall.output, "-p udp -m owner --gid-owner skype -j %s" % Firewall.reject)
It is half-time for me at DebCamp/DebConf11 in Banja Luka, Bosnia-Herzegovina, and that is a good time to write about my work so far. I started with some finger exercises, such as the HTML copying for gnome-terminal (as blogged previously) and cosmetic changes to the buildd.debian.org/status website. After that, I began my main project: A SAT-based solver for the testing transition problem.
In Debian, new software first enters a repository called unstable, where it is tested. Once some requirements are fulfilled (package has been in unstable for usually at least 10 days and has no new release critical bugs), it is entitled to enter the repository called testing, which will eventually form a new stable Debian release. But some packages need to migrate together, usually because either requires the new version of the other. Also, no packages in testing ought to become uninstallable by some seemingly unrelated change.
The software that decides these things is called britney. It is sufficiently good in making sure nothing bad happens, but not smart enough to figure out what to do in case more than two packages need to migrate simultaneously. My goal is to improve this. Now, the the various requirements can all be expressed as predicative formulas, and a lot of research has been going into writing good solvers for such problems, called SAT-solvers. Hence my plan was to only specify what we expect from a testing migration, but leave the search for a solution to such a general purpose and highly optimized program.
My initial progress was good and I had some result after two days of hacking, and the approach is promising. Because the data sets are pretty large (1.5GB of input data, the final SAT problem has 1.8 million clauses with 250.000 variables), so I learned quite a bit about profiling and optimizing Haskell programs, and that parsec is slower than working with BS.lines and BS.split to parse simple input. I also used the FFI to use dpkg code directly to compare Debian version numbers.
At some point I noticed that I actually want to solve PMAX-SAT problems: Given two set of clauses, hard clauses and soft clauses, find a variable assignment that fulfills the hard clauses and as many of the soft clauses as possible. Unfortunately, there are no fast Free PMAX-SAT solvers around. The ones that I found and that were fast enough that I could use them, msuncore by Joao Marques-Silva at the University College Dublin and MiniMaxSat by Federico Heras at the Universitat Polit cnica de Catalunya, are only available as statically linked binaries. It is a shame that this is acceptable by the academic community; imagine mathematicians would stop including the proofs in their papers, and only share their theorems.
So if you happen to have written a PMAX-SAT solver and can solve this instance (in weighted DIMACS format) in less than five minutes, and want to brag that the Debian project is using your code, then please release it under a Free license (e.g. GPL or BSD) and tell me about it!
The code of my SAT-based solver is, of course, available, though slightly unpolished. Parts of it (notably the interface to picosat and the PMAX-SAT solvers) might be of general interest and I plan to put them on Hackage as a separate license.
Update: I have contacted the authors of the SAT solvers mentioned above, and they have reconfirmed that they have no intention of releasing the source. Now I put my hope in maxsatz2009 by Chumin LI, which is GPL but was not able to cope with my large instance directly; I think I need to change the memory management.
The trip down from Gratz to Banja Luka was much easier than the day before.
After a while you just get used to being sat in a car for ages. Plenty of
nice scenery to enjoy through Slovenia. After a while our car's GPS's began
to fail, showing us driving through fields, and we were stuck for 1.5 hours
in a traffic jam when the 4 lane highway seemed to end. Got around
that with some guesswork, and on into Croatia by back roads.
The Bosnian border was an interesting experience, all the guards could say
in English was "green card! green card!" -- which from an American POV is
an unsettling thing to be asked for at a border, especially if they've
already taken your passport away -- but at least we were not
detained overnight.
While drivers were away getting the car insurance settled it descended
toward farce as we had to hand roll the cars forward to let trucks get into
the country. (Or we thought we did.. one was rolled with the keys in it as
it turned out.)
Arrived at the Hotel in Banja Luka in the middle of a wedding,
which was amazingly loud (I could still hear it from the 5th floor at 2 am).
There's also a casino at the hotel, so first impression was garish and
loud! ... But now that it's a rainy Sunday, seems much nicer here.
Our adventurous friends Eric and Katie had invited us to join them on a hike in
the Grand Canyon over the 4th of July weekend. As this struck us as something
we'd never have considered doing otherwise, we thought we'd accept their kind
offer. We're so glad we did.
It was quite a bit of traveling just to get there. We flew out of San Jose on
Thursday night, got into Las Vegas, rented a car, and then drove to Peach
Springs, Arizona, where we stayed the night. We didn't get in at the Grand Canyon Caverns Inn until
around midnight, and we had to get up again for a 5:00am departure (I think we
actually got away by more like 5:30am), to drive to the Hualapai Hilltop, where
the trail head was. Zoe handled all of this very well. She didn't end up falling
asleep in the car until about 10:30pm I think, and dealt with the transfer out
of the car at midnight very well and went back to sleep.
The drive to the Hualapai Hilltop, along Indian Road 18, took about an hour. We
had to dodge a bit of livestock on the road. The road itself was sealed and of
good quality. We remarked on the way back out that as soon as you left the
Havasupai Reservation and entered the Hualapai Reservation that there was a
distinct degradation in the quality of the road.
We parked at the Hilltop, and got ourselves organised, and commenced our
descent by about 7:10am.
The first 1.5 miles was very steep. There were a bunch of switchbacks and there
was a fair few people coming up the other way already. There were also a few
mule trains coming in the opposite direction that we had to dodge. The mule
trains have right of way, so we had to stop and get out of the way to let them
pass. Zoe thought they were pretty cool because they invariably had a few dogs
with them as well, and she thinks dogs are awesome.
The remaining 6.5 miles (it was an 8 mile/13 kilometre hike in total) were
fairly easy. There was a lot of variety in terrain. Rocks, sand, dirt. It
wasn't all in the sun, which was made it more comfortable. Heat wise, I think
it was in the high 30's Celsius, with pretty much no humidity, so it didn't
feel too uncomfortable.
Towards the end, as we got near the water, there was a distinct change in the
canyon. There was more greenery, and we started hearing insects and seeing bird
life. When we first saw the water, it was hard not to just jump in, it looked
so inviting.
The total hiking time was about 4 hours 45 minutes, which included a reasonable
stop to give Zoe some breakfast. We arrived in the village at around midday.
Unfortunately the lodge wasn't ready for check ins until 1pm, so we had to
twiddle our thumbs for a little bit.
Zoe handled the hike incredibly well. We used a Macpac
Possum child carrier that Nigel
had passed down to us, and she didn't complain the whole time. She even
took a nap in it. We were very relieved that it wasn't a problem for her.
Sarah carried her, and I carried
everything else. (I'm so glad I didn't see the photo of how I looked until
well afterwards). In hindsight we probably brought too much stuff, but we
didn't really know what to expect down there, so we'd rather have too much than
too little.
The village completely exceeded my expectations. I had this (silly) mental
picture of it being just the lodge and not much else, but somewhere between 450
and 700 people live in the village. It had two general-type stores, a cafe that
was pretty much like a fast food/takeaway place, an elementary school, and some
sort of basic medical clinic. There was also a small general purpose community
centre of some sort. The main store had pretty much everything you'd need in
the food department. The cafe frequently ran out of various different things,
but you weren't going to go hungry.
For the remainder of Friday, we just stayed put in the village and let Zoe
stretch her legs. Eric and Katie and their kids explored the first set of falls
down from the village, unofficially named Rock Falls.
On Saturday, we all hiked down to Havasu Falls. We met a
couple of other families (amusingly both from the Bay Area) along the way, so
we had some interesting conversations. I have no idea how long the hike was.
Havasu Falls was impressive. Quite tall and narrow at the top, and quite loud.
Zoe was impressed. We took her for a bit of a swim in the pools in the bottom.
We had lunch there, and then Zoe and Sarah stayed there (Zoe took a nap in the
KinderKot (also courtesy of Nigel)
in the shade by the falls, and I took the Macpac with a water bladder in it to
refill it at the spring in the campground, which was further down stream, and
to check out Mooney
Falls with Eric and Katie (and their kids), which was further downstream
again from the campground.
Mooney Falls was pretty insane. A lot taller than Havasu Falls, and a lot more
treacherous to get to the bottom of. Parts of it were vertical. Chains and
rickety ladders were involved. Caves were involved. I'm so glad I didn't have
Zoe in the Macpac, because on multiple occasions, the top of it got bashed
into rocks, so without having Sarah with me also to act as a guide, there's no
way I could have safely descended with Zoe in the backpack. My favourite photo
illustrating how crazy this was is this
one that I took of Eric and Katie. This
photo highlights some of the craziness involved to get down.
I pretty much got to the bottom, had a quick look around and left Eric and
Katie to it, because I figured Zoe would have woken up by now, and was probably
bored. Turned out I had all of the sunscreen with me as well. So I climbed back
up, and trekked back to the campground, refilled at the spring, and headed back
up to Havasu Falls.
After we reunited, we then hiked back up to the village, which to be honest,
was the hardest bit of hiking we did. I was carrying Zoe in the Macpac, and it
was hot, and it was mostly loose sand all the way. We were very glad to get
back to the village.
Zoe started showing signs of coming down with a cold and a cough, so we decided
to cut short our stay in the village and leave on Sunday instead of Monday.
We'd been tossing up between getting a helicopter or horses out. We ended up
opting for the helicopter after learning that the horses still took about 3.5
hours, and you basically had no control over the animal. We were dubious as to
how Zoe would go being bounced around on the back of a horse for that long. The
helicopter ride also took all of about 5 minutes.
The tribal members get first dibs on the helicopter, and there had been a death
in the village, and I think a lot of people had come to the village for the
viewing (the casket itself was flown out earlier on Sunday morning for a burial
out of the village), so I suspect there was a higher number of tribal
passengers than usual. We didn't get out until 2pm. Again, Zoe was incredibly
good. She just hung out with us while we waiting for a flight out. There were
plenty of dogs for her to be entertained by, and some other kids. She also took
a pretty decent nap.
So we finally got out, and got back to our car, and then the heavens opened. It
absolutely poured down with rain. Sarah was keen to check out Hoover Dam, so we
decided to stay near Boulder City in Nevada, and got a suite in the Hacienda Hotel and Casino
for cheap.
The next day was the Monday public holiday for Independence Day, and we were
tossing up whether or not to take Zoe to a doctor to get her checked to see if
she had bronchitis (we've been a bit gun-shy about bronchitis since the time
she came down with it when we were in Australia). She ended up falling asleep
in the car while we were hunting around for an Urgent Care facility that was
open, so we decided to let her sleep and drove to Las Vegas.
After she woke up, we took her to see the flamingos at Flamingo
and the lions at MGM Grand. Zoe
absolutely loved all the lights, sights and sounds of Las Vegas.
In the afternoon, we took her to a doctor, and got the "first child, huh?" from
the doctor (she didn't have bronchitis).
After that, we went and briefly checked out Hoover Dam (just walked half
way across the bridge in front of it and walked across the dam itself).
The following day, we packed up and spent the morning on the Las Vegas strip
again. This time we went to the Venetian
(Zoe thought the gondolas were pretty cool) and then we flew out in the
afternoon.
So it was a lovely little family vacation. We ended up spending about as much
time in Las Vegas as we did in the Grand Canyon, but that was okay. I'd really
like to go back to Supai again, but I'm not sure if the stars will align
themselves appropriately. If we did, knowing what I know now, I'd take a lot
less food and put all of the luggage on a horse, and just hike in with the
minimum of stuff. I'd probably be game to hike out as well if the bulk of the
luggage was on a horse.
Photos from the trip are here.
mksh R40b (nowadays with filled
in user s caveats (for R40, too!)
and packager s upgrade hints) has
just been released. This is a should-have upgrade, fixing a number of
admittedly some obscure bugs, changing things begun in R40, improving
upon others. Thanks to the PLD Linux guys for spotting all these errors;
thanks to them and phpnet.org both for adopting mksh so well.
I have also fixed a bug in nroff(1) which will lead to an even
nicer looking HTML manpage mksh(1) (after the next rebuild and upload of
a MirBSD snapshot scheduled RSN).
jupp 3.1.16 took on the task
of merging Debian joe changes (aiming at an upload). I also split the
jupprc file into three versions (2.8 generic/DOS, 3.1+jupp and 3.7/Unix)
because of the differences in the baseline executables making rc files
partially mutually incompatible (think Insert key), annoyingly warning
(think syntax, hmsg), or less usable (joe s new menu system).
jupp 2.8.2 is a companion to
jupp 3.1.16 mostly because of the new help window character map
Binaries for jupp should be updated RSN too.
Considering Banja Luka is arriving quickly, the r in RSN should be
taken with a few grains of salt. I ve also scheduled working on the pcc
Debian package for the next future; updating lynx and maybe others like
OpenSSH in MirBSD is also due; cvs(1) will receive more of my time, but
before the next Upload I d like to fix LP#12230 once verified.
Builds for Debian/m68k are also still running. I note I did in fact
not manage to make a new base image, yet (but 2.6.39 kernels
miss a patch, anyway, so waiting for 3.0 is ok). It s still using gcc-4.4
because nobody tests gcc-4.6 and gcj-4.6 FTBFS due to SIGSEGV, but that s
ok in my books. rsyslog is broken but sysklogd works.
The #ksh Freenode page finally
got a well-deserved link to Planet Commandline. Throw more my way!
Acronyms and translations,
too. (Got Norwegian and Rumanian covered in the meantime. No idea whether any
RTL languages will work in that beast. But I m young and need the money)
Since I m writing a wlog entry anyway let me thank Gunnar for a nice
summary on the current Free Culture discussion; my comments on Nina s site
seem to be eaten, but let me support it fully, although, of course, I normally
use a copycenter style licence, which
is specifically written for general works of authorship under copyright law,
not limited to software. I did in fact have that in mind. Maybe some people
will like it (it s less than one Kibibyte long) either generally or just for
their everyday random musings (they can then keep CC-BY-SA for the big works
if they so desire).
Wouter, grass background makes green headlines illegible. I ve never liked,
and never installed manually, cups either. (Benny tells me that Apple s new
version refuses to talk with a non-Apple cups, kinda defeating the whole idea
I think.) Port 9100 is JetDirect (probably with an HP in front and some subset
of trailing) and just nice. (Being able to talk ESC/P with your printer
like print '\033K\x07\0\x3E\x81\x99\xA5\xA5\x81\x3E' >/dev/lpa too
rocks though, IMHO. Yes, mine can, and I still can. /dev/lpa is BSD.)
Kai, thanks for your vimrc lines:
:highlight TrailWhitespace ctermbg=red guibg=red :match TrailWhitespace /\s\+$\ \+\ze\t/
Automatic removal is harmful, though I just fell into the trap since jupprc contains needed whitespace at EOL but manual removal (bound to ^K] in jupp) rocks. And I like that your solution uses such strong a colour vim users are the single most represented offender group for actually leaving the redundant whitespace at EOL there, and it should hurt their eyes. (Sadly there is some vehement disagreement preventing them from inclusion in grml-etc-core but that s why I re-post them here.) Ah, and jupp can of course display whitespace visibly (although it uses / , replacing the arrow with if no UTF-8, not ), accessible with ^Ov. Steve, want to put up a checklist for sites? We can crowdsource the testing to maybe get some interesting results Some other people would get more comments if they were idling in IRC (Freenode) or allow comments on their blog, specifically without too high an entrance barrier OpenID is ok, but many other things, and ECMAscript, are not; but I can t really say that loud because our wlog is static HTML compiled from a flat plaintext data source so it doesn t allow such either. I often forget what I wanted to add if I can t get it out quickly enough (especially at work). Sowwy Me like the cat picture postings (Amayita, Tiago, Gracias!).
Sanjog Misra, who
uses Rcpp for
Monte Carlo Markov Chain (MCMC) analyses in quantitative marketing, kindly set me a
short example of Rcpp use.
The example is based on a
blog post by Darren Wilkinson
which itself discusses and compares the suitability of R, Python, Java or C for MCMC analysis, using the
Gibbs sampler as a concrete example. Darren's post is worth checking out: he
stresses the rather pragmatic aspects of how fast and/or easy it is to write the code, rather than just the mere runtime. As such,
he is not too concerned with a speed advantage of Python over R which he sees at a factor of around 2.4, leaving him to continue to prototype in
R. Similarly, with C 'only' being faster than Java by a factor of two, he prefers Java for the numerically more demanding parts.
We do of course advocate the use of Rcpp to combine the best aspects of R and C++,
respectively. This Gibbs sampler example provides a nice backdrop. So working with Darren's example, consider the same Gibbs sampler for
a bivariate distribution (and apologies for the lack of latex typesetting on my blog)
where the conditional distributions aref(x,y) = k x^2 exp( -x y^2 - y^2 + 2y - 4x)
Sanjog then spotted and corrected a small error in the variance expression in Darren's derivation; this is now acknowledged on Darren's website. Full details are in the R script now committed in SVN. The R code for the Gibbs sample can therefore be written as follows below. Note that this uses thinning to minimize serial correlation in the conditional densities--which renders the computation more demanding as 'N times thin' draws have to be generated:f(x y) = (x^2)*exp(-x*(4+y*y)) ## a Gamma density kernel f(y x) = exp(-0.5*2*(x+1)*(y^2 - 2*y/(x+1)) ## a Gaussian kernel
A second variant can be computed using the R bytecode compiler which appeared with the recent release of R 2.13.0 (and which we analysed in this blog post from April). This is as easy as## Here is the actual Gibbs Sampler ## This is Darren Wilkinsons R code (with the corrected variance) ## But we are returning only his columns 2 and 3 as the 1:N sequence ## is never used below Rgibbs <- function(N,thin) mat <- matrix(0,ncol=2,nrow=N) x <- 0 y <- 0 for (i in 1:N) for (j in 1:thin) x <- rgamma(1,3,y*y+4) y <- rnorm(1,1/(x+1),1/sqrt(2*(x+1))) mat[i,] <- c(x,y) mat
Thanks to Rcpp and the inline package, we can also write a C++ variant that can be built and launched from R with ease. The C++ code is assigned to an R text variable## We can also try the R compiler on this R function RCgibbs <- cmpfun(Rgibbs)
gibbscode. (And we used to typeset such
code on the blog as a character string, ie in a faint red color---but have now switched to highlight it as if it were freestanding C++
code. It really is passed as a single string to R which then uses the cxxfunction() to compile, link and load a C++ function
built around the code. See previous posts on the inline package for more.)
It is noteworthy how the code logic is essentially identical between the basic R version, and the C++ version. Two nested loops control draws of x from a Gamma distribution, conditional on y, as well as draws of y from a Normal, conditional on x. Add a small amount of parameter passing to obtain the parameters## Now for the Rcpp version -- Notice how easy it is to code up! gibbscode <- ' using namespace Rcpp; // inline does that for us already // n and thin are SEXPs which the Rcpp::as function maps to C++ vars int N = as<int>(n); int thn = as<int>(thin); int i,j; NumericMatrix mat(N, 2); RNGScope scope; // Initialize Random number generator // The rest of the code follows the R version double x=0, y=0; for (i=0; i<N; i++) for (j=0; j<thn; j++) x = ::Rf_rgamma(3.0,1.0/(y*y+4)); y = ::Rf_rnorm(1.0/(x+1),1.0/sqrt(2*x+2)); mat(i,0) = x; mat(i,1) = y; return mat; // Return to R ' # Compile and Load RcppGibbs <- cxxfunction(signature(n="int", thin = "int"), gibbscode, plugin="Rcpp")
N and thin, allocation of a results matrix and setup of the random number generator state
to remain consistent with R, as well as a return of the matrix---and that is all.
As Darren's code uses the GNU GSL in its C variant, I also became interested in seeing how a C/C++ hybrid variant using our
RcppGSL package would fare. The code is below.
This code is similar to the version using just Rcpp, but we need to allocate space for the GSL random generator object (and later release that memory allocation), and we do of course call the GSL functions. This also necessitates declaring the function using the two header files listed as arguments for thegslgibbsincl <- ' #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> using namespace Rcpp; // just to be explicit ' gslgibbscode <- ' int N = as<int>(ns); int thin = as<int>(thns); int i, j; gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937); double x=0, y=0; NumericMatrix mat(N, 2); for (i=0; i<N; i++) for (j=0; j<thin; j++) x = gsl_ran_gamma(r,3.0,1.0/(y*y+4)); y = 1.0/(x+1)+gsl_ran_gaussian(r,1.0/sqrt(2*x+2)); mat(i,0) = x; mat(i,1) = y; gsl_rng_free(r); return mat; // Return to R ' ## Compile and Load GSLGibbs <- cxxfunction(signature(ns="int", thns = "int"), body=gslgibbscode, includes=gslgibbsincl, plugin="RcppGSL")
include argument of
cxxfunction().
So how is the performance?
The script (now committed in Rcpp's SVN repo as
examples/RcppGibbs/RcppGibbs.R, and also part of the next release) creates the output below when running in non-interactive
mode (whereas interactive mode creates a few charts too):
edd@max:~/svn/rcpp/pkg/Rcpp/inst/examples/RcppGibbs$ r RcppGibbs.R
Replication # 1 complete
Replication # 2 complete
Replication # 3 complete
Replication # 4 complete
N=1000 N=5000 N=10000 N=20000
Elasped Time (R) 0.124 2.650 10.511 41.773
Elasped Time (RC) 0.081 1.916 7.594 30.280
Elapsed Time (Rcpp) 0.003 0.076 0.306 1.221
Elapsed Time (Rgsl) 0.002 0.049 0.196 0.784
SpeedUp Rcomp. 1.530 1.380 1.380 1.380
SpeedUp Rcpp 41.330 34.870 34.350 34.210
SpeedUp GSL 62.000 54.080 53.630 53.280
test replications elapsed relative user.self sys.self
4 GSLGibbs(N, thn) 10 7.845 1.000000 7.84 0
3 RcppGibbs(N, thn) 10 12.218 1.557425 12.22 0
2 RCgibbs(N, thn) 10 312.296 39.808286 311.98 0
1 Rgibbs(N, thn) 10 420.953 53.658764 420.59 0
The first block is a hand-computed comparison using four sets of parameters; the second block uses the excellent rbenchmark package to
compare ten runs at twenty-thousand draws.
We see a nominal increase in performance due to the bytecode compiler, saving roughly 38 percent which seems appropriate given that the R
code mostly controls the loops; actual work in undertaken in the already compiled RNG functions. The Rcpp variant is about 34 times faster
than the pure R code. Sanjog reported higher increases on his OS X machines (and Darren's post echos a similar order of
magnitude). However, on my i7 running Linux I always obtained an improvement in the mid- to high thirties. That is certainly already a
rather pleasant result.
What surprised and stunned me at first was that the GSL solution scores an improvement of around 53 times (close to the factor of 60
reported by Darren). A closer look at the code (shown above) makes it clear that there are very few compute-intensive operations outside of
the RNG draws. I validated this further with a second study timing just one million draws each from a Gaussian and Gamma using R via Rcpp,
and using the GSL. It turns out that the R code is about 2.5 times slower for random draws from the Gamma distribution than the GSL. Inspection of the
source code---in files src/nmath/rgamma.c for R and randist/gamma.c for the GSL shows why. R uses a much more complex
(and presumably more precise) algorithm. I may follow up with Martin Maechler to see if we can illustrative the numerical benefits of this
more expensive approach---this blog entry is getting long enough already.
So to sum up: Gibbs sampling is a somewhat resource-heavy Monte Carlo Markov Chain method for investigating multivariate distributions. R excels at
quick and simple explorations, albeit at somewhat slower execution speed. The
Rcpp package can help by providing easy
means to accelerate simulations by a significant factor. The example discussed here is now in SVN repository for
Rcpp and will be part of the next release.
Updated 2011-07-16: Darren has just updated his comparison; fixed two typos here too.
apt-get build-dep gnucash
apt-get install python-dev
As a non privileged user:
apt-get source gnucash
cd gnucash-N.N.N # varies depending on your version)
Then, edit debian/rules and add --enable-python-bindings to the dhautoconfigure command. I replaced the line:
--enable-locale-specific-tax
With the lines:
--enable-locale-specific-tax \
--enable-python-bindings
Then, update the change log with:
dch
Built the new package:
dpkg-buildpackage -rfakeroot -uc -b
I then wrote a python module. It logs into the server running our members database, runs a script to export tab delimited lists, and then imports them into our gnucash xml file.
It's far from perfect (I'm fairly new to python). Also - I have sheepishly inserted code that searches for certain values by accessing the gnucash file directly (via python's xml handling modules). I couldn't figure out how to do the search I needed with they available python methods, although it may very well be there and I just couldn't figure it out.
If anyone is interested in using it for a template:
#!/usr/bin/python
import sys
import os
import time
import csv
import warnings
from xml.dom.minidom import parse
from gnucash import Session, GncNumeric
from gnucash.gnucash_business import Customer, Invoice, Entry, BillTerm
from decimal import Decimal
import datetime
import tempfile
import subprocess
def main(argv = None):
if argv is None:
argv = sys.argv
path = os.environ['MFPL_GNUCASH_PATH']
if not os.path.exists(path):
print """Path (%s) does not exist. Please set
MFPL_GNUCASH_PATH environment variable\n""" % path
return 1
if os.path.exists(path + '.LCK'):
print """Lock file exists. Is GNUCash running?\n"""
return 1
command = argv[1]
import_file = None
if 2 in argv:
if argv[2] == '--from-file':
if argv[3]:
if os.path.exists(argv[3]):
file_path = argv[3]
import_file = open(file_path,'r')
else:
print "Can't find file to import: %s" % argv[3]
return 1
else:
print "Please pass path to file if using --from-file"
return 1
else:
print "I didn't understand the argument: %s" %s
# download import file if not provided
if import_file == None:
import_file = get_data(command)
# The file might be gzipped, so
# open and save it
s = get_gnucash_session(path)
s.save()
s.end()
# Wait a second, so we can create a backup
# without a name collision
time.sleep(1)
# Open for real now...
s = get_gnucash_session(path)
xml_dom = parse(path)
if command == "members":
ret = import_members_from_file(s, xml_dom, import_file)
if command == "invoices":
ret = import_invoices_from_file(s, xml_dom, import_file)
s.save()
s.end()
return ret
def get_data(command):
import_file = tempfile.NamedTemporaryFile()
if command == 'members':
remote_cmd = 'acc-member-list'
else:
remote_cmd = 'acc-invoice-list'
args = [ '/usr/bin/ssh', 'mayfirst@hay.mayfirst.org', '/home/mayfirst/bin/' + remote_cmd ]
subprocess.call(args,stdout = import_file)
return import_file
def import_invoices_from_file(s, xml_dom, csvfile):
dialect = 'excel-tab'
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
nodes = xml_dom.getElementsByTagName('gnc:GncCustomer')
already_entered = 0
entered = 0
for row in reader:
member_id = row[0]
invoice_id = row[1]
invoice_date = row[2]
invoice_amount = row[3]
invoice_desc = row[4]
if not member_id.isdigit():
# header line or not coded to a member?
continue
member_id = int(member_id)
invoice_id = int(invoice_id)
if invoice_exists(xml_dom, invoice_id):
# print "Already entered %s (%s)" % (invoice_date,invoice_id)
already_entered += 1
else:
if not member_exists(xml_dom, "No Name McGoo - fix me" , member_id):
print "Skipping member id %s, invoice id %s - member doesn't exist" % (member_id, invoice_id)
else:
invoice_enter(s, member_id, invoice_id, invoice_date, invoice_amount, invoice_desc )
entered += 1
print "Invoices entered from last two months: %s (%s already existed)" % (entered, already_entered)
return True
def get_guid_from_member_id(nodes,member_id):
member_id = pad_number(member_id)
for node in nodes:
for child in node.childNodes:
if child.nodeName == 'cust:guid':
guid = child.childNodes[0].data
if child.nodeName == 'cust:id':
if member_id == child.childNodes[0].data:
return guid
def import_members_from_file(s, dom, csvfile):
dialect = 'excel-tab'
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
already_entered = 0
entered = 0
for row in reader:
member = row[0]
member_id = row[1]
if not member_id.isdigit():
# header line?
continue
member_id = int(member_id)
if member_exists(dom, member, member_id):
#print "Already entered %s (%s)" % (member, member_id)
already_entered += 1
else:
member_enter(s, member, member_id )
entered += 1
print "Members entered from last two months: %s (%s already existed)" % (entered, already_entered)
return True
def get_gnucash_session(path):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return Session(path, is_new = False)
def member_enter(s, member, member_id):
print "Entering %s with id %s" % (member, member_id)
book = s.book
root = book.get_root_account()
commod_table = book.get_table()
USD = commod_table.lookup('CURRENCY', 'USD')
member_id = pad_number(member_id)
new_customer = Customer(book, member_id, USD, member)
def invoice_enter(s, member_id, invoice_id, invoice_date, invoice_amount, invoice_desc):
book = s.book
root = book.get_root_account()
commod_table = book.get_table()
USD = commod_table.lookup('CURRENCY', 'USD')
invoice_id = pad_number(invoice_id)
member_id = pad_number(member_id)
invoice_date_object = datetime.datetime.strptime(invoice_date, "%Y-%m-%d %H:%M:%S")
member = book.CustomerLookupByID(member_id)
assert( member != None )
assert( isinstance(member, Customer) )
assets = root.lookup_by_name("Assets")
recievables = assets.lookup_by_name("Recievables")
income = root.lookup_by_name("Membership Dues")
invoice = Invoice(book, invoice_id, USD, member, invoice_date_object )
invoice_value = gnc_numeric_from_decimal(Decimal(invoice_amount))
invoice_entry = Entry(book, invoice)
invoice_entry.SetDescription(invoice_desc)
invoice_entry.SetQuantity( GncNumeric(1) )
invoice_entry.SetInvAccount(income)
invoice_entry.SetInvPrice(invoice_value)
invoice_entry.SetDate(invoice_date_object)
invoice_entry.SetDateEntered(invoice_date_object)
print "Entering invoice %s %s %s" % (invoice_id, invoice_date, invoice_amount)
invoice.PostToAccount(recievables, invoice_date_object, invoice_date_object, "", True)
def pad_number(num):
return "%(number)06d" % 'number': num
def member_exists(dom, member, member_id):
member_id = pad_number(member_id)
for node in dom.getElementsByTagName('gnc:GncCustomer'):
for child in node.childNodes:
if child.nodeName == 'cust:name':
for grandchild in child.childNodes:
if member == grandchild.data:
return True
if child.nodeName == 'cust:id':
for grandchild in child.childNodes:
if member_id == grandchild.data:
return True
return False
def invoice_exists(dom, invoice_id):
invoice_id = pad_number(invoice_id)
for node in dom.getElementsByTagName('gnc:GncInvoice'):
for child in node.childNodes:
if child.nodeName == 'invoice:id':
for grandchild in child.childNodes:
if invoice_id == grandchild.data:
return True
return False
def gnc_numeric_from_decimal(decimal_value):
sign, digits, exponent = decimal_value.as_tuple()
# convert decimal digits to a fractional numerator
# equivlent to
# numerator = int(''.join(digits))
# but without the wated conversion to string and back,
# this is probably the same algorithm int() uses
numerator = 0
TEN = int(Decimal(0).radix()) # this is always 10
numerator_place_value = 1
# add each digit to the final value multiplied by the place value
# from least significant to most sigificant
for i in xrange(len(digits)-1,-1,-1):
numerator += digits[i] * numerator_place_value
numerator_place_value *= TEN
if decimal_value.is_signed():
numerator = -numerator
# if the exponent is negative, we use it to set the denominator
if exponent < 0 :
denominator = TEN ** (-exponent)
# if the exponent isn't negative, we bump up the numerator
# and set the denominator to 1
else:
numerator *= TEN ** exponent
denominator = 1
return GncNumeric(numerator, denominator)
if __name__ == "__main__":
sys.exit(main())
Ten years ago, I started to use ZSH, a shell designed for
interactive use but which is also powerful for scripting usage. I had
a fairly comprehensive .zshrc file splitted in several parts. I have
decided to rewrite it for several reasons:
head, awk,
sed that could be replaced by some ZSH machinery (something easier
to read like $ $ (f)~~"$(</etc/hosts)" %%\#* ).
oh-my-zsh, a nice project trying to
provide a generic and flexible ZSH configuration:
A community-driven framework for managing your zsh configuration. Includes 40+ optional plugins (rails, git, OSX, hub, capistrano, brew, ant, macports, etc), over 80 terminal themes to spice up your morning, and an auto-update tool so that makes it easy to keep up with the latest updates from the community.The idea of such a project is to fork it and make the changes that you need. I was previously hacking around Phil! s ZSH Prompt for my prompt.
oh-my-zsh contains a close theme (jonathan). Neat.
However, I decided to write my .zshrc from scratch (but with some
snippets stolen from oh-my-zsh). Why? Mostly because I want to
precisely configure ZSH. Even with its plugin architecture and its
override mechanism, oh-my-zsh provides some features (options,
aliases, functions) that I do not want. Of course, thanks to git, you
can fork and make any local changes you want but since I would have
modified most of the files, it seemed easier to just start from scratch.
I have published the result on GitHub. You can use it as is,
fork it or (better) steal and adapt some snippets for your own
usage. Here is the mandatory screenshot for the prompt (no much space
left for the commands):
Here is a short snippet used to select a sensible EDITOR depending
on what is available. It uses anonymous functions (to restrict the
scope of local variables), arrays and flags in parameter
expansion. For another example, take a look on
how I select a valid locale.
() local -a editors local editor editors=( "emacs23 -Q -D -nw" # Fast emacs "jove" "mg" "jed" # Emacs clone "vim" "vi" # vi "editor") # fallback for editor in $editors; do (( $+commands[$editor[(w)1]] )) && export EDITOR=$editor break done
__() local -a editors local editor ... && __
We watched the special features on the Blu-Ray disc, and one of them was an interview with director Florian Henckel von Donnersmarck. He described how he spent a lot of time interviewing both victims of the Stasi, as well as ex-Stasi officers. One of the most disturbing things to me was his almost offhand comment that most of the former Stasi officers still had some pride in performing their jobs well. Even now, freed of the state s ideology, they were proud of the work they did which could be put most charitably as ruining people s lives.
What leads a person to view life that way? How can we try to make sure it doesn t happen again elsewhere?
I am happy to say that most of us have never experienced anything like the Stasi. And yet, small reflections of that mindset can be seen almost everywhere. Societies at wartime or feeling under threat, even Western democracies, can drum up those feelings. In the USA, for instance, the McCarthyism era saw people s careers ruined for alleged anti-state behavior. Contemporary examples include the indefinite detention (I hate that word; shouldn t we say imprisonment ?) of terrorism suspects at Guantanamo Bay, and the terrible treatment of Bradley Manning, who revealed some true but embarrassing things about the US military which really needed to be revealed. Even tobacco farmers and companies are selling a product they know ruins lives, but somehow keep doing it.
And there are still members of the public that try to make life difficult for people that don t think like they do. From organizing campaigns of telephone harassment of colleges that don t perform the American national anthem before sporting events, to tossing about the term un-American (a loaded McCarthyist one, which many may not even be aware) at an inflated rate, we are not immune from attempts at forcing conformity or silence in others, and blind loyalty to state.
I am never in a particularly celebratory mood on July 4, the biggest day for American boasting, faux patriotism, militarism, and general flag-waving. We do have a lot to be proud of and thankful for, but it seems that we celebrate all the wrong things on July 4, and see it as an occasion to proclaim American exceptionalism rather than as one to see how far we ve come and bolster hope for how far we can, and should, yet go.
No, I don t think that the land of the free ought to have operated secret prisons in Europe (nor the Europeans to have been complicit in it), or that the American military was defending our freedom 100% of the time they were deployed, or that it is right for governments to mandate daily recitation of an untrue document (the pledge of allegiance) in schools.
And yet, I am mindful that I have a lot to be thankful for stability, lack of much internal violent conflict, etc. And this particular day I am happy that a post like this is not something that gets the attention of some government agency and mostly that I will have a handful of angry emails to delete.
The file properties will show the file size in base10 and base2:
PS: I failed to launch nautilus in English. Therefore the screen shots are in German.
PS : You can grab the modified nautilus package for Ubuntu 10.10 (maverick) from my experimental PPA (at your own risk!).
man 5 byteprefix once installed. Thanks to Stefano Rivera for writing the man page!
For a demonstration how this library used by an application can look like, read my previous post.
[283808.667454] radeon 0000:01:00.0: ffff88021f815c00 unpin not necessaryThe time between going black reduces every time. The system wasn t usable any more in the end. After testing that the screen was going blank on other systems like a live CD of Ubuntu and a not noteworthy proprietary system, it was clear that some hardware component was dying. My first assumption was verified after replacing it: My graphic card, a Radeon HD 4670, died. This was three weeks ago and around 25 month after I bought the graphics card. So I didn t have to worry if replacing the fan voided the guarantee, because the guarantee lasts only 24 month. Conclusion:
[283808.667820] radeon 0000:01:00.0: GPU softreset
[283808.667823] radeon 0000:01:00.0: R_008010_GRBM_STATUS=0xE57024A4
[283808.667825] radeon 0000:01:00.0: R_008014_GRBM_STATUS2=0 00330302
[283808.667826] radeon 0000:01:00.0: R_000E50_SRBM_STATUS=0x200000C0
[283808.667832] radeon 0000:01:00.0: R_008020_GRBM_SOFT_RESET=0x00007FEE
[283808.682844] radeon 0000:01:00.0: R_008020_GRBM_SOFT_RESET=0 00000001
[283808.698840] radeon 0000:01:00.0: R_008010_GRBM_STATUS=0 00003028
[283808.698843] radeon 0000:01:00.0: R_008014_GRBM_STATUS2=0 00000002
[283808.698845] radeon 0000:01:00.0: R_000E50_SRBM_STATUS=0x200000C0
[283808.699845] radeon 0000:01:00.0: GPU reset succeed
[283808.717570] [drm] Clocks initialized !
[283808.765829] [drm] ring test succeeded in 0 usecs
[283808.765838] [drm] ib test succeeded in 1 usecs
[283808.765840] [drm] Enabling audio support
[283812.521265] radeon 0000:01:00.0: GPU lockup CP stall for more than 1000msec
[283812.521269] [ cut here ]
[283812.521294] WARNING: at /build/buildd/linux-2.6.35/drivers/gpu/drm/radeon/radeon_fence.c:235 radeon_fence_wait+0 365/0x3d0 [radeon]()
[283812.521297] Hardware name:
[283812.521299] GPU lockup (waiting for 0x00AE670A last fence id 0x00AE6705)
[283812.521301] Modules linked in: btrfs zlib_deflate crc32c libcrc32c ufs qnx4 hfsplus hfs minix ntfs vfat msdos fat jfs xfs exportfs reiserfs nls_utf8 udf ip6table_filter ip6_tables binfmt_misc ipt_MASQUERADE iptable_nat nf_nat nf_conntrack_ipv4 nf_defrag_ipv4 xt_state nf_conntrack ipt_REJECT xt_tcpudp iptable_filter ip_tables x_tables bridge stp kvm_intel kvm parport_pc ppdev snd_emu10k1_synth snd_emux_synth snd_seq_virmidi snd_seq_midi_emul snd_emu10k1 snd_ac97_codec ac97_bus snd_pcm snd_page_alloc snd_util_mem snd_hwdep snd_seq_midi radeon snd_rawmidi snd_seq_midi_event snd_seq snd_timer snd_seq_device ttm snd pl2303 drm_kms_helper coretemp usbserial joydev psmouse soundcore drm serio_raw intel_agp i2c_algo_bit lp parport hid_cherry usbhid hid firewire_ohci firewire_core usb_storage crc_itu_t e1000e ahci libahci pata_marvell
[283812.521360] Pid: 2194, comm: compiz Tainted: G W 2.6.35-24-generic #42-Ubuntu
[283812.521362] Call Trace:
[283812.521370] [<ffffffff8106089f>] warn_slowpath_common+0x7f/0xc0
[283812.521374] [<ffffffff81060996>] warn_slowpath_fmt+0 46/0 50
[283812.521390] [<ffffffffa01bd775>] radeon_fence_wait+0 365/0x3d0 [radeon]
[283812.521394] [<ffffffff8107f730>] ? autoremove_wake_function+0 0/0 40
[283812.521410] [<ffffffffa01bdf71>] radeon_sync_obj_wait+0 11/0 20 [radeon]
[283812.521418] [<ffffffffa01751a3>] ttm_bo_wait+0 103/0x1c0 [ttm]
[283812.521435] [<ffffffffa01d4e1a>] radeon_gem_wait_idle_ioctl+0x9a/0 150 [radeon]
[283812.521447] [<ffffffffa010f433>] drm_ioctl+0 463/0 520 [drm]
[283812.521465] [<ffffffffa01d4d80>] ? radeon_gem_wait_idle_ioctl+0 0/0 150 [radeon]
[283812.521470] [<ffffffff81162f0d>] vfs_ioctl+0x3d/0xd0
[283812.521473] [<ffffffff811637e1>] do_vfs_ioctl+0 81/0 340
[283812.521477] [<ffffffff811535f1>] ? vfs_read+0 181/0x1a0
[283812.521480] [<ffffffff81163b21>] sys_ioctl+0 81/0xa0
[283812.521484] [<ffffffff8100a0f2>] system_call_fastpath+0 16/0x1b
[283812.521487] [ end trace 6d5e03bab743abfa ]
[283812.521493] [drm] Disabling audio support
[283812.525575] [drm:radeon_ib_schedule] *ERROR* radeon: couldn t schedule IB(10).
[283812.525579] [drm:radeon_cs_ioctl] *ERROR* Faild to schedule IB !
[283812.527021] [drm:radeon_ib_schedule] *ERROR* radeon: couldn t schedule IB(11).
[283812.527024] [drm:radeon_cs_ioctl] *ERROR* Faild to schedule IB !
[283812.527921] [drm:radeon_ib_schedule] *ERROR* radeon: couldn t schedule IB(12).
[283812.527923] [drm:radeon_cs_ioctl] *ERROR* Faild to schedule IB !
Next.