Tuesday, June 22, 2010

random points within a circle

Make randomly distributed points within a circle. Circle radius and origin can be anything. Points are validated to be in the range of x,y +/- radius and also to be within radius of the origin.


Thursday, June 3, 2010

PDF object dissection with macruby

irb(main):001:0> framework 'Quartz'
=> true
irb(main):002:0> url = NSURL.fileURLWithPath('/Users/Tim/Desktop/SU.pdf')
=> #<NSURL:0x2006e94a0>
irb(main):003:0> pdf = PDFDocument.alloc.initWithURL url
=> #<PDFDocument:0x2006cf5a0>
irb(main):006:0> select = pdf.findString("Shinya", withOptions:NSLiteralSearch)
irb(main):014:0> pdf.pageCount
=> 18
irb(main):014:0>

puts (PDFDocument.new.methods(true, true) - Object.new.methods(true, true)).sort

PDFDocumentPrintJobTitle
allowsCopying
allowsPrinting
annotationSubclassForClass
beginFindString:withOptions:
beginFindStrings:withOptions:
cancelFindString
cleanupAfterPrintOperation
cleanupFind
commonInit
coreFindString
coreFindStrings
createInfoDictionary
createPageArray
dataDetector
dataDetectorQueue
dataProvider
dataRepresentation
dataRepresentationWithOptions
delegate
didMatchString
documentAttributes
documentRef
documentURL
enqueueDataDetectionForPage:forPDFView:
exchangePageAtIndex:withPageAtIndex:
findOnPage
findString:fromSelection:withOptions:
findString:withOptions:
findStrings:withinSelection:withOptions:
formData
freePDFData
getNearestOutline:forDestination:
getPrintOperationForPrintInfo:autoRotate:
hasMarkupAnnotations
hasOpenPopupAnnotations
hasText
hasTextAnnotations
indexForPage
indexOfLastPageRemoved
initWithData
initWithPDFDocumentRef
initWithURL
insertPage:atIndex:
isEncrypted
isFinding
isLocked
majorVersion
minorVersion
normalizeFindOptions
originalPageCount
outlineItemForSelection
outlineRoot
pageAtIndex
pageClass
pageCount
pageForOriginalIndex
pageFromPageDictionary
pageSubrange
permissionsStatus
quickString
removePageAtIndex
scheduledFindOnPage
selectionForEntireDocument
selectionFromPage:atCharacterIndex:toPage:atCharacterIndex:
selectionFromPage:atPoint:toPage:atPoint:
setAutoRotate:forPrintOperation:
setDelegate
setDocumentAttributes
setDocumentRef
setOutlineRoot
setPageSubrange
setPrintScalingMode:forPrintOperation:
setUseCorePDF
string
unlockWithPassword
useCorePDF
writeToConsumer:withOptions:
writeToFile
writeToFile:withOptions:
writeToURL
writeToURL:withOptions:
=> nil


Thursday, May 20, 2010

OMG, why are there so many Strings in ObjectSpace?!?

hash = {}
ObjectSpace.each_object.collect{|t| t.class}.uniq.each{|cla| hash[cla]
= ObjectSpace.each_object(cla).to_a.length}
hash

{Tiger=>1, Gem::SourceIndex=>1, Gem::Version=>601, String=>57656,
RubyToken::TkNL=>1, Gem::Dependency=>206, Proc=>127, NoMemoryError=>1,
UnboundMethod=>1, IRB::WorkSpace=>1, Rational=>10, Mutex=>1,
Thread=>1, IO=>5, Object=>64965, Binding=>3, Array=>3761, Float=>18,
OptionParser::Switch::NoArgument=>2,
IRB::Notifier::CompositeNotifier=>1, Range=>51, Bignum=>2, fatal=>1,
OptionParser::OptionMap=>2, Gem::CommandManager=>1, IRB::Locale=>1,
RubyLex::TerminateLineInput=>1, Date::Infinity=>2,
Gem::Requirement=>554, SystemStackError=>1, Module=>495, Hash=>130,
YAML::Syck::Resolver=>2, ThreadGroup=>1, Gem::Specification=>173,
IRB::SLex=>1, Gem::GemPathSearcher=>1, File=>2, Class=>438,
IRB::Notifier::LeveledNotifier=>4, RubyToken::TkLPAREN=>1,
OptionParser::List=>1, OptionParser::CompletingHash=>1,
RubyToken::TkRBRACE=>1, Enumerable::Enumerator=>10, Method=>1,
IRB::ReadlineInputMethod=>1, IRB::StdioOutputMethod=>2, RubyLex=>1,
IRB::SLex::Node=>78, Gem::ConfigFile=>1, MatchData=>4,
IRB::Context=>1, Regexp=>353, IRB::Notifier::NoMsgNotifier=>1,
IRB::Irb=>1, Gem::Version::Part=>481, Time=>176}

And if I do:

ObjectSpace.each_object(String).each{|str| hash[str.object_id] = str}

I find that most of these strings appear to be paths to ruby files. I
am curious if everyone has a similarly large set of string objects in
their ObjectSpace, or is this a result of my personalized setup?


Saturday, May 15, 2010

Test Blogo

This was a test.


Saturday, March 28, 2009

Variables are created and set to nil as soon as they are mentioned

Tim:~> irb
>> local_variables
=> ["_"]
>> if false
>> some_variable = :yahoo
>> end
=> nil
>> some_variable
=> nil
>> local_variables
=> ["_", "some_variable"]

Isn't that interesting? When I define a variable within an if statement that will never be entered (and thus the variable will never be assigned to :yahoo), it is listed as a local variable and set to nil.


Saturday, March 21, 2009

Ruby Variables

  • $global variables are available from anywhere in the program--no matter the object or method, $global will be available.
  • $local variables are only available with the limited context in which they are defined--within a method or block, or if defined outside of a method or block, within whatever self is (a class or module or main).
  • @instance variables are available anywhere within a specific instance of an object.
  • @@class variables are common to all instances of a class. They can be used to count the instance of a class, as shown in the figure above.


Thursday, March 19, 2009

RSpec!

Dr. Laszik is a Hungarian Nephrologist at UCSF. He is an interesting guy, because in contrast to 90% of the pathologists in our department, his office is pristine. Most other pathologist have piles of flats with slides nearly tipping over stacked on shelves next to an endless row of books. They have articles lying on top of texts which they are in the middle of reading--still reading for as long as I have been in the residency program. Coffee makers. Strange toys from Japan. Pictures of their last 6 vacations. But Dr. Laszik is a different clean-fur creature. He is the epitome of organized. When you are working on complicated issues, with various components all at the same time, it really helps to have mastered the art of organization. When I use RSpec while programming, I feel like the programming version of Dr. Laszik. Test are written, followed by code to pass the test. All tests are repeated with each iteration. The reports are in beautiful HTML format. Projects move forward in an organized step by step manor without having to ponder long stretches of code when something goes wrong. "I enjoy being organized."


Saturday, March 14, 2009

Untitled

In my online RUBY class, I missed one of the quiz questions from lesson one! The difficulty came from an apparently inconsistent behavior of the modulus operator (%).

Note the weird behavior demonstrated above.

Here is my explanation. The behavior is actually weird, but can be explained--if you know that ruby always keeps the sign of the divisor (the second value) and understand what modulus is asking for. Modulus returns the remainder after summing successive units until no more can be included without going higher than the goal.

-5 % 3

will therefore give a + (non-negative) result. The value of the result is calculated as follows:
1 unit of -3 is higher than the goal of -5
2 units of -3 (=-6) is not higher than the goal. The remainder, the difference between -6 and -5, is 1.
The result is 1 (sign matches the second number).
Its doubtful anyone uses % with numbers of different signs anyway.

Summary

  • If the numbers differ in their signs, you overshoot the goal and find the difference.
  • The sign of the result always matches the sign of the divisor.


Tuesday, March 10, 2009

The path to happiness...

I suppose programming prodigies begin thinking in kindergarten about automation. When learning how to write letters they must think "the letter 'o' should really be its own class, and then making the letters p, g, b, and q inherit from o, since they are, in essence variations of the o-theme." But the rest of us went through leaning the letters one letter at a time. Without thinking about automation, or packaging actions in reusable forms. The Chinese and Japanese certainly understood modular writing. In the figure above is a set of Kanji related to rain--cloud, snow, frost, fog, hail etc. all inheriting from the symbol for rain. This type of thinking in reusable chunks of information is probably essential to human happiness. The wonderful thing about recognizing a reusable ideas, is that it takes much of the effort out of their application. So in celebration of the encapsulated, reusable concept and its gift of carefree automation (=happiness?), I thought I would show how to add scripts to ruby so that those ideas will always be available for use. I use the RUBYLIB ENV variable as follows.

1. open the /Users/yourname/.profile and add:
export RUBYLIB="/path_to_your/folder"

this is a UNIX file that allows you to set up the starting environment for not only UNIX but other programs, like ruby, which run inside UNIX. That line will add your folder path to the $: variable in ruby (which holds all the paths used for searching for modules).

2. in irb
require "your_file"
=>true

your file is now loaded

3. use the code in the file
Thing.aI(Thing)

my file defines a class, Thing, that can tell you about objects sent in as parameters. The method aI stands for 'all Information', which gives information on ancestors, methods, constants etc. It is the equivalent of pythons dir(), which I mentioned in a previous blog.

Tim:~/Documents/Scripts_Ruby/usable> irb
>> require "Thing"
=> true
>> Thing.aI(Thing)
___Class_ANCESTORS___
Class
Module
Object
Kernel
___Class_CONSTANTS___
___Class_METHODS___
c
m
anc
sM
aI
___Class_SINGLETON_METHODS___
anc
c
yaml_tag_subclasses?
aI
sM
m


Sunday, March 8, 2009

Thing--a classes functionality reporter in ruby

Alan came over today to talk nerdworldese with me today. The topics of conversation included protein phylogeny algorithms, Python, and using Eclipse for CSV repository synchronization. One thing he showed me in Python that caught my interest was the dir() method/function (whatever Pythoners call their methods), which lets you inspect an the functionality of a module. I hadn't thought of needing that before, probably because ruby has the uber helpful object.methods method to get a list of all applicable methods. But when I saw that you could inspect modules I have to admit I was jealous. Surprisingly, no one has written equivalent functionality into ruby yet. Whelp, I set out make up for lost time. The above shows the code for Thing class, which reports on many of the internals of an object (example: Thing.meth(Array.new)). It is capable of introspection--reporting on the Thing class itself. I also found that one can type help 'Hash' from within irb to access the documentation. I am embarrassed that I didn't realize that way earlier. It is obviously nice not to have to flip to another terminal window just to use ri to look at the documentation.
Tim


Saturday, March 7, 2009

Okay, okay, I'll blog to resurrect the economy.


In August of last year, I wrote a blog, which many of my fans (see comments 1-3 of my first blog) are aware, was identified by several economics pundits as the trigger for massive financial collapse, not only in America, but throughout the world. The figure above shows one of my favorite companies, Apple, whose stock began declining shortly after my first (and only blog) from a peak of $180 to its current value of around $80/share. The housing market has dropped even more precipitously. After much consideration, I am certain that it was the pessimistic tone of the first blog--which, at the time seemed quite prescient to me--that it was unlikely I would remember the URL and return to blog ever again. I regret that statement, and the unfortunate effect that it had on all of us on this planet. As no others were involved in the unravelling of our entire economic system, and I am solely to blame, I would like to apologize, from the bottom of my heart, to every man, woman, and child who has been harmed directly or indirectly by the paucity of my blogs. I did not intend to destroy the economy, but I did, there is no mistake. And I do take responsibility. I am therefore announcing today, via blog, that I will be returning to blogging and will additionally be twittering, mostly in English, but occasionally in Japanese (www.twitter.com/timothyrand), in order to return financial stability to the World.
Yours truly,
Timothy A. Rand MD/PhD


Sunday, August 12, 2007

tap, tap, tap, this is a test...check...check


Hi. Every time I try to blog the world comes to a near end, I don't get back to it for a number of months, forget the URL, forget the password and realize that I have a blog page with one lonely entry floating in a cyber-ocean out there somewhere. Here goes another raft with another lonely entry. But Alexis has some interest in blogging so hopefully I can convince her to use this site (before I forget where it is), and then I can just ask her every few months when I want to litter the ocean.