menu

Showing posts with label sintax. Show all posts
Showing posts with label sintax. Show all posts

Syntax - Syntax elasticsearch


Pada tutorial kali ini, codedoct akan sharing syntax2 untuk elasticsearch, apa itu elasticsearch? bisa cari tahu di official websitenya langsung disini,

Untuk mengetesnya bisa menggunakan postman yang diinstall pada chrome,
Oke langsung saja sharing ilmu.

Test elasticsearch

Add index

Get index

Add document

Get document

Search Document

Show Document

Bulk Document

Edit document

Delete document

Delete index


===DONE!===

Syntax - Syntax rails


Operation
# new rails
$ rails new MySite

#bundling
$bundle install

#running server
rails server

#create new controller
rails generate controller Pages
#for edit, on path: routes->controller->page

#create new model
rails generate model Message
#file in db/migrate

#migration
rake db:migrate

#seeder
rake db:seed

HTML
#show content model
<% @messages.each do |t| %>
 <h1>name: <%= t.name %></h1><br>
 description: <%= t.description %>
<% end %>

#show image
<%= image_tag t.image %>

#show link
<%= link_to "Learn more", tag_path(t) %>

Controller
#controller
def messages
 #show all field database
 @messages = Message.all

 #show field database with id
 def show
  @tag = Tag.find(params[:id])
  @destinations = @tag.destinations
 end

 #edit
 def update
  @destination = Destination.find(params[:id])
  if @destination.update(destination_params)
   redirect_to @destination
  else
   render 'edit'
  end
 end
 private 
    def destination_params 
      params.require(:destination).permit(:name, :description) 
    end
end

Model
#model
class Tag < ActiveRecord::Base
 has_many :destinations
 belongs_to :tag
end

Routes
#routes
Rails.application.routes.draw do
 get '/tags' => 'tags#index'
 post '/tags/create' => 'tags#create'
 get '/tags/:id' => 'tags#show', as: :tag
end

Seeder
#db:migrate
class CreateDestinations < ActiveRecord::Migration
  def change
    create_table :destinations do |t|
      t.string :name
      t.string :image
      t.string :description
      t.references :tag
      t.timestamps
    end
  end
end

Syntax - Syntax sass


Sass merupakan salah satu compiler css yang sangat populer, untuk dapat menggunakan sass sebagai compiler css, kita harus menginstallnya terlebih dahulu, lihat disini.

Berikut beberapa syntax sass dan perbandingannya dengan css biasa,

Parent and child
//sass
.test{
    position: absolute;
    border: 4px solid black;
    top: 200px;
    left: 25%;
    width: 50%;
    height: 200px;
    text-align: center;
    span{
      font-size: 24px;
      line-height: 200px;
    }
}
//css
.test span {
  font-size: 24px;
  line-height: 200px;
}

Use one parameter
//sass
.test {
  font-family: 'Pacifico', cursive;
  height: 400px;
  background-image: url("lemonade.jpg");
  border:{
    top: 4px solid black;
    bottom: 4px solid black;
  }
}
//css
.test {
  font-family: 'Pacifico', cursive;
  height: 400px;
  background-image: url("lemonade.jpg");
  border-top: 4px solid black;
  border-bottom: 4px solid black;
}

Use variable
//sass
$translucent-white:rgba(255,255,255,0.3);
$standard-border: 4px solid black;
.test{
 background-color: $translucent-white;
 border: $standard-border;
}
//css
.test{
 background-color: rgba(255, 255, 255, 0.3);
 border: 4px solid black;
}

Use mixin
//sass
@mixin transform($transformation) {
  transform: $transformation;
  -webkit-transform: $transformation;
  -moz-transform: $transformation;
  -ms-transform: $transformation;
  -o-transform: $transformation;  
}
.test {
 width: 300px;
 height: 180px;
 &:hover{
  @include transform (rotatey(-180deg));  
 } 
}
//css
.test {
  width: 300px;
  height: 180px;
}
.test:hover {
  transform: rotatey(-180deg);
  -webkit-transform: rotatey(-180deg);
  -moz-transform: rotatey(-180deg);
  -ms-transform: rotatey(-180deg);
  -o-transform: rotatey(-180deg);
}

Variable on mixin
//sass
$stripe-properties: to bottom, 15%, blue, white;
@mixin stripes($direction, $width-percent, $stripe-color, $stripe-background: #FFF) {
  background: repeating-linear-gradient(
    $direction,
    $stripe-background,
    $stripe-background ($width-percent - 1),
    $stripe-color 1%,
    $stripe-background $width-percent
  );
}
.test {
 width: 100%;
 height: 100%;
 @include stripes($stripe-properties...);
}
//css
.test {
  width: 100%;
  height: 100%;
  background: repeating-linear-gradient(to bottom, white, white 14%, blue 1%, white 15%);
}

Use String
//sass
@mixin photo-content($file) {
  content: url(#{$file}.jpg); //this is ruby???
  object-fit: cover;
}
.image {
    @include photo-content('titanosaur');
    width: 60%;
    margin: 0px auto;  
}
//css
.image {
  width: 60%;
  margin: 0px auto;
  object-fit: cover;
  content: url(titanosaur.jpg);
}

Hover in mixin
//sass
@mixin hover-color($color) {
   &:hover{
       color: $color;
   }
}
.test {
 display: block;
 text-align: center;
 position: relative;
 top: 40%;
 @include hover-color(red);
}    
//css
.test:hover {
  color: red;
}

You can use your math skill
//sass
.test {
  color: red+blue;
}
//css
.math {
  color: magenta; //hahahaha
}

//other math
$width:250px;
.math {
  width: $width;
  border-radius: $width/6;
}
//css
.math{
  width:250px;
  border-radius: 41.66667px;
}

Looping
//use each
$list: (orange, purple, teal);
@each $item in $list { //shit this code same with ruby hahaha,.,.
  .#{$item} {
    background: $item;
  }
}
//css
.orange {
  background: orange;
}
.purple {
  background: purple;
}
.teal {
  background: teal;
}

//use for
$total: 10;
$step: 360deg / $total;
.test {
  height: 30px;
}
@for $i from 1 through $total {
  .test:nth-child(#{$i}) {
    background: adjust-hue(blue, $i * $step);
   }
}
//css
.test {
  height: 30px;
}
.test:nth-child(1) {
  background: #9900ff;
}
.test:nth-child(2) {
  background: #ff00cc;
}
.test:nth-child(3) {
  background: #ff0033;
}
.test:nth-child(4) {
  background: #ff6600;
}
.test:nth-child(5) {
  background: yellow;
}
.test:nth-child(6) {
  background: #66ff00;
}
.test:nth-child(7) {
  background: #00ff33;
}
.test:nth-child(8) {
  background: #00ffcc;
}
.test:nth-child(9) {
  background: #0099ff;
}
.test:nth-child(10) {
  background: blue;
}

Import scss
//import other scss files
@import "test";

//extend
.test{
 position: absolute;
}
.test2 {
    @extend .absolute;
}
//css
.test, .test2, {
  position: absolute;
}

Syntax - Syntax php


Artikel kali ini akan membahas beberapa syntax yang sering digunakan dalam programming PHP.

Tag And comment
===> tag php
<?php ?>

<?php

//===> comment one line
// content comment

//===> comment multi line
/*  
 content comment
 content comment
*/

Display
//===> show string
echo "content string";

//===> show integer
echo 21;

//===> show variabel
echo $variabel;

//===> mix variabel and string
echo "test ".$variabel." test2";

Array
here

Loop
//===> for
for ($i = 2; $i < 11; $i = $i + 2) {
  echo $i;
}
output:
246810

//===> foreach
$sentence = array("Im ", "learning ", "PHP!");        
foreach($sentence as $word) {
  echo $word;
}
output:
Im learning PHP!

//===> while
$loopCond = true;
while ($loopCond){
 echo "<p>The loop is running.<p>";
 $loopCond = false;
}
output:
The loop is running.
//other example
$i=0;
while($i<5){
    echo $i;
    $i++;
}
output:
01234
//with other way
$i=0;
while($i<5):
    echo $i;
    $i++;
endwhile;
output:
01234

//===> do while
$loopCond = false;
do {
 echo "<p>The loop ran even though the loop condition is false.</p>";
} while ($loopCond);
output:
The loop ran even though the loop condition is false.

Library
//===> length
$length = strlen("sayah");
echo $length;
output:
5

//===> partial, uppercase, lowercase
$myname = "Dark King";

$partial = substr($myname, 1, 3);
print $partial;

$uppercase = strtoupper($myname);
print $uppercase;

$lowercase = strtolower($myname);
print $lowercase;

output:
ark
DARK KING
dark king

//===> find position
$myname = "Dark King";
echo strpos($myname, "i");
output:
6

//===> round(pembulatan)
$round = round(M_PI);
print $round;

$round = round(M_PI, 3);
print $round;
output:
3
3.142

//===> rand(random number between)
 print rand(1, 10);

$name = "Dark King";
echo $name[rand(0, strlen($name)-1)];
output:
4
n

//===> length string
$name = "Dark King";
echo strlen($name);
output:
9

Function
//===> play with function
function greetings($name){
    echo "Greetings, " . $name . "!";
}

greetings("Dark King");
output:
Greetings, Dark King!

//===> class
// The code below creates the class
class Person {
    // Creating some properties (variables tied to an object)
    public $isAlive = true;
    public $firstname;
    public $lastname;
    public $age;
    
    // Assigning the values
    public function __construct($firstname, $lastname, $age) {
      $this->firstname = $firstname;
      $this->lastname = $lastname;
      $this->age = $age;
    }
    
    // Creating a method (function tied to an object)
    public function greet() {
      return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
    }
  }
  
// Creating a new person called "boring 12345", who is 12345 years old ;-)
$me = new Person('Dark', 'King', 12345);

// Printing out, what the greet method returns
echo $me->greet(); 
output:
Hello, my name is Dark King Nice to meet you!

//===> other example class
class Dog{
    public $numLegs = 4;
    public $name;
    
    public function __construct($name){
        $this->name = $name;    
    }
    
    public function bark(){
        return "Woof!";   
    }
    
    public function greet(){
        return "My name is ".$this->name;    
    }
}

$dog1 = new Dog("Barker");
$dog2 = new Dog("Amigo");

echo $dog1->bark();
echo $dog2->greet();
output:
Woof! My name is Amigo

//===> cheking class
class Person {
  public $isAlive = true;
  
  function __construct($name) {
      $this->name = $name;
  }
  
  public function dance() {
    return "I'm dancing!";
  }
}

$me = new Person("Shane");
if (is_a($me, "Person")) {
  echo "I'm a person, ";
}
if (property_exists($me, "name")) {
  echo "I have a name, ";
}
if (method_exists($me, "dance")) {
  echo "and I know how to dance!";
}
output:
I m a person, I have a name, and I know how to dance!

//===> cheking class
class Shape {
  public $hasSides = true;
}
class Square extends Shape {

}
$square = new Square();
if (property_exists($square, 'hasSides')) {
  echo "I have sides!";
}
output:
I have sides!

//===> overide class / extends
class Vehicle {
  public function honk() {
    return "HONK HONK!";
  }
}
class Bicycle extends Vehicle {
   public function honk() {
      return "Beep beep!";   
   }
}
$bicycle = new Bicycle();
echo $bicycle->honk();
output:
Beep beep!

//===> call const
class Ninja extends Person {
  const stealth = "MAXIMUM";
}
echo Ninja::stealth;
output:
MAXIMUM

//===> const
class King {
  public static function proclaim() {
    echo "A kingly proclamation!";
  }
}
King::proclaim()
output:
A kingly proclamation!

Syntax - Syntax ruby


Sebelum kita masuk ke tutorial ruby on rails ada baiknya kita mengenal terlebih dahulu beberapa syntax dari ruby,

Berikut beberapa syntax ruby yang sudah codedoct rangkum

Simple Ruby
====> comment one line
#content comment

====> comment many line
=begin
content comment
=end

====> input text
gets.chomp

====> write text
print

====> write text with new line
puts

====> aritmatika
i = 2
kuadrat: i ** 2
tambah: i + 1
kurang: i - 1
bagi: i / 2 # other way: i.fdiv(2)
hasil bagi: i % 2 # output is 0

====> write variabel
v = "test"
puts "value v : "+v

====> write variabel with on string
v = "test"
puts "value v : #{v}"

caption = "A giraffe surrounded by "
caption << "weezards!"
output:
"A giraffe surrounded by weezards!"

====> many way to code
age = 26
"I am " + age.to_s + " years old."
#==> "I am 26 years old."
"I am " << age.to_s << " years old."
#==> "I am 26 years old."
"I am #{age} years old."
#==> I am 26 years old.

Looping
====> each array
v = [1, 2, 3]
v.each {|x| puts x}

====> each array with other way
v = [1, 2, 3]
v.each do |x| 
  puts x
end

====> while
i = 0
while i<=20 do
 puts i
 i += 1
end

====> repeat until
i = 0
until i==20 do
 puts i
 i += 1
end

====> for
for i in 0..20
 puts i
end

====> times
i = 0
20.times do
 puts i
 i += 1 #it same about i = i+1
end

====> loop
i = 20
loop do
  i -= 1
  next if i>=19 
  puts "#{i}"
  break if i <= 0
end

Array
====> in ruby array can write with hash syntax
php: x = array();
 or just x = [];
ruby x = Hash.new() #remember Hash write with capitalize!
 or just x = Hash.new
 or just x = {}

====> array with key
x = {
 "red" => "merah"
 "green" => "hijau"
 "black" => "hitam"
}

====> array multidimensional
x = [[1, 2, 3], ["iam", "dark", "king"]]

====> write array multidimensional
x.each {|n,v| puts "number: "+n+" value: #{v}\n"}

====> write just one value array
x = ["red", "green", "black"]
puts x[1] #will display green

====> write just one key of array multidimensional
x = {
 "red" => "merah"
 "green" => "hijau"
 "black" => "hitam"
}
puts x[red]

====> write all value of array multidimensional
x = {
 "red" => "merah"
 "green" => "hijau"
 "black" => "hitam"
}
x.each do |eng,ina|
 puts ina
end

====> sort array integer
x = [1, 4, 5, 3, 2]
x.sort! # will display [1, 2, 3, 4, 5]

====> sort array string
x = ["a", "c", "b", "d", "e"]
x.sort! # will display ["a", "b", "c", "d", "e"]

====> sort with other way
books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]
books.sort! { |firstBook, secondBook| firstBook <=> secondBook }
books.sort! {|firstBook, secondBook| secondBook <=> firstBook}

====> sorting array with simple way
def alphabetize(arr, rev=false)
    arr.sort!
    if rev
        arr.reverse!
    end
    return arr
end
numbers = [5, 1, 3, 8]
puts alphabetize(numbers)

====> array with semi colon
menagerie = { :foxes => 2,
  :giraffe => 1,
  :weezards => 17,
  :elves => 1,
  :canaries => 4,
  :ham => 1
}
output: {:foxes=>2, :giraffe=>1, :weezards=>17, :elves=>1, :canaries=>4, :ham=>1}

====> push array with push
strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbols = []
strings.each do |s|
    s = s.to_sym
    symbols.push(s)
end
easy way with this:
alphabet = ["a", "b", "c"]
alphabet << "d"
output:
["a", "b", "c", "d"]

====> push array multidimensional
movies = {
    "warkop" => "4",
    "deadpool" => "4"
}
puts "what is movie title?"
title = gets.chomp
puts "how about the rating?"
rating = gets.chomp
movies[title] = rating
output:
{"warkop"=>"4", "deadpool"=>"4"}
what is movie title?
 jumanji
how about the rating?
 3
movie was added!
{"warkop"=>"4", "deadpool"=>"4", "jumanji"=>"3"}

Symbol
====> symbol not use string
movies = {
    :warkop => "comedy",
    :jumanji => "advanture"
}

====> other way write symbol
movies = {
    warkop: "comedy",
    jumanji: "advanture"
}

====> how fast symbol
require 'benchmark'
string_AZ = Hash[("a".."z").to_a.zip((1..26).to_a)]
symbol_AZ = Hash[(:a..:z).to_a.zip((1..26).to_a)]

====> select the symbols
movie_ratings = {
  memento: 3,
  primer: 3.5,
  the_matrix: 5,
  truman_show: 4,
  red_dawn: 1.5,
  skyfall: 4,
  alex_cross: 2,
  uhf: 1,
  lion_king: 3.5
}
good_movies = movie_ratings.select{|m,r| r > 3}
puts good_movies

====> write just key other way
movie_ratings = {
  memento: 3,
  primer: 3.5,
  the_matrix: 3,
  truman_show: 4,
  red_dawn: 1.5,
  skyfall: 4,
  alex_cross: 2,
  uhf: 1,
  lion_king: 3.5
}
movie_ratings.each {|m,r| puts m}

Condition
====> use unless for false
ruby_is_ugly = false

unless ruby_is_ugly
 puts "Ruby's not ugly!"
end

====> this is ruby
ruby_is_eloquent = true
ruby_is_ugly = false
puts "Ruby is eloquent!" if ruby_is_eloquent
puts "Ruby's not ugly!" unless ruby_is_ugly

====> Ternary
puts 1>0 ? "benar":"salah" #this is same with php he..he..he..

====> Case
puts "Hello there!"
greeting = gets.chomp
case greeting
    when "english" then puts "Hello!"
    when "french" then puts "Bonjour!"
    when "german" then puts "Guten Tag!"   
    when "finnish" then puts "Haloo!"
    else puts "I don't know that language!"
end

====> Case another way
puts "Hello there!"
greeting = gets.chomp
case greeting
    when "english"
      puts "Hello!"
    when "french"
      puts "Bonjour!"
    when "german"
      puts "Guten Tag!"   
    when "finnish"
      puts "Haloo!"
    else puts "I don't know that language!"
end

====> set value that nill
favorite_book = nil
puts favorite_book
favorite_book ||= "Cat's Cradle"
puts favorite_book
favorite_book ||= "Why's (Poignant) Guide to Ruby"
puts favorite_book
favorite_book = "Why's (Poignant) Guide to Ruby"
puts favorite_book
output:
Cat's Cradle
Cat's Cradle
Why's (Poignant) Guide to Ruby'

====> write code that divisible of 2
my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_array.each {|x| puts x if x % 2 == 0  }
output: 2
4
6
8
10

====> use upto
"L".upto("P") {|x| puts x }
output:
L
M
N
O
P
test

====> Play with array(CRUD array)
movies = {
    "warkop" => "4",
    "deadpool" => "4"
}

puts "what do you want your movie"
choice = gets.chomp

case choice
    when "add"
        puts movies
        puts "what is movie title?"
        title = gets.chomp
        if movies[title].nil?
            puts "how about the rating?"
            rating = gets.chomp
            movies[title.to_sym] = rating.to_i
            puts "movie was added!"
            puts movies
        else
            puts "that the movie already exists"
        end
    when "update"
        puts movies
        puts "What movie that you want to update rating?"
        title = gets.chomp
        if movies[title].nil?
            puts "Your movie not found!"
        else
            puts "Set the rating movie"
            rating = gets.chomp
            movies[title] = rating.to_i
            puts "rating was update!"
            puts movies
        end
    when "display"
        movies.each do |m,r|
            puts "#{m}: #{r}"
        end
    when "delete"
        puts movies
        puts "Type movie that you want to delete?"
        title = gets.chomp
        if movies[title].nil?
            puts "Movie not found!"
        else
            movies.delete(title)
            puts "That movie was deleted"
            puts movies
        end
    else puts "Error!"
end

Library
====> collect 
my_nums = [1, 2, 3]
my_nums.collect { |num| num ** 2 }
output:
[1, 4, 9]
=begin
This is because .collect returns a copy of my_nums,
but doesn't change (or mutate) the original my_nums array. 
If we want to do that, we can use .collect!
=end
my_nums.collect! { |num| num ** 2 }
=begin
Recall that the ! in Ruby means "this method could do something dangerous or unexpected!"
In this case, it mutates the original array instead of creating a new one.
=end

====> example collect
fibs = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
print "#{fibs}\n"
doubled_fibs = fibs.collect {|x| x**2}
print "#{fibs}\n"
print doubled_fibs
output:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
[1, 1, 4, 9, 25, 64, 169, 441, 1156, 3025]
print "#{fibs}\n"
doubled_fibs = fibs.collect! {|x| x**2}
print "#{fibs}\n"
print doubled_fibs
output:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
[1, 1, 4, 9, 25, 64, 169, 441, 1156, 3025]
[1, 1, 4, 9, 25, 64, 169, 441, 1156, 3025]

====> yield
def double(param)
    puts "yeehhaaaa"
    yield(param)
    puts "end"
end

double(2) {|x|puts x*2}
output:
yeehhaaaa
4
end

====> Proc
multiples_of_3 = Proc.new do |n|
  n % 3 == 0
end
(1..100).to_a.select(&multiples_of_3)
output:
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99] 

====> Proc with call
hi = Proc.new do
    puts "Hello!"
end
hi.call
output:
Hello!

====> floor
floats = [1.2, 3.45, 0.91, 7.727, 11.42, 482.911]

round_down = Proc.new do |x|
    x.floor
end

ints = floats.collect(&round_down)
output:
[1, 3, 0, 7, 11, 482]

====> symbols meet 
Procnumbers_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
strings_array = numbers_array.map(&:to_s)
output:
["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

====> lambda
def lambda_demo(a_lambda)
  puts "I'm the method!"
  a_lambda.call
end
lambda_demo(lambda { puts "I'm the lambda!" })
output:
I'm the method!
I'm the lambda!

====> wonderfull lambda
strings = ["leonardo", "donatello", "raphael", "michaelangelo"]
symbolize = lambda {|x| x.to_sym}
symbols = strings.collect(&symbolize)
output:
[:leonardo, :donatello, :raphael, :michaelangelo]

====> different proc and lambda?
def batman_ironman_proc
  darkking = Proc.new { return "Batman will win!" }
  darkking.call
  "Iron Man will win!"
end

puts batman_ironman_proc

def batman_ironman_lambda
  darkking = lambda { return "Batman will win!" }
  darkking.call
  "Iron Man will win!"
end

puts batman_ironman_lambda

output:
Batman will win! #this is pro
Iron Man will win! #this is lambda

====> filter with array
my_array = ["raindrops", :kettles, "whiskers", :mittens, :packages]
symbol_filter = lambda {|x| x.is_a? Symbol}
symbols = my_array.select(&symbol_filter)
output:
[:kettles, :mittens, :packages] 

Method
====> method
def name_method
  content_method
end

====> method with return boolean
def is_true?
  content_method
end

====> method with parameter
def welcome(name)
  return "Hello #{name}"
end
welcome("Dark King")

====> to string, float, integer, simbol
i = 2
i.to_s
i.to_f
i.to_i
i.to_sym

====> sorting array with method
def alphabetize(arr, rev=false)
  if rev
    arr.sort { |item1, item2| item2 <=> item1 }
  else
    arr.sort { |item1, item2| item1 <=> item2 }
  end
end
books = ["Heart of Darkness", "Code Complete", "The Lorax", "The Prophet", "Absalom, Absalom!"]
puts "A-Z: #{alphabetize(books)}"
puts "Z-A: #{alphabetize(books, true)}"

====> the function semicolon
puts "string".object_id
puts "string".object_id
puts :symbol.object_id
puts :symbol.object_id
output:
15100680
15100480
319848
319848

string_time = Benchmark.realtime do
  100_000.times { string_AZ["r"] }
end
symbol_time = Benchmark.realtime do
  100_000.times { symbol_AZ[:r] }
end
puts "String time: #{string_time} seconds."
puts "Symbol time: #{symbol_time} seconds."

====> class
class Computer
  $manufacturer = "Mango Computer, Inc."
  @@files = {hello: "Hello, world!"}
  def initialize(username, password)
    @username = username
    @password = password
  end
  def current_user
    @username
  end
  def self.display_files
    @@files
  end
end

# Make a new Computer instance:
hal = Computer.new("Dave", 12345)
puts "Current user: #{hal.current_user}"
# @username belongs to the hal instance.
puts "Manufacturer: #{$manufacturer}"
# $manufacturer is global! We can get it directly.
puts "Files: #{Computer.display_files}"
# @@files belongs to the Computer class.
output:
Current user: Dave
Manufacturer: Mango Computer, Inc.
Files: {:hello=>"Hello, world!"}

====> you can do thisclass ApplicationError
  def display_error
    puts "Error! Error!"
  end
end
class SuperBadError < ApplicationError
end
err = SuperBadError.new
err.display_error
output:
Error! Error!

====> Override class
class Creature
  def initialize(name)
    @name = name
  end
  def fight
    return "Punch to the chops!"
  end
end
class Dragon < Creature
   def fight
       return "Breathes fire!"
   end
end
show = Dragon.new
puts show.fight
output:
Breathes fire!

====> OOP
class Account
    attr_reader :name, :balance
    def initialize(name,balance=100)
        @name = name
        @balance = balance
    end
    private 
    def pin
        @pin = 1234
    end
    def pin_error
        return "Access denied: incorrect PIN."
    end
    public
    def display_balance(pin_number)
        if pin_number == pin
            puts "Balance: $#{@balance}."
        else
            pin_error
        end
    end
    def withdraw(pin_number,amount)
        if pin_number == pin
            puts "Withdrew #{amount}. New balance: $#{@balance}."
        else
            pin_error
        end
    end
end
checking_account = Account.new("Conteriano",10_000_000)
puts checking_account.display_balance(4321)
puts checking_account.display_balance(1234)
puts checking_account.withdraw(4321,10001)
puts checking_account.withdraw(1234,10001)
output:
Access denied: incorrect PIN.
Balance: $10000000.
Access denied: incorrect PIN.
Withdrew 10001. New balance: $10000000.

===DONE!!!===

Sintax - Mysql


Mysql merupakan sebuah perangkat lunak sistem manajemen basis data SQL yang paling sering digunakan untuk sebuah project sistem skala besar, jika anda ingin membuat sebuah project sistem yang simpel dan ringan maka lebih baik menggunakan SQL Lite, adapun PostgreSQL yang lebih sering digunakan pada project sistem cloud untuk pembackup-an database.

Pada kesempatan kali ini codedoct  akan berbagi beberapa sintax SQL pada mysql yang akan sering kita gunakan pada tutorial yang ada pada website ini.

Select
//select database
USE database_name

//select table and show all column
SELECT * FROM table_name

//select table and show all column with limit field
SELECT * FROM table_name
LIMIT 10

//select table and show all column with sorting field ASC or DSC
SELECT * FROM table_name
ORDER BY id ASC

//select table and show all column with condition
SELECT * FROM table_name
WHERE id=1

//select join table and show column
SELECT t1.column1, t2.column2
FROM table1 as t1
INNER JOIN table2 as t2 on t1.id=t2.t1_id

Operation Table
//insert table
INSERT table1 (column1,column2,column3)
VALUES ('column1_field','column2_field','column3_field')

//insert table with other databse table field
USE database_name
INSERT INTO table1(field1, field2, field3)
SELECT field1, field2, field3
FROM database2.table2
WHERE (some condition)

//update field table
UPDATE table_name 
SET column1='ss', column2='ss@mail.com', column3='dasdasdasdasds' 
WHERE id=4

//delete all column
DELETE FROM table_name

//delete column with condition
DELETE FROM table_name
WHERE id=4

//delete foreign_key
ALTER TABLE Orders
DROP FOREIGN KEY fk_PerOrders

//drop primary_key
ALTER TABLE `user_logs`
DROP PRIMARY KEY

//add primary_key
ALTER TABLE `user_logs`
ADD PRIMARY KEY(`id`);

Syntax - Syntax ubuntu


Untuk menunjang tutorial Ruby on rails yang menggunakan OS Ubuntu maka disini akan saya share beberapa syntax terminal pada Ubuntu beserta cara penggunaannya yang sering digunakan untuk programming.

Structure file
//for go to the folder
cd name_folder

//To user home
cd

//back 1 path folder
cd ..

//show list folder
ls

//show list folder with detail
ll

//show path active
pwd

Operation file
//move or cut file or folder
mv name_file_or_folder

//copy file or folder
cp name_file_or_folder

//remove file
rm name_file

//remove empty folder
rmdir name_folder

//remove folder and contains
rm -rf name_folder

//make folder
mkdir name_folder

//show file content
cat name_file

//change access permissions? read this
chmod

//change owner file or group
chown

//copy file to server or different computer with scp
scp username@IP:path/to/file(source) path/to/destination
or
scp path/to/file(source) username@IP:path/to/destination

Vim
//before inserting code click Esc first

//open file with vim
vim name_file

//save vim
:w

//just quit vim
:q

//save and quit
:wq

//force quit
:q!

Nano
//exit
Ctrl + X

//write or save
Ctrl + O

/find
Ctrl + W

//replace
Ctrl + \

//cut text
Ctrl + K

//get help
Ctrl + G

Apache
//show error log apache
tail -f /var/log/apache2/error.log

Play with Ubuntu
//running with user active
sudo

//install application ubuntu
sudo apt-get install name_application_ubuntu

//update application ubuntu
sudo apt-get update

Syntax - Syntax laravel


Artisan
== reset table database
php artisan migrate:reset

== create table to database
php artisan migrate

== isi table database
php artisan db:seed

== refresh migrate + seed
php artisan migrate:refresh --seed

== migrate + seed
php artisan migrate --seed

== versi laravel
php artisan -v

== list function artisan
php artisan list

== make migrate
php artisan migrate:make (nama migrate)


Composer
== compile composer.phar
php composer.phar dump-autoload 


Unit Test
== run all
phpunit

== run file
phpunit app/tests/NameFileTest.php


Command
== run file commands on Laravel
php artisan command:name_file

Syntax - Syntax github


Sintax - sintax yang perlu diketahui digithub
$ git init => initialize .git membuat folder .git

$ git config --global user.name "YOUR NAME" => menambahkan username global github
$ git config --global user.email "YOUR EMAIL ADDRESS" => menambahkan email global github

$ git add -A => manambahkan semua perubahan pada folder ke log github
$ git add (folder/file) => menambah file / folder ke log github 
$ git checkout -- (folder/file) => menghapus perubahan git

$ git status => melihat status perubahan pada folder

$ git commit -m " " => commit ke log github dengan comment

$ git log => melihat log github

$ git checkout -f => kembalikan perubahan
$ git checkout (nama_branch) => pindah branch
$ git branch -d (nama_branch) => delete branch local yang belum di push
$ git branch -D (nama_branch) => delete branch yang sudah di push
$ git push origin :(nama_branch) => delete branch remote
$ git checkout -b (nama_branch) => menambah branch baru
$ git checkout . => hapus semua perubahan

$ git remote add origin https://github.com/username/project.git => with login
$ git remote add origin git@github.com:/project.git => with key
$ git remote set-url origin (new_url) => mengganti remote url
$ git remote -v => melihat list remote url
$ git fetch => display change on remote

$ git pull origin master => menarik data master dari github
$ git pull --rebase => sinkronisasi

$ git push -u origin (master/branch) => push ke origin github

$ git merge branch_name_source => merger master ke branch
$ git merge origin/master => merge from master on remote

$ git clone path_source filename => cloning git folder

$ gitg => show modify 

$ git reset --hard => back to top HEAD