Djangoのmigrationでforeignkeyを設定する

意外とModel側と似たような書き方で思ったとおりに書ける。シンプル。

        migrations.CreateModel(
            name='ChildModel',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True)),
                ('parent_model', models.ForeignKey('ParentModel', on_delete=models.CASCADE)),
            ],
            options=[
                ('db_table', 'child_models'),
            ]
        ),

これでMulキーも付きます。
int型。
DB上のカラム名は 'parent_model_id' になる。
環境:Django2.0 Python3.6

macのクリーンインストール @ansibleで自動インスコ付き【2018/01版】

雑なメモ書きですが

OSのクリーンアップ

  • 必要なファイル等は外付けHDDなどに退避する。

今回は新規のMBPにインストールしたのでディスク消去はしていない

  • 電源起動時に、command + Rを押しっぱなしにする
  • OS X ユーティリティからディスクユーティリティを選択
  • ディスクを消去する
  • OS X ユーティリティからOS Xを再インストールするを選択
  • ソフトウェア使用許諾契約に同意する
  • インストール先のディスクを選択してインストール
  • AppleIDとパスワードを入力
  • OSダウンロードが始まり、その後インストールが開始されるので放置

  • 今は情報の転送はしないを選択
  • Macを探すは許可する
  • コンピュータアカウントを作成(iCloudアカウントは使わなかった)
  • FileVaultディスク暗号化を有効にする
  • 診断と使用状況はチェックした
  • クリーンインストールが終わったらApp storeからシステムアップデートをかける。

最新のOSをインストール

  • 新規で購入したMBPなのにHighSierraが入っていなかったのでインストール

Xcodeをインストール

  • 時間がかかるので最初にやる。App storeからXcodeをインストール。
  • インストールが終わったらXcodeを起動して規約に同意する
  • Xcodeのライセンス認証。
  • sudo xcodebuild -license

Dock

  • サイズを小さくする
  • 拡大にチェック。1/4ぐらい
  • 画面上の位置を左に変える
  • 以下をDockから消去
    Siri、Safari、連作先、カレンダー、メモ、リマインダー、マップ、写真、メッセージ、FaceTime
    Pages、Numbers

セキュリティとプライバシー

  • スリープとスクリーンセーバの解除を15分後に
  • Apple WatchでこのMacのロックを解除できるようにする → チェック入れても動かなかったので未設定

キーボード

  • キーのリピートを速く(最速)
  • リピート入力時間を短く(最短)

トラックパッド

  • タップでクリックにチェック
  • 軌跡の速さを速くする(最速)

サウンド

  • メニューバーに音量を表示にチェック

iCloud

  • iCloud、キーチェーン、Macを探すにチェックのみ

共有

  • コンピュータ名をかわいいのに変える

日付のオプション

  • 曜日を表示
  • 日付を表示

表示オプション

  • デスクトップを右クリック → 表示オプションを表示
  • アイコンサイズ 16x16
  • ラベルの位置 右側
  • 表示順序 名前

Homebrewをインストールする

Homebrewのインストール

xcode-select --install
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/insta

参考サイトの情報のままだと上手く行かないのでanacondaインストールする

brew install python ---> 2.7系が入るので嫌。3系のanaconda入れたい
brew install ansible ---> pythonのフォルダにインストールしようとする
brew install caskroom/cask/brew-cask ---> エラー出る

anacondaは以下からダウンロード
https://www.anaconda.com/download/#macos

chmod 755 ./Anaconda3-5.0.1-MacOSX-x86_64.sh
./Anaconda3-5.0.1-MacOSX-x86_64.sh

確認

Python -V
Python 3.6.3 :: Anaconda, Inc.

ansibleインストール

brew install ansible

どうもこれ↓は入れなくて良い様子

brew install caskroom/cask/brew-cask ---> エラー出る

試しにbrew install cask atomと打ってみたところ行けた

Ansibleの実行

プロビジョニング用のディレクトリ作成。

mkdir .macbook-provisioning
cd .macbook-provisioning/

ansible用のinventoryファイル作成

echo 'localhost' > hosts

テキストを開き、以下をlocalhost.ymlとして保存

- hosts: localhost
  connection: local
  gather_facts: no
  sudo: no
  vars:
    homebrew_taps:
      - homebrew/binary
      - homebrew/dupes
      - caskroom/cask
      - homebrew/services
    homebrew_packages:
      - { name: readline }
      - { name: openssl }
      - { name: openssl, state: linked, install_options: force }
      - { name: git }
      - { name: wget }
      - { name: curl }
      - { name: go }
      - { name: rbenv }
      - { name: ruby-build }
      - { name: vim }
      - { name: mysql }
      - { name: redis }
    homebrew_enabled_services:
      - mysql
      - redis
    homebrew_cask_packages:
      - { name: iterm2 }
      - { name: firefox }
      - { name: google-chrome }
      - { name: google-japanese-ime }
      - { name: atom }
      - { name: skype }
      - { name: slack }
      - { name: vagrant }
      - { name: virtualbox }
      - { name: phpstorm }
      - { name: pycharm }
      - { name: datagrip }
      - { name: sequel-pro }
      - { name: postman }
      - { name: cyberduck }
      - { name: gimp }
      - { name: marp }
      - { name: vmware-fusion }
      - { name: sourcetree }

  tasks:
    - name: homebrew の tap リポジトリを追加
      homebrew_tap: tap={{ item }} state=present
      with_items: "{{ homebrew_taps }}"

    - name: homebrew update確認
      homebrew: update_homebrew=yes

    # brew
    - name: brew packageのインストール
      homebrew: >
        name={{ item.name }}
        state={{ item.state | default('latest') }}
        install_options={{
          item.install_options | default() | join(',')
          if item.install_options is not string
          else item.install_options
        }}
      with_items: "{{ homebrew_packages }}"
      register: brew_result
    - name: brew パッケージの情報保存先ディレクトリを作成
      file: path=brew_info state=directory
    - name: brew パッケージの情報を保存
      shell: brew info {{ item }} > brew_info/{{ item }}
      with_items: "{{ brew_result.results | selectattr('changed') | map(attribute='item') | map(attribute='name') | list }}"

    # brew services
    - name: Get currently available brew services.
      shell: "brew services list | sed '1 d' | cut -d ' ' -f 1"
      register: brew_services

    - name: Enable brew services.
      command: "brew services start {{ item }}"
      with_items: "{{ homebrew_enabled_services }}"
      when: "'{{ item }}' in brew_services.stdout_lines"

    # - name: Install bundler(インストールは成功するが、Projectによってはうまく動作しなかった)
    #   gem:
    #     name: bundler
    #     user_install: no
    #     executable: /usr/local/bin/gem

  handlers:
    - name: run fc-cache
      shell: fc-cache -vf

Homebrew Caskオプションを設定

echo 'export HOMEBREW_CASK_OPTS="--appdir=/Applications"' >> ~/.bash_profile
source ~/.bash_profile

作成したPlaybookを実行する

ansible-playbook -i hosts -vv localhost.yml

※MacBookPro 2017 Mid 15インチ (High Sierra)で動作確認済み

SettingWithCopyWarningメモ

こんな感じでdataframeにseriesを入れようとするとエラーが出る

df2['time'] = s1

表示されるエラー文はこんな感じ

/Users/Suzuki_Yasuharu/miniconda3/lib/python3.6/site-packages/ipykernel_launcher.py:3: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  This is separate from the ipykernel package so we can avoid doing imports until

対策

# こう↓するとエラーが出なくなる
pd.options.mode.chained_assignment = None
df2['time'] = s1

消費メモリを小さくするためのワーニングですんで、そのこと理解した上で使いましょー(・ω・)ノシ


参考サイト
indexing-view-versus-copy(エラー文に書いてあるページ)
pandas 0.21.0 documentation
How to deal with SettingWithCopyWarning in Pandas?


ちなみにこちら↓のようにconcatするとワーニング出ません(なんかちょっとやりたいことがが変わってしまう気はしますが)
python pandasでの列(column)へのSeriesの追加


要素1つ1つを選択しているのならこちらのやり方が正です。
Pythonの覚え書き(DataFrameのSettingWithCopyWarningの対処方法)

minicondaでPython3.5とPython2.7の共存環境を構築する

condaでの共存環境も作りやすくなったし
minicondaでPython3.5とPython2.7の共存環境を構築する
最近みんな3系なので(汗)

anacondaを入れている時は削除する
  1. anacondaを入れていると邪魔なので削除します。(インストールしていない方は読み飛ばしてください)
  2. 現在のバージョンを確認

    python -V
    Python 2.7.13 :: Anaconda 4.3.1 (x86_64)

    入ってますねー。アンインストールしましょう




  3. まずはコマンドで削除
  4. conda install anaconda-clean     (これだけでは消えない)
    anaconda-clean                   (これだけでは消えない)
    rm -rf anaconda                  (消す)
    rm -rf AnacondaProjects          (消す)



  5. PythonのPATHを消す

  6. 私のマシンには以下のように入っていたので.bash_profileから消しました。(zsh使っている人はたぶん.zshrc)

    # added by Anaconda3 4.3.1 installer
    export PATH="/Users/Suzuki_Yasuharu/anaconda/bin/python:$PATH"



  7. Anacondaのショートカット削除

  8. アプリケーションフォルダ内にAnacondaのショートカットの残骸が残っている
    → Finderから削除


minicondaのインストール


  1. ダウンロードしたファイルからインストール
  2. chmod 777 ./Miniconda3*
    ./Miniconda3-latest-MacOSX-x86_64.sh

  3. 利用規約で「press ENTER to continue」と聞かれる

  4. → ENTERキーを押し続ける。

  5. Do you approve the license terms? [yes|no]と聞かれる

  6. → YESと答える

  7. Miniconda3 will now be installed into this location:

  8. /Users/ユーザー名/miniconda3
    → ENTER


Python2.7 / Python3.5 のセットアップ
  1. condaのupdate
  2. 先にconda自身をupdateしておく

    conda update conda

  3. 現在のバージョンを確認
  4. python -V
    Python 3.6.1 :: Continuum Analytics, Inc.

  5. python仮想環境を作る
  6. 3.5系
    conda create -n py35 python=3.5 anaconda
    
    2.7系
    conda create -n py27 python=2.7 anaconda
    ※3系のanacondaを入れたあとで2系を入れるとダウンロード量が多いので注意。

  7. エラー

  8. このエラーが出た時は unset PYTHONPATH する。

    Failed to import the site module
    Your PYTHONPATH points to a site-packages dir for Python 2.x but you are running Python 3.x!
         PYTHONPATH is currently: ":/usr/local/lib/python2.7/site-packages/"
         You should `unset PYTHONPATH` to fix this.

  9. 3.5系への入り方
  10. source activate py35 (仮想環境に入る)
    python -V
    Python 3.5.3 :: Anaconda 4.4.0 (x86_64)  (3.5系になっている)
    source deactivate (仮想環境から出る)

  11. 2.7系への入り方
  12. source activate py27 (仮想環境に入る)
    python -V
    Python 2.7.13 :: Anaconda, Inc.     (2.7系になっている)
    source deactivate (仮想環境から出る)


Jupyterのセットアップ
  1. インストール
  2. 普通に入れると3.6だけでなく、3.5系 / 2.7系でも動きます。

    conda install jupyter

  3. 起動
  4. jupyter notebook

  5. pandasのインストール

  6. pip install 〜 は conda install 〜でインストールします。

    conda install pandas

Laravel MixのbrowserSyncで.cssや.jsの変更もリロードさせる

Laravel MixのbrowserSyncで
.cssや.jsの変更もリロードさせる
もう調べるのめんどいから標準でつけてぇ〜(心の叫び)




browserSyncの拡張を使う
  1. webpack.mix.js
  2. webpack.mix.jsの最後にこれを追加

    // Hot reloadingを有効にする (npm run watchで実行してください)
    mix.browserSync({
        files: [
            "resources/views/**/*.blade.php",
            "public/**/*.*"     // 公開フォルダを指定しないとリロードが効きません。注意
        ],
        proxy: {
            target: "http://my-domain.dev/",
        }
    });

    これだけっす〜(・ω・)ノシ

Vagrant使ってみた(MacにVagrant+VirtualBox(CentOS7)をインストール)

今さらだけど
Vagrant 使ってみた
WEBエンジニアみんな使ってるので使ってみた





vagrantのインストール
  1. ダウンロード
  2. まずVagrantから。ここ↓からダウンロード
    https://www.vagrantup.com/downloads.html
    ver 1.9.7 (2017/07/08 時点の最新)
    
  3. インストール
  4. vagrant_1.9.7_x86_64.dmg をダウンロード後、ダブルクリック(マウントする)
    vagrant.pkg をダブクリック(インストーラを起動)
    あとは指示に従ってインストールするだけ。
    
  5. バージョン確認
  6. $ vagrant --version
    Vagrant 1.9.7


    動いてますね(`・ω・´)ゞ





VirtualBoxのインストール

  1. ダウンロード
  2. 次にVirtualBox。ここ↓からダウンロード
    https://www.virtualbox.org/wiki/Downloads
    VirtualBox 5.1.22 (2017/07/08 時点の最新)
    [OS X hosts]をクリックしてダウンロード
    
  3. ダウンロード
  4. VirtualBox.pkgをダブルクリック(インストーラを起動)
    あとは指示に従ってインストールするだけ。
    





Boxの追加

  1. ダウンロードURL一覧ページへ
  2. Box : VagrantのOSイメージみたいなもの
    Boxはここ↓にダウンロードURLの一覧がある
    http://www.vagrantbox.es/
    実際にダウンロードするときはコマンドを打つ
    
    今回は以下をダウンロード
    CentOS 7.0 x64 (Minimal, VirtualBox Guest Additions 4.3.28, Puppet 3.8.1 - see here for more infos)
    URLをコピーしておく
    
  3. ダウンロード
  4. 以下のコマンドでboxを追加
    

    vagrant box add {name} {url}


    {name}はcentos64にして実行。20分ぐらいかかりました。

    vagrant box add centos64 https://github.com/tommy-muehle/puppet-vagrant-boxes/releases/download/1.1.0/centos-7.0-x86_64.box


  5. boxの確認


  6. boxの確認コマンドを打つ

    $ vagrant box list
    centos64 (virtualbox, 0)


    CentOSのバージョン名に、box名を変更

    $ cd ~/.vagrant.d/boxes/
    $ mv centos64 centos70


    で変更完了。確認してみる。

    $ vagrant box list
    centos70 (virtualbox, 0)






    VMの作成&起動

    1. ~/Vagrant/CentOS70を作業ディレクトリにする。
    2. $ mkdir -p ~/Vagrant/CentOS70
      $ cd ~/Vagrant/CentOS70/


    3. 初期化コマンド
    4. $ vagrant init centos70
      A `Vagrantfile` has been placed in this directory. You are now
      ready to `vagrant up` your first virtual environment! Please read
      the comments in the Vagrantfile as well as documentation on
      `vagrantup.com` for more information on using Vagrant.


      これで Vagrantfile 完成。確認してみる。

      $ ls
      Vagrantfile


    5. 起動
    6. $ vagrant up
      Bringing machine 'default' up with 'virtualbox' provider...
      ==> default: Importing base box 'centos70'...
      ==> default: Matching MAC address for NAT networking...
      ==> default: Setting the name of the VM: CentOS70_default_1499570759675_77339
      ==> default: Clearing any previously set forwarded ports...
      ==> default: Clearing any previously set network interfaces...
      ==> default: Preparing network interfaces based on configuration...
          default: Adapter 1: nat
      ==> default: Forwarding ports...
          default: 22 (guest) => 2222 (host) (adapter 1)
      ==> default: Booting VM...
      ==> default: Waiting for machine to boot. This may take a few minutes...
          default: SSH address: 127.0.0.1:2222
          default: SSH username: vagrant
          default: SSH auth method: private key
          default:
          default: Vagrant insecure key detected. Vagrant will automatically replace
          default: this with a newly generated keypair for better security.
          default:
          default: Inserting generated public key within guest...
          default: Removing insecure key from the guest if it's present...
          default: Key inserted! Disconnecting and reconnecting using new SSH key...
      ==> default: Machine booted and ready!
      ==> default: Checking for guest additions in VM...
          default: The guest additions on this VM do not match the installed version of
          default: VirtualBox! In most cases this is fine, but in rare cases it can
          default: prevent things such as shared folders from working properly. If you see
          default: shared folder errors, please make sure the guest additions within the
          default: virtual machine match the version of VirtualBox you have installed on
          default: your host and reload your VM.
          default:
          default: Guest Additions Version: 4.3.28
          default: VirtualBox Version: 5.1
      ==> default: Mounting shared folders...
          default: /vagrant => /Users/y.suzuki/Vagrant/CentOS70

      VirtualBoxを見るとCentOSが起動している。




    7. 状態の確認
    8. $ vagrant status
      Current machine states:
      
      default                   running (virtualbox)
      
      The VM is running. To stop this VM, you can run `vagrant halt` to
      shut it down forcefully, or you can run `vagrant suspend` to simply
      suspend the virtual machine. In either case, to restart it again,
      simply run `vagrant up`.




    9. Vagrantへ接続
    10. $ vagrant ssh
      Last login: Thu Jul 16 08:48:31 2015 from 10.0.2.2
      Welcome to your Vagrant-built virtual machine.
      [vagrant@localhost ~]$ exit
      logout
      Connection to 127.0.0.1 closed.




    11. 停止
    12. $ vagrant halt
      ==> default: Attempting graceful shutdown of VM...




      とりあえずここまで(`・ω・´)ゞ




    13. 初めて使った感想


    14. くっそ便利




CocoaPods 使ってみた(iOS開発)

今さらだけど
CocoaPods 使ってみた
ゼロから構築するのはひさびさだったのでブログにしてみた





CocoaPodsのインストール
  1. ruby gemを最新にする
  2. sudo gem update --system

  3. インストール
  4. sudo gem install -n /usr/local/bin cocoapods

  5. セットアップ
  6. pod setup





CocoaPodsを使う

  1. プロジェクトフォルダへ移動
  2. cd /Users/Suzuki_Yasuharu/Documents/Project/..../

  3. pod init


  4. "pod init"とコマンドを打ちます。

    pod init


    Podfileというファイルが作成されます。

    # Uncomment the next line to define a global platform for your project
    # platform :ios, '9.0'
    
    target 'ys_test01' do
      # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
      use_frameworks!
    
      # Pods for ys_test01
    
    end

  5. Firebaseを追加


  6. 試しにFirebaseをCocoaPodsに追加してみます。


    Firebase用の設定ファイル「GoogleService-Info.plist」を追加


    Podfileを編集 → pod install


    AppDelegate で FirebaseApp.configure() を呼ぶ


    これでFirebaseの組み込みは終了です。




  7. .xcworkspace から起動


  8. CocoaPods初心者がハマるやつです。
    普段はプロジェクトを開くために .xcodeproj から起動しますが、CocoaPodsをインストールした後は、.xcworkspace から起動します。




ライブラリを追加する場合

  1. CocoaPodsライブラリを新たに追加したい場合
  2. Podfileに別のライブラリ情報を記入後、
    

    pod update


    このコマンドでライブラリが追加されます。