tag:pedroassuncao.com,2013:/posts Ramblings Of a Madman 2018-12-11T00:40:58Z Pedro Assunção tag:pedroassuncao.com,2013:Post/1352270 2018-12-11T00:40:58Z 2018-12-11T00:40:58Z UE4 Tutorial 9 - PowerCables - Part 1

In this tutorial we lay all the ground work that will allow connecting power cables to the generators and energy containers. The end goal being to be able to provide power from source to consumers via electrical wiring as well.]]>
Pedro Assunção
tag:pedroassuncao.com,2013:Post/1347264 2018-11-25T19:08:38Z 2018-11-25T19:08:38Z UE4 Tutorial 8 - Quadcopter - part 3

In this tutorial we finish our quadcopter, including the yaw capability, going through the several flight modes possible with this approach (free style, stabilization with momentum, and full stabilization). Subscribe if you like it, and feel free to leave any comments or suggestions in the comments section.]]>
Pedro Assunção
tag:pedroassuncao.com,2013:Post/1345592 2018-11-19T22:48:27Z 2018-11-19T22:48:28Z UE4 Tutorial 8 - Quadcopter pitch and roll - part 2 ]]> Pedro Assunção tag:pedroassuncao.com,2013:Post/1345184 2018-11-19T00:05:27Z 2018-11-19T00:05:28Z UE4 Tutorial 8 - Quadcopter with altitude stabilization - Part 1 ]]> Pedro Assunção tag:pedroassuncao.com,2013:Post/1325073 2018-09-24T13:01:55Z 2018-09-24T13:01:55Z Tutorial 5 - Solar Panel - Part 1 ]]> Pedro Assunção tag:pedroassuncao.com,2013:Post/1202996 2017-11-03T12:01:10Z 2017-11-17T15:19:26Z Mysql access denied for user root

Clean installation of mysql-server on Ubuntu (also happened to me on Debian), i can't connect with root and no password (even though on installation i set a blank password). This is not MariaDB, it's the proper 5.7 version installed via package repository after using the Mysql APT tool to set it up.

Here's the shit i had to do to make this work:

sudo emacs /lib/systemd/system/mysql.service

In this file, add --skip-grant-tables to the Exec command. After that run:

sudo systemctl daemon-reload
sudo service mysql restart

Now login into Mysql:

mysql -uroot

And run these commands to reset the root user's credentials:

use mysql;
update user set authentication_string=PASSWORD("") where User='root';
update user set plugin="mysql_native_password" where User='root';
flush privileges;
quit;

Now, just revert what you did to the startup script, don't forget to run systemctl reload and restart the service and logging in with root should work. 

I curse you, Oracle.

]]>
Pedro Assunção
tag:pedroassuncao.com,2013:Post/1202811 2017-11-02T22:30:43Z 2017-11-17T15:19:13Z Commonly used (and abused) Ruby Gems

Following up on my last post about Ruby gems, here's a list of some of my typical choices for various tasks in the Ruby and Ruby on Rails world:

active_model_serializers

Makes it real easy to define exactly how to serialize models in an API
@RubyGems

annotate

Annotates Rails/ActiveRecord Models, routes, fixtures, and others based on the database schema. Very cool to know exactly which fields are present in your models, without having to look it up in the schema.rb file.
@RubyGems

awesome_print

Great Ruby dubugging companion: pretty print Ruby objects to visualize their structure. Supports custom object formatting via plugins.
@RubyGems

aws-sdk

The Amazon Web Services SDK allows you use those services with ease. Especially great as a backend for paperclip attachments.
@RubyGems

brakeman

Brakeman detects security vulnerabilities in Ruby on Rails applications via static analysis. Just install and run it at your RoR root folder.
@RubyGems

bugsnag

A Ruby notifier for bugsnag.com. It allows you to receive debug emails when stuff is broken in production. Priceless.
@RubyGems

cancancan

Simple authorization solution for Rails. All permissions are stored in a single location. Allows you to define who has access to what in your RoR in a very simple way.
@RubyGems

chosen-rails

Chosen is a javascript library of select box enhancer for jQuery and Protoype. This gem integrates Chosen with Rails asset pipeline for easy of use.
@RubyGems

ckeditor_rails

This gem provides CKEditor driver for your Rails 3 application. CKEditor is the the fastest and easiest way to integrate a rich text editor into your application.
@RubyGems

devise

Flexible authentication solution for Rails with Warden. Extremely modular way of authenticating users in your app.
@RubyGems

devise-i18n

Everyone knows devise, but not everyone knows there is a gem with translations (i18n) for most languages. 
@RubyGems

factory_girl

factory_girl provides a framework and DSL for defining and using factories - less error-prone, more explicit, and all-around easier to work with than fixtures. Basically allows you to create model instances for your tests in a very easy manner.
@RubyGems

factory_girl_rails

factory_girl_rails provides integration between factory_girl and rails 3 or newer (currently just automatic factory definition loading). The simplest way to start using factory_girl in a RoR app.
@RubyGems

figaro

Simple, Heroku-friendly Rails app configuration using ENV and a single YAML file. Another way to manage env variables in a cross environment way would be rbenv-vars. But figaro also works really well.
@RubyGems

foreman

Process manager for applications with multiple components. Just create a Procfile with the processes you wish to start and fire foreman. It will dump the logs in different colors per process to make it easier to read.
@RubyGems

httparty

Makes http fun! Also, makes consuming restful web services dead easy. Allows you to make a REST call to wherever and get the results properly parsed into a Ruby hash, independently of the response format (XML, JSON, etc).
@RubyGems

i18n-js

It's a small library to provide the Rails I18n translations on the Javascript. No more interpolation from slim, haml, or erb for translations. Just use plain javascript.
@RubyGems

js-routes

Generates javascript file that defines all Rails named routes as javascript helpers. Same as above but for rails routes instead of localizations.
@RubyGems

leaflet-rails

This gem provides the leaflet.js map display library for your Rails 4/5 application. Leaflet is an awesome javascript abstraction to handle a map on a webpage, agnostic to the map provider itself. You can use OpenstreetMaps, Mapbox, Bing and other map tile providers.
@RubyGems

materialize-rails

Materialize (http://materializecss.com) set up for the Rails 4+ asset pipeline. Beautiful Material Design by Google at your fingertips.
@RubyGems

mina

Do you know Capistrano? Meet Mina, a blazing fast application deployment tool. It opens only one ssh connection for all commands, so it's a gazillion times faster than good old cap.
@RubyGems

nested_form_fields

Rails gem for dynamically adding and removing nested has_many association fields in a form. Uses jQuery and supports multiple nesting levels.
@RubyGems

newrelic_rpm

New Relic is a performance management system, developed by New Relic, Inc (http://www.newrelic.com). New Relic provides you with deep information about the performance of your web application as it runs in production. They have a free tier so you can keep an eye in your web app in terms of performance without any cost.
@RubyGems

nokogiri

Nokogiri (鋸) is an HTML, XML, SAX, and Reader parser. Among Nokogiri's many features is the ability to search documents via XPath or CSS3 selectors. If you need to do any XML manipulation, or HTML scraping, this is your go to tool.
@RubyGems

oj

The fastest JSON parser and object serializer. Just drop it into any Rails application and get the instance performance increase in JSON handling.
@RubyGems

opencage-geocoder

Need to do some geocoding or reverse geocoding? Opencage has a free tier. This gem gives you the client to interact with their services.
@RubyGems

paperclip

Everyone knows the most common and easy upload management for ActiveRecord. Need an attachment on your models? Done.
@RubyGems

ransack

Ransack is the successor to the MetaSearch gem. It improves and expands upon MetaSearch's functionality, but does not have a 100%-compatible API. It basically helps you build search forms for models in an easy way.
@RubyGems

react_on_rails

With webpacker you can already get React integration, but React on Rails can give you additional features, like:
  1. Server rendering, often for SEO optimization.
  2. Easy passing of props directly from your Rails view to your React components rather than having your Rails view load and then make a separate request to your API.
  3. Redux and React-Router integration
  4. Localization support
  5. Rspec test helpers to ensure your Webpack bundles are ready for tests
@RubyGems

ribbonit

Display an elegant Github like ribbon to your Rails application showing environment informations (Rails environment, Ruby version, Rails version, ...). For example:
@RubyGems

rspec-html-matchers

Nokogiri based 'have_tag' and 'with_tag' matchers for rspec 3. Does not depend on assert_select matcher, provides useful error messages. Makes it a breeze to test for presence of certain tags in an HTML response body.
@RubyGems

sidekiq

One of the simplest, most efficient background processing tools for Ruby.
@RubyGems

sidekiq-cron

Enables you to setup sidekiq background jobs to be run at a specified time (using CRON notation).
@RubyGems

slim

Slim is a template language whose goal is reduce the syntax to the essential parts without becoming cryptic. Do you hate ERB's spaghetti syntax? So do I. Slim is a more Ruby'esc template system, based on indentation.
@RubyGems

spreadsheet

The Spreadsheet Library is designed to read and write Spreadsheet Documents. As of version 0.6.0, only Microsoft Excel compatible spreadsheets are supported. Spreadsheet is a combination/complete rewrite of the Spreadsheet::Excel Library by Daniel J. Berger and the ParseExcel Library by Hannes Wyss. Spreadsheet can read, write and modify Spreadsheet Documents.
@RubyGems

stamp

Oldie but goldie, Stamp formats dates and times based on human-friendly examples, not arcane strftime directives.
@RubyGems

thinreports

Need to do some reporting and don't want the hassle of handling XML to pass to Jasper Reports? Try ThinReports, an open source report generation tool for Ruby.
@RubyGems

validates_timeliness

Adds validation methods to ActiveModel for validating dates and times. Works with multiple ORMS.
@RubyGems

will_paginate

will_paginate provides a simple API for performing paginated queries with Active Record, DataMapper and Sequel, and includes helpers for rendering pagination links in Rails, Sinatra and Merb web apps.
@RubyGems

dropzonejs-rails

Adds Dropzone, a great JS File upload by Matias Meno, to the Rails Asset pipeline. DropzoneJS is an open source library that provides drag’n’drop file uploads with image previews. It’s lightweight, doesn’t depend on any other library (like jQuery) and is highly customizable.
@RubyGems
]]>
Pedro Assunção
tag:pedroassuncao.com,2013:Post/1176863 2017-07-25T11:25:45Z 2017-07-25T11:32:12Z Choosing a Ruby gem
Instead of writing yet another list of gems you should be using, i'll try to explain how i choose a gem for a particular task or function. This is by no means a complete checklist, it's just my typical way of going about things.

Rubygems

If you're a Ruby developer you are probably familiar with the website rubygems.org. It's "the" repository for all information about Ruby gems.

Things i find important when looking for a gem:

Number of total downloads

Though it will not tell you whether a gem is any good, it does tell you whether a lot of people looked at it as a good candidate for the job you need done. It's also an indicator for the community you can expect around this gem (helps when looking for tutorials, documentation, and general help).

Release date of the last versions

This will show you how frequently is the gem updated, which is useful to know how fast are fixes and new features introduced.

Sometimes it can happen that a really good gem hasn't had a release in a while. For example a couple of weeks ago i was looking for a gem that wrapped the Marvel Comics API. If you look for gems for that you find that most are really old. Doesn't mean they don't work properly, it just means that the API hasn't changed since and they are still relevant. When that's the case, i usually go for the one that was released last, just because the author had the gift of hindsight over the other ones and might have done a better, more polished job at it. Not always true, but... :)

Dependencies and License

To a lesser degree, i also take a look at these.

The less dependencies a gem has the lighter your code will be. Again, not always true, but it's a good rule of thumb. Also pay attention if the license is compatible with your own project.

    If a particular gem feels like a good candidate, I then visit its...

    ...Github/Repository/Website

    There, i usually check for a couple of things:

    Documentation

    This is how you learn how to use the gem, so it helps if the docs are really good (and maintained!).

    If it's an opensource project (which most gems are), then i also look for:

    Last commit date

    A clear indicator of the health of the gem. Also, take into consideration what i wrote earlier about gems that don't update often: it might be because they just don't need to.

    Number of contributors, commenters, discussions

    They show how active the community is around this gem. If big, it helps later when trying to find information how to do things if you get stuck, for example.

    Number of open issues (and resolved)

    If you take a glance at the last issues, when they were created, when they were replied to or resolved, this will also give you a good idea of how active the developers are, and how fast can you expect a response if you report something.

    Code

    Looking at the source code, though not as important as the rest, can also provide some insight to how performant, optimized the gem is at the job it does. It might also help you figure out if will be easy to monkey patch something to fit your needs later. And who knows, you mighty also learn something new from it :)

    Conclusion

    Though not (by any means) a complete guide for choosing a gem, this might be a good starting point. Also, some of these "metrics" might apply for choosing other software and code libraries.

    Like most things in life, your mileage may vary.

    Happy coding!

    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/1136812 2017-03-08T09:27:35Z 2017-11-17T15:19:59Z Java in Firefox after v52.0 (Checkpoint VPN)

    Firefox has changed a few things in its plugin infrastructure and that means Java will no longer work properly after version 52.0 (especially if you are using Checkpoint VPN to access work).

    Fortunately one can always install older versions, present here:

    https://ftp.mozilla.org/pub/firefox/releases

    Also, be sure to disable automatic updates in the settings to prevent the browser from updating itself (default).


    Bonus step (if you are on the mac configuring Checkpoint):

    The newest OSX has a safety feature called SIP (System Integration Protection) that will prevent the checkpoint from installing the required files in the system. To work around this, you need to disable it temporarily:

    • Boot into recovery mode (restart and press Command + R on hearing the beep)
    • Open the terminal and type:
    • csrutil disable
    • Reboot
    • Access the vpn and the snx_extender installation step will work.
    • Go back into recovery and enable SIP again:
    • csrutil enable

    Happy VPN'ing

    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/998927 2016-02-22T15:34:18Z 2017-11-17T15:20:13Z OCR using the open Google Cloud Vision API Just create a new api key in the developer console, replace it in the code below and it should work. Then you can call "whatever_you_call_the_file.rb /Downloads/some_image_with_text.jpg" and google will OCR-it and the script will print out the recognized text.
    require "base64"
    require 'net/http'
    require 'json'
    
    # Base 64 the input image
    b64_data = Base64.encode64(File.open(ARGV[0], "rb").read)
    
    # Stuff we need
    api_key = "<YOUR_GOOGLE_API_KEY>"
    content_type = "Content-Type: application/json"
    url = "https://vision.googleapis.com/v1/images:annotate?key=#{api_key}"
    data = {
      "requests": [
        {
          "image": {
            "content": b64_data
          },
          "features": [
            {
              "type": "TEXT_DETECTION",
              "maxResults": 1
            }
          ]
        }
      ]
    }.to_json
    
    # Make the request
    url = URI(url)
    req = Net::HTTP::Post.new(url, initheader = {'Content-Type' =>'application/json'})
    req.body = data
    res = Net::HTTP.new(url.host, url.port)
    res.use_ssl = true
    
    # res.set_debug_output $stderr
    
    detected_text = ""
    res.start do |http| 
      puts "Querying Google for image: #{ARGV[0]}"
      resp = http.request(req)
      # puts resp
      json = JSON.parse(resp.body)
      # puts json
      if json && json["responses"] && json["responses"][0]["textAnnotations"] && json["responses"][0]["textAnnotations"][0]["description"]
        detected_text = json["responses"][0]["textAnnotations"][0]["description"]
      end
    end
    
    puts "Google says the image is: #{detected_text}"
    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/973146 2016-01-18T09:16:55Z 2018-09-15T18:27:59Z Lock and unlock Ubuntu using your iPhone
    If, like me, you suffer from lazius extremis (lazy bastard, for the layman), you probably hate having to lock your computer when you leave and entering a password when you come back.

    Fear not, young padawan, UDEV and xdotool to the rescue!

    Here's how it works: UDEV (a linux mechanism that detects device events (including USB)) can be configured with rules that fire whenever something changes (i.e. a device is connected or disconnect from the system). When that happens, you want to run a script to lock or unlock your system, based on the type of rule that was fired. So, let's get started:

    1. Create the UDEV rules:
    1.1. Create a new file at /etc/udev/rules.d/100-lock-unlock-with-iphone.rules, with the following contents:

    SUBSYSTEM=="usb", ENV{PRODUCT}=="2bc/12c8/520", ENV{DEVTYPE}=="usb_device", ACTION=="add",    RUN+="/home/youruser/bin/unlock"
    SUBSYSTEM=="usb", ENV{PRODUCT}=="2bc/12c8/520", ENV{DEVTYPE}=="usb_device", ACTION=="remove", RUN+="/home/youruser/bin/lock"

    1.2. In those lines, replace 2bc/12c8/520 with your device product id, which you can find running the following command in the terminal:

    udevadm monitor --environment -u | grep PRODUCT

    1.3. Disconnect or connect your iphone and you should see something like this:

    PRODUCT=2bc/12c8/520

    1.4. That's the value you put in the rules.
    1.5. Replace youruser with your own user name, by the way.

    2. Which leaves us with the /home/youruser/bin/lock and unlock scripts to create. Here is the lock script:

    #!/bin/bash
    export XAUTHORITY=/home/youruser/.Xauthority
    export DBUS_SESSION_BUS_ADDRESS=`ps -u youruser e | grep -Eo 'dbus-daemon.*address=unix:abstract=/tmp/dbus-[A-Za-z0-9]{10}' | tail -c35`
    log=/home/youruser/lock-unlock.log
    echo `date` "-" `whoami` "- Locking system..." >> $log
    su youruser -c "DISPLAY=:0 gnome-screensaver-command -a"
    echo `date` "-" `whoami` "- System locked!" >> $log

    2.1. Again, replace youruser with your own.
    2.2. You might be wondering what those lines about DBUS and the X server are all about. The reason for those is that UDEV runs stuff as root. And we want to lock and unlock the screen as our own user. Those lines make sure of that.
    2.3. For the unlock script we need to install a tool called xdotool. It's basically an automation command that allows you to make the computer type stuff and control the mouse automatically. The reason to use this is because there is no way in hell you can unlock a locked screensaver (believe me, i've tried). This tool simulates user input (moves the mouse a little bit and the enters your password and presses enter). I know it's not the most secure thing in the world but it's the only way i could make it work. Install it with:

    sudo apt-get install xdotool

    2.4. Here's the unlock script:

    #!/bin/bash
     export XAUTHORITY=/home/youruser/.Xauthority
     export DBUS_SESSION_BUS_ADDRESS=`ps -u youruser e | grep -Eo 'dbus-daemon.*address=unix:abstract=/tmp/dbus-[A-Za-z0-9]{10}' | tail -c35`
     log=/home/youruser/lock-unlock.log
     echo `date` "-" `whoami` "- Unlocking system..." >> $log
     export DISPLAY=:0
     xdotool mousemove 0 0 && xdotool type yourpassword && xdotool key Return
     echo `date` "-" `whoami` "- System unlocked!" >> $log

    2.5. Replace youruser with your own user and yourpassword with your user password.

    3. Reload the UDEV rules with:

    sudo udevadm control --reload-rules

    4. And now when you disconnect your phone from the computer, it should lock it. When you plug it back in it should unlock.

    5. Happy hacking!
    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/921201 2015-10-23T15:18:04Z 2017-11-17T15:20:57Z Helium - A floating window for your media [OSX]

    My new favorite application for OSX is called Helium

    It's basically something that allows you to keep an always-on-top window with whatever video (youtube, local, etc.) you want to have playing while you do other things. 

    Pretty awesome!

    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/897815 2015-08-26T10:13:15Z 2017-11-17T15:21:08Z OSX - Command line battery cycles information

    Here's how to get the number of battery charging cycles on your laptop on OSX:

        ioreg -l | grep LegacyBatteryInfo | cut -d '{' -f 2 | tr -d \} | tr ',' '=' | awk -F'=' '{print $12}'

    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/896205 2015-08-21T10:24:49Z 2017-11-17T15:21:20Z Hammerspoon - OSX automation in Lua for the win

    For those who don't know, Hammerspoon is a fantastic automation tool for OS X.  It's basically a bridge between the operating system and the Lua scripting language. With its set of extensions (which you can write your own, by the way) you can automate pretty much anything.

    You can write Lua code that interacts with OS X APIs for applications, windows, mouse pointers, filesystem objects, audio devices, batteries, screens, low-level keyboard/mouse events, clipboards, location services, wifi, and more.

    Here's the current script i'm using on my development laptop. It currently does the following:

    • Auto reloads whenever i change the configuration script;
    • Sets up a menu bar button so i can control whether my laptop goes to sleep or is continuously awake. If you know the app Caffeine, you know what i'm saying;
    • Monitors my Wifi connection and warns me when i lose connection or connect to a different SSID;
    • Monitors my battery and warns me when i get to 10 and 5%.
    • Work in progress: Monitor google.com and bing.com from times to times to check if i have Internet connection.

    The great thing about it is its simplicity. Even if you don't know Lua, you'll find it very easy to write simple watchers and callbacks.

    Give it a try! :)

    init.lua

    -------------------------------------------------------------------------------------
    -- Auto Reloading when config changes
    -------------------------------------------------------------------------------------
    function reload_config(files)
      -- Kill bat watcher
      if batWatcher then
        batWatcher:stop()
      end
      -- Kill wifi watcher
      if wifiWatcher then
        wifiWatcher:stop()
      end
      -- Kill caffeine
      if caffeine then
        caffeine:delete()
      end
      -- Reload config
      hs.reload()
    end
    hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reload_config):start()
    hs.alert.show("Config reloaded")
    
    -------------------------------------------------------------------------------------
    -- Keep display on or allow going to sleep
    -------------------------------------------------------------------------------------
    local caffeine = hs.menubar.new()
    function setCaffeineDisplay(state)
        if state then
            caffeine:setTitle("AWAKE")
        else
            caffeine:setTitle("SLEEPY")
        end
    end
    function caffeineClicked()
        setCaffeineDisplay(hs.caffeinate.toggle("displayIdle"))
    end
    if caffeine then
        caffeine:setClickCallback(caffeineClicked)
        setCaffeineDisplay(hs.caffeinate.get("displayIdle"))
    end
    
    -------------------------------------------------------------------------------------
    -- Network connection and disconnection
    -------------------------------------------------------------------------------------
    local wifiWatcher = nil
    function ssidChangedCallback()
        newSSID = hs.wifi.currentNetwork()
        if newSSID then
          hs.alert.show("Network connected: " .. newSSID)
        else
          hs.alert.show("Network lost :(")
        end
    end
    wifiWatcher = hs.wifi.watcher.new(ssidChangedCallback)
    wifiWatcher:start()
    
    -------------------------------------------------------------------------------------
    -- Battery Low warnings
    -------------------------------------------------------------------------------------
    local batWatcher = nil
    local lastBatVal = hs.battery.percentage()
    function batPercentageChangedCallback()
      currentPercent = hs.battery.percentage()
      if currentPercent == 10 and lastBatVal > 10 then
        hs.alert.show("Getting low on juice...")
      end
      if currentPercent == 5 and lastBatVal > 5 then
        hs.alert.show("Captain, she can't take any more!")
      end
      lastBatVal = currentPercent
    end
    batWatcher = hs.battery.watcher.new(batPercentageChangedCallback)
    batWatcher:start()
    
    --status, data, headers = hs.http.get("http://example.com")
    --hs.alert.show(status)
    --hs.alert.show(data)
    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/879443 2015-07-10T15:53:07Z 2015-07-10T15:54:43Z Making video presentations from photos Untitled

    Here's a little Java application i made to make it easier to create video presentations based on images. It allows you to add pictures and superimpose text on them. The resulting video is H264 encoded (and thus very small).

    Source code is available here.

    A prebuilt (ready to use) version can be found here.



    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/861225 2015-05-26T16:49:44Z 2015-05-26T16:53:03Z Problem starting Sidekiq in development

    If you ever get this error:

    can't link outside actor context

    Followed by something like:

        /Library/Ruby/Gems/2.0.0/gems/celluloid-0.16.0/lib/celluloid.rb:176:in `new_link'
        /Library/Ruby/Gems/2.0.0/gems/sidekiq-3.3.4/lib/sidekiq/launcher.rb:21:in `initialize'
        /Library/Ruby/Gems/2.0.0/gems/sidekiq-3.3.4/lib/sidekiq/cli.rb:81:in `new'
        /Library/Ruby/Gems/2.0.0/gems/sidekiq-3.3.4/lib/sidekiq/cli.rb:81:in `run'
        /Library/Ruby/Gems/2.0.0/gems/sidekiq-3.3.4/bin/sidekiq:8:in `<top (required)>'
        /Library/Ruby/Gems/2.0.0/bin/sidekiq:23:in `load'
        /Library/Ruby/Gems/2.0.0/bin/sidekiq:23:in `<main>'

    It's mostly likely somehow related with either ZenTest or another testing framework. 

    In my case, i was adding the ZenTest gem both in the development and test groups of my Gemfile. Moving it away from the development group solved the problem.

    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/860785 2015-05-25T17:21:19Z 2015-05-25T17:22:22Z Planetary terrain in Unity 3D [video]

    Here's a little something i've been working on in my spare time. Maybe it'll end up as a space game, who knows? :)

    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/814863 2015-02-24T17:56:19Z 2017-11-17T15:21:59Z AES encryption in Ruby and Decryption in Java This one is precious, as it took me a long time to figure out. As a side-note, Java apparently only supports 128bit AES.

    Here's the Ruby code:

    def encrypt(string, pwd)
        salt = OpenSSL::Random.random_bytes(16)

        # prepare cipher for encryption
        e = OpenSSL::Cipher.new('AES-128-CBC')
        e.encrypt

        # next, generate a PKCS5-based string for your key + initialization vector
        key_iv = OpenSSL::PKCS5.pbkdf2_hmac_sha1(pwd, salt, 1024, e.key_len+e.iv_len)
        key = key_iv[0, e.key_len]
        iv  = key_iv[e.key_len, e.iv_len]

        # now set the key and iv for the encrypting cipher
        e.key = key
        e.iv  = iv

        # encrypt the data!
        encrypted = '' << e.update(string) << e.final
        [encrypted, iv, salt].map {|v| ::Base64.strict_encode64(v)}.join("--")   
     end

    And the Java part:

    public static String decrypt(String encrypted, String pwd) throws Exception {

            String[] parts = encrypted.split("--");
            if (parts.length != 3) return null;

            byte[] encryptedData = Base64.decodeBase64(parts[0]);
            byte[] iv = Base64.decodeBase64(parts[1]);
            byte[] salt = Base64.decodeBase64(parts[2]);

            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
            KeySpec spec = new PBEKeySpec(pwd.toCharArray(), salt, 1024, 128);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKey aesKey = new SecretKeySpec(tmp.getEncoded(), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));

            byte[] result = cipher.doFinal(encryptedData);
            return new String(result, "UTF-8");
    }
    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/810704 2015-02-12T13:09:25Z 2015-09-30T05:57:06Z Atlas, the awesome balancing robot...

    ...or "how they are training robots to destroy us soon enough" :)

    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/810061 2015-02-11T11:53:13Z 2015-02-11T11:53:13Z Great solution for a camping light, especially if near the coast

    It's a lamp powered by water and salt, i kid you not :)

    http://www.salt.ph

    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/806310 2015-02-03T12:18:03Z 2015-02-03T12:18:04Z Helicopter pilot goes out of his way to retrieve an RC plane

    Gotta love people using their awesome skills to do some good in the world :)

    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/805806 2015-02-02T12:05:47Z 2015-02-02T12:05:48Z Kill process by fuzzy name Sometimes you want to kill a process but you either don’t know the exact name of the executable file, or you know part of the command arguments. killall is not your friend in those situations. Here’s a quick script to grep on part of a process name or arguments and kill it.


    Full script (put it in a path included folder and change it’s permissions to executable +x):

    #!/bin/bash
    ps aux | grep $1 | grep -v grep | awk '{print $2}' | xargs kill -9
    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/805794 2015-02-02T11:00:57Z 2015-02-02T11:00:57Z $499 electric bike on indiegogo Too bad it’s US made, shipping would be expensive :(

    Still, pretty cool specs:

    - Top speed of 20mph (around 32 km/h)
    - 50 mile range (80 km)
    - Full battery charge in 90 minutes

    https://www.indiegogo.com/projects/storm-electric-bike
    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/805057 2015-01-30T17:50:11Z 2015-01-30T18:00:12Z Another awesome video Take a peak inside the most awesome BASE jumping boogie ever created. The 3rd annual AZ BASE Boogie, hosted by Matt Frohlich of anitgravityBASE and also Apex BASE. Witness a sample of what a huge group of awesome jumpers can get themselves into over a big party weekend in the winter desert. Thanks to Matt and all the local jumpers, all the participants and the guys who contributed footage for this video. Absolute success!!! 

    from Vimeo 
    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/804472 2015-01-29T18:30:45Z 2015-01-29T18:30:45Z Working on a RC transmitter FPV screen mount Gotta love 3D printing :)

    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/804270 2015-01-29T11:28:31Z 2015-01-29T17:59:55Z Another awesome video from Vimeo 
    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/803871 2015-01-28T17:21:35Z 2015-01-28T17:21:36Z New live show from Louis CK

    This guy is my favorite comedian of today.

    If you have $5 to spare, buy his latest live show. If you love dark, often self-deprecating, intelligent humor you will not regret it :)

    https://louisck.net/purchase/live-at-the-comedy-store

    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/803296 2015-01-27T16:22:56Z 2015-01-27T16:22:56Z Web application hacker's toolbox A pretty cool web app that allows you to perform common task related to web development, like URL encode, Base64, MD5, formatting, and a lot more.]]> Pedro Assunção tag:pedroassuncao.com,2013:Post/802877 2015-01-26T18:20:05Z 2015-01-26T18:20:06Z Two awesome sports in one day It’s not every day that you find out about great people in awesome sports.

    First, this guy puts Robin Hood and Legolas to shame with his archery skills. A lot of interesting things about his technique which, once again, comes to show that Hollywood distorts reality like crazy: 
    http://cheezburger.com/68175617/epic-win-video-archer-archery

    Second, there are Long Sword fights. For real. Enough said:
    http://www.nytimes.com/video/sports/100000003040466/inside-the-world-of-longsword-fighting.html
    ]]>
    Pedro Assunção
    tag:pedroassuncao.com,2013:Post/802666 2015-01-26T11:06:11Z 2015-01-26T11:06:12Z Avoiding SSL redirect loop
    If you are configuring an nginx website to use SSL and - by any chance - you need to setup more than one “server” entry (for instance to make www redirect to the plain URL), keep in mind that you need to declare the ssl certificate mumbo-jumbo in both entries, otherwise browsers will enter a redirect loop.

    Something like the following will do:

    server {
            listen 443 ssl;
            server_name www.zenblast.com;

            include zenblast-ssl.conf;

            return 301 $scheme://zenblast.com$request_uri;
    }

    server {
            server_name zenblast.com;
            listen              443 ssl;

            include zenblast-ssl.conf;

            ...
    }

    zenblast-ssl.conf is where we define stuff like ssl_certificate, ssl_certificate_key, ssl on, ssl_ciphers, ssl_prefer_server_ciphers on, and ssl_protocols. Notice that the file is included in both entries.

    Hope this helps save someone 30 minutes of Googling :)
    ]]>
    Pedro Assunção