Todo list by vue.js

v-on, v-attr, v-classで機能追加しています。データの追加はpush,削除はspliceです。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>My ToDos</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="styles.css">
	<style>
		body {
			font-size: 13px;
			font-family: Arial;
		}
		h1 {
			font-size: 14px;
			border-bottom:1px solid #ddd;
			padding: 0 0 5px;
		}
		ul {
			list-style-type: none;
			padding: 0;
			margin: 0 0 5px;
		}
		ul > li {
			padding: 0 0 5px;
		}
		input[type=text]{
			padding: 4px;
			border-radius: 4px;
		}
		.done {
			text-decoration: line-through;
			color: #aaa;
		}
		.linkLike {
			color: blue;
			cursor: pointer;
			font-weight: normal;
		}
	</style>
</head>
<body>
	<div id="myapp">
		<h1>
			My ToDos
			<small>({{remaining}}/{{todos.length}})</small>
			<span class="linkLike" v-on="click:purge">[purge]</span>
		</h1>
		<ul>
			<li v-repeat="todos">
				<input type="checkbox" v-attr="checked: done" v-on="click: done = !done">
				<span v-class="done: done">{{task}}</span>
				<span class="linkLike" v-on="click:del($index)">[x]</span>
			</li>
		</ul>
		<input type="text" v-model="newTask" placeholder="new task..." v-on="keyup:add | key enter">
	</div>
	<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/0.11.4/vue.min.js"></script>
	<script>
	var vm = new Vue({
            el: '#myapp',
            data: {
            	newTask: '',
            	todos : [
            	 {task: 'task 1', done: false},
            	 {task: 'task 2', done: true},
            	 {task: 'task 3', done: false}
            	]
            },
            computed: {
            	remaining: function(){
            		var count = 0;
            		for (var i = 0, j = this.todos.length; i < j; i++){
            			if(!this.todos&#91;i&#93;.done){
            				count++;
            			}	
            		}
            		return count;
            	}
            },
            methods: {
            	add: function(){
            		this.todos.push({
            			task: this.newTask,
            			done: false
            		});
            		newTask = ''
            	},
            	del: function(index){
            		if (confirm("are you sure?")){
            			this.todos.splice(index, 1);
            		}
            	},
            	purge: function(){
            		var i = this.todos.length;
            		while (i--){
            			if(this.todos&#91;i&#93;.done){
            				this.todos.splice(i, 1);
            			}
            		}
            	}
            }
        });
	</script>
</body>
</html>

Vue.js

-インタラクティブなインターフェイス
-JavaScriptフレームワーク
-軽量、他のライブラリに依存しない
-ブラウザIE8以下は対応しない
object data/method interface MVVM

CDN :https://cdnjs.com/libraries/vue

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.0/vue.common.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Vue.js</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="styles.css">
	<style>
	</style>
</head>
<body>
	<div id="mycounter">
		<div v-text="count"></div>
		<button v-on="click: countUp">Up</button>
	</div>
	<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/0.11.4/vue.min.js"></script>
	<script>
	// object data/method interface MVVM
	// counter

	var vm = new Vue({
		el: '#mycounter',
		data: {
			count: 0
		},
		methods: {
			countUp: function(){
				this.count++;
			}
		}
	});
	</script>
</body>
</html>

mustatch, v-html

<div>{{'content: ' + content}}</div>
<div v-html="content"></div>

表示非表示

var vm = new Vue({
		el: '#myapp',
		data: {
			content: 'helloworld',
              myStyle: 'red'
			showContent: true
		}
	});

v-repeat

<div id="myapp">
		<ul>
			<li v-repeat="d1">{{$value}}</li>
		</ul>
		<ul>
			<li v-repeat="d2">{{$key}} - {{$value}}</li>
		</ul>
		<ul>
			<li v-repeat="d3">{{name}} - {{score}}</li>
		</ul>
	</div>
		<p>
			<input type="text" v-model="name">
			{{name}}
		</p>

フィルター

		<div v-text="msg | uppercase"></div>
		<div v-text="msg | capitalize"></div>
		<div>{{$data | json}}</div>
        <div id="myapp">
		<li v-repeat="users | filterBy 't' in 'name'">
                <li v-repeat="users | filterBy | orderBy 'name' -1">
		{{name}} - {{score}}
	</div>

computed property

	<div id="myapp">
		side: <input type="text" v-model="side">
		area: {{area}}
	</div>
	<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/0.11.4/vue.min.js"></script>
	<script>
	var vm = new Vue({
            el: '#myapp',
            data: {
            	side: 20
            },
            computed: {
            	area: function(){
            		return this.side * this.side;
            	}
            }
        });
	</script>

TypeScript tutor

静的型付け

var x:number  = 10;
x = "hello";

コンパイルエラーとなります。

var x:number  = 10;
x = "hello";

様々な型

// number, string boolean, any
var i = 10;
var x; // var x: any

var results: number[]
results = [10, 5, 3]

列挙型

enum Signal {
  Red = 0,
  Blue = 1,
  Yellow = 2
}
var result: Signal;

// if (result === Signal.Yellow){}
// if (result === Signal['Yellow']){}
console.log(Signal[2])

関数宣言

function add(a: number, b?: number): number {
 if (b){
 return a + b;
 } else{
 return a + a;
 }
}

console.log(add(5, 3));

関数式

var add = (a: number, b: number): number =>{
 return a + b;
}
var add = (a: number, b: number): number => a + b
console.log(add(5, 3));

関数のオーバーロード

function add(a: number, b: number): number; //シグネチャ
function add(a: string, b: string): string;

function add(a: any, b: any): any {
 if(typeof a === "string" && typeof b === "string"){
 return a + " " + b;
 }
 return  a + b;
}
console.log(add(5, 3));
console.log(add("hello", "world"));

class

class User {
  name: string;
  constructor(name: string){
     this.name = name;
  }
  sayHi(); void {
  console.log("hi! i am " + this.name);
  }
}

var tom = new User("tom");
console.log(tom.name);
tom.sayHi();

getter, setter

class User {
  name: string;
  constructor(private _name: string){
     this.name = name;
  }
  sayHi(); void {
  console.log("hi! i am " + this.name);
  }
  get name(){
   return this._name;
  }
  set name(newValue: string){
    this._name = newValue;
  }
}

extends, override

class User {
  name: string;
  constructor(private _name: string){
     this.name = name;
  }
  sayHi(); void {
  console.log("hi! i am " + this.name);
  }
}

class AdminUser extends User{
 private _age: number;
 constructor(_name: string, _age: number){
  super(_name);
  this._age = _age;
 }
  public sayHi(): void {
    console.log("my age:" + this._age);
    super.sayHi();
  }
}

private:メソッドの中のみ可能
protected:クラスの中のみアクセス可能

静的メンバ:static

class User {
  name: string;
  constructor(private _name: string){
     this.name = name;
     User.count++;
  }
  sayHi(); void {
  console.log("hi! i am " + this.name);
  }
  static count: number = 0;
  
}

インターフェイス

interface Result {
  a: number;
  b: number;
}


function getTotal(result: {a: number; b: number}){
  return result.a + result.b;
}

var result = {
 a: 32,
 b: 58
};

console.log(getTotal(result));

interfaceの継承

interface SpringResult {
  a: number;
}

interface FallResult{
 b: number;
}

interface FinalResult extends SpringResult, FallResult {
 final?: number;
}

ジェネリクス

function getArray<T>(value: T): T[]{
 return[value, value, value];
}

console.log(getArray<number>(3));
console.log(getArray<string>("hello"));

ジェネリクスの制約

interface Result {
  a: number;
  b: number;
}


class MyData<T extends Result>{
  constructor(public value: T){}
  getArray(): T[]{
    return [this.value, this.value, this.value];
  }
}

内部モジュール

module UserModule{
  export var name = "yamada";
  export modlue AddressModlue {
     var zip = "123-4567"
  }
}

console.log(UserModule.name);
console.log(UserModlue.AddressModlue.zip);

Getting started Type Script

TypeScriptは大規模開発にも適したjavascriptの拡張ランゲージです。microsftが開発しています。npmでインストールします。

[vagrant@localhost typescript]$ sudo npm install -g typescript
/usr/bin/tsc -> /usr/lib/node_modules/typescript/bin/tsc
/usr/bin/tsserver -> /usr/lib/node_modules/typescript/bin/tsserver
typescript@2.0.10 /usr/lib/node_modules/typescript

拡張子はtsを使います。
main.ts

class User {

}

console.log("hello world")

変換後のjsファイルです。
main.js

var User = (function () {
    function User() {
    }
    return User;
}());
console.log("hello world");
[vagrant@localhost typescript]$ tsc main.ts
[vagrant@localhost typescript]$ ls
main.js  main.ts
[vagrant@localhost typescript]$ node main.js
hello world

phpでMySQLに接続する書き方

phpでMySQLに接続, sql文にてデータを挿入する書き方例
$stmt->executeにて実行しています。変数の$dbhはdbhandlerの略です。

  try {
    $dbh = new PDO('mysql:host='/DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASSWORD);
  } else (PDOException $e){
    echo $e->getMessage();
    exit;
  }

  $stmt = $dbh->prepare("select * from users where instagram_user_id=:user_id limit 1");
  $stmt->execute(array(":user_id"=>$json->user->id));
  $user = $stmt->fetch();

if (empty($user)){
    $stmt = $dbh->prepare("insert into users(instagram_user_id, instagram_user_name, instagram_profile_picture, instagram_access_token, created, modified) values (:user_id, :user_name, :profile_picture,  :access_token, now(), now());");
    $pramas = array(
      ":user_id" =>$json->user->id,
      ":user_name" =>$json->user->username,
      ":profile_picture" =>$json->user->profile_picture,
      ":access_token"=>$json->access_token
    );
    $stmt->execute($params);

データの取得

$stmt = $dbh->prepare("select * from users where id=:last_insert_id limit 1");
    $stmt->execute(array(":last_insert_id"=>$dbh->lastInsertId()));
    $user = $stmt->fetch();

Instagram Authentication

Client ID, Client Secretを発行し、php、mysqlでInstagramのOauthの仕組みを使ったログインを実装していきます。

リフェレンス
http_build_query:Generates a URL-encoded query string from the associative (or indexed) array provided.
PDO::prepare — 文を実行する準備を行い、文オブジェクトを返す
$dbh = new PDO:PDOオブジェクトのメソッドでデータベースを操作、$dbhという変数でPDOオブジェクトを管理
fetch:フィールドの配列参照として次の行を取り出す
Instagram Authentication: https://www.instagram.com/developer/authentication/

<?php

require_once('config.php');

session_start();

if (empty($_GET&#91;'code'&#93;)){
   // 認証前の準備
   $params = array(
     'client_id' => CLIENT_ID,
     'redirect_uri' => SITE_URL.'redirect.php',
     'scope' => 'basic',
     'response_type' => 'code'
   );
   $url = 'https://api.instagram.com/oauth/authorize/?'.http_build_query($params);

   header('Location: '.$url);
   exit;
   // instagramへ飛ばす
} else {
  // 認証後の処理
  // usr情報の取得
  $params = array(
    'client_id' => CLIENT_ID,
    'client_secret' => CLIENT_SECRET,
    'code' => $_GET['code'],
    'redirect_uri' => SITE_URL.'redirect.php',
    'grant_type' => 'authorization_code'
  );
  $url = "https://api.instagram.com/oauth/access_token";

  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

  $res = curl_exec($curl);
  curl_close($curl);

  var_dump($res);
  exit;

  //user情報の格納
  // ログイン処理
  // index.phpに飛ばす
}

Using OAuth 2.0 to Access Google APIs

Google APIでクライアントID、クライアントシークレットを発行し、OauthでGoogle APIにアクセスします。

<?php

require_once('config.php');
require_once('functions.php');

session_start();

if (empty($_GET&#91;'code'&#93;)){
  // 認証前

  // 認証ダイアログ
  // csrf
  $_SESSION&#91;'state'&#93; = sha1(uniqid(mt_rand(), true));

  $params = array(
        'client_id' => CLIENT_ID,
        'redirect_uri' => 'dev.hogehoge.com:8000/redirect.php',
        'state' => $_SESSION['state'],
        'approval_prompt' => 'force',
        'scope' => 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email',
        'response_type' => 'code'
    );

  // googleへ飛ばす
  $url = 'https://accounts.google.com/o/oauth2/auth?'.http_build_query($params);
    header('Location: '.$url);
    exit;
} else {
  // 認証後
  // ssrf state check
  if ($_SESSION['state'] != $_GET['state']){
    echo "不正な処理でした!";
    exit;
  }

  // access_tokenを取得

  // ユーザー情報

  // DBに格納

  // ログイン処理

  // index.phpへ飛ばす
}

A Tour to Go

The rule is that public functions, types, etc., should be upper case.

Variable

package main

import "fmt"

func main(){
  var msg string
  msg = "hello world"
  fmt.Println(msg)

 msg := "hello world"
  fmt.Println(msg)

  a, b:= 10, 15
}

基本データ型

package main
import "fmt"

func main(){
  a := 10
  b := 12.3
  c := "hoge"
  var d bool
  fmt.Printf("a: %d, b:%f, c:%s, d:%t\n", a, b, c, d)
}

const, iota: https://github.com/golang/go/wiki/Iota

package main
import "fmt"

func main(){
  // const name = "yoshida"
  // name = "tanaka"

  const (
    sun = iota
    mon
    tue
  )
  fmt.Println(sun, mon, tue)
}

pointer

package main
import "fmt"

func main(){
  a := 5
  var pa *int
  pa = &a // a address
  fmt.Println(pa)
  fmt.Println(*pa)
}

function

package main
import "fmt"

func hi(name string) string{
  msg := "hi!" + name
  return msg
}

func main(){
  fmt.Println(hi("tanaka"))
}

swap

package main
import "fmt"

func swap(a, b int)(int, int){
  return b, a
}

func main(){
  fmt.Println(swap(5, 2))
}

array

a := [...]int{1, 3, 5}
a := [5]int{1, 3, 5, 8, 9}
  s := a[2:4]
  fmt.Println(s)
  fmt.Println(len(s))
  fmt.Println(cap(s))
  s := []int{1, 3, 5}
  s = append(s, 8, 2, 10)
  t := make([]int, len(s))
  n := copy(t, s)

map

  m := make(map[string]int)
  m["tanaka"] = 200
  m["sato"] = 300
  fmt.Println(m)

if

score := 83
  if score > 80 {
    fmt.Println("great")
  } else {
    fmt.Println("soso")
  }

range

s := []int{2, 3, 8}
  for i, v := range s{
    fmt.Println(i, v)

構造体

type user struct {
  name string
  score int
}

func main(){
    u := new(user)
    u.name = "tanaka"
    fmt.Println(u)

}

go routine

package main
import (
  "fmt"
  "time"
  )

func task1(){
  time.Sleep(time.Second * 2)
  fmt.Println("task1 finished!")
}
func task2(){
  fmt.Println("task2 finished!")
}

func main(){
  go task1()
  go task2()

  time.Sleep(time.Second * 3)
}

Getting started with Go lang

Go is a cool programming language. Check out golang.org

install:sudo yum install golang

[vagrant@localhost go]$ go version
go version go1.7.3 linux/amd64
package main
import "fmt"

func main(){
  fmt.Println("hello world")
}

Go言語では、go buildでコンパイルしますが、go run xxx.goの1行で、実行することも可能です。

[vagrant@localhost go]$ go build hello.go
[vagrant@localhost go]$ ls
hello  hello.go
[vagrant@localhost go]$ ./hello
hello world
[vagrant@localhost go]$ go run hello.go
hello world