Thursday, December 29, 2016

Concept Diagram

A Concept Diagram is a graphic organizer that clarifies central concepts in a reading selection and in relating similar or associated information to this key idea. The steps to build a Concept Diagram:

Convey the central idea.
Offer the overall concept.
Note any key words.
Classify characteristics.
Explore examples and non-examples.
Practice with new examples.
Tie down the definition.

This sequence of steps provides a process for organizing and interpreting the content of a reading selection.

Steps to a Concept Diagram:

  1. Select a reading text for discussion.
  2. Have students identify the overall theme of the document and the major subthemes or concepts that together make up the document.
  3. Ask students to write down all key words in the selection and then group these terms in logical categories.
  4. Encourage students to suggest examples and non-examples of the key terms and concepts identified.
  5. Have the students produce a final, formal definition of key words and concepts by combining the things they learned when categorizing the words and providing examples.

References

1. Reading Educator
2. Lenski, Susan D., Wham, Mary Ann, & Johns, Jerry L. (1999). Reading and learning strategies for middle and high school students. Dubuque, IA: Kendall/Hunt.

RubyPlus Podcast Episode 21


require dlopen rvm ruby rails


/Users/bparanj/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/irb/completion.rb:10:in `require': dlopen(/Users/bparanj/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/x86_64-darwin13/readline.bundle, 9): Library not loaded: /usr/local/opt/readline/lib/libreadline.6.dylib (LoadError)

Use:

group :development, :test do
  gem 'rb-readline'
end

and install the gem. Now the rails console will work.

GraphQL Basics in Rails 5

Checkout the GraphQL Basics in Rails 5 screencast

This screencast covers the basics of GraphQL. Demonstrates a simple hello GraphQL program using graphql gem and exposing a person has many friends nested ActiveRecord relationship as an API using graphql. The Rails engine graphiql-rails is used to play with the backend API.

Tuesday, December 27, 2016

Sunday, December 25, 2016

Orthogonality in Coding

Orthogonality is one of the most important properties that can help make even complex designs compact. In a purely orthogonal design, operations do not have side effects; each action (whether it's an API call, a macro invocation, or a language operation) changes just one thing without affecting others. There is one and only one way to change each property of whatever system you are controlling.
- The Art of UNIX Programming
Orthogonality means that features can be used in any combination, that the combinations all make sense, and that the meaning of a given feature is consistent, regardless of the other features with which it is combined.
- Programming Language Pragmatics
An orthogonal language is one in which you can express a lot by combining a small number of operators in a lot of different ways.
- On Lisp

The Principles of Modular and Maintainable Design by Jens Dietrich

Orthogonality is a concept often used to describe modular and maintainable software. The concept of orthogonality is based on the Greek word orthog┼Źnios, meaning "right-angled." It is often used to express the independence between different dimensions. When an object moves along the x-axis in a three-dimensional space, its y and z coordinates don't change. Change in one dimension does not cause change in another dimension, which means that one dimension cannot cause side-effects for others.

This explains why the concept of orthogonality is often used to describe modular and maintainable software design: thinking about systems as points in a multi-dimensional space (spawned by independent, orthogonal dimensions) helps software developers to ensure that our changes to one aspect of system will not have side-effects for another.

Orthogonality is a powerful concept because it enables us to establish a relatively simple mental model for complex application use cases. In particular, we can focus on one dimension while ignoring other aspects.

Testing is a common scenario where orthogonality is useful. We can test the functionality of log levels using a suitable fixed pair of an appender and a layout. Orthogonality ensures us that there will be no surprises: log levels will work the same way with any given combination of appender and layout. Not only is this convenient (there is less work to do) but it is also necessary, because it would be impossible to test log levels with every known combination of appender and layout. This is especially true given that Log4j, like many software tools and utilities, is designed to be extended by third parties.

Designing and coding for orthogonality

 The key idea is to use abstraction. Each dimension of an orthogonal system addresses one particular aspect of the program. Such a dimension will usually be represented by a class. Each of these classes represent a dimension, while the objects represents the points within the given dimension.

Pending Work: This code here:  Monads in Recurring Payment Handling seriously needs some orthogonal love.

References

 Flattening Arrow Code
 Arrow Anti Pattern
 Java Tip: Orthogonality by example by Jens Dietrich

In Memory Full Text Search in Ruby

My site rubyplus.com uses elasticsearch.  I want something lightweight for development environment. I was looking for something similar to SQLite for full-text search. I wanted this to be:
  1. Fast
  2. In Memory
  3. No Server Process
Main motivation was a replacement for elasticsearch in development and test environments. I wanted it to be:
  • Zero-configuration - No setup or administration needed.
  • Small code footprint.
  • Simple, easy to use API.
  • Well-commented source code with 100% branch test coverage.
  • Self-contained: no external dependencies.
Picky is the simplest in-memory full-text search library for Ruby. I probably need only a subset of the solar features such as:
  • ranked searching -- best results returned first
  • many powerful query types: phrase queries, wildcard queries, proximity queries, range queries and more
  • fielded searching (e.g. title, author, contents)
  • sorting by any field
  • multiple-index searching with merged results
  • allows simultaneous update and searching
  • flexible faceting, highlighting, joins and result grouping
  • fast, memory-efficient and typo-tolerant suggesters
  • pluggable ranking models, including the Vector Space Model and Okapi BM25
  • configurable storage engine (codecs)
Peter Keen has evaluated some of the options available and he says in his blog:

sqlite3 has built-in FTS but I would have to build a bunch of stuff around it.
xapian is a FTS engine but like with sqlite3 I'd have to build stuff.
elasticsearch would work but it's an external process that I'd have to run and it's an awful lot of overhead
Some kind of hosted elasticsearch or solr provider would work, but again lots of overhead and not free and I'm then dependent on their uptime.

Whistlepig is a small text search index. This is written in C. Small as in not very many features and not much code, but the features that are there are perfect for my needs:
  • Full query language
  • In-memory, in-process
  • Arbitrary number of indexes for the same document
Here's a full example of how to index and query a document:

require 'rubygems'
require 'whistlepig'

document = "Hi there"

index = Whistlepig::Index.new "index"
entry = Whstilepig::Entry.new
entry.add_string "body", document

docid = index.add_entry entry

query = Query.new("body", "hi")
result = index.search(query)
assert_equal docid, result[0]


This controller suffers from nested if-else:

http://valve.github.io/blog/2014/02/22/rails-developer-guide-to-full-text-search-with-solr/

Came across lunr.js, a simple javascript library for full-text search in your browser.

Comes with a standalone command-line interface (CLI) client that can be used to administer SQLite databases.
Sources are in the public domain. Use for any purpose.

Saturday, December 24, 2016

Head HTTP Request using Curl to Test Amazon Cloudfront Configuration

You can use Curl with -I switch to test if the Cloudfront configuration is working. You can see that when I hit media subdomain, the first time it misses the Cloudfront, the next request hits the Cloudfront. This means Cloudfront is configured properly.
$ curl -I  https://media.rubyplus.com/graphql.mp4
HTTP/1.1 200 OK
Content-Type: application/octet-stream
Content-Length: 107703153
Connection: keep-alive
Date: Sun, 25 Dec 2016 01:25:07 GMT
Last-Modified: Sat, 24 Dec 2016 22:34:51 GMT
ETag: "55bf4669c44224e46e19531d-2"
Accept-Ranges: bytes
Server: AmazonS3
X-Cache: Miss from cloudfront
Via: 1.1 ca9fae216afadb306ee73a147fd8d410.cloudfront.net (CloudFront)
X-Amz-Cf-Id: 3TG8nVVEZHVICu9N1wLydenNBhSb7Yy8Ko57NWw==

$ curl -I  https://media.rubyplus.com/graphql.mp4
HTTP/1.1 200 OK
Content-Type: application/octet-stream
Content-Length: 107703153
Connection: keep-alive
Date: Sun, 25 Dec 2016 01:25:07 GMT
Last-Modified: Sat, 24 Dec 2016 22:34:51 GMT
ETag: "55bf4669c44224e46e195bc3f993a31d-2"
Accept-Ranges: bytes
Server: AmazonS3
Age: 33
X-Cache: Hit from cloudfront
Via: 1.1 ae7118021d1020068bf9f.cloudfront.net (CloudFront)

X-Amz-Cf-Id: hA2bDLM2QfD_nYy8jXJqV8zY6Tg==

Sunday, December 18, 2016

Amazon S3 as Image Hosting Service

Create and Configure S3 Bucket

1. Login to AWS Console and create a bucket. In my case images.rubyplus.com.
2.  Add the bucket policy to provide read access to everyone:

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"AddPerm",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::examplebucket/*"]
    }
  ]
}




3. Upload the image to the S3 bucket. You can also access the image using SSL like this: https://s3.amazonaws.com/images.rubyplus.com/no-op-cgol.png

This is the image for my upcoming book TDD in Ruby to be released by Apress in 2017. The SSL is important because when your site uses SSL and some of the links are not https, the browser will show SSL errors in the SSL padlock.

Tip: Use http://jsonlint.com to validate bucket policy and fix issues before configuring the bucket.

Use Amazon CloudFront CDN to Speed Up Image Access

Go to Cloudfront and click Create Distribution, provide the bucket name and accept the default values for other form fields. It will take some time for the changes to take effect.




Once the changes are complete, you can access the images using Cloudfront URL like this:
http://images.rubyplus.com.s3.amazonaws.com/no-op-cgol.png

Using your Own Subdomain to Access Assets

You can create CNAME using the UI provided by your host to map the URL:

http://xyz123.cloudfront.net to http://images.yourdomain.com

I host my Rails app on Linode. I used the dashboard of Linode to map images.rubyplus.com to the cloudfront.net URL by creating a CNAME. Now, we can access the same image without s3.amazonaws.com like this:

https://images.rubyplus.com/no-op-cgol.png





Saturday, December 17, 2016

Webpack in Rails 5.1

Webpack will be available in Rails 5.1, in this screencast learn the basics of Webpack:  https://rubyplus.com/episodes/201-Webpack-Basics


Thursday, December 15, 2016

GraphQL Learning Links

https://rmosolgo.github.io/graphql-ruby/
https://github.com/github/graphql-client
http://graphql-ruby-demo.herokuapp.com/graphiql
https://learngraphql.com/basics/querying-graphql/4
https://sandbox.learngraphql.com/
http://syndicode.co/2016/06/03/graphql-in-ruby-on-rails/
http://mgiroux.me/2015/getting-started-with-rails-graphql-relay/

Top 10 Links of 2016 RubyPlus Podcast

  1. Get Your Conference Proposal Accepted by Richard Schneeman.
  2. Face Recognition using Google Cloud Vision API by Netguru
  3. Writing a Test Framework From Scratch by Ryan Davis
  4. Mastering Programming by Kent Beck
  5. Token Based API Authentication by Bala Paranj
  6. How to Integrate Google Calendar with Rails
  7. 10 Steps to Learn Anything Quickly by John Sonmez
  8. The GitHub GraphQL API by Brandon Black
  9. Hunting for great names in programming by DHH
  10. Writing custom Asset Pipeline processors to compress images by David Verhasselt

Wednesday, December 14, 2016

Vague Error Message by Bundler

Bundler could not find compatible versions for gem "sass":
  In Gemfile:
    compass-rails (~> 2.0.4) was resolved to 2.0.4, which depends on
      compass (~> 1.0.0) was resolved to 1.0.0, which depends on
        sass (< 3.5, >= 3.3.13)

    sass-rails (~> 4.0.2) was resolved to 4.0.2, which depends on
      sass (~> 3.2.0)

compass gem has an indirect dependency on sass gem version >= 3.3.13 or < 3.5
compass-rails gem has indirect dependency on sass gem version == 3.2

Ideally, the software should state the cause of the problem and the resolution in a easy to understand language. In this case, The sass gem must be the same for sass-rails and compass-rails gems to install successfully.

undefined method `[]' for "image":Sass::Script::Value::String

Problem:

undefined method `[]' for "image":Sass::Script::Value::String

Resolution:
gem 'sprockets', '3.4'
gem 'sprockets-rails', '2.3.3'

Chnage any asset-url to image-url that takes one parameter (no image is required as the second parameter).

Tuesday, December 13, 2016

Monday, December 12, 2016

Saturday, December 10, 2016

Securing an API in Rails 5

Watch the latest Rails screencast on Securing an API using Token Based Authentication in Rails 5: https://itunes.apple.com/us/podcast/rails-screencast/id1142573687

Filtering with ActiveRecord Has Many Through

I wanted to search published episodes that are tagged with a given term. The tag class:

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :episodes, through: :taggings
end

The tagged_with returns all episodes that tagged with the given term including the unpublished ones:

def self.tagged_with(name)
  Tag.find_by!(name: name).episodes
end
The episode model has published class method.

  def self.published
    where('published_at <= ?', Time.now.utc)
  end
We can accomplish this as follows:

tag = Tag.find_by!(name: 'great')
tag.episodes.merge(Episode.published)
Reference

Friday, December 09, 2016

Self reference doesnt match document location

This error is due to the redirect from http to https in Rails app, because SSL is forced. Change  http to https to avoid redirection in the tag as follows:

xml.tag!("atom:link",  "href"=>"https://rubyplus.com/episodes.rss", "rel"=>"self", "type"=>"application/rss+xml") 
This way, the feed validator will not get confused due to the redirect.

unbound prefix atom feed valid

I was getting this error when I wanted to add atom:link to my RSS feed. You must declare the xml name space like this:

xml.rss "xmlns:itunes" => "http://www.itunes.com/dtds/podcast-1.0.dtd",  "xmlns:media" => "http://search.yahoo.com/mrss/",  :version => "2.0", "xmlns:atom" => "http://www.w3.org/2005/Atom" do

Tuesday, December 06, 2016

jQuery Script to Hide Notice

This code is stolen from McKenzie Child youTube video.

$(document).ready(function(){
    setTimeout(function(){
        $('#notice_wrapper').fadeOut('slow', function() {
            $(this).remove();
        })
    }, 4500);
});

Monday, December 05, 2016

Securing an API in Rails 5

Securing an API in Rails 5 from Scratch using Token based authentication with token expiration and mitigation of time based attacks.

Writing Tips for Technical Topics

Preliminary Steps

Have all necessary information before you start (data,references,tables,figures,etc.)

Before you Start

Spend time thinking about the content. Write down ideas in a free form. Create a general outline:
  1.  What is the message?
  2.  What is the new contribution you want to describe?
  3.  What do you want to convince people?
Summarize these ideas in bullets that each will eventually become a paragraph. This is like a To Do list. Later, you will categorize this list according to the structure of the book.

Organize bullets in a logical structure and develop them into a few key sentences. Don't worry about the correctness, details at this point. Once you categorize your notes for each category, you start expanding those bullets in each category into sentences.

If this outline is convincing, the chapter is successful. At this stage, have a technical reviewer review your outline.

Reference

How to write a research journal paper by Mohammad Noori

Friday, December 02, 2016

Find gems that are depending on a given gem

To find the gems that are dependent on a given gem, you can use the following command:


gem dependency eventmachine --reverse-dependencies

Gem eventmachine-1.2.0.1
  rake-compiler (~> 0.9.5, development)
  rake-compiler-dock (~> 0.5.1, development)
  test-unit (~> 2.0, development)
  Used by
    excon-0.51.0 (eventmachine (>= 1.0.4, development))
    thin-1.7.0 (eventmachine (>= 1.0.4, ~> 1.0))

I wanted to find out what is depending on eventmachine in my project. Because, concurrent-ruby is a better alternative to eventmachine. My suspicion was that sucker_punch gem was using it. I was wrong because as you see in the about output, it is not the culprit. The version 2.0 of sucker punch uses concurrent-ruby. Luckily, only the development environment has dependency on the eventmachin gem.

How to provide proper error messages to users of your software

Shitty error message when the Internet connection is turned off. When you do:

git remote show origin

Error is:

ssh: Could not resolve hostname bitbucket.org: nodename nor servname provided, or not known
fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.

This is meaningless error message. Does not tell the user in simple language the cause of the problem and how to resolve it. How about:

Hey, you dummy, you are not connected to the Internet. Check your Internet connection and try again.

Auto-Complete Association in Rails 5

Checkout the Rails screencast latest episode Auto-Complete Association in Rails 5.

Cool Places to Hack

https://github.com/diasdavid/awesome-hacking-spots
https://spoonuniversity.com/place/the-8-best-coffee-shops-in-downtown-asheville
http://spoonuniversity.com/place/the-10-best-nyc-coffee-shops-to-get-work-done
http://jlord.us/hack-spots

Being able to upload the screenshot of Internet speed test would be great.