Tuesday, May 24, 2016

Better Errors & RailsPanel in Rails 5

Better Errors & RailsPanel  works fine in Rails 5. Here is the instructions to get it working in Rails 5:

rails g model project name
rails g model task name project:references completed_at:datetime
rake db:migrate

rails g controller projects index show new edit
rails g controller tasks


The routes:

  resources :projects
  resources :tasks
  root to: 'projects#index'

Everything works except:
 
http://localhost:3000/__better_errors

undefined method `cause' for nil:NilClass             

    def original_exception(exception)
      if @@rescue_responses.has_key?(exception.cause.class.name)
        exception.cause
      else
        exception

Rails Panel 

Top Links for May 30, 2016

Pointless Features Add to Browser Bloat and Insecurity

83 % of browser features are used by under 1 % of the most popular 10,000 websites. These features are also not used by the end users. 50 % of the JavaScript provided features in the web browser are never used by the top ten thousand most popular websites. Read this article to get an idea of what features to avoid using in your Rails apps to prevent your app getting blocked by blockers.

Streaming data with ActionController::Live

Rails 5 final release is almost here. The most exciting feature is the ActionCable. Why do we need ActionController::Live when we have ActionCable? The short answer is that Server Side Events are one-way, it goes from the server to the client, whereas ActionCable is two-way communication between client and server. Checkout this article to learn more.

 


Monday, May 23, 2016

Analytics Strategies for Rails

Analyze this... Analytics Strategies for iOS and Rails by Lance Gleason
Data-Driven Documents
D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation.
D3.js Gallery


Sunday, May 22, 2016

Amazon CDN CORS problem in Rails App

Problem

Font from origin 'https://d1b5oz78c0udqh.cloudfront.net' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://rubyplus.com' is therefore not allowed access.

Solution

1. Point your subdomain to your AWS Cloudfront domain. Go to AWS Cloudfront control panel, select your Cloudfront distribution and enter your CDN subdomain into the Alternate Domain Names (CNAMEs) field. Something like cdn.myawesomeapp.com will do.

2. Create a CNAME for cdn.myawesomeapp.com pointing to sdf73n7ssa.cloudfront.net.

3. Test your new CDN domain by making sure assets served are from cloudfront.

curl -I http://cdn.myawesomeapp.com/assets/image.png

4. AWS supports SSL Server Name Indication (SNI). Upload your SSL certificate to AWS first.
   Install the AWS command line tool first (that’s easy). Once you have your AWS command line tool installed and configured with the AWS keys, you can upload your SSL certificate:
 
   aws iam upload-server-certificate --server-certificate-name my_certificate_name --certificate-body file://my_cert.crt --private-key file://my_key.key --certificate-chain file://intermediate_cert.pem --path /cloudfront/my_cert_name_here/
 
5. Head back to your CDN distribution on AWS Cloudfront and select “Custom SSL Certificate (stored in AWS IAM)” and “Only Clients that Support Server Name Indication (SNI)” options.  

6. Now you should be able to see your assets both on HTTP and HTTPS served from CDN. Test it with CURL:

curl -I https://cdn.myawesomeapp.com/assets/image.png

7. Change your config.action_controller.asset_host in your production.rb to //cdn.myawesomeapp.com

Reference

Cross Origin Resource Sharing (CORS) Blocked for Cloudfront in Rails

Thursday, May 19, 2016

How to find the location based on IP address

Use geocoder gem:

rails c
> Geocoder.search('209.249.19.172').first
 => #"209.249.19.172", "country_code"=>"US", "country_name"=>"United States", "region_code"=>"CA", "region_name"=>"California", "city"=>"Moraga", "zip_code"=>"94556", "time_zone"=>"America/Los_Angeles", "latitude"=>37.8381, "longitude"=>-122.1026, "metro_code"=>807}, @cache_hit=nil>

Uncaught Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)

Add this:

source 'https://rails-assets.org' do
  gem 'rails-assets-tether', '>= 1.1.0'
end

to Gemfile. Run bundle.

//= require tether

after jQuery in application.js.

Pinterest Clone in Rails 5

Pinterest Clone in Rails 5


Why Display Popular Articles?

It can help visitors to easily find more of your best content. This can help new visitors find your best articles, as soon as they arrive at your website. This will increase the time spent on your website, reduce bounce rate, and improve the number of page views per visit.

RubyPlus Podcast Episode 5

Wednesday, May 18, 2016

Elasticsearch::Transport::Transport::Errors::BadRequest

Error: [400] No handler found for uri [/_alias/articles_development] and method [GET]
Resolution : Make sure elasticsearch server is running.

Waiting for the day when the error messages are meaningful and the searchkick code becomes robust.

Autocomplete in Rails 5 Apps

Autocomplete using Typeahead and Searchkick in Rails 5

The Railscast episode #399 has been updated in the above article. Check it out.

Benefits of Search Suggest Systems

1. Spelling mistakes are avoided
2. Fewer keys need to be typed
3. Suggestions provide immediate feedback in terms of what queries are possible.

The absence of a suggestion could indicate that there many not be responses for the query. Will this affect collecting search terms that we may discover for creating new content?

Use auto-complete to:
  •     Facilitate accurate and efficient data entry
  •     Select from a finite list of names or symbols
Use auto-suggest to:
  •     Facilitate novel query reformulations
  •     Select from an open-ended list of terms or phrases
  •     Encourage exploratory search (with a degree of complexity and mental effort that is appropriate to the task). Where appropriate, complement search suggestions with recent searches

Use instant results to:

    Promote specific items or products
   

References  

Designing Search: As-You-Type Suggestions   
Search Auto Complete
Autocomplete as a Research Tool: A Study on Providing Search Suggestions

7 Factors to Consider when Evaluating a Library

Consider the following 7 factors when evaluating a third-party library.

1. Efficacy: How well does it work?
2. Performance: How well does it perform?
3. Reliability: Can I depend on it?
4. Ease of Use: How much effort does it require?
5. Flexibility: How many things does it do?
6. Aesthetic Appeal: How aesthetically pleasing is it?
7. Time Sink: How much time do I have to give up to maintain it?

How well is it written?
Can I customize it easily?
How responsive are the developers in fixing bugs?
Does it support the latest version of the language it is written?

I recently had to use Customer instead of User for using a Ruby gem. The assumptions made by this library was not applicable to my project. I sent an email to the author. He never responded. It is better to develop your own library if you can simplify the existing library code.

Tuesday, May 17, 2016

Railscast Episode 190 Upgrade Attempt to Rails 5

rails g model category name
rails g model product name price:decimal category:references description:text custom_url

rails g controller categories
rails g controller products

class Category < ApplicationRecord
  has_many :products
end

Rails.application.routes.draw do
  resources :products
  resources :categories
 
  root 'products#index'
end

Category.delete_all
['Electronics', 'Office Supplies', 'Toys', 'Clothing', 'Groceries'].each do |name|
  Category.create!(name: name)
end

Product.delete_all
categories = Category.all
words = File.readlines("/usr/share/dict/words")
lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
25.times do
  Product.create!(name: words.pop.titleize,
                  category: categories.sample,
                  description: lorem, price: [4.99, 9.99, 14.99, 19.99, 29.99].sample)
end


rails db:seed

Use SelectorGadget to find the CSS selector to use in the script.

rake fetch_prices rake task is broken because Walmart UI has changed.

Paperclip::Errors::NotIdentifiedByImageMagickError

identify Captain-America-2011-Movie-Poster-1.jpg
dyld: Library not loaded: /System/Library/Frameworks/OpenCL.framework/Versions/A/Libraries/libclparser.dylib
  Referenced from: /usr/local/bin/identify
  Reason: image not found
Trace/BPT trap: 5

identify -version
dyld: Library not loaded: /System/Library/Frameworks/OpenCL.framework/Versions/A/Libraries/libclparser.dylib
  Referenced from: /usr/local/bin/identify
  Reason: image not found
Trace/BPT trap: 5

This means ImageMagick is not installed on your machine. It would be useful if the paperclip gem makes the assumption explicit. If the pre-requisite software is not installed, ideally, it should throw an exception that identifies the cause of the problem and the resolution to inform the user on how to overcome that error.

You can do:

brew install imagemagick

If you get an error like this:

brew install imagemagick
Warning: Your Xcode (4.5.2) is outdated
Please install Xcode 4.6.2.
Warning: It appears you have MacPorts or Fink installed.
Software installed with other package managers causes known problems for
Homebrew. If a formula fails to build, uninstall MacPorts/Fink and try again.
==> Installing imagemagick dependency: jpeg
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/jpeg-8d.lion.bottle.1.tar.gz
######################################################################## 100.0%
==> Pouring jpeg-8d.lion.bottle.1.tar.gz
Warning: Could not link jpeg. Unlinking...
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
You can try again using `brew link jpeg'
==> Summary
🍺  /usr/local/Cellar/jpeg/8d: 18 files, 784K
==> Installing imagemagick
==> Downloading http://downloads.sf.net/project/machomebrew/mirror/ImageMagick-6.8.0-10.tar.gz
######################################################################## 100.0%
==> ./configure --disable-osx-universal-binary --without-perl --prefix=/usr/local/Cellar/imagemagick/6.8.0-10 --enable-shared --disa
==> make install
brew: superenv removed: -L/usr/X11/lib -L/usr/local/lib -O2
brew: superenv removed: -L/usr/X11/lib -L/usr/local/lib -O2
brew: superenv removed: -L/usr/X11/lib -L/usr/local/lib -O2
make[1]: *** [install-recursive] Error 1
make: *** [install] Error 2

READ THIS: https://github.com/mxcl/homebrew/wiki/troubleshooting

You can install it from the source. Download 

http://www.imagemagick.org/download/ImageMagick.tar.gz
tar xvzf ImageMagick.tar.gz
cd ImageMagick-7.0.3
./configure
make
sudo make install

The ImageMagick Installer for Mac  also failed for me on Mac OS 10.7.5.

Rails Upgrade from 3.2 to 4.2 Active Record Update Checklist

To migrate dynamic finders to Rails 4.1+:
  • find_all_by_... should become where(...).
  • find_last_by_... should become where(...).last.
  • scoped_by_... should become where(...).
  • find_or_initialize_by_... should become find_or_initialize_by(...).
  • find_or_create_by_... should become find_or_create_by(...).
https://github.com/rails/activerecord-deprecated_finders

Notes for Ahoy User Analytics Gem

Checking for a bot so that we can exclude it from the analytics

def bot?
  @bot ||= request ? Browser.new(request.user_agent).bot? : false
end

Location : Geocoder.search(@ip).first

Look at these classes:

RequestDeckhand
TechnologyDeckhand
TrafficSourceDeckhand
UtmParameterDeckhand

Dependent Gems

addressable, browser, geocoder, referer-parser, user_agent_parser, request_store, uuidtools, safely_block, rack-attack

How to Develop Moonshine Plugin

1. Create a new Rails 4.2.6 project
2. Add gem 'plugger' and run bundle
3. plugger install git://github.com/railsmachine/moonshine.git
4. rails g to list all available generators
5. rails g moonshine:plugin wordnet
6. rails g moonshine:plugin wordnet
      create  vendor/plugins/moonshine_wordnet/LICENSE
      create  vendor/plugins/moonshine_wordnet/README.markdown
      create  vendor/plugins/moonshine_wordnet/moonshine/init.rb
      create  vendor/plugins/moonshine_wordnet/lib/moonshine/wordnet.rb
      create  vendor/plugins/moonshine_wordnet/spec/moonshine/wordnet_spec.rb
      create  vendor/plugins/moonshine_wordnet/spec/spec_helper.rb
7. Automate these commands:

      cd /tmp
      curl -o wordnet.tar.gz http://wordnetcode.princeton.edu/3.0/WNprolog-3.0.tar.gz
      tar -zxvf wordnet.tar.gz
      mv prolog/wn_s.pl /var/lib

in lib/moonshine/wordnet.rb.





Reference:
 
Mongodb Moonshine Plugin:

exec 'install_mongodb',
        :command => [
          "wget http://downloads.mongodb.org/linux/mongodb-linux-#{arch}-#{options[:version]}.tgz",
          "tar xzf mongodb-linux-#{arch}-#{options[:version]}.tgz",
          "mv mongodb-linux-#{arch}-#{options[:version]} /opt/local/mongo-#{options[:version]}"
        ].join(' && '),
        :cwd => '/tmp',
        :creates => "/opt/local/mongo-#{options[:version]}/bin/mongod",
        :require => [
          file('/opt/local'),
          package('wget')
        ]

Top Links for May 17, 2016

[23 Years of Ruby with Matz (Yukihiro Matsumoto)](https://changelog.com/202 23 Years of Ruby with Matz)

Matz, the creator of Ruby discusses the origins of the Ruby programming language, its history and future, Ruby 3.0, Concurrency and Parallelism, Streem, Erlang, Elixir, and more.

[Rails 5.0.0rc1 Released – Is ActionCable Ready for Prime Time? ](https://www.clearvoice.com/rails-5-0-0rc1-released-actioncable-ready-prime-time/ 'Rails 5.0.0rc1 Released – Is ActionCable Ready for Prime Time? ') by clearvoice\

As the web evolves and users become more demanding, the need for web applications to be interactive and immediate grows. Rails 5.0 is now more than ready to play with. This is a quick introduction to getting it up and running and a very simple Action Cable example.


[How to Build a Simple Math Evaluation Engine](https://blog.codeship.com/build-math-evaluation-engine/ 'How to Build a Simple Math Evaluation Engine') by Jesus Castello

Early on in Ruby, you learn to evaluate a math expression in irb. What’s the magic behind this operation? Create your own evaluation engine and find out.

[Jeremy Daer's RailsConf 2016 Opening Keynote](https://www.youtube.com/watch?v=nUVsZ4vS1Y8 'Jeremy Daer RailsConf 2016 Opening Keynote')
Relaxed reflections on the history and meaning of Rails and Basecamp as a way to explain Rails' ongoing relevance. The final 10 minutes has the more feature-based/newsy stuff.

[Ruby on Google App Engine goes beta](https://cloudplatform.googleblog.com/2016/05/Ruby-on-Google-App-Engine-goes-betaruntime.html 'Ruby on Google App Engine goes beta')

Frameworks such as Ruby on Rails and Sinatra make it easy for developers to rapidly build web applications and APIs for the cloud. App Engine provides an easy to use platform for developers to build, deploy, manage, and automatically scale services on Google’s infrastructure.

[Don't Forget About Infinite Enumerators](http://aaronlasseigne.com/2016/05/11/dont-forget-about-infinite-enumerators/ 'Don't Forget About Infinite Enumerators') by AAaron Lasseigne

When was the last time you created an Enumerator? We use enumerables all over the place but it’s rare to see Enumerator.new. Sometimes you forget it’s an option. With finite enumerations you are immediately limiting where they can be used. They come with an extra expectation that must be addressed. Are there enough elements for me? When they’re infinite you can just go crazy.

[Notes from RailsConf 2016 opinion]( 'Notes from RailsConf 2016 opinion')
Kir Shatrov shares his thoughts and observations from this year’s RailsConf.

[WYSIWYG Editor with Trix](https://www.driftingruby.com/episodes/wysiwyg-editor-with-trix 'WYSIWYG Editor with Trix')

Compose beautifully formatted text in your web application. Trix is a WYSIWYG editor for writing messages, comments, articles, and lists.


[Rails Performance and the root of all evil](http://blog.scoutapp.com/articles/2016/05/09/rails-performance-and-the-root-of-all-evil 'Rails Performance and the root of all evil') By Sudara

This article talks about how to identify what matters in performance, measure twice : cut once, evil and non evil optimizations.

[Do You Need That Gem?](rightonruby.com/2015/do-you-need-that-gem-sam-phippen 'Do You Need That Gem') by Sam Phippen
Sam Phippen looks at the trials and tribulations of managing third party dependancies in our Ruby apps. It's a 18 minutes video. Checkout the podcasts section of rubyplus.com for the link.

[The Top Rails Code Smell To Avoid to Keep Your App Healthy](https://medium.com/planet-arkency/the-biggest-rails-code-smell-you-should-avoid-to-keep-your-app-healthy-a61fd75ab2d3#.xujqf0g9i 'The Top Rails Code Smell To Avoid to Keep Your App Healthy') by Marcin Grzywaczewski
Marcin ponders what common pattern in Rails causes the most pain and settles for ActiveRecord callbacks. Here he explains why.

[An Introduction to Rails Testing Antipatterns](http://code.tutsplus.com/articles/antipatterns-basics-rails-tests--cms-26011 'An Introduction to Rails Testing Antipatterns') by Ed Wassermann

An introduction to testing anti-patterns in Rails aimed at developers who want to pick up some valuable best practices.




[Allow accessing all helpers at the controller level](https://github.com/rails/rails/pull/24866 'Allow accessing all helpers at the controller level')
With this helper proxy, users can reuse helpers in the controller without having to include all the modules related to view context.

[Add ActiveModel::RangeError](https://github.com/rails/rails/pull/24835 'Add ActiveModel::RangeError')
When provided with large numbers, Active Model now fails with a new ActiveModel::RangeError that makes it easier to rescue from, and inherits from RangeError to maintain backward compatibility.

[Ensure compatibility between Rails Session and Rack Session](https://github.com/rails/rails/pull/24820 'Ensure compatibility between Rails Session and Rack Session')
Rails session is now compatible with other Rack frameworks like Sinatra that are mounted in Rails. They can also use session tooling of Rails without any issues now.

[RailsConf Talks on YouTube]
Confreaks has posted videos for each session on confreaks.tv.

elasticsearch-rails vs searchkick

I have implemented search feature using elasticsearch-rails and searchkick for rubyplus.com. Searckick requires less code, is elegant and makes it easy to implement fuzzy search that handles spelling mistakes. Search Feature using ElasticSearch in Rails 5 shows how to use elasticsearch-rails gem and Search Feature using Searchkick in Rails 5 show how to use searchkick.

How to Install ElasticSearch on Linode using Moonshine

1. Install elasticsearch mooonshine plugin.

plugger install git://github.com/railsmachine/moonshine_elasticsearch.git --force
2. Add the elasticsearch configuration in config/moonshine.yml:
:elasticsearch:
  :version: 0.90.12
  :cluster_name: mycluster
3.  Include the recipe in manifest file. 

recipe :elasticsearch
Deploy it using Capistrano. You can see a demo on rubyplus.com search feature.

Saturday, May 14, 2016

Integrating Twitter Bootstrap 4 with Rails 5

I have upgraded the movies database Rails app that uses Twitter Bootstrap 3 and Rails 4 developed by Mackenzie Child to Twitter Bootstrap 4 and Rails 5, check it out:
Integrating Twitter Bootstrap 4 with Rails 5

Install Nodejs on Linux

curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash -
sudo apt-get install -y nodejs

Friday, May 13, 2016

How to update git in Ubuntu

sudo add-apt-repository ppa:git-core/ppa -y
sudo apt-get update
sudo apt-get install git
git --version

How to debug httpparty gem


If you want to see the request and the body sent to the server, use debug_output method.

      include HTTParty
      debug_output $stdout

Thursday, May 12, 2016

How to style search form using Twitter Bootstrap 3 in Rails 4.2.6 Apps





Failed to open TCP connection to localhost:9200 (Connection refused - connect(2) for "localhost" port 9200)

sudo /usr/local/bin/elasticsearch

Full Text Search using ElasticSearch in Rails 5

Full Text Search using ElasticSearch in Rails 5

Learn how to use full text search using elasticsearch gems in Rails 5 apps.

Bounce Rate

What does high bounce rate mean?

It means landing pages are not relevant to your visitors.

How to Improve Bounce Rate?

1. Add links to more pages within your website in your content. Think about other pages that people interested in that piece of content will want to see, and link to them throughout the content and at the end in a “if you liked this, you’ll love this” kind of way.
2. Provide relevant content. Create landing pages tailored to each keyword and ad so that visitors can find what was promised.
3. Link to a glossary page that defines industry terms.
4. Place search function prominently. In the articles page, search box should have autocomplete and show relevant articles in the results.
5. Open external links in a new window.
6. Speed up page load.
7. Get rid of pop-up ads.
8. Keep the category list short (12 or less).

Tuesday, May 10, 2016

Trouble Shooting Psych::SyntaxError

I was getting:
Psych::SyntaxError:
       (): did not find expected key while parsing a block mapping at line 59 column 7
in the yml file.

To troubleshoot use Online YAML Parser  and check which line is having the problem and remove the line to get back to working version. Gradually introduce more text into the yml file to figure out the cause of the problem. 

How to listen to RubyPlus Podcast on Google Play using any Browser

You can listen to RubyPlus podcast that covers the latest news from Ruby and Rails community on Google Play. You can use any browser to listen to the episodes. Go to https://play.google.com/music and search for rubyplus podcast. You can click on any episode you want to listen to enjoy the podcast.

Monday, May 09, 2016

Preserving Exact Body Bytes in VCR

1. If you look at the VCR cassettes, you can see the response in JSON or Base64 encoded response.
2. Copy the Base64 encoded response and decode it using online Base64 decoder.
3. The result can be pasted on online JSON formatter and you will the JSON response.

Why does VCR do this for some requests?
What is the use of knowing this fact?

If you are having difficulty in making a test pass. You can change the string to a known input by encoding the known output for a given input in the VCR fixture file. This will make the test pass.

Saturday, May 07, 2016

Ruby Podcast Episode 4

Learn about the basic software development laws such as Linus's Law, Occam's Razor, Hanlon's Razor, The Pareto Principle, Postel's Law, Hofstadter's Law and The 90-90 Rule. Listen to RubyPlus Ruby Podcast 4 .

Wednesday, May 04, 2016

error: git-credential-osxkeychain died of signal 11

When I git push to my repository I got an error on Mac OS 10.7.5
>>>git push
error: git-credential-osxkeychain died of signal 11
There's a bug in git-credential-osxkeychain so simply replace that with new one on S3.
$which git git-credential-osxkeychain
/usr/local/git/bin/git-credential-osxkeychain
$curl -O http://github-media-downloads.s3.amazonaws.com/osx/git-credential-osxkeychain
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 15520  100 15520    0     0   5446      0  0:00:02  0:00:02 --:--:-- 11014
$ sudo mv git-credential-osxkeychain /usr/local/git/binn
$ chmod 755 /usr/local/git/bin/git-credential-osxkeychain

RailsCast Episode 168

The name of the gem has been changed. Here is the same code from the gem home page.

gem install feedjira




url = "http://feedjira.com/blog/feed.xml"
feed = Feedjira::Feed.fetch_and_parse url
feed.title
entry = feed.entries.first
entry.title
entry.url

Tuesday, April 26, 2016

Localhost Proxy ngrok Help

NAME:
   ngrok - tunnel local ports to public URLs and inspect traffic

DESCRIPTION:
    ngrok exposes local networked services behinds NATs and firewalls to the
    public internet over a secure tunnel. Share local websites, build/test
    webhook consumers and self-host personal services.
    Detailed help for each command is available with 'ngrok help '.
    Open http://localhost:4040 for ngrok's web interface to inspect traffic.

EXAMPLES:
    ngrok http 80                    # secure public URL for port 80 web server
    ngrok http -subdomain=baz 8080   # port 8080 available at baz.ngrok.io
    ngrok http foo.dev:80            # tunnel to host:port instead of localhost
    ngrok tcp 22                     # tunnel arbitrary TCP traffic to port 22
    ngrok tls -hostname=foo.com 443  # TLS traffic for foo.com to port 443
    ngrok start foo bar baz          # start tunnels from the configuration file

VERSION:
   2.0.25

AUTHOR:
  inconshreveable -

COMMANDS:
   authtoken    save authtoken to configuration file
   credits    prints author and licensing information
   http        start an HTTP tunnel
   start    start tunnels by name from the configuration file
   tcp        start a TCP tunnel
   test        test ngrok service end-to-end
   tls        start a TLS tunnel
   update    update ngrok to the latest version
   version    print the version string
   help        Shows a list of commands or help for one command

Monday, April 25, 2016

Tool to deploy static sites to GAE

GAE Static Tool
GAE Static Site Template Use this as the starter template for your static sites. Images and CSS are go in www/assets folder. Feel free to delete folder1 if you don't need it. The html pages go in the www folder. You can customize the app.yaml according to your needs.

Saturday, April 23, 2016

How to check the version of Sphinx

$ searchd --help
Sphinx 2.2.10-id64-release (2c212e0)
Copyright (c) 2001-2015, Andrew Aksyonoff
Copyright (c) 2008-2015, Sphinx Technologies Inc (http://sphinxsearch.com)

Usage: searchd [OPTIONS]

Options are:
-h, --help display this help message
-c, --config read configuration from specified file
(default is sphinx.conf)
--stop send SIGTERM to currently running searchd
--stopwait send SIGTERM and wait until actual exit
--status get ant print status variables
(PID is taken from pid_file specified in config file)
--iostats log per-query io stats
--strip-path strip paths from stopwords, wordforms, exceptions
and other file names stored in the index header
--replay-flags=
extra binary log replay options (the only current one
is 'accept-desc-timestamp')

Debugging options are:
--console run in console mode (do not fork, do not log to files)
-p, --port listen on given port (overrides config setting)
-l, --listen listen on given address, port or path (overrides
config settings)
-i, --index only serve given index(es)
--nodetach do not detach into background
--logdebug, --logdebugv, --logdebugvv
enable additional debug information logging
(with different verboseness)
--pidfile force using the PID file (useful with --console)
--safetrace only use system backtrace() call in crash reports

Examples:
searchd --config /usr/local/sphinx/etc/sphinx.conf

git ls-files help

~/projects/lafon $git ls-files --junk 
error: unknown option `junk'
usage: git ls-files [] [...]

    -z                    paths are separated with NUL character
    -t                    identify the file status with tags
    -v                    use lowercase letters for 'assume unchanged' files
    -c, --cached          show cached files in the output (default)
    -d, --deleted         show deleted files in the output
    -m, --modified        show modified files in the output
    -o, --others          show other files in the output
    -i, --ignored         show ignored files in the output
    -s, --stage           show staged contents' object name in the output
    -k, --killed          show files on the filesystem that need to be removed
    --directory           show 'other' directories' names only
    --empty-directory     don't show empty directories
    -u, --unmerged        show unmerged files in the output
    --resolve-undo        show resolve-undo information
    -x, --exclude
                          skip files matching pattern
    -X, --exclude-from
                          exclude patterns are read from
    --exclude-per-directory
                          read additional per-directory exclude patterns in
    --exclude-standard    add the standard git exclusions
    --full-name           make the output relative to the project top directory
    --error-unmatch       if any is not in the index, treat this as an error
    --with-tree
                          pretend that paths removed since are still present
    --abbrev[=]        use digits to display SHA-1s
    --debug               show debugging data

Friday, April 22, 2016

ImageMagick Help

Version: ImageMagick 6.9.1-0 Q16 x86_64 2015-03-22 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2015 ImageMagick Studio LLC
License: http://www.imagemagick.org/script/license.php
Features: DPC OpenCL
Delegates (built-in): bzlib fftw jng jpeg lcms lzma png tiff webp xml zlib

Usage: convert [options ...] file [ [options ...] file ...] [options ...] file

Image Settings:
  -adjoin              join images into a single multi-image file
  -affine matrix       affine transform matrix
  -alpha option        activate, deactivate, reset, or set the alpha channel
  -antialias           remove pixel-aliasing
  -authenticate password
                       decipher image with this password
  -attenuate value     lessen (or intensify) when adding noise to an image
  -background color    background color
  -bias value          add bias when convolving an image
  -black-point-compensation
                       use black point compensation
  -blue-primary point  chromaticity blue primary point
  -bordercolor color   border color
  -caption string      assign a caption to an image
  -channel type        apply option to select image channels
  -clip-mask filename  associate a clip mask with the image
  -colors value        preferred number of colors in the image
  -colorspace type     alternate image colorspace
  -comment string      annotate image with comment
  -compose operator    set image composite operator
  -compress type       type of pixel compression when writing the image
  -define format:option
                       define one or more image format options
  -delay value         display the next image after pausing
  -density geometry    horizontal and vertical density of the image
  -depth value         image depth
  -direction type      render text right-to-left or left-to-right
  -display server      get image or font from this X server
  -dispose method      layer disposal method
  -dither method       apply error diffusion to image
  -encoding type       text encoding type
  -endian type         endianness (MSB or LSB) of the image
  -family name         render text with this font family
  -fill color          color to use when filling a graphic primitive
  -filter type         use this filter when resizing an image
  -font name           render text with this font
  -format "string"     output formatted image characteristics
  -fuzz distance       colors within this distance are considered equal
  -gravity type        horizontal and vertical text placement
  -green-primary point chromaticity green primary point
  -intensity method    method to generate intensity value from pixel
  -intent type         type of rendering intent when managing the image color
  -interlace type      type of image interlacing scheme
  -interline-spacing value
                       set the space between two text lines
  -interpolate method  pixel color interpolation method
  -interword-spacing value
                       set the space between two words
  -kerning value       set the space between two letters
  -label string        assign a label to an image
  -limit type value    pixel cache resource limit
  -loop iterations     add Netscape loop extension to your GIF animation
  -mask filename       associate a mask with the image
  -matte               store matte channel if the image has one
  -mattecolor color    frame color
  -moments             report image moments
  -monitor             monitor progress
  -orient type         image orientation
  -page geometry       size and location of an image canvas (setting)
  -ping                efficiently determine image attributes
  -pointsize value     font point size
  -precision value     maximum number of significant digits to print
  -preview type        image preview type
  -quality value       JPEG/MIFF/PNG compression level
  -quiet               suppress all warning messages
  -red-primary point   chromaticity red primary point
  -regard-warnings     pay attention to warning messages
  -remap filename      transform image colors to match this set of colors
  -respect-parentheses settings remain in effect until parenthesis boundary
  -sampling-factor geometry
                       horizontal and vertical sampling factor
  -scene value         image scene number
  -seed value          seed a new sequence of pseudo-random numbers
  -size geometry       width and height of image
  -stretch type        render text with this font stretch
  -stroke color        graphic primitive stroke color
  -strokewidth value   graphic primitive stroke width
  -style type          render text with this font style
  -support factor      resize support: > 1.0 is blurry, < 1.0 is sharp
  -synchronize         synchronize image to storage device
  -taint               declare the image as modified
  -texture filename    name of texture to tile onto the image background
  -tile-offset geometry
                       tile offset
  -treedepth value     color tree depth
  -transparent-color color
                       transparent color
  -undercolor color    annotation bounding box color
  -units type          the units of image resolution
  -verbose             print detailed information about the image
  -view                FlashPix viewing transforms
  -virtual-pixel method
                       virtual pixel access method
  -weight type         render text with this font weight
  -white-point point   chromaticity white point

Image Operators:
  -adaptive-blur geometry
                       adaptively blur pixels; decrease effect near edges
  -adaptive-resize geometry
                       adaptively resize image using 'mesh' interpolation
  -adaptive-sharpen geometry
                       adaptively sharpen pixels; increase effect near edges
  -alpha option        on, activate, off, deactivate, set, opaque, copy
                       transparent, extract, background, or shape
  -annotate geometry text
                       annotate the image with text
  -auto-gamma          automagically adjust gamma level of image
  -auto-level          automagically adjust color levels of image
  -auto-orient         automagically orient (rotate) image
  -bench iterations    measure performance
  -black-threshold value
                       force all pixels below the threshold into black
  -blue-shift factor   simulate a scene at nighttime in the moonlight
  -blur geometry       reduce image noise and reduce detail levels
  -border geometry     surround image with a border of color
  -bordercolor color   border color
  -brightness-contrast geometry
                       improve brightness / contrast of the image
  -canny geometry      detect edges in the image
  -cdl filename        color correct with a color decision list
  -charcoal radius     simulate a charcoal drawing
  -chop geometry       remove pixels from the image interior
  -clamp               keep pixel values in range (0-QuantumRange)
  -clip                clip along the first path from the 8BIM profile
  -clip-path id        clip along a named path from the 8BIM profile
  -colorize value      colorize the image with the fill color
  -color-matrix matrix apply color correction to the image
  -connected-components connectivity
                       connected-components uniquely labeled
  -contrast            enhance or reduce the image contrast
  -contrast-stretch geometry
                       improve contrast by `stretching' the intensity range
  -convolve coefficients
                       apply a convolution kernel to the image
  -cycle amount        cycle the image colormap
  -decipher filename   convert cipher pixels to plain pixels
  -deskew threshold    straighten an image
  -despeckle           reduce the speckles within an image
  -distort method args
                       distort images according to given method ad args
  -draw string         annotate the image with a graphic primitive
  -edge radius         apply a filter to detect edges in the image
  -encipher filename   convert plain pixels to cipher pixels
  -emboss radius       emboss an image
  -enhance             apply a digital filter to enhance a noisy image
  -equalize            perform histogram equalization to an image
  -evaluate operator value
                       evaluate an arithmetic, relational, or logical expression
  -extent geometry     set the image size
  -extract geometry    extract area from image
  -features distance   analyze image features (e.g. contrast, correlation)
  -fft                 implements the discrete Fourier transform (DFT)
  -flip                flip image vertically
  -floodfill geometry color
                       floodfill the image with color
  -flop                flop image horizontally
  -frame geometry      surround image with an ornamental border
  -function name parameters
                       apply function over image values
  -gamma value         level of gamma correction
  -gaussian-blur geometry
                       reduce image noise and reduce detail levels
  -geometry geometry   preferred size or location of the image
  -grayscale method    convert image to grayscale
  -hough-lines geometry
                       identify lines in the image
  -identify            identify the format and characteristics of the image
  -ift                 implements the inverse discrete Fourier transform (DFT)
  -implode amount      implode image pixels about the center
  -interpolative-resize geometry
                       resize image using 'point sampled' interpolation
  -kuwahara geometry   edge preserving noise reduction filter
  -lat geometry        local adaptive thresholding
  -level value         adjust the level of image contrast
  -level-colors color,color
                       level image with the given colors
  -linear-stretch geometry
                       improve contrast by `stretching with saturation'
  -liquid-rescale geometry
                       rescale image with seam-carving
  -magnify             double the size of the image with pixel art scaling
  -mean-shift geometry delineate arbitrarily shaped clusters in the image
  -median geometry     apply a median filter to the image
  -mode geometry       make each pixel the 'predominant color' of the
                       neighborhood
  -modulate value      vary the brightness, saturation, and hue
  -monochrome          transform image to black and white
  -morphology method kernel
                       apply a morphology method to the image
  -motion-blur geometry
                       simulate motion blur
  -negate              replace every pixel with its complementary color
  -noise geometry      add or reduce noise in an image
  -normalize           transform image to span the full range of colors
  -opaque color        change this color to the fill color
  -ordered-dither NxN
                       add a noise pattern to the image with specific
                       amplitudes
  -paint radius        simulate an oil painting
  -perceptible epsilon
                       pixel value less than |epsilon| become epsilon or
                       -epsilon
  -polaroid angle      simulate a Polaroid picture
  -posterize levels    reduce the image to a limited number of color levels
  -profile filename    add, delete, or apply an image profile
  -quantize colorspace reduce colors in this colorspace
  -radial-blur angle   radial blur the image (deprecated use -rotational-blur
  -raise value         lighten/darken image edges to create a 3-D effect
  -random-threshold low,high
                       random threshold the image
  -region geometry     apply options to a portion of the image
  -render              render vector graphics
  -repage geometry     size and location of an image canvas
  -resample geometry   change the resolution of an image
  -resize geometry     resize the image
  -roll geometry       roll an image vertically or horizontally
  -rotate degrees      apply Paeth rotation to the image
  -rotational-blur angle
                       rotational blur the image
  -sample geometry     scale image with pixel sampling
  -scale geometry      scale the image
  -segment values      segment an image
  -selective-blur geometry
                       selectively blur pixels within a contrast threshold
  -sepia-tone threshold
                       simulate a sepia-toned photo
  -set property value  set an image property
  -shade degrees       shade the image using a distant light source
  -shadow geometry     simulate an image shadow
  -sharpen geometry    sharpen the image
  -shave geometry      shave pixels from the image edges
  -shear geometry      slide one edge of the image along the X or Y axis
  -sigmoidal-contrast geometry
                       increase the contrast without saturating highlights or
                       shadows
  -sketch geometry     simulate a pencil sketch
  -solarize threshold  negate all pixels above the threshold level
  -sparse-color method args
                       fill in a image based on a few color points
  -splice geometry     splice the background color into the image
  -spread radius       displace image pixels by a random amount
  -statistic type geometry
                       replace each pixel with corresponding statistic from the
                       neighborhood
  -strip               strip image of all profiles and comments
  -swirl degrees       swirl image pixels about the center
  -threshold value     threshold the image
  -thumbnail geometry  create a thumbnail of the image
  -tile filename       tile image when filling a graphic primitive
  -tint value          tint the image with the fill color
  -transform           affine transform image
  -transparent color   make this color transparent within the image
  -transpose           flip image vertically and rotate 90 degrees
  -transverse          flop image horizontally and rotate 270 degrees
  -trim                trim image edges
  -type type           image type
  -unique-colors       discard all but one of any pixel color
  -unsharp geometry    sharpen the image
  -vignette geometry   soften the edges of the image in vignette style
  -wave geometry       alter an image along a sine wave
  -white-threshold value
                       force all pixels above the threshold into white

Image Sequence Operators:
  -append              append an image sequence
  -clut                apply a color lookup table to the image
  -coalesce            merge a sequence of images
  -combine             combine a sequence of images
  -compare             mathematically and visually annotate the difference between an image and its reconstruction
  -complex operator    perform complex mathematics on an image sequence
  -composite           composite image
  -crop geometry       cut out a rectangular region of the image
  -deconstruct         break down an image sequence into constituent parts
  -evaluate-sequence operator
                       evaluate an arithmetic, relational, or logical expression
  -flatten             flatten a sequence of images
  -fx expression       apply mathematical expression to an image channel(s)
  -hald-clut           apply a Hald color lookup table to the image
  -layers method       optimize, merge, or compare image layers
  -morph value         morph an image sequence
  -mosaic              create a mosaic from an image sequence
  -poly terms          build a polynomial from the image sequence and the corresponding
                       terms (coefficients and degree pairs).
  -print string        interpret string and print to console
  -process arguments   process the image with a custom image filter
  -separate            separate an image channel into a grayscale image
  -smush geometry      smush an image sequence together
  -write filename      write images to this file

Image Stack Operators:
  -clone indexes       clone an image
  -delete indexes      delete the image from the image sequence
  -duplicate count,indexes
                       duplicate an image one or more times
  -insert index        insert last image into the image sequence
  -reverse             reverse image sequence
  -swap indexes        swap two images in the image sequence

Miscellaneous Options:
  -debug events        display copious debugging information
  -distribute-cache port
                       distributed pixel cache spanning one or more servers
  -help                print program options
  -list type           print a list of supported option arguments
  -log format          format of debugging information
  -version             print version information

By default, the image format of `file' is determined by its magic
number.  To specify a particular image format, precede the filename
with an image format name and a colon (i.e. ps:image) or specify the
image type as the filename suffix (i.e. image.ps).  Specify 'file' as
'-' for standard input or output.

Wednesday, April 20, 2016

RubyPlus Podcast 3

Top Links for April 27

1. [Go faster - Benchmarks for your whole Rails app](https://github.com/schneems/derailed_benchmarks 'Go faster - Benchmarks for your whole Rails app')

Tools to benchmark a Rails app. It consists of:

    Static Benchmarking
    Memory used at require time
    Objects created at require time
    Dynamic app benchmarking
    Detecting memory leaks
    Dissecting a memory leak
    Get a heap dump
    My app is slow
    Memory is large at boot
    Is this perf change faster?

2. [Ability to add database comments](https://github.com/rails/rails/pull/22911 'Ability to add database comments')

It is possible to specify comments for tables, columns, and indexes in the database itself now with this addition. It currently works for MySQL and PostgreSQL adapters.

3. [`create_join_table` works with non-integer column types](https://github.com/rails/rails/pull/24221 'create_join_table works with non-integer column types')

Creating a join table with create_join_table helper used to always create the columns with integer type. But now if you want to have uuid columns or any other type, it's possible!

4. [15 Fundamental Laws of Software Development]( http://www.exceptionnotfound.net/fundamental-laws-of-software-development/ '15 Fundamental Laws of Software Development') by Matthew Jones

Linus's Law : "Given enough eyeballs, all bugs are shallow."

Occam's Razor : "Among competing hypotheses, the one with the fewest assumptions should be selected."

Hanlon's Razor : Don't assume people are malicious; assume they are ignorant, and then help them overcome that ignorance. Most people want to learn, not be mean for the fun of it.

The Pareto Principle : Have you even been in a situation where your app currently has hundreds of errors, but when you track down one of the problems, a disproportionate amount of said errors just up and vanish? If you have (and you probably have), then you've experienced the Pareto Principle in action. Many of the problems we see, whether coding, dealing with customers, or just living our lives, share a small set of common root issues that, if solved or alleviated, can cause most or all of the problems we see to disappear.

In short, the fastest way to solve many problems at once is the find and fix their common root cause.

Postel's Law : "Be conservative in what you do, be liberal in what you accept from others."

Hofstadter's Law : Nothing ever goes as planned, so you're better off putting extra time in your estimates to cover some thing that will go wrong, because it unfailingly does.

The 90-90 Rule : "The first 90 percent of the code accounts for the first 90 percent of the development time. The remaining 10 percent of the code accounts for the other 90 percent of the development time."

Parkinson's Law : "Work expands so as to fill the time available for its completion."

Dunning-Kruger Effect : "Unskilled persons tend to mistakenly assess their own abilities as being much more competent than they actually are."

5. Ruby 2.3.1 Released: A Bugfix Release. Minor bugfixes, no security fixes.

6. [How to Specify Local Ruby Gems in Your Gemfile](https://rossta.net/blog/how-to-specify-local-ruby-gems-in-your-gemfile.html 'Specify Local Ruby Gems') by Ross Kaffenberger

A look at using the bundle config command to develop against local gems instead of specifying a :path option in your Gemfile.

7. [A Guide to Ruby Gem Post-Install Messages](http://brandonhilkert.com/blog/ruby-gem-post-install-message/ 'Gem Post-Install Messages') by Brandon Hilkert

As gem authors, one of the ways we can provide important information to users of our gems is through post-install messages. This article explores what they are, how to set them up, what to include and when to use them.

8. [Unobtrusive JavaScript via AJAX in Rails](https://blog.codeship.com/unobtrusive-javascript-via-ajax-rails/ 'Unobtrusive JavaScript via AJAX') by Daniel P. Clark

9. [Ruby for Good](http://rubyforgood.org 'Ruby Event'): A Practical Ruby Event in Washington DC, June 16-19
The goal is to build projects that help local communities.

10. [Goruco 2016](http://goruco.com/ 'Ruby Conference')
A One Day Ruby Conference in NYC, June 25th.

11. [Rails 5: What's in It for Me?](https://www.youtube.com/watch?v=ECDX1NH7yWE 'Rails 5') video
An hour long presentation on Rails 5. Check out the podcasts section of rubyplus.com for the link.

12. [Rails 5 officially supports MariaDB](http://blog.bigbinary.com/2016/04/21/rails-5-official-supports-mariadb.html 'Rails 5 officially supports MariaDB') by Vipul

MariaDB is an open source fork of the MySQL database and it acts as a drop-in replacement for MySQL. After the Oracle’s take over of MySQL there was some confusion about the future of MySQL. To remove any ambiguity about whether in future MySQL will remain free or not MariaDB was started. To learn about the advantages MariaDB offers over MySQL checkout the podcasts section for the link to an article which lists 10 reasons to migrate to MariaDB from MySQL.

[Top 10 Reasons to Migrate to MariaDB](https://seravo.fi/2015/10-reasons-to-migrate-to-mariadb-if-still-using-mysql 'Top 10 Reasons to Migrate to MariaDB')



Tuesday, April 12, 2016

Sunday, April 10, 2016

Timeline of Products

2002 Passed UML Certification in May
2003 OOAD Certification Book and Videos $40. Clickbank
2004 a1-truckparts.net                       Adsense
     Started Programming Blog
2005 Static sites like problemsolvingskills.net hosted on hostmysite.com.
2006 Started to work with Rails
2007 12-12 rubyplus.org registered
     12-02 rubyplus.com registered
     Take over Silicon Valley Ruby Meetup
2008 rubyplus.org Jan  29 episodes
     May 2008 Over 75 Rails screencasts According to http://readwrite.com/2008/05/28/15_places_to_find_great_screencasts/
2009 First iPhone App Goes Live
2010 British Accent iPhone App, 3/10 iPad App approved
2011 Finance Site : $10k on content creation goes waste without any adsense revenue. $10k spent in demolition recycling research.
2012 TDD Workshops, In dec, registered clickplan.net
2013 rubyplus.com goes live
     clickplan.net goes live
     Jan clickplan.info blog goes live
2014 Upgrading Rails version and TB3 takes fucking too long and clickplan.net goes offline.
2015 TDD Course and Email Blast for rubyplus.com launch (Replusion vs Attraction), 3/15 TDD Course free coupon Tweets. Jan TDD in Ruby Kindle book published.

2007 July : Outdoor Adventure Club Event Management
2008  or 2009 Abandoned adventurelogic.net ?

Started selling ebooks and videos before the term screencast was coined in 2004. UML certification study guide sold from 2003 to 2006 for $49.99 ooad package and $17 test package.

Dot 1 : 2003

Selling ebook and videos using eBookPro and ClickBank. Learned about order processing and the end to end usage of digital products.

Dot 2 : 2005

Buying AssocTrac to manage affiliates. Learned about how the affiliate management software works and how to track the effectiveness of marketing campaigns. problemsolvingskills.net. Mistake: Developing the product before building the audience. Promotional posts on forums sounded spammy.

Dot 3 : 2007

Launched rubyplus.org. Screencasting with no time limitation and no continuous improvement. No lesson learned.

Dot 4 : 2010

First Mobile app hit. Learned about the power of the Internet in driving sales and the lifetime value of a customer.

Dot 5 : 2011

Read Millionaire in the Fast Lane. Learned how to apply filters to all the business ideas and narrow down to the most promising ideas to execute. 

Fastlane education is about learning specific skills to grow your business skill. Slowlane education is about increasing the intrinsic value of the person being educated.


It opened up the possibility. What if, I could increase my intrinsic skills and use that as the core of my business plan? I can teach other developers how to increase their intrinsic value. If I can help other developers make a six figure income, I can make million a year.

Dot 6 : 2013

First version of ClickPlan goes live. Infopreneur business success template. Learned that SaaS is very similar to selling infoproducts. It differs only in one aspect, the backend sales is not infoproduct but is a software that solves problems.

Dot 7 : 2016

Learned that consistently publishing video podcast that applies time limitation can be very effective in building an audience. Observing other players on how they apply Robert Cialdini's Principles of Persuasion.

It is too much effort to market 1-1. Focus on 1-N. Tweeting to each individual takes more time and money than targeting a few who can share the content with their followers.

Making the Connections

Dot 1 and 2 were the big picture view of the infopreneur business. Dot 4 is the technical 'How to' aspect of creating the product for that market. Dot 5 is the big picture of building a successful SaaS business.

Connect Dot 1-2-4 : 2013
Connect Dot 3-6 : 2016

Missing Pieces / Obstacles

Demo video. Marketing
Dot 4 - Implementation ...
2011
Distracted by Learn Startup crap.