underscore.js

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Underscore.js</title>
  </head>
  <body>
      <script src="underscore-min.js"></script>
      <script>
        (function(){
          var x;
          x = _.shuffle([2, 8, 10, 3]);
          console.log(x);
        })();
      </script>
  </body>
</html>

eachとmap

<script src="underscore-min.js"></script>
      <script>
        (function(){
          /*
          _.each([2, 5, 8], function(num)){
              console.log(num * 2);
          });
          */

          var x = _.map([2, 5, 8], function(num){
              return num * 2;
          });
          console.log(x);

        })();
      </script>

find,filter,contain

      <script>
        (function(){
          
          var a = [2, 5, 8, 42, 12];
          var x;
          /*
          x = _.find(a, function(num){
            return num > 5;
          });
          */
          /*
          x = _.filter(a, function(num){
            return num > 5;
          });
          */
          x = _.contains(a, 10);
          console.log(x);

        })();
      </script>

groupBy, countBy

      <script>
        (function(){
          
          var a = [1, 2, 5, 8, 42, 12];
          var x;
          /*
          x = _.groupBy(a, function(num){
            return num % 3;
          })
          x = _.countBy(a, function(num){
              return num % 2 == 0 ? 'even' : 'odd';
          });
          */
          x = _.sortBy(a, function(num){
              return Math.sin(num);
          });

          console.log(x);

        })();
      </script>

shell script

linux shell script
シェルスクリプトを操作していきます。

[vagrant@localhost shell]$ echo $SHELL
/bin/bash
[vagrant@localhost shell]$ vi hello.sh

vimを使って、hello.shを書き込みます。正常終了でexit 0とします。コメントは#を使います。

#!/bin/bash

echo "hello world"
exit 0

実行権限を与えます。

[vagrant@localhost shell]$ chmod +x hello.sh
[vagrant@localhost shell]$ ./hello.sh
hello world

変数

#!/bin/bash

s="hello"
echo $s$s
exit 0

数値演算はバッククォート`(shift + @)expr `で処理します。

#!/bin/bash

x=10
echo `expr $x + 2`
exit 0

掛け算は、\でエスケープが必要です。()も\( $x + 5 \)と\のエスケープが必要です。
echo `expr $x \* 2`

配列は添え字を使います。全ての要素は@を使います。

a=(2 4 6)
echo ${a[2]}

echo ${a[@]}
echo ${#a[@]}
exit 0

代入、要素の追加

a[2] = 10
a+=(20, 30)

-eqで正しいか否かの条件分岐を行っています。0は正常、1は不正となります。
-eq, -ne, -gt, -ge, -lt, -le、=, !=, -nt, -ot, -e, -dなどのコマンドがあります。

#!/bin/bash

test 1 -eq 2; echo $?

test -e new.sh; echo $?
論理演算子には、-a(and),-o(or),!などあります。

ifの条件分岐

#!/bin/bash

x=70
if test $x -gt 60
then
 echo "ok!"
fi
x=70
if [ $x -gt 60 ]; then
 echo "ok!"
else
 echo "soso.."
fi

case条件分岐

signal="red"
case $signal in
 "red")
  echo "stop!"
  ;;
  "yellow")
  echo "caution"
  ;;
  "green")
  echo "go!"
  ;;
  *)
  echo "...."
  ;;
esac

while文

i=0
while [ $i -lt 10 ]
do
 i=`expr $i + 1`
 echo $i
done

for文: `seq 1 100`

a=(1 2 3 4 5)
for i in ${a[@]}
do
 echo $i
done

コマンド引数を使うと柔軟にプログラムを書けるようになります。
ユーザからの入力を受け付ける。

while :
do
 read key
 echo "you pressed $key"
 if [ $key = "end" ]; then
  break
 fi
done

ファイルの読み込み

i=1
while read line
do
 echo "$i: $line"
 i=`expr $i + 1`
done <$1

関数

function hello(){
 echo "hello"
}

hello

sed

unix系には入っているテキスト処理の仕組みで、パターンスペースで処理を行います。

[vagrant@localhost sed]$ sed --version
GNU sed 4.2.1版

Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE,
to the extent permitted by law.

GNU sed home page: .
General help using GNU software: .
E-mail bug reports to: .
Be sure to include the word ``sed'' somewhere in the ``Subject:'' field.

sedコマンド

[vagrant@localhost sed]$ sed -e '3d' names.text
1 yamada
2 yokoi
4 hirose
5 inui

バックアップを作成し、元ファイルを上書き

[vagrant@localhost sed]$ sed -i.bak '3d' names.text
[vagrant@localhost sed]$ cat names.text.bak
1 yamada
2 yokoi
3 sakamoto
4 hirose
5 inui

コマンドファイルの作成

[vagrant@localhost sed]$ vi ex1.sed
[vagrant@localhost sed]$ sed -f ex1.sed names.text
1 yamada
2 yokoi
4 hirose
5 inui

アドレスの種類


[vagrant@localhost sed]$ sed '3d' names.text
1 yamada
2 yokoi
4 hirose
5 inui
[vagrant@localhost sed]$ sed '!3d' names.text
sed: -e 表現 #1, 文字数 2: 未知のコマンドです: 「3」
[vagrant@localhost sed]$ sed '3!d' names.text
3 sakamoto
[vagrant@localhost sed]$ sed '1d;3d' names.text
2 yokoi
4 hirose
5 inui
[vagrant@localhost sed]$ sed '1,3d' names.text
4 hirose
5 inui
[vagrant@localhost sed]$ sed '1~2d' names.text
2 yokoi
4 hirose
[vagrant@localhost sed]$ sed '$d' names.text
1 yamada
2 yokoi
3 sakamoto
4 hirose

追加コマンド

[vagrant@localhost sed]$ sed '3p' names.text
1 yamada
2 yokoi
3 sakamoto
3 sakamoto
4 hirose
5 inui
[vagrant@localhost sed]$ sed -n '3p' names.text
3 sakamoto
[vagrant@localhost sed]$ sed '3q' names.text
1 yamada
2 yokoi
3 sakamoto
[vagrant@localhost sed]$ sed '1i\--start--' names.text
--start--
1 yamada
2 yokoi
3 sakamoto
4 hirose
5 inui
[vagrant@localhost sed]$ sed '1i\--start --' -e '$a\-- end --' names.text
1 yamada
2 yokoi
3 sakamoto
4 hirose
5 inui
-- end --

Yコマンドによる置換

[vagrant@localhost sed]$ sed 'y/y/Y/' names.text
1 Yamada
2 Yokoi
3 sakamoto
4 hirose
5 inui
[vagrant@localhost sed]$ sed 'y/yo/YO/' names.text
1 Yamada
2 YOkOi
3 sakamOtO
4 hirOse
5 inui

sコマンドで文字列の置換、フラグgですべての文字列を置換します。&の置換もあります。
sed ‘s/\([-5]\) \(.*\)/\2’items.text

ホールドスペースとは、パターンスペースの裏バッファのようなものです。
h:hold -> パターンスペースをホールドスペースに
g:get -> ホールドスペースからパターンスペースに
x:exchange -> パターンスペースとホールドスペースを交換

Regular Expression-正規表現

      <script>
      var s = '@yamada, @sato, @ito';
      var rs = s.match(/yamada/);

      if (rs){
        console.log('マッチしました!');
      }
      </script>

キャレットを使うと、否定、下の例だと、abc以外となります。
[abc]:abc
[a-z]:a~z
[^abc]:abc以外
. :任意の一文字 /y…da/
^ :行頭 /^@yamada/
$ :行末 /@yamada$/
{} :直前の文字の繰り返し回数 0{2} ->00 0{2,}->00以上 0{2,4}->00,000,0000
[a-z]{5} ->a-zの五文字以内
[a-z]{3,6} ->a-zの3~6文字以内
a? : 0or1-> ,a
a* : 0 or more ->, a, aa, aaa
a* : 1 or more -> a, aa, aaa
() :(abc)* -> abc, abcabac
| :or ->(abc|def)
\: \n ->改行, \t ->タブ, \d ->[0-9],\w -> [a-zA-Z0-9_], \s -> スペース \メタ文字 ->メタ文字
i : 大文字小文字を区別しない -> (/yamada/i)
g : 全てのマッチした要素を配列で解す -> s.match(/a/g)
m : 複数行に対応させる -> ^$は一行のみだが、mオプションは複数行
* or + の後の?: 最小マッチ +?, *?
()RegExp s.match(/(.+?)@yamada) , RegExp.$1

<script>
      var s = '@yamada';
      var rs = s.match(/(@[A-Za-z0-9_]{1,15})/);
      console.log(RegExp.$1);
</script>
<script>
      var s = '<title>google.com</title>';
      var rs = s.match(/<title>([^<&#93;+)<\/title>/);
      console.log(RegExp.$1);
</script>

日付の取得

<script>
      var s = '2016-12-01';
      var rs = s.match(/(\d{4})[-\/](\d{2})[-\/](\d{2})/);
      console.log(RegExp.$1+'年'+RegExp.$2+'月'+RegExp.$3+'日');
</script>

mustache

data.yml

title: my data
score: 32

template.mustache

title: my data
score: 32

コマンドライン

[vagrant@localhost mustache]$ mustache data.yml template.mustache
- my data
- 32
title: my data
score: 32
html: <p>
- {{title}}
- {{score}}
- {{{html}}}
- {{&html}}

区切り記号の変更

- {{=<% %>=}}
- <% html %>
<%={{ }}=%>

真偽値の表示

{{#showScore}}
- {{score}}
{{/showScore}}
{{^showScore}}
- score not available
{{/showScore}}

複雑なデータ処理

users:
  - name: yamada
    email: yamada@gmail.com
  - name: hayashi
    email: hayashi@gmail.com
{{#users}}
- {{name}}({{email}})
{{/users}}

部品化して書くことも可能です

{{#users}}
{{>user}}
{{/users}}

YAML

YAMLは構造化されたデータの表現記法で、シンプルに記述することが可能です。スカラー(値)、シーケンス(配列)、マッピング(ハッシュ:key/value)のデータを扱います。

require 'yaml'
emails = YAML.load_file('mydata.yml')
p emails
- yamada@gmail.com
- nakamura@gmail.com
- saitou@gmail.com
[vagrant@localhost mustache]$ ruby parse.rb
["yamada@gmail.com", "nakamura@gmail.com", "saitou@gmail.com"]

シーケンス

[a, b, c]
- a
- 
  - b-1
  - b-2
- c

ハッシュ

name: yamada
score: 90
{name: yamamoto, score: 88}

name: igarashi
score:
  game-1: 30
  game-2: 35

複雑なデータ構造

names:
  - yamada
  - ito
scores:
   - 70
   - 77

names: [yamada, ito]
scores: [70, 77]

- name: yamada
 score: 70
- name: ito
 score: 77

改行

- |+
 this
 is
 a
 pen.

変更

- &leader tanaka
- *leader
- $staff sasaki
- *staff
- *staff
- *staff
- *staff

ハッシュのマージ

common: &common
    user: dbuser
    password: dbpassword
development:
  database: myapp_dev
  <<: *common
production:
  database: myapp_prod
  <<: *common
test:
  database: myapp_test
  <<: *common

ファイル読み出し

require 'yaml'

File.open('mydata.yml') do |io|
 YAML.load_documents(io) do |d|
    p d
  end
end

yamlへの変換を教えてくれる命令です。
puts users.to_yaml

Tabs

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>jQuery UI</title>
    <link rel="stylesheet" href="jquery-ui.min.css">
    <script src="./external/jquery/jquery.js"></script>
    <script src="jquery-ui.min.js"></script>
    <style>
    .ui-selected {
      background: red;
    }
  </style>
  </head>
  <body>
  <div id="tabs">
  
  <ul>
    <li><a href="#menu1">Menu1</a></li>
    <li><a href="#menu2">Menu2</a></li>
    <li><a href="#menu3">Menu3</a></li>
  </ul>

  <div id="menu1">menu 1</div>
  <div id="menu2">menu 2</div>
  <div id="menu3">menu 3</div>
  </div>
  <script>
    $(function(){
      $('#tabs').tabs();
      });
  </script>
  </body>
</html>

Progressbar and slider

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>jQuery UI</title>
    <link rel="stylesheet" href="jquery-ui.min.css">
    <script src="./external/jquery/jquery.js"></script>
    <script src="jquery-ui.min.js"></script>
    <style>
    .ui-selected {
      background: red;
    }
  </style>
  </head>
  <body>
  <div id="bar" style="width:200px"></div>
  <div id="slider" style="width:200px; margin-top:20px"></div>

  <script>
    $(function(){
      $('#bar').progressbar({
          value: 0
      });
      $('#slider').slider({
        slide: function(event, ui){
          console.log(ui.value);
          $('#bar').progressbar('option', 'value', ui.value);
        }
      });
      });
  </script>
  </body>
</html>

Datepicker

Datepickerは表示する日付を制限できます。例:上の動画のように、本日から1カ月先まで
minDate:0,
maxDate: “+1M”

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>jQuery UI</title>
    <link rel="stylesheet" href="jquery-ui.min.css">
    <script src="./external/jquery/jquery.js"></script>
    <script src="jquery-ui.min.js"></script>
    <style>
    .ui-selected {
      background: red;
    }
  </style>
  </head>
  <body>
  <input type="text" id="datepicker">

  <script>
    $(function(){
        $('#datepicker').datepicker({
          dateFormat: "yy-mm-dd",
          minDate:0,
          maxDate: "+1M"
        });
      });
  </script>
  </body>
</html>

dialog

<body>
  <button>open!</button>
  <div id="msg">こんにちは。
  </div>

  <script>
    $(function(){
        $('button').click(function(){
          $('#msg').dialog('open');
        });
        $('#msg').dialog({
          autoOpen: false,
          buttons: {
            "ok": function (){
              $(this).dialog('close');
            }
          },
          title: "title",
          modal: true
        });
      });
  </script>
  </body>

Accordion

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>jQuery UI</title>
    <link rel="stylesheet" href="jquery-ui.min.css">
    <script src="./external/jquery/jquery.js"></script>
    <script src="jquery-ui.min.js"></script>
    <style>
    .ui-selected {
      background: red;
    }
  </style>
  </head>
  <body>
  <div id="accordion">
  <h3><a href="">title</a></h3>
  <div>こんにちは。</div>
  <h3><a href="">title</a></h3>
  <div>こんにちは。</div>
  <h3><a href="">title</a></h3>
  <div>こんにちは。</div>
  <h3><a href="">title</a></h3>
  <div>こんにちは。</div>
  </div>
  <script>
    $(function(){
        $('#accordion').accordion();
      });
  </script>
  </body>
</html>

autocomplete

 <script>
    $(function(){
        var langs = ["ja", "en", "cn", "fr", "sp"];
        $('#langs').autocomplete({
            source: langs
        });
      });
  </script>