Tech Guru Guide Bookazine 11 (Sampler)

Page 1

gem “therubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rai new todolist --skip-test-unit respond_to do |format| if @task.update_attributes(params[:task]) format.html { redirect_to @task, notice: ‘...’ } format.json { head :no_content } els format.html { render action: “edit” } format.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails generate migration add_priority_to_task priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_in_the_past error add(:due_at, ‘is in the past!’) if due_at < Time.zone.now #!/usr/bin/en python import pygame from random import randrange MAX_STARS = 100 pygame.init() screen pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = for i in range(MAX_STARS): star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] star append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use Time::HiRes qw(usleep use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1 $screen->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refres usleep 50000; gem “therubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rben rehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_attributes(params[:task]) format.html { redirect_to @task, notice: ‘...’ } format.json { hea :no_content } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails generate migration add priority_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_in the_past errors.add(:due_at, ‘is in the past!’) if due_at < Time.zone.now #!/usr/bin/en python import pygame from random import randrange MAX_STARS = 100 pygam init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = for i in range(MAX_STARS): star = [randrange(0, 639), randrange(0, 479), randrange( 16)] stars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use Time::HiRe qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + } while (1) { $screen->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”) $screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rai --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_attributes(params[:task]) format.html { redirect_to @task, notic ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rai generate migration add_priority_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the past def due_at_is_in_the_past errors.add(:due_at, ‘is in the past!’) if due_at < Time.zone.now #!/usr/bin/en python import pygame from random import randrange MAX STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = for i in range(MAX_STARS): star = [randrange(0, 639 randrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/pe $numstars = 100; use Time::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$ = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen >addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0” $ gem insta bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_attributes(params[:task]) format.htm redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unprocessable_enti } $ bundle exec rails generate migration add_priority_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server valida :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in the past!’) if due_at < Time.zone.now #!/usr/bin/en python import pygame from random impo randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = for i in range(MAX_STARS): star [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: exit( #!/usr/bin/perl $numstars = 100; use Time::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80 $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80 $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0” gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_attributes(params[:task format.html { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { render json: @task.errors, statu :unprocessable_entity } $ bundle exec rails generate migration add_priority_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ bund exec rails server validate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in the past!’) if due_at < Time.zone.now #!/usr/bin/en python impo pygame from random import randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = for i range(MAX_STARS): star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.typ == pygame.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use Time::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= $star_s[$i]; ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :development, :te do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_to do |format| if @tas update_attributes(params[:task]) format.html { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { rend json: @task.errors, status: :unprocessable_entity } $ bundle exec rails generate migration add_priority_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exe rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in the past!’) if due_at < Time.zone.now #!/us bin/en python import pygame from random import randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock stars = for i in range(MAX_STARS): star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame.even get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use Time::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” grou :development, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_ do |format| if @task.update_attributes(params[:task]) format.html { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” format.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails generate migration add_priority_to_tasks priority:integer $ bundle exec rak db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in the past!’) if due_ < Time.zone.now #!/usr/bin/en python import pygame from random import randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) cloc = pygame.time.Clock() stars = for i in range(MAX_STARS): star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) fo event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use Time::HiRes qw(usleep); use Curses; $screen = new Curses; noech curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < $numstars $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “therubyracer”, “~ 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-un respond_to do |format| if @task.update_attributes(params[:task]) format.html { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { render actio “edit” } format.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails generate migration add_priority_to_tasks priority:integer $ bundle exe rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in the past!’) due_at < Time.zone.now #!/usr/bin/en python import pygame from random import randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480

Fully revised & updated EDITion

learn to code fast today! • python • swift • perl • PHP • sql • unity • webgl

180 pages of tutoRials learn core coding techniques and advanced skills


em “therubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails sk.update_attributes(params[:task]) format.html { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { ren undle exec rails generate migration add_priority_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate : dd(:due_at, ‘is in the past!’) if due_at < Time.zone.now #!/usr/bin/en python import pygame from random import randrange MAX_STARS = 100 pygame.init() screen = pyg lock() stars = for i in range(MAX_STARS): star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame. n/perl $numstars = 100; use Time::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $s screen->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refres evelopment, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_ rmat.html { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unpro dd_priority_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_ Time.zone.now #!/usr/bin/en python import pygame from random import randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) cl TARS): star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pyg me::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “theru spec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_ otice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in th mport pygame from random import randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = f ndrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $nu screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen-> star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :dev stall bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_attributes(params[:task]) format o_content } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails generate migration add_priorit bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in the past!’) if due_at < Time.zone mport randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = for i in range(MAX_STARS): star = ars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use Time::HiRes qw(us et(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < $numstars ; $i++) 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0 rbenv rehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_attributes(params[:task]) format.html { redirect_to @task, notice: ‘...’ } format.json { h ormat.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails generate migration add_priority_to_tasks priority:integer $ bundle exec rake db:m erver validate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in the past!’) if due_at < Time.zone.now #!/usr/bin/en python import pygame from it() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = for i in range(MAX_STARS): star = [randrange(0, 639), randrange(0, 479), randrang vent in pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use Time::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --versio nit respond_to do |format| if @task.update_attributes(params[:task]) format.html { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { rende atus: :unprocessable_entity } $ bundle exec rails generate migration add_priority_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ ef due_at_is_in_the_past errors.add(:due_at, ‘is in the past!’) if due_at < Time.zone.now #!/usr/bin/en python import pygame from random import randrange MAX_ST ode((640, 480)) clock = pygame.time.Clock() stars = for i in range(MAX_STARS): star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while Tru pe == pygame.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use Time::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numst star_s[$i] = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star em “therubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails sk.update_attributes(params[:task]) format.html { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { ren undle exec rails generate migration add_priority_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate : dd(:due_at, ‘is in the past!’) if due_at < Time.zone.now #!/usr/bin/en python import pygame from random import randrange MAX_STARS = 100 pygame.init() screen = pyg lock() stars = for i in range(MAX_STARS): star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame. n/perl $numstars = 100; use Time::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $s screen->clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refres evelopment, :test do gem “rspec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_ rmat.html { redirect_to @task, notice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unpro dd_priority_to_tasks priority:integer $ bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_ Time.zone.now #!/usr/bin/en python import pygame from random import randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) cl TARS): star = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pyg me::HiRes qw(usleep); use Curses; $screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = numstars ; $i++) { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “theru spec-rails”, “~> 2.13.0” $ gem install bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_ otice: ‘...’ } format.json { head :no_content } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails bundle exec rake db:migrate $ bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in th mport pygame from random import randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = f ndrange(0, 479), randrange(1, 16)] stars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $nu screen = new Curses; noecho; curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen-> star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :dev stall bundler $ gem install rails --version=3.2.12 $ rbenv rehash $ rails new todolist --skip-test-unit respond_to do |format| if @task.update_attributes(params[:task]) format o_content } else format.html { render action: “edit” } format.json { render json: @task.errors, status: :unprocessable_entity } $ bundle exec rails generate migration add_priorit bundle exec rake db:migrate $ bundle exec rails server validate :due_at_is_in_the_past def due_at_is_in_the_past errors.add(:due_at, ‘is in the past!’) if due_at < Time.zone mport randrange MAX_STARS = 100 pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() stars = for i in range(MAX_STARS): star = ars.append(star) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use Time::HiRes qw(us et(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < $numstars ; $i++) 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group :development, :test do gem “rspec-rails”, “~> 2.13.0


Fundamentals Using Python, we’ll take you through essential coding steps 10

Different types of data How Python handles various variables

12

More Python data types Beyond the previous ones, of course

14

Reliability by abstraction Open your coding mind and think differently

16

Files and modules done quickly The easy way to break things apart

20

Write your own UNIX program Rewriting cat for fun and (no) profit

28

Neater code with modules Use them wisely for super-clean programs

30

Embrace storage and persistence Make your software remember things

32

Lock down with data encryption Look after your data and it will look after you

Coding Academy 2016 | 9

Fundamentals | Intro

s new todolist --skip-test-unit respond_to do |format| if @ nder json: @task.errors, status: :unprocessable_entity } $ :due_at_is_in_the_past def due_at_is_in_the_past errors. ygame.display.set_mode((640, 480)) clock = pygame.time. .event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/ star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { sh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group d_to do |format| if @task.update_attributes(params[:task]) ocessable_entity } $ bundle exec rails generate migration _in_the_past errors.add(:due_at, ‘is in the past!’) if due_at lock = pygame.time.Clock() stars = for i in range(MAX_ game.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < ubyracer”, “~> 0.11.4” group :development, :test do gem _attributes(params[:task]) format.html { redirect_to @task, generate migration add_priority_to_tasks priority:integer he past!’) if due_at < Time.zone.now #!/usr/bin/en python for i in range(MAX_STARS): star = [randrange(0, 639), umstars = 100; use Time::HiRes qw(usleep); use Curses; >clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= velopment, :test do gem “rspec-rails”, “~> 2.13.0” $ gem t.html { redirect_to @task, notice: ‘...’ } format.json { head ty_to_tasks priority:integer $ bundle exec rake db:migrate e.now #!/usr/bin/en python import pygame from random = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] sleep); use Curses; $screen = new Curses; noecho; curs_ { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] 0” $ gem install bundler $ gem install rails --version=3.2.12 head :no_content } else format.html { render action: “edit” migrate $ bundle exec rake db:migrate $ bundle exec rails random import randrange MAX_STARS = 100 pygame. ge(1, 16)] stars.append(star) while True: clock.tick(30) for curs_set(0); for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] _x[$i] = 80; } $screen->addch($star_y[$i], $star_x[$i], “.”); } ion=3.2.12 $ rbenv rehash $ rails new todolist --skip-tester action: “edit” } format.json { render json: @task.errors, bundle exec rails server validate :due_at_is_in_the_past TARS = 100 pygame.init() screen = pygame.display.set_ ue: clock.tick(30) for event in pygame.event.get(): if event. tars ; $i++) { $star_x[$i] = rand(80); $star_y[$i] = rand(24); r_y[$i], $star_x[$i], “.”); } $screen->refresh; usleep 50000; s new todolist --skip-test-unit respond_to do |format| if @ nder json: @task.errors, status: :unprocessable_entity } $ :due_at_is_in_the_past def due_at_is_in_the_past errors. ygame.display.set_mode((640, 480)) clock = pygame.time. .event.get(): if event.type == pygame.QUIT: exit(0) #!/usr/ star_y[$i] = rand(24); $star_s[$i] = rand(4) + 1; } while (1) { sh; usleep 50000; gem “therubyracer”, “~> 0.11.4” group d_to do |format| if @task.update_attributes(params[:task]) ocessable_entity } $ bundle exec rails generate migration _in_the_past errors.add(:due_at, ‘is in the past!’) if due_at lock = pygame.time.Clock() stars = for i in range(MAX_ game.QUIT: exit(0) #!/usr/bin/perl $numstars = 100; use = rand(4) + 1; } while (1) { $screen->clear; for ($i = 0; $i < ubyracer”, “~> 0.11.4” group :development, :test do gem _attributes(params[:task]) format.html { redirect_to @task, generate migration add_priority_to_tasks priority:integer he past!’) if due_at < Time.zone.now #!/usr/bin/en python for i in range(MAX_STARS): star = [randrange(0, 639), umstars = 100; use Time::HiRes qw(usleep); use Curses; >clear; for ($i = 0; $i < $numstars ; $i++) { $star_x[$i] -= velopment, :test do gem “rspec-rails”, “~> 2.13.0” $ gem t.html { redirect_to @task, notice: ‘...’ } format.json { head ty_to_tasks priority:integer $ bundle exec rake db:migrate e.now #!/usr/bin/en python import pygame from random = [randrange(0, 639), randrange(0, 479), randrange(1, 16)] sleep); use Curses; $screen = new Curses; noecho; curs_ { $star_x[$i] -= $star_s[$i]; if ($star_x[$i] < 0) { $star_x[$i] 0” $ gem install bundler $ gem install rails --version=3.2.12


Fundamentals | Write a program

Finish up your UNIX program Our guide to the Python programming language continues. This tutorial, we’re going to finish our clone of cat.

W

e’ve come quite a long way over the last two tutorials, having implemented the ability to echo the contents of multiple files to the screen, the ability to echo standard input to the screen and the ability to detect and act upon options passed by the user of our program. All that remains is for us to implement the line number option and to gather together everything else we’ve written into a single, working program.

nested for loops, although they’re not nearly as readable as object-oriented code. When building complicated programs, figuring out how to organise them so they remain easy to read, easy to track which variables are being used by which functions, and easy to update, extend, or add new features, can be challenging. To make this easier, there are various paradigms that provide techniques for managing complexity. One of these paradigms is the concept of object-oriented programming. In objectoriented programming, the elements of the program are broken down into objects which contain state – variables, in other words – that describe the current condition of the object, and methods, that allow us to perform actions on those variables or with that object. It’s a very natural way of thinking, because it mirrors the real world so closely. We can describe a set of properties about your hand, such as having five fingers that are in certain locations, and we can describe certain methods or things you can do with your hand, such as moving one finger to press a key, or holding a cup. Your hand is an object, complete with state and methods that let you work with it. We’re going to turn our cat program into an object, where its state records how many lines have been displayed, and its methods perform the action of the cat program – redisplaying file contents to the screen.

“It’s a very natural way of thinking because it mirrors the real world”

Objects Last time, we ended by saying that there are many ways we could implement the line counting option in our program. We’re going to show you how to do it in an object-oriented style, because it gives us an excuse to introduce you to this aspect of Python programming. You could, however, with a little careful thought, implement the same function with some

Python objects

Just to prove that it works, here’s our cat implementation, with all of the options being put to use.

24 | Coding Academy 2016

Python implements objects through a class system. A class is a template, and an object is a particular instance of that class, modelled on the template. We define a new class with a keyword, much like we define a new function: class catCommand: Inside the class, we specify the methods (functions) and state that we want to associate with every instance of the object. There are some special methods, however, that are frequently used. One of these is the init method. This is run when the class is first instantiated into a particular object, and allows you to set specific variables that you want to belong to that object. def __init__(self): self.count = 1 In this case, we’ve assigned 1 to the count variable, and we’ll be using this to record how many lines have been displayed. You probably noticed the self variable, passed as the first argument to the method, and wondered what on


The run method We next need to write a method that will execute the appropriate logic depending on whether certain options are set. We’ve called this the run method: def run(self, i, options): #set default options e = “” for line in i: #modify printed line according to options if options.showend: [...last time] if options.shownum: line = “{0} {1}”.format(self.count, line) self.count += 1 print(line, end=e) Notice that we’ve passed the self variable to this method, too. The two other arguments passed to this function are arguments that we’ll pass when we call the method later on, just like with a normal function. The first, i, is going to be a reference to whichever file is being displayed at this moment, while the options variable is a reference to the options decoded by the OptParse module. The logic after that is clear – for each line in the current file, modify the line depending on what options have been set. Either we do as last time, and modify the end character to be “$\n” or we modify the line, using the .format method that we suggested you research last time, to append the count variable, defined in the init method, to the rest of the line. We then increment the count and print the line. The most important part is the use of self. It lets us refer to variables stored within the current instance of the object. Because it’s stored as part of the object, it will persist after the current execution of the run method ends. As long as we use the run method attached to the same object each time we cat a new file in the argument list, the count will remember how many lines were displayed in the last file, and continue to count correctly. It might seem more natural – given the description of methods as individual actions that can be taken by our objects – to split each argument into a different method, and this is a fine way to approach the problem. The reason we’ve done it this way, though, is that we found it meant we could re-use more code, making it more readable and less error-prone. Now all that’s left to do is to tie everything together. We are going to do this by writing a main function. This isn’t actually required in Python, but many programs follow this idiom, so we will too: def main(): [option parsing code ...] c = catCommand() if len(args) > 1:

The completed program isn’t very long, but it has given us a chance to introduce you to many different aspects of the Python language.

for a in args: f = open(a, “r”) c.run(f, options) else: c.run(sys.stdin, options) We haven’t filled in the object parsing code from the previous tutorial, because that hasn’t changed. What is new is the c = catCommand() line. This is how we create an instance of a class – how we create a new object. The c object now has a variable, count, which is accessible by all its methods as the self.count variable. This is what will enable us to track the line numbers. We then check to see whether any arguments have been passed. If they have, then we call the run method of the object c for each file that was passed as an argument, passing in any options extracted by OptParse along the way. If there weren’t any arguments, though, we simply call the run method with sys.stdin instead of a file object. The final thing we need to do here is actually call the main function when the program is run: if __name__ == “__ main__”: main() These last two lines are the strangest of all, but quite useful in a lot of circumstances. The name variable is special – when the program is run on the command line, or otherwise as a standalone application, it is set to main; however, when it is imported as an external module to other Python programs, it’s not. In this way, we can automatically execute main when run as a standalone program, but not when we’re importing it as a module. n

“The last thing to do is call the main function when the program runs”

Coding Academy 2016 | 25

Fundamentals | Write a program

earth that was about. Well, it is the main distinguishing feature between methods and ordinary functions. Methods, even those which have no other arguments, must have the self variable. It is an automatically populated variable, which will always point to the particular instance of the object that you’re working with. So self.count is a count variable that is exclusive to individual instances of the catCommand object.


Python | Gimp plugin

Code your own Gimp plugin Use Python to add some extra features to the favourite open source imagemanipulation app, without even a word about Gimp masks.

M

ultitude of innuendoes aside, Gimp enables you to extend its functionality by writing your own plugins. If you wanted to be hardcore, then you would write the plugins in C using the libgimp libraries, but that can be pretty off-putting or rage-inducing. Mercifully, there exist softcore APIs to libgimp so you can instead code the plugin of your dreams in Gimp’s own Script-Fu language (based on Scheme), Tcl, Perl or Python. This tutorial will deal with the last in this list, which is probably most accessible of all these languages, so even if you have no prior coding experience you should still get something out of it.

Get started On Linux, most packages will ensure that all the required Python gubbins get installed alongside Gimp; your Windows and Mac friends will have these included as standard since version 2.8. You can check everything is ready by starting up Gimp and checking for the Python-Fu entry in the Filters menu. If it’s not there, you’ll need to check your installation. If it is there, then go ahead and click on it. If all goes to plan this should open up an expectant-looking console window, with a prompt (>>>) hungry for your input. Everything that Gimp

can do is registered in something called the Procedure Database (PDB). The Browse button in the console window will let you see all of these procedures, what they operate on and what they spit out. We can access every single one of them in Python through the pdb object. As a gentle introduction, let’s see how to make a simple blank image with the currently selected background colour. This involves setting up an image, adding a layer to it, and then displaying the image. image = pdb.gimp_image_new(320,200,RGB) layer = pdb.gimp_layer_new(image,320,200,RGB,'Layer0',100 ,RGB_IMAGE) pdb.gimp_image_insert_layer(image,layer,None,0) pdb.gimp_display_new(image) So we have used four procedures: gimp_image_new(), which requires parameters specifying width, height and image type (RGB, GRAY or INDEXED); gimp_layer_new(), which works on a previously defined image and requires width, height and type data, as well as a name, opacity and combine mode; gimp_image_insert_layer() to actually add the layer to the image, and gimp_display_new(), which will display an image. You need to add layers to your image before you can do anything of note, since an image without layers is a pretty ineffable object. You can look up more information about these procedures in the Procedure Browser – try typing gimp-layer-new into the search box, and you will see all the different combine modes available. Note that in Python, the hyphens in procedure names are replaced by underscores, since hyphens are reserved for subtraction. The search box will still understand you if you use underscores there, though.

Draw the line

You can customise lines and splodges to your heart’s content, though frankly doing this is unlikely to produce anything particularly useful.

40 | Coding Academy 2016

All well and good, but how do we actually draw something? Let’s start with a simple line. First select a brush and a foreground colour that will look nice on your background. Then throw the following at the console: pdb.gimp_pencil(layer,4,[80,100,240,100]) Great, a nicely centred line, just like you could draw with the pencil tool. The first parameter, gimp_pencil(), takes just the layer you want to draw on. The syntax specifying the points is a little strange: first we specify the number of coordinates, which is twice the number of points because each point has an x and a y component; then we provide a list of the form [x1, y1, …, xn, yn]. Hence our example draws a line from (80,100) to (240,100). The procedures for selecting and adjusting colours, brushes and so forth are in the PDB too: pdb.gimp_context_set_brush('Cell 01')


Python | Gimp plugin

pdb.gimp_context_set_foreground('#00a000') pdb.gimp_context_set_brush_size(128) pdb.gimp_paintbrush_default(layer,2,[160,100]) If you have the brush called ‘Cell 01’ available, then the above code will draw a green splodge in the middle of your canvas. If you don’t, then you’ll get an error message. You can get a list of all the brushes available to you by calling pdb. gimp_brushes_get_list(‘’). The paintbrush tool is more suited to these fancy brushes than the hard-edged pencil, and if you look in the procedure browser at the function gimp_paintbrush, you will see that you can configure gradients and fades too. For simplicity, we have just used the defaults/current settings here. Download the code pack from http://bit.ly/1RZp1WS and you will find a file linesplodge.py which will register this a fully-fledged Gimp plugin, replete with a few tweaks. For the rest of the tutorial we will describe a slightly more advanced plugin for creating bokeh effects in your own pictures. ‘Bokeh’ derives from a Japanese word meaning blur or haze, and in photography refers to the out-of-focus effects caused by light sources outside of the depth of field. It often results in uniformly coloured, blurred, disc-shaped artefacts

in the highlights of the image, reminiscent of lens flare. The effect you get in each case is a characteristic of the lens and the aperture – depending on design, one may also see polygonal and doughnut-shaped bokeh effects. For this exercise, we’ll stick with just circular ones. Our plugin will have the user pinpoint light sources using a path on their image, which we will assume to be singlelayered. They will specify disc diameter, blur radius, and hue

Applying our bokeh plugin has created a pleasing bokeh effect in the highlights.

“Our plugin creates a layer with ‘bokeh discs’ and another with a blurred copy of the image” and saturation adjustments. The result will be two new layers: a transparent top layer containing the ‘bokeh discs’, and a layer with a blurred copy of the original image. The original layer remains untouched beneath these two. By adjusting the opacities of these two new layers, a more pleasing result may be achieved. For more realistic bokeh effects, a part of the image should remain in focus and be free of discs, so it may

Coding Academy 2016 | 41


Python | Tkinter

Tkinter: Make a basic calculator Why not use Python’s default graphical toolkit to build a simple – yet easily extensible – visual calculator? Here’s a more practical example that creates a window with a title and two widgets, one of which quits the application when clicked: import tkinter as tk class App(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): self.hi = tk.Label(self) self.hi[“text”] = “Hello World” self.hi.pack(side=“top”) self.EXIT = tk.Button(self, text=“EXIT”, fg=“red”, command=root.destroy) self.EXIT.pack(side=“bottom”)

P

Quick tip The code in this tutorial is based on vegaseat’s Updated Tiny Tkinter Calculator, listed on DaniWeb.com (http://tinyurl. com/h3eotvf).

ython provides various options for developing graphical user interfaces, such as wxPython, JPython and Tkinter. Of these, Tkinter is the standard GUI library that ships by default with Python. Tkinter is the Python interface to Tk, the GUI toolkit for Tcl/Tk. Tk was developed as a GUI extension for the Tcl scripting language in the early 1990s. One of the reasons for its popularity is that it’s easier to learn than other toolkits. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit. To use Tkinter, you don’t need to write Tcl code, because Tkinter is a set of wrappers that implement the Tk widgets as Python classes. Creating a GUI application using Tkinter is an easy task. We begin by first importing the Tkinter module, which is then used to create the graphical app’s main window. Next we add one or more of the supported widgets (see box opposite) to the main window, before entering the main event loop to take action against each event triggered by the user. For example, the following code will display a window: import tkinter as tk window = tk.Tk() # Insert code to add widgets window.mainloop()

60 | Coding Academy 2016

root = tk.Tk() app = App(master=root) app.master.title(‘Sample Application’) app.master.geometry(“250x70+550+150”) app.mainloop() We’ll explain the individual elements of the code as we build our calculator. For now, it’s important to note that we’ve explicitly created an instance of Tk with root = tk.Tk() . Tkinter starts a Tcl/Tk interpreter behind the scenes, which then translates Tkinter commands into Tcl/Tk commands. The main window of an application and this interpreter are intrinsically linked, and both are required in order for a Tkinter application to work. Creating an instance of Tk initialises this interpreter and creates the root window. If you don’t explicitly initialise it, one will be implicitly created when you create your first widget. While this is perfectly fine, it goes against the spirit of Python, which states that ‘explicit is better than implicit’.

Graphical calculator As you can see, it doesn’t take much effort to drape a Python app with a graphical interface. We’ll use the same principles to write our graphical calculator. We’ll add various widgets to our calculator, including an editable display, which can be used to correct mistakes and to enter symbols and hexadecimals not on our calculator’s keypad. For example,


if you enter 0xAA, it’ll print the decimal equivalent, that is 170. Similarly, the editable display can also be used to manually type in functions that aren’t represented on the keypad but are defined in Python’s math module, such as the logarithmic and trigonometric functions. Furthermore, our calculator will also have the ability to temporarily store and retrieve a result from its memory bank. The complete code for the calculator is available online. Let’s dissect individual elements to get a better grasp of the Tkinter library and its interactions with Python. import tkinter as tk from math import * from functools import partial class Calculator(tk.Tk): def __init__(self): tk.Tk.__init__(self) We begin by importing the various libraries and functions for our calculator. Besides the Tkinter toolkit, we’ll also need the math library to handle the calculations. The partial function from the functools module helps us write reusable code. We’ll explain how we’ve used it later in the tutorial. After importing the libraries, we begin defining the Calculator class. To begin with, we initialise the instance

variables with the __init__ method in the class body. This method is executed automatically when a new instance of the class is created. Python passes the instance as the first argument, and it is a convention to name it self. In other words, the __init__ method is the constructor for a class in Python. The basic idea is that it is a special method, which is automatically called when an object of that class is created. So when you call Calculator() , Python creates an object for you, and then passes it as the first parameter to the __init__ method. The self variable and the __init__ method are both OOP constructs. The self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object, but Python does not. You have to declare it explicitly. When you create an instance of the Calculator class and call its methods, it will be passed automatically. It is important to use the self parameter inside an object’s method if you want to persist the value with the object.

Define the layout The first order of business is to create the graphical interface for the calculator. In this section we define different parameters for the positioning and appearance of our

Commonly used Tkinter widgets The Tkinter toolkit supports over a dozen types of controls or widgets that you can use in your graphical application. Here are some of the most commonly used ones. The Button widget is used to create buttons that can display either text or images. You can define a function for a button, which is called automatically when you click the button. The Checkbutton widget is used to display a number of options to a user as toggle buttons, and can also display images in place of text. Similarly, the Listbox widget is useful for displaying a list of items from which a user can select multiple options. The Message widget provides a

multiline and non-editable object that displays texts. Then there’s the Menubutton, which creates the part of a drop-down menu that stays on the screen all the time. Every menubutton is associated with a Menu widget, which can display the choices for that menubutton when the user clicks on it. The Menu widget can create different types of menus, including pop-up, toplevel and pull-down. The Scrollbar widget provides a slide controller that is used to implement vertical scroll bars on other widgets, such as Listbox, Text and Canvas. You can also create horizontal

scrollbars on Entry widgets. The Canvas widget creates an area that can be used to place graphics, text or other widgets. All these widgets have the same syntax: w = <widgetname> (parent, option1=value, option2=value, ... ) Similarly, they also share several options, such as the ones to define background colour ( bg ), the type of border ( relief ), and the size of the border ( bd ). Refer to the Tkinter documentation (http://infohost.nmt.edu/ tcc/help/pubs/tkinter/web/index.html) for a list of all the options supported by each of these widgets.

Coding Academy 2016 | 61

Python | Tkinter

Tkinter makes it relatively easy to build a basic graphical calculator in Python.


Databases | Riak NoSQL Everything you wanted to know about NoSQL, but were too afraid to ask. Discover why admins love this high-speed system.

T

he world of databases moves slowly (but perhaps not when transacting), so when a revolution hits it can take decades for the repercussions to be felt. Coined back in 1998, NoSQL are databases that started life not using the then standard query language SQL. But more revolutionary the actual database designs themselves, moved away from the standard relational model altogether for speed and ease of design. As you might expect by the name, even though NoSQL databases were originally designed not to use SQL, they can now, instead they use various different query languages. While these originally might have appeared in 1998, NoSQL didn’t gained prevalence until the late Noughties when it was adopted as a rallying Twitter hashtag for a group of non-relational distributed database projects that were after something small and unique.

If you are wondering whether or not it’s worth considering NoSQL databases, you should be aware that according to DB-Engines Ranking (https://db-engines.com/en/ ranking), MongoDB, a popular NoSQL database, is currently the fifth most popular after Oracle, MySQL, Microsoft SQL Server and PostgreSQL – and even Oracle has a NoSQL version of its famous database. The problem with relational databases is that in order to store complex information you

The next logical step is to use many machines to run your database, but that also creates a problem because relational databases were originally designed to run as single-node systems. So, large companies, such as Google and Amazon, developed their own database systems, Bigtable and Dynamo respectively, that were quite different from traditional relational database systems, and which inspired the NoSQL movement. It’s quite difficult to define what a NoSQL database is but there are common characteristics among NoSQL databases: they are non-relational; open source (although not always); schemaless; easy to be distributed on many machines (again, not always) and trying to serve data from the 21st century web culture. So, NoSQL databases are designed for the web and don’t support joins, complex transactions and other features of the SQL language. Their terminology is also a little different, but lets dive into the details.

“NoSQL DBs are designed for the web and don’t support joins and complex transactions…”

110 | Coding Academy 2016

have to deconstruct it into bits and fields, and store it in lots of different tables. Likewise, in order to restore the data, you have to retrieve all those bits and fields and put them back together. Neither of those two tasks is efficient particularly if you have a big and busy website that’s storing and querying data all the time.


Installing Riak Every Riak server has a web interface. In this case, we’re accessing the server statistics, using http://localhost:10018/stats/ The port number and IP are defined in riak.conf.

The main advantage of a NoSQL database is that they are suited to and efficient for big data and real-time web applications. They also offer easy scalability, and enable you to implement high availability painlessly. They are also generally easier to administer, set up and run, and they can store complex objects. Additionally, it’s easier to develop applications for and with NoSQL databases. Their schema can change easily without any downtime because, in reality, they have no schema. Most of them, with the exception of Oracle NoSQL, are open source projects. Key disadvantages of NoSQL databases include the fact that they require a totally new way of thinking and that you still need a DBA on large and/or critical projects. If your company needs to use both SQL and NoSQL databases, you will have two entirely different systems to program and administer and therefore will need even more people. Being relatively new, they are not as mature as relational databases; therefore choosing a NoSQL database for a critical problem may not always be the safest solution, but this will not be a problem in a couple of years. The last disadvantage is the fact that although they look like they have no schema, you will need to assume an implicit schema in order to do some serious work with your data. This isn’t unexpected because as long as you are

working with data, you cannot get away with having a schema, even an informal one. There are several kinds of NoSQL database each of them being good in one or more areas but not all. You can categorise NoSQL databases according to their data model: Document This is a very common data model. It thinks of the database as a big storage for documents where each document is a multipart data structure that’s usually represented in forms of JSON. You can still store documents in any format you want. MongoDB, CouchDB and RavenDB are representative document NoSQL databases. Key-Value This is also a common data model that’s similar to the hash map data structure, where you have a key and you ask the database to return the value stored for that particular key. The value can be anything from a single number to a whole document. The database knows nothing about the stored data. Examples of key-value NoSQL databases include Riak, Redis and Project Voldemort. Column-family This is a rather complex data model. You have a ‘row key’ that enables you to store and access multiple column families. Each column family is a combination of columns that fit together. Row keys must be unique within a column family. The data model might be more complicated than the others but it results in faster retrieval times. Examples

The first thing you should know before installing Riak is that you need Erlang on your system. The best way to install Riak is by compiling it from source because you have better control and a totally autonomous build of Riak. Follow the next steps: $ wget http://s3.amazonaws.com/ downloads.basho.com/riak/2.0/2.0.2/riak2.0.2.tar.gz $ tar zxvf riak-2.0.2.tar.gz $ cd riak-2.0.2 $ make rel Alternatively, you can get the Riak source code from GitHub and compile it as before: $ git clone git://github.com/basho/riak.git $ cd riak $ make rel Both ways should work without any particular problems; we used the first way to compile Riak. After successfully compiling Riak, you can find its main binary files inside the ./rel/riak/bin directory. In the same directory that you build Riak, you can run make devrel and get eight ready to run Riak

Generating a Riak cluster with five nodes is pretty easy, see p113 for details.

Map and Reduce MapReduce is an advanced querying technique and a tool for data aggregation used in NoSQL databases. It’s an alternative technique for querying a database that differs from the usual declarative querying techniques. You give instructions to the database on how to find the data you are looking for and MapReduce tries to find the data. (See the top of p112 for a simple

example of how MapReduce works.) Using MapReduce can be very tricky sometimes. Nevertheless, it enables you to create queries that would have been extremely challenging to create using SQL. Once you understand the MapReduce process and practice it, you will find it both very reliable and handy. The MapReduce solution

takes more implementation time but it can expand better than an SQL solution. It provides some flexibility that’s not currently available in the aggregation pipeline. The tricky thing is deciding whether or not the MapReduce technique is appropriate for the specific problem you are trying to solve. This kind of knowledge comes with experience!

Coding Academy 2016 | 111

Databases | Riak NoSQL

of column-family NoSQL databases include Cassandra and Apache HBase. Graph This model is totally different from the other three as it is based on the Graph structure. As a logical consequence Graph NoSQL databases handle hierarchies and relationships between things very well; doing similar things with a relational database would be an extremely challenging and slow task. Neo4j is a graph NoSQL database. For this article, we’ll be using Riak as our NoSQL database test case.


Reference | Loops

Using loops and using loops If we have explained how to use loops adequately, move to the next page. Otherwise, try reading this again.

A

If you want to build your own C++ application, add the source code to a text file and build it with the command ‘g++ helloworld. cpp -o helloworld’. Just run ‘./ helloworld’ to see the results.

fter losing ourselves in the surprisingly complex domain of using numbers in our code, we’re returning to a simpler concept. It’s the idea of a loop, and how programmers use them to solve problems. A loop, in the programming sense, is a chunk of the same code that’s designed by the programmer to be run over and over again. It’s different from a function or a method, because while they’re both designed to be re-run over and over again too, they’re self-contained islands of logic. With a method or a function, the programmer needs to know only what input is needed and what output to expect. Everything else should be handled by the function. A loop is a much more primitive construction, and without loops almost any programming task would become impossibly tedious. This is because they encapsulate what computers do well: repetition and iteration. Without loops, programmers are forced to write everything in longhand, and write code that can’t accommodate unknown values or sizes. It’s the difference between sowing a field by hand or by using Jethro Tull’s horse-drawn seed drill. Loops are so integral to code, we’ve already used several of them in our examples in previous tutorials in this bookazine. They’re used as counters, as ways to step through data, for when you need to wait for a condition, and for filling arrays and files. But we’ve not spent any time discussing the various kinds of loops you can implement, or how you might attempt to solve a linear

172 | Coding Academy 2016

problem by adding a loop in your code. In many ways, they’re related to the idea of recursion. But where a loop or function in recursion calls another instance of itself, usually to build a more complex solution, a loop on its own is used mostly to solve a simple calculation, or for waiting for a specific condition. Which is why, perhaps, the most common loop combines a conditional statement within a loop’s structure – and that’s the for keyword. The for loop is one of those peculiar parts of any language, because it requires a specific syntax that doesn’t feel that logical. In the case of Python, a typical for loop looks like the following: >>> for i in range (5): ... print (i) ... 0 1 2 3 4 You can see in this snippet that the initial for statement requires a variable, which for some reason is nearly always called i in examples. Ours is no exception. This is followed in Python by the phrase in range (5). Range is a special keyword in Python that we’ll revisit in a couple of paragraphs. On the following line, we print the value of i. This line needs to be tabbed or spaced in because it’s going to be executed as part of the for loop (as denoted by the :). But without prior experience, you can’t really guess at the output from the syntax of the for loop, and it’s the same with other languages. This is because for is slightly different from most loops, because it includes the implicit definition of a variable. You just have to accept that whatever syntax they do use does the equivalent of defining a variable and creating an acceptable set of circumstances for the execution of your program to leave the loop. In our previous example, the variable i iterates between 0 and 4, leaving the loop when it gets to 5 (a total of five steps when you include zero). We print the value of i within the loop so you can see what’s happening. If you write the same thing in C or C++, the syntax looks slightly different, but it gives you a better insight into what’s happening: for ( int i=0 ; i < 5 ; i++ ){ cout << i << endl; } When compiled, linked and run (this is the big difference

“Without loops, almost any programming task would become impossibly tedious”


Infinite loop If you don’t need the iteration of a for loop, the best alternative is a while loop. This includes only the conditional check, and you’re free to make that check positive in any way you choose. You could easily emulate the behaviour of a for loop, for example, by making the while loop wait for a variable to reach a certain value. Then, within your block of code, make sure your calculations attain that value at some point. In Python, we could recreate the previous for loop using while, like this: >>> i = 5 >>> while i > 0: ... i -= 1 ... print (i) ... 4 3 2 1 0 It’s simpler this way, and by using while you can make the conditional checks for leaving a loop as complex as you need, rather than adhering to those required by for. Another trick in other languages, but not Python, is to place the conditional checking at the end of the block of code. This is normally called a do...while loop, because the do is used to start the section and the while is used to close the section. Most importantly, the while statement at the end of the loop is checking the condition, such as ‘do the washing up while there are still some dirty plates’. This can be helpful in certain circumstances, such as when you want the loop to take some input and then only test against that input at the end of the test. In C++, this function would look like this:

Reference | Loops

between compiled languages such as C/C++ and interpreted languages such as Python and JavaScript), the output is identical to our Python example from earlier. In the C++ code, the variable i is declared as an integer (int) and incremented (i++) one value at a time for as long as it remains less than 5 (<5). This is exactly what the Python loop is doing, and the cout line is simply printing out the value of i during each iteration. You should be able to see from this that both the value of i and the value checked for by the condition can be changed, so you could get the value of i to count down instead by changing the loop to: for ( int i=5 ; i > 0 ; i--){ cout << i << endl; } To do the same in Python, we need to take a closer look at the range keyword used in the first example. Range is a function in Python that takes a start point, a stop point and a step size, much the same as the inputs for a C++ for loop. It’s also much more versatile, as you don’t need to restrict yourself to numbers – range can use indices of a sequence. If you put on one value in the range, as we did in the original loop, the function counts from zero up to the value -1. However, anything else will create a different effect. The advantage of farming it out to a function is that you’re no longer restricted to using it in just the for loop, and you’ll find many programmers use range for convenience throughout their code. If you wanted to count down in Python, for example, you could modify the for loop, as follows: for i in range(5, 0, -1): print (i)

char c; do { cin >> c; } while (c != ‘x’); This example is oversimplified, and isn’t useful in itself, but it illustrates one example where do...while works well, and that’s taking input. If you want to check the state of some input, whether it’s from a file or from someone typing on the keyboard, you need to have first grabbed the input. You could do this in a normal while loop by asking for the input before you enter the loop, but it’s slightly more efficient and elegant if you use a do...while loop to encapsulate the entire function. This is all the above loop is doing in C++. It grabs some input from the keyboard using cin, and waits for that input to consist only of the x character, after which it quits the loop. Another common use for while is to create what’s known as an infinite loop – simply a loop that never satisfies its exit condition. This might sound like insanity if you ever want the processor to skip over the remainder of your code, but there are certain times, and languages, where the use of an infinite loop is the best way of building your application. One example is if you want to build a tool to monitor the state of a server or some other service. You also find infinite loops watching hardware inputs or controlling the rendering within a game engine. Using an infinite loop means you can be sure your application is running, and hasn’t exited under some other condition, and using while is probably the easiest way of creating one. while (true) {} is all that’s needed. However, many languages also provide an escape from loops like this, and that’s using something called the break command. break can be used to escape from an infinite loop, as well as leaving other kinds of loops early if you need to. You might want to escape from a for loop quickly, for example if you have detected that the user wants to quit the application. Using break, the execution of your code continues after the loop section, and you’d normally use this section of code to tidy up files, processes and memory before an exit. Of course, there’s a good case for arguing against infinite loops, and building into your code the ability to escape on a specific condition, but this can take more effort and might not be as efficient, especially for smaller applications. n

Python is still a great language to learn with because it lets you experiment and see results as soon as you’ve typed your code.

Quick tip Nearly all languages count zero as a value, such as the first position in an array. This seems illogical at first, because we’re used to thinking of zero as nothing, but it’s just something you have to get used to.

Coding Academy 2016 | 173



Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.