diffコマンドメモ

  • すぐ忘れる、環境によってコマンドがあったりなかったりなのでメモ

  • 作業で使ったコマンドのメモ

  • 参考

stackoverflow.com

9 Best File Comparison and Difference (Diff) Tools for Linux

unix.stackexchange.com

www.computerhope.com

what you will learn

  • 環境準備
  • side-by-sideでdiff (human readable)
  • 色付けしてさらに視覚的に見やすくする
  • unified modeでdiff (not human readable)
  • diff outputの見方

環境準備

  • とりあえずcolordiffだけインストール
sudo apt-get install colordiff

side-by-sideでdiff

  • man見れば一瞬だが-yをつければOK
  • 人間が視覚的に見やすいoutput
diff -y ${file1 pacht}/file1 ${file2 pacht}/file2
  • さらに、パイプでlessすると便利
diff -y ${file1 pacht}/file1 ${file2 pacht}/file2 | less
  • さらに、--widthで幅を指定できる(デフォルトは130)
diff -y --width=${columns} ${file1 pacht}/file1 ${file2 pacht}/file2

色付けしてさらに視覚的に見やすくする

  • colordiffにパイプでつなげる
diff -y ${file1 pacht}/file1 ${file2 pacht}/file2 | colordiff
  • 注意点として、file1が表示しきれていないとcolordiffが効かない(デフォルトの130文字で足りない)。その場合は、--widthで割当て幅を広くしてあげる
  • これはcolordiffコマンド単体で使っても同じ
diff -y --width=${columns} ${file1 pacht}/file1 ${file2 pacht}/file2 | colordiff

unified modeでdiff

  • 今度はプログラム的に処理しやすい形
  • -cのcontext modeもあるけどよりシンプルで扱いやすいと思う
diff -u ${file1 pacht}/file1 ${file2 pacht}/file2
diff -u ${file1 pacht}/file1 ${file2 pacht}/file2 | grep -E "${keyword}"
  • unified modeのcharacterでgrep
#file2で追加された行を抽出(+)
diff -u ${file1 pacht}/file1 ${file2 pacht}/file2 | grep -E "^\+"
#file2では削除された行を抽出(-)
diff -u ${file1 pacht}/file1 ${file2 pacht}/file2 | grep -E "^\-"
  • 変更行についての解釈
    • contect modeは変更行は!で表示される
    • unified modeは変更行は削除(-) -> 追加(+)という形で表現されるみたい

diff outの見方

  • 結構雰囲気で見てるから、書いておく
  • diff -y ${file1 pacht}/file1 ${file2 pacht}/file2の場合
  • diff output
    • <

      < - denotes lines in file1.txt

    • >

      > - denotes lines in file2.txt

Docker PHP開発環境 ブラウザリロード自動化(Gulp + Browsersync)

目的

Docker上でPHP開発を行う際のブラウザ自動リロードをGulp+Browersyncで行う

前提

  • Ubuntu16.04

  • npm, nodeはインストール済み

この記事で追加するパッケージ

  • gulp-minify-css : cssファイルのminify
  • gulp-coffee : coffeeのcompile
  • gulp-sass : sassのcompile
  • gulp-notify : 通知
  • browser-sync : ブラウザ自動リロード
  • gulp-connect-php : phpのビルドインサーバーを起動

Task RunnerとしてGulpのビルドシステムをセットアップ

  • Gulpをインストールし、minify cssタスクを実行してみる

  • 参考:

phpocean.com

1. install node

  • 省略

  • 確認

node -v

2. install npm

  • 省略

  • 確認

npm -v

3. テスト用のディレクトリ(プロジェクトディレクトリ)を作成しておく

  • gulpをインストールする前にプロジェクトディレクトリを用意しておく
  • よくプロジェクトという単語が出てくるが、ただのルートとなるディレクトリのこと(だと思う)
  • まず、以下の構成でスタート
Build
└── index.html
  • ちなみに、↑のためにtreeコマンドをインストール

vitux.com

4. install gulp

  • Gulpはグローバルインストール
sudo npm install --global gulp

5. package.jsonを用意する

  • プロジェクトディレクトリ(Build)直下にpackage.jsonを作成する
  • 今回は手動で作る(仕組みを理解するためにnpm initは使わない)
  • 以下の様に最初は空っぽでよい
{

}
  • この時点での構成
Build
├── index.html
└── package.json

6. プロジェクトディレクトリ(Build)でGulpをセットアップする

cd Build
sudo npm install --save-dev gulp
  • ちなみに

--save-dev is used to save the package for development purpose. Example: unit tests, minification..

--save is used to save the package required for the application to run.

  • 空っぽだったpackage.jsonに依存関係が追記されている
{
  "devDependencies": {
    "gulp": "^4.0.2"
  }
}
  • この時点での構成
❯ tree -L 1 Build
Build
├── index.html
├── node_modules
├── package-lock.json
└── package.json

7. Gulp Taskを作成する

  • ここからがGulpのメイン
  • 本題とは関係ないけど、minify cssタスクを設定、実行してみる
  • まずは、プロジェクトディレクトリ(Build)直下に、gulpfile.jsを作る。

In order to tell Gulp what tasks it should run, we need to create a special file that will contain/list those tasks -the file is named gulpfile.js.

  • この時点での構成
❯ tree -L 1 Build
Build
├── gulpfile.js
├── index.html
├── node_modules
├── package-lock.json
└── package.json
  • gulp-minify-cssをインストールする。
sudo npm install --save-dev gulp-minify-css
  • インストール後、gulpfile.jsに以下のコードを追記。(今回は参考サイトのコードをそのまま流用)
var gulp = require('gulp');

var minifyCss = require('gulp-minify-css');

gulp.task('mincss', function(){

    var fb = gulp.src('main.css');

        fb.pipe(minifyCss());

        fb.pipe(gulp.dest('main'));

        return fb;
});

8. minify cssタスクを実行してみる

  • まず、テスト用のcssファイル(main.css)を作成する。
  • このcssファイルの内容がタスク実行後にminifyされることを確認する。
body{
    margin:0;
    padding:0;

    background-color:teal;
}
  • この時点での構成
❯ tree -L 1 Build
Build
├── gulpfile.js
├── index.html
├── main.css
├── node_modules
├── package-lock.json
└── package.json
  • 準備が整ったところで、プロジェクトディレクトリ(Build)をカレントにしてタスクを実行しみてる。
❯ gulp mincss
zsh: correct 'gulp' to 'ul' [nyae]? n
[19:53:56] Using gulpfile ~/Build/gulpfile.js
[19:53:56] Starting 'mincss'...
[19:53:56] Finished 'mincss' after 40 ms
  • zshが反応してしまった。。。とりあえずnにしたらgulpコマンドは実行された。

  • タスク実行後にmainディレクトリが作成されている。その中にminifyされたcssファイルが生成されていれば成功。

❯ tree -L 1 Build
Build
├── gulpfile.js
├── index.html
├── main
├── main.css
├── node_modules
├── package-lock.json
└── package.json
  • 確かに、minifyされたcssファイルが生成されている。これでひとまずGulpタスクを1つ設定、実行することができた。
❯ cat main.css
body{margin:0;padding:0;background-color:teal}

fileのwatchとタスク完了のnotifyタスクを追加する

  • fileをwatchするタスクを追加する
  • 今回はcssファイルを修正し、保存した時に↑のminify cssタスクが自動実行されるようにする
  • また、sass fileのcompileが完了した際にnotifyを出すようにする
  • 参考:

phpocean.com

1. 必要なパッケージをインストール

  • プロジェクトディレクトリ(Build)で以下パッケージをインストール
  • permissionの原因でgulp-sassはsudoなしで実行。。
sudo npm install --save-dev gulp-notify

npm install --save-dev gulp-sass

2. Watchタスクを追加、、する前に

  • ここで、Gulpの公式ページでgulpコマンドラインが新しくなっていることを知ったので、インストールしたgulpを一度アンインストールして再度インストール。(参考にしている記事が古いため、gulpfile.jsのjsの書き方も古そう。。。)
sudo npm rm --global gulp

sudo npm install --global gulp-cli

gulpjs.com

  • そして、gulpfile.jsもさすがに書き直した。
const { src, dest } = require('gulp');
const minifyCss = require('gulp-minify-css');

exports.default = function() {
    return src('main.css')
        .pipe(minifyCss())
        .pipe(dest('main'))
}
  • タスク名を設定していないのでこの場合のタスクの実行は引数なし
gulp
  • プロジェクトのtaskを確認できる
❯ gulp --tasks
[22:52:17] Tasks for ~/Build/gulpfile.js
[22:52:17] └── default
  • せっかくなので、task名を設定しておく。あと関数に切り出しておく
const { src, dest } = require('gulp');
const minifyCss = require('gulp-minify-css');

function mincss(cb) {
    return src('main.css')
        .pipe(minifyCss())
        .pipe(dest('main'))
}

exports.mincss = mincss;
❯ gulp --tasks
[22:59:31] Tasks for ~/Build/gulpfile.js
[22:59:31] └── mincss
❯ gulp mincss
  • TaskにはPublic tasksPirvate tasksがある。publicはgulpコマンドで指定して独立で実行できるタスク。

gulpjs.com

  • さらにGulpでは複数あるタスクを直列or並列に結合(compose)し巨大なタスク群を構成できる。
  • series()

    To have your tasks execute in order, use the series() method.

  • parallel()

    For tasks to run at maximum concurrency, combine them with the parallel() method.

gulpjs.com

3. watchタスクを追加

  • watchsrcdestと同じくgulpのobject。
  • なので、watchに関しては今までインストールしてきたパッケージは関係ない
  • 参考記事の書き方が古いので同じことを公式のページを参考にES6以降のJS風に書き換える(これが今時なのかよくわからん。。。)
  • 一番シンプルな使い方はwathc(${監視対象ファイル}, ${TASK})
  • listenするeventはdefaultは全て。対象eventを明示的に指定もできる。

     The watch function takes two arguments: the file(s) to watch and a call to action. The second argument can be a closure (anonymous function) or a javascript object.

const { src, dest, series, watch } = require('gulp');
const minifyCss = require('gulp-minify-css');

function mincss(cb) {
    return src('main.css')
        .pipe(minifyCss())
        .pipe(dest('main'))
}

exports.mincss = function() {
    watch('main.css', series(mincss));
    console.log('seen');
}
  • gulp mincssを実行すると、seenが表示される。(バックグラウンド実行ではない)。この状態がfileをwatchしている状態

  • 複数種類のファイルをwatchしてみる

  • 今回はcoffeeスクリプトwatchを追加してみる
  • まず、gulp-coffeeをインストール
npm install --save-dev gulp-coffee
  • gulpfile.jsを編集。
    • coffeeスクリプトコンパイルする関数を追加
    • タスクをdefaultに変更
    • watchに登録するタスクにscriptsを追加。
    • 並列でいいかと思ったのでparallelに変更
  • defaultにしたので実行コマンドは以下でOK
gulp
  • 変更後
const { src, dest, parallel, watch } = require('gulp');
const minifyCss = require('gulp-minify-css');
const coffee = require('gulp-coffee');

function mincss(cb) {
    return src('*.css')
        .pipe(minifyCss())
        .pipe(dest('main'))
}

function scripts(cb) {
    return src('*.coffee')
        .pipe(coffee())
        .pipe(dest('js'));
}

exports.default = function() {
    watch(['*.css', '*.coffee'], parallel(scripts, mincss));
    console.log('seen');
}
  • 追加したわりに試さないんかーいとなった

4. さらにSassファイルもcompileしてみる

  • さらに本題が外れるがSassのcompileもしてみる
  • まずは、gulp-sassをインストールする
npm install --save-dev gulp-sass
  • main.cssmain.scssにリネーム
  • sassをcompileするタスクを追加する。
    • それ以外にも、watchを切り出したのとseries,parallelをネストして整理してみた
    • parallelとseriseのネストは公式ドキュメントの通りにした。(色々やるとエラーが出た。非同期怖い)
const { src, dest, series, parallel, watch } = require('gulp');
const minifyCss = require('gulp-minify-css');
const coffee = require('gulp-coffee');
const sass = require('gulp-sass');

function mincss(cb) {
    return src('main.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(minifyCss())
        .pipe(dest('main'))
}

function scripts(cb) {
    return src('script.coffee')
        .pipe(coffee())
        .pipe(dest('js'));
}

function watcher(cb) {
    watch(['*.scss', '*.coffee'], series(mincss, scripts));
    console.log('seen');
}

exports.build = series(mincss, scripts);
exports.default = parallel(series(mincss, scripts), watcher);
  • main.scssの中身を編集する
$color-title: #333;

h1{
    color:$color-title;
}
  • gulpを実行してみる(gulp buildでもいい)
  • mainディレクトリに以下の内容でmain.cssが生成されていれば成功
h1{color:#333}

5. Nofificationが出るようにする

  • まだまだ本題から外れる
  • まずは、gulp-sassをインストールする
npm install --save-dev gulp-notify
  • gulpfile.jsを編集する
const { src, dest, series, parallel, watch } = require('gulp');
const minifyCss = require('gulp-minify-css');
const coffee = require('gulp-coffee');
const sass = require('gulp-sass');
const notify = require('gulp-notify');

function mincss(cb) {
    return src('main.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(minifyCss())
        .pipe(dest('main'))
        .pipe(notify('Done!'));
}

function scripts(cb) {
    return src('script.coffee')
        .pipe(coffee())
        .pipe(dest('js'));
}

function watcher(cb) {
    watch(['*.scss', '*.coffee'], series(mincss, scripts));
    console.log('seen');
}

exports.build = series(mincss, scripts);
exports.default = parallel(series(mincss, scripts), watcher);
  • gulp or gulp buildを実行して、通知が出ればOK

Browsersyncを用いたLive Reloading [静的ファイル]

  • 少し本題に近づく
  • 参考:

phpocean.com

www.browsersync.io

1. Browsersyncでブラウザ自動リロードしてみる

npm install --save-dev browser-sync
  • gulpfile.jsを編集する
    • この設定はBrowsersyncの公式ドキュメントを参考に書いてみた
    • https://www.browsersync.io/docs/gulp
    • Browsersyncはローカルサーバーを立ち上げる
      • baseDir: たぶんローカルサーバーのドキュメントルート。プロジェクトのディレクトリにしておけばよさそう
      • port: ローカルサーバーのポート。指定しない場合は3000
      • open: task実行時にブラウザの自動起動のon/off
      • notify: 通知するかどうか
    • 今回はindex.htmlだけwatchして、変更があった際に自動リロードするようにした
const { src, dest, series, parallel, watch } = require('gulp');
const minifyCss = require('gulp-minify-css');
const coffee = require('gulp-coffee');
const sass = require('gulp-sass');
const notify = require('gulp-notify');
const browserSync = require('browser-sync').create();

function mincss(cb) {
    return src('main.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(minifyCss())
        .pipe(dest('main'))
        .pipe(notify('Done!'));
}

function scripts(cb) {
    return src('script.coffee')
        .pipe(coffee())
        .pipe(dest('js'));    
}

function html(cb) {
    src('index.html');
}

function browserSyncInit(cb) {
    browserSync.init({
        server : {
            baseDir: './' 
        },
        port: 8081,
        open: true,
        notify: true
    });
}

function watcher(cb) {
    browserSyncInit();
    // compile tasks
    watch(['*.scss', '*.coffee', 'index.html'], series(mincss, scripts, html));
    // live reload task
    watch('index.html').on('change', browserSync.reload);

    console.log('under watching...');
}

exports.build = series(mincss, scripts);
exports.default = parallel(series(mincss, scripts), watcher);
  • gulp実行を実行すると自動でブラウザ(or tab)も起動し、index.htmlの内容が表示される
gulp
  • 試しに、index.htmlの内容を変更するとブラウザが自動でリロードされることが確認できればOK

エラー ENOSPC: System limit for number of file watchers reached

1.発生したエラー

  • 次の作業をするために試行錯誤しているうちにこのエラーが発生するようになった。
❯ gulp
[22:46:02] Using gulpfile ~/Build/gulpfile.js
[22:46:02] Starting 'default'...
[22:46:02] Starting 'watcher'...
[22:46:02] Starting 'mincss'...
[22:46:02] 'watcher' errored after 56 ms
[22:46:02] Error: ENOSPC: System limit for number of file watchers reached, watch 'index.html'
    at FSWatcher.start (internal/fs/watchers.js:165:26)
    at Object.watch (fs.js:1275:11)
    at createFsWatchInstance (/home/shouhei/Build/node_modules/chokidar/lib/nodefs-handler.js:38:15)
    at setFsWatchListener (/home/shouhei/Build/node_modules/chokidar/lib/nodefs-handler.js:81:15)
    at FSWatcher.NodeFsHandler._watchWithNodeFs (/home/shouhei/Build/node_modules/chokidar/lib/nodefs-handler.js:233:14)
    at FSWatcher.NodeFsHandler._handleFile (/home/shouhei/Build/node_modules/chokidar/lib/nodefs-handler.js:262:21)
    at FSWatcher.<anonymous> (/home/shouhei/Build/node_modules/chokidar/lib/nodefs-handler.js:495:21)
    at FSReqCallback.oncomplete (fs.js:160:5)
[22:46:02] 'default' errored after 61 ms
[22:46:02] The following tasks did not complete: <series>, mincss
[22:46:02] Did you forget to signal async completion?

2.原因

  • 原因はgulpではなくOS(Ubuntu)のinotifyの監視ファイル数のlimitを超えたことによるエラーだった。

参考:

github.com

3.対処

  • 参考:

github.com

  • まず、現在のinotifyの上限を確認
❯ cat /proc/sys/fs/inotify/max_user_watches
8192
  • 今回は一時的に上限を変更
❯ sudo sysctl fs.inotify.max_user_watches=524288
fs.inotify.max_user_watches = 524288

~/Build
❯ cat /proc/sys/fs/inotify/max_user_watches
524288
  • sysctl関連のファイルのリロード(ipv6の設定ファイルがないらしいが今回の件とは関係ないので放置)
❯ sudo sysctl -p
sysctl: cannot stat /proc/sys/net/ipv6/conf/all/disable_ipv6: そのようなファイルやディレクトリはありません
sysctl: cannot stat /proc/sys/net/ipv6/conf/default/disable_ipv6: そのようなファイルやディレクトリはありません
  • 上限を変更後、gulpを実行するとエラーは発生しなくなった

Browsersyncをを用いたLive Reloading [動的ファイル]

1. index.phpを用意

  • phpファイルをwatchして、ブラウザ自動リロードする
  • index.htmlindex.php に変更

2. gulpfile.jsも修正

  • gulpfile.jsもindex.phpに変更する
const { src, dest, series, parallel, watch } = require('gulp');
const minifyCss = require('gulp-minify-css');
const coffee = require('gulp-coffee');
const sass = require('gulp-sass');
const notify = require('gulp-notify');
const browserSync = require('browser-sync').create();

const paths = {
    html: 'index.php',
    css: 'main.scss',
    script: 'script.coffee'

}

function mincss(cb) {
    return src(paths.css)
        .pipe(sass().on('error', sass.logError))
        .pipe(minifyCss())
        .pipe(dest('main'))
        .pipe(notify('Done!'));
}

function scripts(cb) {
    return src(paths.script)
        .pipe(coffee())
        .pipe(dest('js'));    
}

function html(cb) {
    src(paths.html);
}

function browserSyncInit(cb) {
    browserSync.init({
        server : {
            baseDir: './' 
        },
        port: 8081,
        open: true,
        notify: true
    });
}

function watcher(cb) {
    browserSyncInit();
    // compile tasks
    watch(['*.scss', '*.coffee', paths.html], series(mincss, scripts, html));
    // live reload task
    watch(paths.html).on('change', browserSync.reload);

    console.log('under watching...');
}

exports.build = series(mincss, scripts);
exports.default = parallel(series(mincss, scripts), watcher);

3. gulp実行するが、Errorとなる

  • gulpを実行。しかし、ローカルサーバーが起動し、ブラウザも自動起動するがCannot GET / が表示されるだけ。(タブにはErrorと表示されている。)
  • 原因は、gulpのローカルサーバーではphpまでは実行してくれない。何かしらphpサーバーを用意する必要がある

4. gulp-connect-php

  • 今回は、phpのビルドインサーバーを起動するパッケージ gulp-connect-php を使ってみる

www.npmjs.com

5. 必要なパッケージをインストール

npm install --save-dev gulp-connect-php

6. gulpfile.jsを修正

  • 前回のstatic file serverの場合: Browsersyncがローカルサーバーとなっていた
  • 今回はgulp-connect-phpでビルドインのサーバーを立ち上げ、BrowsersyncはそのサーバーのProxyとなる
    • クライアント(ブラウザ)からProxy(Browsersync localhost:3000)を介して、phpビルドインサーバー(localhost:8082)に接続する
const { src, dest, series, parallel, watch } = require('gulp');
const minifyCss = require('gulp-minify-css');
const coffee = require('gulp-coffee');
const sass = require('gulp-sass');
const notify = require('gulp-notify');
const browserSync = require('browser-sync').create();
const connectPHP = require('gulp-connect-php')

const paths = {
    html: 'index.php',
    css: 'main.scss',
    script: 'script.coffee'
}

function mincss(cb) {
    return src(paths.css)
        .pipe(sass().on('error', sass.logError))
        .pipe(minifyCss())
        .pipe(dest('main'))
        .pipe(notify('Done!'));
}

function scripts(cb) {
    return src(paths.script)
        .pipe(coffee())
        .pipe(dest('js'));
}

function html(cb) {
    src(paths.html);
}

function browserSyncInit(cb) {

    //-------------------------------------
    // Start a Browsersync static file server
    //-------------------------------------
    // browserSync.init({
    //     server : {
    //         baseDir: './' 
    //     },
    //     port: 8081,
    //     open: true,
    //     notify: true
    // });

    //-------------------------------------
    // Start a Browsersync proxy
    //-------------------------------------
    browserSync.init({
        proxy: 'http://localhost:8082'
    });
}

function watcher(cb) {
    browserSyncInit();
    // compile tasks
    watch(['*.scss', '*.coffee', paths.html], series(mincss, scripts, html));
    // live reload task
    watch(paths.html).on('change', browserSync.reload);

    console.log('under watching...');
}

function php(cb) {
    connectPHP.server({
        base: '.',
        hostname: 'localhost',
        port:8082
    })
}

exports.build = series(php, mincss, scripts);
exports.default = parallel(series(php, mincss, scripts), watcher);

7. gulpを実行

  • ブラウザが自動起動するが今回はBrowsersyncのプロキシを介すので、localhost:3000にアクセスすることになる
    • なので、裏で起動してるphpサーバー(localhost:8082)には直接アクセスしない

f:id:mizushou:20190609231727p:plain

❯ gulp
[01:58:06] Using gulpfile ~/Build/gulpfile.js
[01:58:06] Starting 'default'...
[01:58:06] Starting 'watcher'...
[01:58:06] Starting 'mincss'...
under watching...
PHP 7.0.33-0ubuntu0.16.04.4 Development Server started at Sun Jun  9 01:58:07 2019
Listening on http://localhost:8082
Document root is /home/shouhei/Build
Press Ctrl-C to quit.
[Browsersync] Proxying: http://localhost:8082
[Browsersync] Access URLs:
 -------------------------------------
       Local: http://localhost:3000
    External: http://192.168.1.23:3000
 -------------------------------------
          UI: http://localhost:3001
 UI External: http://localhost:3001
 -------------------------------------
[Sun Jun  9 01:58:07 2019] 127.0.0.1:56466 [200]: /
[01:58:07] gulp-notify: [Gulp notification] Done!
[01:58:07] Finished 'mincss' after 250 ms
[01:58:07] Starting 'scripts'...
[01:58:07] Finished 'scripts' after 102 ms
[Sun Jun  9 01:58:07 2019] 127.0.0.1:56474 [200]: /
[01:58:17] Starting 'mincss'...
[01:58:17] gulp-notify: [Gulp notification] Done!
[01:58:17] Finished 'mincss' after 28 ms
[01:58:17] Starting 'scripts'...
[01:58:17] Finished 'scripts' after 12 ms
[01:58:17] Starting 'html'...
[Browsersync] Reloading Browsers... (buffered 2 events)
[Sun Jun  9 01:58:17 2019] 127.0.0.1:56532 [200]: /

8. 最後にブラウザ自動リロードが実行されるかを確認する

  • index.phpを編集し、ブラウザ自動リロードが実行されればOK

コマンドラインorスクリプトでのSQLコマンドメモ

SQL作業コマンドメモ

  • 作業で使ったコマンドのメモ

  • 参考

www.shellhacks.com

Shell Script or Command line からのQuery実行

$ mysql -u${USER} -p${PASSWORD} -e "SQL_QUERY"
  • database指定
$ mysql -u${USER} -p${PASSWORD} -D ${DATABASE} -e "SQL_QUERY"

テーブル一覧表示

$ mysql -u${USER} -p${PASSWORD} -D ${DATABASE} -e "show tables";
  • Suppressing column headings
$ mysql -u${USER} -p${PASSWORD} -D ${DATABASE} -N -e "show tables";
  • Suppress table borders
$ mysql -u${USER} -p${PASSWORD} -D ${DATABASE} -B -e "show tables";

全テーブルのshcema情報をファイル出力

$ for TABLE in `mysql -u${USER} -p${PASSWORD} -D ${DATABASE} -N -e "show tables"`; do echo -e "TABLE : $TABLE \n" >> schema.txt; mysql -u${USER} -ppassword -D ${DATABASE} -e "describe $TABLE" >> schema.txt; echo -e "\n" >> schema.txt; done;

18.6501x Bayesian Statistics(Unit5) チェックリスト

What you learned

Lec 17: Introduction to Bayesian Statistics

  • frequentist
    • 古典的な統計学。Unit4までやってきた統計。Bayesianに対する言葉。
  • frequentist vs bayesian
    • bayesian
      • 特徴
        • prior beliefを具現化したprior distributionをdataでupdateして、posterior distributionを得る
      • true parameter
        • r.v or unccertanity regarding the true parameter
      • specifyするもの
        • set of possible parameter
        • prior distribution π(theta)
    • frequentist
      • 特徴
        • dataからのみ推定
        • true parameter thetaをfixして推定する (MLE,MM,M-estimation)
      • true parameter
        • r.vではない
      • specifyするもの
        • statical model for the observation
          • set of possible parameter
          • probability model
  • Beta distribution
    • 統計の道具としてのベータ分布
    • 針金細工のような分布
    • prior beliefを反映した分布を表現するのに便利

ja.wikipedia.org

  • priorのデザイン
    • 確率pがパラメーターであれば、uniform,betaなど
    • prior beliefを反映した分布を選択する
  • prior and posterior
    • prior
      • 慣習的にπで表すことが多い
    • data/experiment
      • Ln(|theta)はconditional joint liklihood.つまり、conditional joint pdf/pmf. thetaをfix.
      • これは、frequentistのlikelihoodと同じ
    • posterior
      • データX1,,,,,,Xnの条件付きのthetaの分布をposteriorと呼ぶ
      • likelihoodにpriorをかけたものに比例する(not normarization).proportional notationで表される。
      • normarizationはposteriorが1になるようなな定数
    • you have likelihood
      • frequentist
        • maximize this thing
      • baysian
        • multiple a prior to likelihood and I have a posterior
  • no imformative priors
    • 事前情報がない場合でもBayesianアプローチは使える。その場合はpriorをどのように選択すればよいか?
      1. constant pdf : π(θ) ∝ 1
      2. boundedの場合 : uniform
      3. unboundedの場合 : properなpdfを定義できない
        • improper prior : not integrableなπ(θ).つまり、積分したら数値に収束せず発散してしまう関数。measurable, non-negative function
        • improperでもBaysianのstepは適用できる。

What you noticed

  • priorのπ(theta)の分布を見るときに注意。thetaの分布なのでthetaがxと入れ替わる。parameterと勘違いしないようにする
  • proporthional notationに慣れる。基本的にパラメーターに依存しない項は除いてシンプルな形にして考える
  • proportionality notation in the process of computing the posterior distribution for a parameter of interest proportionality notationが結構重要

Lec 18: Jeffrey's Prior and Bayesian Confidence Interval

  • Explain the important factors involved in choosing a prior distribution.

    • Bernoulli experimentの場合
      • prior
        1. Beta(a,a) : informativeの時。何かしら実験前に事前情報がある場合
          • 確率を表す1 parameterの分布を表すの適している
        2. Uniform : non-infomativeの時
          • MLE = Maximum a posteriorになる
  • Distinguish between conjugate priors and non-conjugate priors .

    • conjugate : priorとposteriorの分布同じ分布族であるとき
      • 特にBeta分布はBayesianに適した分布。BetaはposteriorもBeta分布になる?  
  • Compute Jeffreys Prior and understand the intuition behind its significance.

    • Jeffreys Prior
      • Def
        • πj(θ) ∝ √detI(θ)
          • fisher infoで定義される。d=1の時は単にfisher info root squared.
      • お気持ち
        • これもnon-informativeの時のprior
        • データ(observation)のstatical model(分布)に関連したpriorを定義しとけば何かと便利そうじゃないという感じ?
        • experimentの分布でpriorが決まる(決めちゃう)
        • This prior depends on the statistical model used for the observation data and the likelihood function.
      • property
        1. The Jeffreys prior gives more weight to values of theta whose MLE estimate has less uncertainty.
        2. As a result, the Jeffreys prior yields more weight to values of theta where the data has more information towards deciding the parameter.
        3. The Fisher information can be taken as a proxy for how much, at a particular parameter value theta, would equivalent shifts to the parameter influence the data. Thus, Jeffreys prior gives more weight to regions where the potential outcomes are more sensitive to theta slight changes in .
      • ↑の話はなんとなく共振回路のq値的な話と似てるかも。shapeのシャープさがsenstivieに関わるところ。
      • つまり、fisher-infoが大きいほど、senstiveなJeffreys priorになる
      • reparamaetrization invariance(パラメーター付け替え不変)
        • まだ理解できていない
        • prameterを媒介変数表示した時に、Jeffreys priorは媒介変数で置換しても不変
        • Jeffereys priorをただ媒介変数で置換しただけではだめ。媒介変数でのfisher-infoを求め直す必要がある。その際に元のパラメーターを媒介変数で微分する項が出てくるなど変換には注意。(と言っても高校数学レベルの話)
  • Apply Bayesian statistics in simple estimation and inference problems.

    • Bayesian confidence region
      • これはfrequentistのC.IとBayesian confidence regionは明確に異なる概念
      • posteriorのparameter spaceのrandom subset RがBayesian confidence region
      • 求め方は簡単で、posteriorから1-αの区間(なので、いまいちC.Iとの明確な違いがわからない)
      • あと、Rはpriorい依存する
    • Bayesian estimation
      • Bayesian Frameworkでも、frequentistでやったようにパラメーター推定ができる
      • [1] Bayes estimator
        • posteriorをpdf/pmfとしたパラメーターの期待値
        • つまり、posterior mean
        • priorに依存する
        • 実際の計算
          1. そのまま積分をする。(しかし大概は手計算は厳しいことが多い)
          2. posteriorがfamousなdistributionだと見抜く
            • posteriorがBeta分布やGamma分布であることが多い。その場合はBeta分布やGamma分布のパラメーターに対応する値を抜き出して、各々の期待値の形に代入して求める(問題ではこのパターンが一番多かった)
      • [2] Maximum a posteriori(MAP)
        • posteriorを最大にするパラメーター
  • Compare and contrast results from Bayesian and frequentist statistical methods.

What you noticed

  • Bayesでは、Beta分布、Gamma分布にお世話になることが多い
  • proper or improperの判別は、parameter spaceで積分して収束するかしないかで判別。収束しないと正規化できない。
  • inverse Gammaだと?!ってなった。気づかなかった

en.wikipedia.org

その他

  • Beta,Gamma関数出てくると、すぐにstring theoryの教科書とか出してくるから、弦理論ちょっと読みたくなった。
  • 以下は、参考文献ではなく読みたいなという本(ちょうどMITだし、学部レベルの量子力学電磁気学程度の知識で読めるらしい。)

参考文献

初級講座弦理論 基礎編

初級講座弦理論 基礎編

カナダのStudy Permits(学生ビザ、学生パーミット)の有効期限について

カナダのStudy Permitの失効について

カナダの学生に関する規則に関しては、司法局のWebサイト(この記事の中程にlinkを記載)にある、Table Contentsの PART12 - Students に記載されている。 特に、Study Permitの失効に関してはその中の No.222 - DIVISION 5 に記載されいている。 以下、No.222より。(誤訳、解釈の誤りなどがある可能性があるのでこの記事に貼ったlinkで原文を確認して欲しい)

  • Study Permitは以下の内、いずれか一番早い日付が失効日となる
    1. 学業が修了した日(卒業した日?)から90日目の日
    2. removal orderが失効可能になった日
    3. Permitの有効期限が切れた日

上記を調べるために得た知識を、以下にまとめておく。

法律、規則の確認

確かな確証を得たいのであれば、日本で言う法務省のサイトを確認するしかない。 カナダでは直訳では司法省となる「Department of Justice」のWebサイトで法律、規則等を確認できる。 https://www.justice.gc.ca/eng/

移民および難民保護規則

1. Table of Contents(目次)

Immigration and Refugee Protection Regulations

https://laws-lois.justice.gc.ca/eng/regulations/SOR-2002-227/index.html

2. Study Permitsの有効性と満期について

以下のNo.222に該当規則が記載されている。(2019.4月現在)

210 PART 12 - Students - No. 222 - DIVISION 5 - Validity and Expiry of Study Permits https://laws-lois.justice.gc.ca/eng/regulations/SOR-2002-227/section-222.html

No.222に記載されている、Study Permitsの文章

Invalidity

222 (1) A study permit becomes invalid upon the first to occur of the following days:

(a) the day that is 90 days after the day on which the permit holder completes their studies,

(b) the day on which a removal order made against the permit holder becomes enforceable, or

(c) the day on which the permit expires.

Marginal note:Exception

(2) Paragraph (1)(a) does not apply to

(a) a person described in any of paragraphs 300(2)(a) to (i); or

(b) a family member of a foreign national who resides in Canada and is described in any of paragraphs 215(2)(a) to (i).

SOR/2014-14, s. 16.

DockerコンテナでPHP練習環境構築

用意した動機

Udemyのphpのコースを受講し始めたが、そのコースではCodeanywhereを前提としていた。Codeanywhere自体はネットワーク環境さえ問題なければ使いやすいのだが、無料期間が一週間のため自前でphpの簡易な練習環境を用意した。

www.udemy.com

PHP実行環境

  • Dockerコンテナで用意した。
  • 今回はシンプルにApacheをappサーバーとしたイメージを利用している。
  • コンテナ起動時にコンテナのルートディレクトリとホストのディレクトリを共有ディレクトリにすることで、ホスト側で普段使用しているテキストエディターでPHPファイルを編集、追加して作業する。
  • ローカルなので、サーバーはファイル一覧を表示するようにしている。

1. git cloneをする

github.com

2. Dockerfileからイメージを作成(Dockerfileに修正がなければ初回のみ)

  • イメージ作成
docker build -t php-pg .
  • イメージ確認
docker images

3. 共有ディレクトリを指定してコンテナ起動

docker run -it -d --name php-pg -v ${PATH}/contents:/var/www/html/ -p 8080:80 php-pg
docker run -it -d -v /home-dir-path/php/php-playgrounds/contents:/var/www/html/ --name php-pg -p 8080:80 php-pg

4. ブラウザで確認

http://localhost:8080/ にアクセスしてHello, World!が表示されることを確認する

5. 実際に練習

  • 3.で指定したホストの共有ディレクトリ内で作業する。元々あるindex.phpを編集してもいいし、新規にファイルやディレクトリを作成するなどしてもいい。

  • http://localhost:8080/をブックマークしておくと作業効率がいい。

その他

Apacheのファイルの一覧表示の設定の該当箇所。(Indexesを追加)

php-playground/apache2.conf at d18b69900bfb5723a4b7dc07e9dc0da10f3eeab9 · mizushou/php-playground · GitHub

18.6501x Fundamentals of Statistics(Unit3) チェックリスト

Unit3 Methods for estimation

What you learned

Lec8: Distance measures between distributions

  • Unit2までは、estimatorをsample aveとして直感的に決めてきた
  • 今回は、最適なestimatorを決める手法を学ぶ
  • 今までは、sample aveの期待値がLLNよりパラメーターに収束する場合だけしか、ほぼ扱ってこなかった。
  • そのため、sample aveはestimatorとして活用できた。
  • しかし、パラメーターの値に収束しない場合は、estimatorは何にすればよいだろうか?
  • 大きく、次の3つの方法が考えられる。
    1. Maximum likelihood estimation(最尤法)
    2. Method of moments
    3. M-estimators
  • Total variation distance(TV)
    • これはいわゆる、距離
  • Kullback-Leibler divergence(KL)
    • 相対エントロピーとしても有名
    • 確率測度間の距離を最小化問題は、KLを使って考える
    • TVは距離であったが、KLは距離の定義を満たさないので距離ではない、divergenceと呼ばれる
    • KLの最小 ⇔ likelihoodの最大値。This is the maximum likelihood principle
  • Likelihood
    • データとパラメーターを引数にとる関数
    • 値は確率or確率密度と考えていい。joint pmf or joint pdf

Lec9: Introduction to Maximum Likelihood Estimation

  • 以下の確率変数のlikelihoodを計算

    • Bernoulli
    • Poisson
    • Gussian
    • Exponenssial
    • Uniform
  • Maximum likelihood estimator(MLE)

    • log-likelihood estimatorは実際に計算するときに便利なのでよく使う
  • 一般的な教科書はだいたいminimizingで書かれているが、この授業ではmaximizingで進める
  • concave(上に凸)/convex(下に凸)の判定
    • gradientの導入
    • Hessian matrixの導入
    • Hessian matrixからconcave/convexを判定
  • 実際にMLEを計算
    • Bernoulli
    • Poisson
    • Gaussian

What you noticed

  • concave/convexの判定は、Hessian matrixから数値化、または固有値を求めて判断
  • MLEを計算する際は、log-likelihoodを使うことが大半。便利だから。
  • パラメーターが1つの場合は、高校数学と同じ。

その他

  • ベクトル解析を少し復習が必要

参考文献

自然科学の統計学 (基礎統計学)

自然科学の統計学 (基礎統計学)

プログラミングのための線形代数

プログラミングのための線形代数