8 Kasım 2016 Salı

Redux store fonksiyonları

The store binds together the three principles of redux. It holds the current applications state object. It lets you dispatch actions. When you create it, you need to specify the reducer that tells how state is updated with actions.

The store has three important methods.
The first method of store is "getState". It retrieves the current state of the redux store.
The second and the most commonly used store method is called "dispatch". And it lets you dispatch actions that changes the state of your application.
Third redux store method is called "subscribe". It lets you register a callback that the redux store will call anytime an action has been dispatched.



Store, redux’ın üç prensibini birleştirir. Uygulamanın state objesini tutar. Action’ları dispatch eder (dağıtır). Store’u oluştururken state’lerin action’larla nasıl güncelleneceği belirtilmelidir. (createStore function’ına parametre olarak reducer verilmelidir.)

Store’un 3 önemli yöntemi/metodu/fonksiyonu vardır.
İlki “getState”tir. Redux store’unun mevcuttaki state’ini getirir.
İkincisi ve en çok kullanılanı “dispatch”tir. Uygulamadaki state’leri değiştirecek action’ları dağıtır.
Üçüncüsü “subscribe”dır. Store’a bir callback ekler. Bir action çalıştığında redux store tarafında çağrılır.

ve devamındaki videolar.

Redux prensipleri

First principle of redux; everything that changes in your application including the data and the ui state is contained in a single object. we call that state or state tree. (store)

Second principle of redux is that the state tree is read only. You cannot modify or write through it.

The pure functions are the functions whose return value depends only on the values of arguments. They do not have any observable side affects. They do not modify the values passed to them.

Impure functions may call the database or the network. They may have side affects. They may operate on the DOM. They may override the values passed to them.

The third principle of redux is some functions that makes the changes on states have to be pure in redux. (Reducer must be pure.)



Redux’ın ilk prensibi, uygulama içindeki herhangi bir data olsun veya ui olsun, olan herhangi bir değişikliğinin tek bir obje içerisinde tutulmasıdır. Buna “state” veya “state tree” denir.

Redux’ın ikinci prensibi, “state”in sadece okunur olması, üzerinde herhangi bir değişiklik yapılamaması veya üzerine yazılamamasıdır.

“Pure functions (Katışıksız fonksiyonlar)” sadece aldığı parametreleri kullanarak değer dönen metotlardır. Bu fonksiyonların herhangi bir yan etkisi yoktur. Fonksiyon, kendisine geçirilen parametreleri değiştirmez.

“Impure functions (karışık fonlsiyonlar)” database’den veya network’ten bilgi çekiyor olabilir. Yan etkileri olabilir, DOM’u yönetebilir. Kendilerine geçirilen parametreleri değiştirebilirler.

Redux’ın üçüncü prensibi state’lerde değişiklik yapan fonksiyonlar “pure function” olmalı. (Reducer pure function olmalı.)


ve devamındaki videolar.

30 Ekim 2016 Pazar

Go'da sıralama işlemleri

Go programlama dilinde bir obje dizisini sıralayabilmek için sort.Interface kullanılabilir. Bu interface 3 basit metoda ihtiyaç duyar: Len, Less ve Swap


// dizideki eleman sayısını döner
Len() int
// Dizideki iki elemanı karşılaştırır. Burada karşılaştırma için // özel kod yazılır
Less(i, j int) bool
// i ve j indekslerindeki elemanların yerini değiştirir
Swap(i, j int)`

Aşağıdaki gibi bir struct tipinde elemanlar içeren bir dizi olsun.

type AboutMe struct {
       Id          int
       Name        string
       Description string
}

type AboutMeList []AboutMe

Aşağıdaki gibi bir fonksiyon ile test için geçici olarak aşağıdaki gibi data listesi oluşturulabilir.

func prepareTestData() AboutMeList {
       aboutList := make([]AboutMe, 0)
       about1 := AboutMe{}
       about1.Id = 3
       about1.Name = "Ali"
       about1.Description = "test1"
       about2 := AboutMe{}
       about2.Id = 3
       about2.Name = "Veli"
       about2.Description = "test2"
       about3 := AboutMe{}
       about3.Id = 1
       about3.Name = "Ahmet"
       about3.Description = "test3"
       about4 := AboutMe{}
       about4.Id = 4
       about4.Name = "Mehmet"
       about4.Description = "test4"
       aboutList = append(aboutList, about1)
       aboutList = append(aboutList, about2)
       aboutList = append(aboutList, about3)
       aboutList = append(aboutList, about4)
       return aboutList
}

Dizideki elemanlar id’ye göre sıralansın. Bunun için Len, Less ve Swap metotları aşağıdaki gibi düzenlenebilir:


func (aboutMe AboutMeList) Len() int {
       return len(aboutMe)
}

func (aboutMe AboutMeList) Less(i, j int) bool {
       return aboutMe[i].Id < aboutMe[j].Id
}

func (aboutMe AboutMeList) Swap(i, j int) {
       aboutMe[i], aboutMe[j] = aboutMe[j], aboutMe[i]
}

Servis çağrıldığında çalışacak handler metodu da aşağıdaki gibi yazılabilir:

func sortHandler(w http.ResponseWriter, r *http.Request) {
       about := prepareTestData()
       sort.Sort(about)
       b, err := json.Marshal(about)
       if (err != nil) {
              panic(err)
       }
       w.Write(b)
}

Main metodu:
func main() {
       http.HandleFunc("/sort", sortHandler)
       http.ListenAndServe(":8080", nil)
}


golang sort


Eğer birden fazla değere göre sıralama yapılmak istenirse, örneğin önce id sonra name gibi, Less fonksiyonu aşağıdaki gibi düzenlenebilir:

func (aboutMe AboutMeList) Less(i, j int) bool {
       if (aboutMe[i].Id < aboutMe[j].Id) {
              return true;
       }
       if (aboutMe[i].Id > aboutMe[j].Id) {
              return false;
       }
       return aboutMe[i].Name < aboutMe[j].Name
}

Go'da bir dizideki elemanların tamamında dönmek (for each)

for key, value := range myArray {
       .....
}
 

myArray --> Tamamı işlenecek olan dizi (array veya slice) 
key --> İşlenen elemanın index'i. (dizide kaçıncı eleman) 
value --> İşlenen eleman (myArray[key])

29 Ekim 2016 Cumartesi

Go’da RESTful microservice yazma

Basit bir microservice yazımı: http://www.eyupdalan.com/2016/10/goda-basit-restful-microservice-yazma.html

İhtiyaca göre daha kompleks handler’lar, function’lar da oluşturulabilir.

type AboutMe struct {
     Name        string
     Description string
}

func aboutHandler(w http.ResponseWriter, r *http.Request) {
     about := AboutMe{}
     about.Name = "eyüp dalan"
     about.Description = "software developer"

     b, err := json.Marshal(about)

     if (err != nil) {
            panic(err)
     }

     w.Write(b)
}

Örneğin yukarıdaki örnek, ilkine nazaran biraz daha kompleks.
İlk olarak bir AboutMe isimli, Name ve Desription adında iki string property’si olan bir struct tanımlanır. “aboutHandler” fonsiyonu da bu struct tipinde bir datayı json’a çevirerek servis üzerinden dönmesini sağlar. Obje json’a “json.Marshal” ile çevrilir. Bir hata oluşması durumunda hata “panic” metodu ile fırlatılır. Son olarak da oluşan json bayte array http.ResponseWriter ile response olarak dönülür.

main fonksiyonunda bu handler için yeni bir endpoint eklenir. Sonuç  olarak maşn fonksiyonu aşağıdaki gibi olur:

func main() {
    http.HandleFunc("/", handler)
    http.HandleFunc("/about", aboutHandler)
    http.ListenAndServe(":8080", nil)
}


28 Ekim 2016 Cuma

Go’da basit RESTful microservice yazma

import (
    "fmt"
    "net/http"
)

İlk olarak projeye “net/http” kütüphanesini eklemek gerekmektedir. 

package main

import (
     "fmt"
     "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
     fmt.Fprintln(w, "Welcome ", r.URL.Path)
     fmt.Fprintln(w, "Welcome ", r.URL.Path[1:])
}

func main() {
     http.HandleFunc("/", handler)
     http.ListenAndServe(":8080", nil)
}

Bu kod parçası iki önemli kısımdan oluşuyor: handler ve main
Handler fonksiyonu http.ResponseWriter ve http.Request tiplerinde iki parametre alır. Bu parametreleri de kullanarak server’a bir text döner. Bu text sabit bir “Welcome” string’inden ve url’den alınmış değerden oluşmaktadır. Örneğin url “http://localhost:8080/eyupdalan” ise “r.URL.Path” ile buradaki “/eyupdalan” kısmı alınır. başındaki “/” kısmı, “r.URL.Path[1:]” şeklinde atılabilir.

Main fonksiyonu kısmında, “http.ListenAndServe” fonksiyonundan faydalanılarak microservice’teki tanımlı tüm handler fonksiyonlarının 8080 portundan yönetilmesi sağlanmaktadır. 

Ubuntu'da bir porttaki servisi sonlandırmak

Servisin process id’sinin (PID) bulunması
fuser 8080/tcp

Bir portta çalışan process’in sonlandırılması:
fuser -k 8080/tcp

24 Ekim 2016 Pazartesi

Ubuntu'da GIT yükleme ve temel bazı komutlar

  • Ubuntu’da git yükleme:
sudo apt-get install git
  • git versiyon kontrolü:
git --version



  • Bazı temel komutlar


git clone <project git path>
path’teki projeyi içinde bulunulan dizine indirir
git clone git@github.com:whatever
git clone <project git path> --save
path’teki projeyi içinde bulunulan dizine indirir ve kaydeder. (packages.json’a ekler)
git clone git@github.com:whatever --save
git pull
içinde bulunulan dizindeki projenin son halini çeker

git add <file>
değişiklik yapılmış, yeni eklenmiş dosyayı git’e ekler

git add -A
değişiklik yapılmış, yeni eklenmiş tüm dosyaları git’e ekler

git add .
değişiklik yapılmış, yeni eklenmiş tüm dosyaları git’e ekler (-A ile aynı)

git commit -am ‘<comment>’
yapılmış tüm değişiklikleri, ekleme ve çıkarmaları yorum ile birlikte commit’ler

git push
commit’lenmiş olan değişiklikleri git’e gönderir

 

Ubuntu'da node.js yükleme

curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs
  • versiyon kontrolü:
node -v 





Kaynak:
https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions

Ubuntu’da terminal üzerinden golang yükleme

  • go’nun son versiyonu kontrol edilir
https://storage.googleapis.com/golang
  • son versiyonu işletim sistemine uygun şekilde belirlenir ve terminalde aşağıdaki komut yazılır:
sudo curl -O https://storage.googleapis.com/golang/go1.7.1.linux-amd64.tar.gz  
  • indirilen sıkıştırılmış dosyayı açmak için aşağıdaki komut kullanılır:
sudo tar -xvf go1.7.1.linux-amd64.tar.gz
  • çıkarılan klasör /usr/local altına taşınır:
sudo mv go /usr/local 
  • golang’ı path’e ekleme işlemi: 
export PATH=$PATH:/usr/local/go/bin
  • go kurulum kontrolü:
go version 
 



Kaynaklar: