Pedro Assunção

Count (group by) number of line occurrences in file

Here’s a neat ruby script to group and count the number of occurrences of lines inside a given file.

count.rb

list = IO.readlines(ARGV[0])
h = Hash.new {|hash, key| hash[key] = 0}
list.each {|item| h[item] += 1}
h = h.sort_by { |k,v| v }.reverse
h.each_with_index do |p,i|
  puts "(#{p[1]}) #{p[0]}"
  if ARGV[1] and ARGV[1].to_i <= i + 1
    break
  end
end

Usage is:

ruby count.rb <file> [show_at_most_n]

If you have a file named “faren.txt” comprised of the following lines:

test
test
awesome
dude
dude
dude
faren
meran

Running the script  with:

ruby count.rb faren.txt

Will yield the following result:

(3) dude
(2) test
(1) awesome
(1) faren
(1) meran

In addition, if you pass the “show_at_most_n” parameter (a number), it will only print that number of results. For example 2 will show the following:

(3) dude
(2) test


				

Red Hot Chili Peppers lyrics generator

Here’s a little something i tried yesterday: a ruby script that mixes and matches verbs, nouns, adjectives, and colors to come up with crazy ass lyrics, red hot style. Enjoy :)

$nouns = IO.readlines('names.txt')
$adjectives = IO.readlines('adjectives.txt')
$verbs = IO.readlines('verbs.txt')
$adjectives << ['red','blue','green','white','black','yellow','brown','gray']
$pronouns = IO.readlines('pronouns.txt')
$adverbs = IO.readlines('adverbs.txt')
$prepositions = IO.readlines('prepositions.txt')

def get_rand(collection)
  sleep rand / 10000
  collection[rand * collection.length.to_i - 1]
end

def preposition_phrase
  "#{get_rand($prepositions).strip} the #{get_rand($nouns).strip}"
end

def adjectivated_subject_phrase
  the_part = "the" if rand.to_f > 0.5
  adjective = get_rand($adjectives).strip if rand.to_f > 0.5
  return "#{the_part} #{adjective} #{get_rand($nouns).strip}" if the_part and adjective
  nil
end

def generate_phrase
  as = adjectivated_subject_phrase
  adjectivated_subject_part = as.nil? ? get_rand($pronouns).strip : as
  preposition_part = rand.to_f > 0.5 ? preposition_phrase : ""
  verb_part = get_rand($verbs).strip
  object_part = rand.to_f > 0.25 ? get_rand($nouns).strip : ""
  the_part = (rand.to_f > 0.5 and object_part != "") ? "the" : ""
  adverb_part = rand.to_f > 0.75 ? get_rand($adverbs).strip : ""

  "#{adjectivated_subject_part} #{preposition_part} #{verb_part} #{the_part} #{object_part} #{adverb_part}".squeeze(" ").strip
end

def generate_lyrics
  result = ""
  (1..5).each do
    first_phrase = generate_phrase
    new_phrase = generate_phrase
    while new_phrase[-2, 2] != first_phrase[-2, 2] or new_phrase.split(" ")[-1] == first_phrase.split(" ")[-1] do
      new_phrase = generate_phrase
    end
    result << "#{first_phrase}\r\n#{new_phrase}\r\n\r\n"
  end
  result
end

puts generate_lyrics

Here are the sources: rhcp_lyrics_v2.tar. As a bonus there is a script to see how many attempts are required to reach the phrase “The quick brown fox” :)


HTML WYSIWYG editor with Flickr upload support?

A picture from flickr :)Lately i’ve been tinkering around with the idea of recreating my blog in a more handcrafted way (ruby on rails) as opposed to the current implementation using WordPress. Don’t get me wrong WordPress is awesome. It has many years and millions of websites as a testament of it’s awesomeness behind it. But i guess my hacker’s vein popups up every now and then to whisper the reasons why i should have something custom made :)

The biggest problem with this, is that WP’s interface to create posts is, again, awesome. You can find plugins for pretty much anything, especially to do tasks that are otherwise plain boring, like uploading pictures to your flickr account and instantly have them available in your post for inclusion. I’ve been trying to find something like that for those nice HTML editors out there (like tinyMCE and CKEditor), but so far have had no luck.

Anyone out there knows if something like that exists yet and where can i find it?


Self physiotherapy

This is what my evenings look like now: moving my arm slowly, trying to recover wrist movement. It’s unbelievable what one month of no mobility will do to your tendons and muscles. Hopefully next week I can start proper (professional) physiotherapy and do it faster.


Arm broken equals free time

I have broken an arm. This is the 1st time in my life that I have broken any bones in my body. And it sucks!

But, rather than being all pessimistic about it, I prefer to see the positive side. See, you get a lot of free time to do things that you probably have been postponing for ages. For instance, taking care of your taxes, organizing all the receipts of last year’s expenses, or even turning an old laptop into a hallway digital information system (yes, with one arm). These are the kind of things that I would definitely be dragging on for years before I finally came around to doing them.

Another good side of this situation is the fact that you learn how to be more resourceful because, obviously with only one available arm, trivial everyday tasks become rather challenging. To give you an example I bet that you have never tried to put on socks or open bottles with only one hand. This actually gave me an interesting idea which is to write a couple of posts about easier ways to perform some of these tasks. But that’s something for another occasion.

The same good side about breaking a bone, time, is also in itself really crappy. I cannot wait to go skydiving again so, naturally, I had to ask my doctor whether there was a way I could speed up the healing process. Maybe with some kind of calcium and/or vitamin supplements, I thought, my body would be good to go in a month. Of course the doctor, after laughing in my face, proceeded to explain that there isn’t really anything you can do but wait. The tissue regeneration takes about 3 weeks. Because, when you break a bone, you also do a lot of damage to the surrounding flesh, tendons, and muscles. The bone itself takes about 5 weeks to reach a state of good calcification. Finally, when you get the cast taken off, you have to do a bit of physiotherapy to get back the amplitude of movement on the joint(s) that have been on cast. The bone calcification will continue on for one or 2 months, after which it will be so much stronger that you will never break it in that same place again.

The bottom line is my doctor has now become my newest skydiving instructor: I will only be allowed to go up when he says so :-)


Export Mysql result as CSV

Don’t ask me how the sed magic works, but it does. Taken from here.

Running this:

mysql -u<USER> -p<PASSWORD> <DATABASE> -B -e "select * from videos_video;" | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g'

will produce something like this:

"id","title","url"
"1","video 1","http://youtube(...)"
"2","video 2","http://youtube(...)"
"3","video 3","http://youtube(...)"

Just pipe it to a .csv file and you’re done :)


Nice tweaks for OSX

I think most of them work on both Snow Leopard and Lion. Not sure about previous versions. Just type the ones you want to activate/deactivate on the command line and have fun.

# Enable full keyboard access for all controls (e.g. enable Tab in modal dialogs)
defaults write NSGlobalDomain AppleKeyboardUIMode -int 3

# Enable the 2D Dock
defaults write com.apple.dock no-glass -bool true

# Disable menu bar transparency
defaults write -g AppleEnableMenuBarTransparency -bool false

# Expand save panel by default
defaults write -g NSNavPanelExpandedStateForSaveMode -bool true

# Expand print panel by default
defaults write -g PMPrintingExpandedStateForPrint -bool true

# Disable shadow in screenshots
defaults write com.apple.screencapture disable-shadow -bool true

# Enable highlight hover effect for the grid view of a stack (Dock)
defaults write com.apple.dock mouse-over-hilte-stack -bool true

# Enable spring loading for all Dock items
defaults write enable-spring-load-actions-on-all-items -bool true

# Disable press-and-hold for keys in favor of key repeat
defaults write -g ApplePressAndHoldEnabled -bool false

# Disable auto-correct
defaults write NSGlobalDomain NSAutomaticSpellingCorrectionEnabled -bool false

# Disable window animations
defaults write NSGlobalDomain NSAutomaticWindowAnimationsEnabled -bool false

# Disable disk image verification
defaults write com.apple.frameworks.diskimages skip-verify -bool true
defaults write com.apple.frameworks.diskimages skip-verify-locked -bool true
defaults write com.apple.frameworks.diskimages skip-verify-remote -bool true

# Automatically open a new Finder window when a volume is mounted
defaults write com.apple.frameworks.diskimages auto-open-ro-root -bool true
defaults write com.apple.frameworks.diskimages auto-open-rw-root -bool true

# Avoid creating .DS_Store files on network volumes
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true

# Disable Safari’s thumbnail cache for History and Top Sites
defaults write com.apple.Safari DebugSnapshotsUpdatePolicy -int 2

# Enable Safari’s debug menu
defaults write com.apple.Safari IncludeDebugMenu -bool true

# Remove useless icons from Safari’s bookmarks bar
defaults write com.apple.Safari ProxiesInBookmarksBar "()"

# Disable send and reply animations in Mail.app
defaults write com.apple.Mail DisableReplyAnimations -bool true
defaults write com.apple.Mail DisableSendAnimations -bool true

# Disable Resume system-wide
defaults write NSGlobalDomain NSQuitAlwaysKeepsWindows -bool false

# Enable Dashboard dev mode (allows keeping widgets on the desktop)
defaults write com.apple.dashboard devmode -bool true

# Reset Launchpad
rm ~/Library/Application\ Support/Dock/*.db

# Show the ~/Library folder
chflags nohidden ~/Library

# Disable local Time Machine backups
sudo tmutil disablelocal

# Kill affected applications
for app in Safari Finder Dock Mail; do killall "$app"; done

# Fix for the ancient UTF-8 bug in QuickLook (http://mths.be/bbo)
echo "0x08000100:0" > ~/.CFUserTextEncoding

The original source can be found here.


Browser and visitor statistics

Was just now looking at google analytics for my blog and got some surprises, especially when it comes to the browser people use to access it. Seems that Chrome is leading and Internet Explorer is dead. Long live Internet Explorer :D

Browser usage

Also, very interesting is the fact that i’m Portuguese and Portugal is not on the top visitors’ countries list. Special thanks to my followers in India, you know who you are :)

Language

UPDATE: As requested by a friend of mine, here are some more statistics: Top sources and keywords.

Top sources chart

Top sources list

Top keywords

Peace out ;)


Enable/disable spotlight in OSX

This is just a self reminder on how to disable and enable spotlight in Snow Leopard and Lion. Open a terminal and type:

To enable:

sudo mdutil -a -i on

To disable:

sudo mdutil -a -i off

In system preferences you can control which drives and/or folders are not to be indexed.


Venting, or how humans no longer respect each other

Is it me or people are respecting each other less and less every day? You see it all the time: someone trying to get in line in front of you – at the supermarket, people yelling at their kids in the middle of the street (and the kids yelling back at their parents), you name it. I’m not even trying to take me out of it; how many times have i felt compelled – while driving my car – to accelerate a bit more not to let another driver get into a roundabout in front of me, or something like that? But i digress into specifics. Heck, this post was started because i was trying to sleep and my neighbors’ kids are having a party at midnight on a Wednesday, when people usually work the next day. And even though my Buddhist part tries its best to compensate it’s always hard.

I often wonder what will happen to us, people, if we continue down this path of disrespectfulness towards each other. What kind of future can we expect, when we treat each other with such poor manners? Shouldn’t we think about these things more often and try to improve ourselves?


The knee: it no worky!

A couple of years ago I sustained a knee injury while snowboarding and, although not very dramatic, it did leave kind of a light pain that comes out every now and then, especially when I put a lot of effort in my left leg.

After not giving it much thought for some time I recently discovered that, after putting on a bit of extra weight due to weight lifting every day, my knee started complaining again. So I went to a doctor to get some x-rays done and try to figure out what’s wrong. Today I got the results.

Simple FolkNow, I don’t know if the guys that write the x-ray reports have a ‘cryptic writing’ lecture in college or something like that, but it sure seems so. No simple folk can understand what they write on those things. And I don’t even mean the medical terms. The sheer effort they put into sounding more “professicocky” (a word I promise I didn’t just make up) is astonishing.

Simple folk

They're simple folk, you know, morons.....

Why, oh why, can’t you write for the simple people like me? :)

 


200 skydives and a long way to go

This Saturday – while coming back from the dropzone – i noticed that my last jump of the day had been my 200th. After realizing it, i started thinking about what it means and came to the conclusion that it means nothing. Think about it: that’s only about 3 hours of training (each skydive is around 1 minute), diluted across endless times of waiting to jump. Now, in any other sport, you can easily practice much more frequently and more at a time. And you would still be far, far away from becoming a pro. Hell, even people with 30 hours of skydiving time would not be considered even remotely close to pro in any other sport, since it takes much more than that to master anything.

So, while it does make me feel good to have achieved almost half of one of my current skydiving goals (becoming an instructor) and fully accomplishing another one (have enough jumps to start practicing wingsuit flying) i have to conclude that there is still a loooong way to go to achieve perfection. In the meantime, one tries to have fun walking the path ;)

Blue skies.