28 February 2017

Git | Github | Summary and get started

Quick setup

  • Install git, sudo apt-get install git
  • Create Github account
  • In terminal, generate SSH key cd ~/.ssh && ssh-keygen leave passphrase empty, just press enter until the key is created
  • While still in ssh directory, cat id_rsa.pub and copy the entire key
  • Go to your Github setting, SSH and add SSH. paste the key in the key field. Give it a proper name and save
  • Go back to terminal, setup username and email on git git config --global user.name "john" and git config --global user.email "john.doe@gmail.com" Remember the username and email address muss be the same as the ones used for Github account
  • Go back to Github, create a new repository.
  • Now go to the folder of your application. cd /path/of/your/application and run these command
  • git init
  • git add -A
  • git commit -m "any message e.g. 'my first commit'"
  • Add your ssh URL or copy paste from your Github repository page git remote add origin ssh://login@IP/path/to/repository
  • git push -u origin master

27 February 2017

Javascript | Important functions

  • document.querySelctor('.class_name') using query selector you can grab the html tags by its class
  • example of query selector and event listener within a module
    'click' in above example is the type of listener. You can find any kind of listener on this event reference
  • To add an event listener to any key of a keyboard e.g. 'Enter' (13) key, you can do it like this:
  • change keyCode to any code of the keyboard.
    You can find the code of any key of your keyboard from keycode.info

Important concept or features in programming languages.

Ternary operator

Javascript: var result = (condition) ? (value1) : (value2) ; in this code, the 'var result' will have either 'value1' or 'value2' depend on the condition provided.

Javascript | Basic Knowledge

IIFE

IIFE or 'immediately invoked function expression' is basically an anonymous function wrapped in parenthesis.

add function is private and publicTest is a public function
variable x is still exist even though the anonymous function has already returned. This is possible thanks to the power of 'closure'. All variables inside the IIFE are private and the functions inside the return statement are public.
IIFE can also have arguments like this:
Go to browser console and call 'hello' to see the output

Closures

In Javascript you can have nested functions or function inside a function. The inner functions will have access to all variables of the parent function. This feature, combined with IIFE build another Javascript feature called 'closure'.

Modules

Javascript doesn't natively support classes. To implement classes in Javascript, we use modules. To create a module, we combine self-invoking function (IIFE), encapsulation and closures altogether
Three modules in an application. The third module connected the other modules

Callback function

Callback function is basically a function that is passed to another function as a parameter or an argument. Do not attach the ( ) (function brackets) to the callback function, because the function will be called only if the parent function is called. So the calling process is done by the parent function. 
ctrlAddItem is passed as parameter. No function brackets needed.

24 February 2017

How to access your windows documents folder from the ubuntu bash

  1. make sure you are in root. cd ~
  2. type in cd /mnt and ls to list the content
  3. Now you can go to the volume where your data stored using cd path/../
  4. To go to 'Documents' from root, cd /mnt/c/Users/YourUserName/Documents

How to install Ubuntu linux bash on windows 10

As developer, it sometimes easier to use bash to do some process. e.g. it's easier to install Git from the bash and also it's easier to commit a file or create and delete a branch from the command line.

Steps:
  1. Go to start >> settings >>  Update & security
  2. Go to For developers and active the Developer mode radio button. 
  3. Go to Programs and Features >> Turn Windows features on or off
  4. Select the check box on Windows Subsystem for Linux(Beta)
  5. Reboot your computer
  6. To use the bash, go to start, type in "Ubuntu" or "bash"

22 February 2017

Python | Basic Syntax And Rules

Indentation

  • Very important! in Python indentation is relevant! see this examples:
  • Indentation is correct!
    Wrong indentation gives different result

Operators

  • To check if one variable is exist in another variable, use in
  • To check if a variable is equal to a specific value, use is
  • in and is
  • In python, 5 ** 3 means 5 to the power of 3 and it will return 125 as a result
  • In python and most of programing languages, \n means 'new line'. But how if we want to print out a path like this "C:\Arkad\Desktop\notepad"? if you write print("C:\Arkad\Desktop\notepad") you'll get this result:
  • \n means newline
    To avoid this, put 'r' before the quote sign. like this print(r"C:\Arkad\Desktop\notepad")
    put 'r' before the quote sign
  • In Python you can do 'multiplication' operations with strings name = "John" and name * 5 this will return "John John John John John"
  • To create an array or a list, variable = [12 , 15 , 10 ]
  • To add elements to a list, variable + [10 , 9]
  • how to add items to a list
  • In Python, colon operator like this variable[0:2] will return the first and second elements of the list. it means index '2' is not included. This is different to e.g. Matlab where an array is started with number '1' and the colon operator include the number coded

String format

  • The number inside the curly brackets refers the index of the arguments inside the round brackets. '0' means the first argument etc.
  • '{2}' means 'third argument'

Looping

  • For loop in Python can be very flexible. Look at this code:

Ruby on Rails | Production

Add Admin role in Production

  • Go to heroku console heroku run rails console grab the user you want to set to admin. user = User.find(id) or user = User.first and use this command to toggle the admin from false to true. user.toggle!(:admin)
  • Rails console at heroku

21 February 2017

MatLab | Basic Knowledge

Arrays and Metrices:

  • Variable for one dimensional vector should be start with lowercase.
  • Variable for two dimensional vector (matrix) should be start with Uppercase.
  • Scalars is  one by one matrices. 
  • Not like java or ruby, the first element of an array in Matlab is indexed by number 1
  • Let say x is a 3x3 matrix. X(2,2) return the element from second row and second column. If you want to change the value, simply assign a new value. X(2,2) = 5
  • If a variable XYZ doesn't exist and you type in a command XYZ(2,2) = 3 Matlab will give you 2x2 matrix with XYZ(2,2) equals to 3 and rest elements of 0
  • X(2,[1 3]) gives you the 1st and the 3rd elements of the second row of a matrix.
  • X([1 2],2) gives you the 1st and the 2nd elements of the second column of a matrix.
  • For matrix multiplication the inner dimension muss be equal. 5x3 matrix * 3x4 matrix works just fine. but 5x3 matrix * 2x4 matrix gives you an error.
  • Use randi( maxNumber , numberOfRow , numberOfColumn) to create a random matrix of integers
  • let say X is a matrix. X^2 means X*X or matrix multiplication. and X.^2 means to square each element of X. And X.^Y means to tell Matlab to exponentiate each element of X to the power of element of Y of the same index. 
  • Use find(A); to find all non zero elements of matrix A. The output of this function is a vector containing linear indices of each non zero elements in matrix A
  • Elements with index: 1, 3, 5 and 7 are not zero

Operators:  

  • Colon ':' operator: x = 1 : 3 : 7 means we tell Matlab to create row vector start from 1 increment it by 3 till its maximum of 7. it will give you a result x = 1 4 7
  • Colon operator is very useful to create an array of odd or even numbers 1:2:7 will return an array of odd numbers[1, 3, 5, 7]
  • Colon operator can also give you an array in a decreasing order. 10:-3:1 will return [10, 7, 4, 1]
  • ints = 1 : 10 means give me an array of numbers from one to ten
  • A * B or mtimes(A,B)means matrix A times matrix B. A .* B or times(A,B)
  • More operator can be found in Matlab Operators
  • size(variable) gives you the size of a matrix. e.g. x = [3 2 4 ; 2 5 6] and size(x) gives you ans = 2 3 matrix of 2 rows and 3 columns 
  • Any scalar for. e.g. x = 2 and size(x) gives you ans = 1 1 since in Matlab scalar is one by one matrix.
  • Some operators can also be written as a function: plus(1,2) means 1+2 ans = 3and colon(1,7) gives you [1, 2, 3, 4, 5, 6, 7]

Function handles

Function handles are Variables that allow you to invoke a function indirectly. Using function handles you can pass a function as a parameter of another function. For example I have a function f(x)=3x^4 - 2x^2
And we want to pass this function to another function like this:
Now if you try to call the function using diffQuotF(f, x0, h) you'll get an error message.
The right way to pass the ' f ' function as a parameter is by using the @ (at) sign before the ' f '. like this:

Git | Github | Basic Knowledge

  • If we work on feature of an application, we have to be careful that changes that have been made aren't going to break the application. In Git, we have a master branch where the application is stored in production and we can also have a feature branch to work on a feature in development. Any changes made in this branch will not affect our master branch. this allows many developers to work on different features of an application without touching the application in production. 
  • to create a new branch type in this command in the application directory: git checkout -b branchName
  • To check in what branch you are currently in and to see all existing branches in git: git branch (your current location will be marked with asterisk)
  • To go back to master branch: git checkout master
  • When creating new branch, keep in mind that you cannot "git push" from your new branch. You'll have first to create a new branch in your github. You can use this one command line to set up a new branch and pushing all at once: git push --set-upstream origin yourNewBranch
  • If you're using Rubymine and you want to merge your branches. I recommend to use merging function from Rubymine interface, not from terminal. I often have merging issues wenn merging from terminal. 
  • Merging is done from the master-branch otherwise changes wont be merge to master and you'll get a message "branch is already up to date.

Useful Command Line

  • To delete a branch (if you're in master branch): git branch - d branchName
  • To delete a folder in git but not in local git rm -r --cached myFolder

Ruby on Rails | Data Base

Database

  • IDs columns are mostly generated by rails.
  • To create a single migration use this command: rails generate migration create_tableName >> e.g. rails generate migration create_articles
  • after generating migration, you'll need to add column to your table. By adding it to your migration file. When you're finished type in: rake db:migrate
  • To create table and everything related to it, you can simply type in this command line: rails generate scaffold Tablename firstColumn:dataTyp secondColumn:dataTyp >> e.g. rails generate scafold User username:string email:string
  • A scaffold in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
  • To migrate your database type in: rake db: migrate
  • Migrations are a convenient way to alter your database schema over time in a consistent and easy way. They use a Ruby DSL so that you don't have to write SQL by hand, allowing your schema and changes to be database independent.
  • In 'rails console' you can change the data of your database using ruby code. For example, in the 'users' table you can grab any user by 'user_id' using User.find(userID) or if you want to toggle any Boolean information in your database, you can use this code: user = User.find(1) and user.toggle!(:admin) this code will change admin status of user 1 to true or false. change User and :admin to your need

Validation

  • Validations are added in model class. 
  • Example of validations of presence and length: validates :username, presence: true, length:{minimum: 3, maximum: 25}
  • Example of validations of uniqueness: validates :email, uniqueness:{case_sensitive:false}
  • If you want that all emails are to be formatted to lowercase in your database, simply add before_save {self.email = email.downcase} to your User model.
  • more example: http://guides.rubyonrails.org/active_record_validations.html

Association

  • To create foreign key association when creating scaffold, type in: rails generate scaffold TableName firstColumn:dataType secondColumn:dataType tableTobeAssociated:references >> e.g. rails generate scaffold Comment description:text user:references 
  • Now we know that association has been made between users and comments, we might want to explicit some details of association. for example we want to tell our database that a user can have many comments, we have to add this line to the User model: has_many :comments
  • If you want to associate two tables manually, you will have to make some changes to the model of each table. In the User model, we have to add has_many :articles ; and in the Article model, we have to add belongs_to :user
  • This will store the userID in your table whenever a comment is made.

 

Useful command line

  • To go to rails console for testing your database : rails console
  • To exit the console: exit
  • To see the existing routes: rake routes
  • To destroy scaffold in case you made mistakes: rails destroy scaffold TableName
  • You have to be in your app directory before using all this command.

Ruby on Rails | Secure password

To store a secure password we have do the following:
  • add gem 'bcrypt' in application gemfile
  • add has_secure_password method in model (user.rb)
  • add password_digest of type string in the table attribute (users)

Ruby on Rails | Gemfile

Useful command line

  • bundle install --without production to install the gem in development environment.

Ruby on Rails | Routes

The Rails router recognizes URLs and dispatches them to a controller's action. It can also generate paths and URLs, avoiding the need to hardcode strings in your views.

-Rails Guide-
If you type in www.example.com in your browser, this request will be sended to your webserver. Your router (routes.rb) recognize the URLs as a root, and dispatches it to whatever Controller's action you've specified in your routes.rb file. root 'pages#home' will dispatch your request to PagesController and call the home action.

If you have a form in your page, you will need to have a route so whenever you pressed the submit button, it will understand what action to perform.

To add routes you can add this code to your routes.rb file: resources :pluralObjectName e.g. resources :photos this will create 7 different routes in your application. You can also create any route manually. for a form for example, you can add post 'users', to:users#create" with this whenever you press submit, it will call the 'create' action in the UsersController and eventually redirect user to the page you've specified in the UsersController

Ruby on Rails | Partials

If you have exactly or almost exactly the same code in different places, you can make one generic code of them and use it as a template using partials.

Examples

  • In views folder, you might have the same code for a form in  new.html.erb and edit.html.erb. You can create another file named _form.html.erb and put all the same lines of code in it. In the original place, you can replace the code with <%= render 'file_path' %> please keep in mind that the path should begin with folder name where the file is located.
  • In your partial template, you can also declare variables and you can assign the value of the variable in the target page like this <%= render 'file_path' , variableName: value %>
  • Now and then you will have the situation where the codes are exactly the same except one or two lines. Fortunately rails give us method to handle this. e.g. you want to have different label for a button; on the new page you want it to be labeled "create" and on the edit page you want it to be labeled "update". Simply modify your code into this: <%= f.submit(@user.new_record? ? "sign up" : "update your account" %>

Ruby on Rails | Action Controllers

Things to know

  • Controller are connected to the view by the actions defined in it. If you declare a variable within the action, this variable will also be accessible in the views template file. e.g. if you define a @user in users_controller, @user will also be accessible in whatever template you created in users sub-folder of views.

Ruby on Rails | Application Helper

All methods used in views muss be defined in the application_helper.rb file. Once you defined a method in application helper, it will be available in all views pages.

Ruby on Rails | Pagination

As time went by, the number of article in your blog has increased rapidly. Your articles page become very long. To solve this we can use pagination.

Steps:

  1. In your gemfile, add gem 'will_paginate','version' and gem 'bootstrap-will_paginate', 'version' change the version to current version of the gem. 
  2. bundle install --without production --If production group exists-- to install the gem. 
  3. In articles_controller, at index action, change the variable value to Article.paginate(page: params[:page], per_page: 10) If you want to show more than 10 articles, simply change the number. 
  4. Add <%= will_paginate %> wherever you want to place the pagination.

Ruby on Rails | Sessions (login logout)

How to create session in Rails

  • Create route: get 'login', to: 'sessions#new'
  • Create route: post 'login', to: 'sessions#create'
  • Create route: delete 'logout', to: 'sessions#destroy'
  • Create sessions sub folder in controllers directory, and create new file, sessions_controller.rb
  • Create new, create and destroy actions.
  • In views, create new.html.erb
  • In application_controller.rb, create current_user, logged_in and require_user actions

Ruby on Rails | Basic knowledge

Things you should know in Ruby on Rails:

  • Actions that you created in application controller will be available in all your controller but they are not available to views by default. 
  • To make those actions to be available to views, add this code in the same file: helper_method :action1, :action2, and so on. 
  • In Ruby, "foo".equal? "foo" will return false and :foo.equal? :foo will return true It works that way because strings in Ruby are mutable. Unlike strings, symbols(:foo) are immutable.
  • params[:foo] in @user = User.find(params[:id]) means to tell rails to get the ':foo' or ':id' from the URL of the page that user requested
  • In this case, params[:id] is 1

Ruby on Rails | Syntax

Important syntax you have to know:

  • <% code %> to embed Ruby code in your HTML file. 
  • <%= code %> to generate HTML code with ruby methods. 
  • !!code to convert the code into Boolean statement.  
  • Local variable will be declared as variable and instance variable will be declared as @variable
  • Local variable only exists within its scope. Declaring variables in the controller as instance variables @variable makes them available to your view. 
  • a ||= b This operator means if 'a' is undefined then assign it the value of 'b', otherwise leave it alone.
  • @current_user ||= User.find(2) this means if @current_user is undefined, assign the value of user with user_id 2 to the @current_user otherwise perform nothing.
Please check this link for more Ruby Operators

Virtual Box | Windows Host & Ubuntu Guest | Shared Folder

Follows this steps to create a shared folder between windows host and ubuntu guest

  • Create shared folder at Vbox -> settings -> Shared Folders -> plus button -> specify path 
  • Go to your ubuntu guest create new folder somewhere: sudo mkdir newFolder
  • Mount your shared folder to the new folder you just created sudo mount -t vboxsf sharedFolder newFolder change shared folder with the folder you specified in Virtual box settings

Ruby on Rails | Typing Convention

Working with databases

  • Model class name is singular, starts with uppercase. e.g. class Article < ActiveRecord::Base
  • Model file name is singular, all lowercase. e.g. article.rb
  • Table name is plural of model name, all lowercase e.g. articles

Working with Buttons and Controllers

  • Controller class name is plural and written in CamelCase e.g. class ArticlesController
  • Controller file name is also plural but separated by "_" e.g articles_controller.rb

Ruby on Rails | Bootstrapping

What you should know about using Bootstrap alongside of RoR

    • Understanding Bootstraps 12 columns grid system.
    • Combine <blockquote> and <footer>  to get awesome quote effects. 
    • With class="row" you'll get a column without padding
    • When designing responsive website, keep in mind, Bootstrap will use the smallest break point first. for eg. class="col-lg-6 col-xs-4" On ipads or tablets (medium size) col-xs-4 will be used.
    • All columns will be placed from left to right. If you want to force them to be placed more right than it should be, you can use offset attribute. class="col-lg-3 col-lg-offset-6" This will create an element that take 3 columns and place it six column from the left or from its original place .
    • Class="container" will centered your container, while class="container-fluid" will stretch the your container to cover the whole screen.    
    • To apply Bootsraps forms to rails model backed form, you'll need to modify your ruby code into something like this: <%= form_for(@variableName, :html => {class= "BootstrapFormElement", role: "form"}) do |f| %>