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.

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

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.

awesome_print

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

aws-sdk

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

brakeman

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

bugsnag

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

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.

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.

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.

devise

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

devise-i18n

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

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.

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.

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.

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.

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).

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.

js-routes

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

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.

materialize-rails

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

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.

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.

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.

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.

oj

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

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.

paperclip

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

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.

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

ribbonit

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

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.

sidekiq

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

sidekiq-cron

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

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.

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.

stamp

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

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.

validates_timeliness

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

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.

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.

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!

    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

    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}"