つけじょにーのすぱげていコード

主に、競技プログラミング、セキュリティのお勉強の際に書いたすぱげていコードを書き込みます

loggerの話

RoRデバッグする際、loggerさんがとっても役に立ちます

logger.debug("デバッグ")

という具合に書けば、サーバーにロギングされ、デバッグの時にとっても役立ちます

これと組み併せて、

@object.inspect #オブジェクトの中身を表示
request.body.read #リクエストのボディ
params #POSTパラメータ

などを使えば、かなり便利だと思います!

Arduino&Processing楽器作成3 書き換えてみた

まとめも兼ねて、主にProcessingのコードを書き換えました。
コメントも付け加え、少しわかりやすくなったかなと思います。

Arduino近辺の写真
f:id:tukejonny:20141215223349j:plain

Arduino(変更なし)

void setup() {
  Serial.begin(19200);
}

void loop() {
  String cdsVal = String(analogRead(0));
  String tuning = String(analogRead(1));
  Serial.println(cdsVal + "," + tuning);
  delay(500);
}

・Processing (変更あり)

import processing.serial.*;
import ddf.minim.*;
import ddf.minim.signals.*;
PFont myFont;
Minim minim;
Serial arduino;
AudioOutput out;

//setup function
void setup() {
  size(1000, 1000); //display-size
  
  arduino = new Serial(this, Serial.list()[2], 19200);
  arduino.bufferUntil('\n');
  
  minim = new Minim(this);
  out = minim.getLineOut(Minim.STEREO);
  
  prevTime = millis(); //preview Time
  currentTime = millis(); //current Time
  
  textSize(64); //set text-size
}

//fadeout function
void fadeToBlack() {
  noStroke();
  fill(0, 10);
  rectMode(CORNER);
  rect(0, 0, width, height);
}

int tuneEllipse[] = {500, 400, 300, 200, 100, 50};
int x = width/2, y = height/2;
//draw function
void draw() {
  //draw division
  for(int r = 0; r < 6; r++) {
    for(int c = 0; c <= 360; c+=(int)random(5)) {
      ellipse(tuneEllipse[r]*cos(c), tuneEllipse[r]*sin(c), 5, 5);
      fill(0, 0, 255, 100);
    }
  }
  //draw ellipse
  for(int r = 0; r <= 360; r++) {
    ellipse(x * cos(r), y * sin(r), 5, 5);
    fill(255, 0, 0);
  }
  fadeToBlack(); //fadeout
}

String indata = ""; //tuning
String indata2 = "";//cdsVal
int currentTime, prevTime;
void serialEvent(Serial port) {
  try {
    indata = port.readStringUntil('\n');
    print(indata); print(indata2);
    if(indata != null && indata2 != null) {
      indata = trim(indata); indata2 = trim(indata2); //triming
      int tuning = Integer.parseInt(split(indata, ",")[0]);
      int cdsVal = Integer.parseInt(split(indata, ",")[1]);
      print("cdsVal:" + cdsVal + "\n");
      print("tuning:" + tuning + "\n");
      
      x = tuning; y = tuning; //set (x,y)
      //display tuning value
      String displayTuning = "tuning=" + str(tuning);
      text(displayTuning, width/2, height/2-100);
      
      //Displaying text which express tone.
      if(tuning >= 500) {
        text("do", width/2, height/2); //do
      } else if(tuning >= 400) {
        text("re", width/2, height/2); //re
      } else if(tuning >= 300) {
        text("mi", width/2, height/2); //mi
      } else if(tuning >= 200) {
        text("fa", width/2, height/2); //fa
      } else if(tuning >= 100) {
        text("so", width/2, height/2); //so
      } else if(tuning >= 50) {
        text("ra", width/2, height/2);; //la
      } else if(tuning >= 0) {
        text("si", width/2, height/2); //si
      } else {                   
        text("out of volume", width/2, height/2);
      }
    
      // many sounds
      //do-re-mi-fa-so-la-si
      if(cdsVal >= 850) { //outer if statement
        if(tuning >= 500) { //inner if statement
          out.playNote(261.6); //do
        } else if(tuning >= 400) {
          out.playNote(293.7); //re
        
        } else if(tuning >= 300) {
          out.playNote(329.6);//mi
          
        } else if(tuning >= 200) {
          out.playNote(349.2);//fa
          
        } else if(tuning >= 100) {
          out.playNote(392.1);//so
          
        } else if(tuning >= 50) {
          out.playNote(440);//la
        } else if(tuning >= 0) {
          out.playNote(494.1);//si
        } //end of inner if statement
      } //end of outer if statement
    }
  } catch(Exception e) { //catch Exception
    e.printStackTrace();
  }
}

gitコマンド まとめ

ちょこちょこ使うんですが、なかなか忘れてしまうのでメモ

リポジトリをとってくる

git clone https://github.com/[ユーザ名]/[リポジトリ名]

リポジトリを追加

git add [ファイル名]

リポジトリを削除

git rm [ファイル名]

リポジトリの状況を確認

git status

・コミット詳細を確認

git show

・コミットログを確認

git log

・変更差分を確認

git diff

・コミット

git commit -m 'メッセージ'

・プッシュする

git push origin master

・単一のコミットを元に戻す

git revert [コミット]

curlコマンド

またまた、まとめ

・ページ丸ごと取得

curl http://www.yahoo.co.jp

・それを丸ごと保存(名前指定)

curl -o sample.txt http://www.yahoo.co.jp

・それを丸ごと保存(デフォルト名)

curl -O sample.txt http://www.yahoo.co.jp

・POST送信

curl -d name=admin -d pass=aokfw34543 http://nanika.co.jp/index.php

・サーバのHTTPヘッダ取得
ヘッダの閲覧が主な目的。

curl -I yahoo.co.jp

・証明書エラースキップ

curl -k https://secure-socket-layer.co.jp

・サーバとのやりとり取得

curl -v yahoo.co.jp

・File Transfer Protocolを用いてファイルアップロード

curl -T sample.jpg -u [username]:[password] ftp://ftp.example.com/static/imgs/

Arduino&Processingのシリアル通信による、楽器作成 Part2

f:id:tukejonny:20141125204659j:plainf:id:tukejonny:20141125204720j:plainさて、第2弾です
今度は、「可変抵抗」を用いてチューニングし、音を出すというものにしました
さて、今回は中々苦戦しました。
というのも、シリアル通信の際、Processingで値を読み取り、切り分けるとなぜかcdsの値と可変抵抗の値が逆になってしまうのです!!
仕方ないので、理由はおいといて変数名を逆にして完成、としましたが、いかんせん納得いきません。
授業の時聞くかぁ・・・
あ、今回回路図書くのめんどかったので写真とってここに貼っときます(2枚:ブレッドボード、Arduino)

Arduino

void setup() {
  Serial.begin(19200);
}

void loop() {
  String cdsVal = String(analogRead(0));
  String tuning = String(analogRead(1));
  Serial.println(cdsVal + "," + tuning);
  //Serial.println(tuning);
  delay(500);
}

・Processing

import processing.serial.*;
import ddf.minim.*;
import ddf.minim.signals.*;
int tuneEllipse[] = {500, 400, 300, 200, 100, 50};
PFont myFont;
Minim minim;
Serial arduino;
AudioOutput out;
int currentTime, prevTime;
int x = width/2, y = height/2;
void setup() {
  size(1000, 1000);
  arduino = new Serial(this, Serial.list()[2], 19200);
  arduino.bufferUntil('\n');
  minim = new Minim(this);
  out = minim.getLineOut(Minim.STEREO);
  prevTime = millis();
  //delay(5);
  currentTime = millis();
  textSize(64);
}


void fadeToBlack() {
  noStroke();
  fill(0, 10);
  rectMode(CORNER);
  rect(0, 0, width, height);
}

void draw() {
  for(int r = 0; r < 6; r++) {
    for(int c = 0; c <= 360; c+=(int)random(10)) {
      ellipse(tuneEllipse[r]*cos(c), tuneEllipse[r]*sin(c), 5, 5);
      fill(0, 0, 255, 100);
    }
  }
  
  for(int r = 0; r <= 360; r++) {
    ellipse(x * cos(r), y * sin(r), 5, 5);
    fill(255, 0, 0);
  }
  fadeToBlack();
}
String indata = "";
String indata2 = "";
void serialEvent(Serial port) {
  try {
    indata = port.readStringUntil('\n');
    print(indata); print(indata2);
    if(indata != null && indata2 != null) {
      indata = trim(indata); indata2 = trim(indata2);
      //Why these two data were reversed?
      int tuning = Integer.parseInt(split(indata, ",")[0]);
      int cdsVal = Integer.parseInt(split(indata, ",")[1]);
      print("cdsVal:" + cdsVal + "\n");
      print("tuning:" + tuning + "\n");
      
      x = tuning; y = tuning;
      String displayTuning = "tuning=" + str(tuning);
      text(displayTuning, width/2, height/2-100);
      if(tuning >= 500) {
          text("C3", width/2, height/2);
        } else if(tuning >= 400) {
          text("D4", width/2, height/2);
        
        } else if(tuning >= 300) {
          text("E4", width/2, height/2);
          
        } else if(tuning >= 200) {
          text("F#4", width/2, height/2);
          
        } else if(tuning >= 100) {
          text("G3", width/2, height/2);
          
        } else if(tuning >= 50) {
          text("A#", width/2, height/2);;
        } else if(tuning >= 0) {
          text("B#", width/2, height/2);
        } else {
          text("out of volume", width/2, height/2);
        }
      /*
      if(cdsVal >= 400) {
        currentTime = millis();
        if(currentTime - prevTime > 1) {
          out.playNote("C4");
        }
        prevTime = currentTime;
      }
      */
      // many sounds
      if(cdsVal >= 850) {
        if(tuning >= 500) {
          out.playNote("C3");
        } else if(tuning >= 400) {
          out.playNote("C#");
        
        } else if(tuning >= 300) {
          out.playNote("D4");
          
        } else if(tuning >= 200) {
          out.playNote("E4");
          
        } else if(tuning >= 100) {
          out.playNote("F#");
          
        } else if(tuning >= 50) {
          out.playNote("A#");
        } else if(tuning >= 0) {
          out.playNote("B#");
        }
      }
    }
  } catch(Exception e) {
    e.printStackTrace();
  }
}

っとと、忘れてた
設定をメモメモ...

Arduinoで選択したポート:/dev/cu.usbmodem1421
なぜかどのポート選んでも、競合するときがある(笑)

簡単なオセロ

ざーっと書いて、まだテストもろくにしてないので、バグだらけだと思います
一応アップしておきます

//簡単なオセロ(プレイヤーが、正確に石を置く想定)
#include <bits/stdc++.h>
#define MAX_W 8
#define MAX_H 8
using namespace std;
string board[MAX_W]; //盤面 e...empty(空) w...white(白) b...black(黒)
//上、右上、右、右下、下、左下、左、左上
//0  1    2   3    4  5    6  7
int fdx[] = {0, 1, 1, 1, 0, -1, -1, -1}; //x軸方向
int fdy[] = {1, 1, 0, -1, -1, -1, 0, 1}; //y軸方向
char side[] = {'W', 'B'};

//初期化
void init() {
    for(int r = 0; r < MAX_H; r++) {
        for(int c = 0; c < MAX_W; c++) {
            board[r][c] = 'e';
        }
    }
    board[3][3] = side[0];board[4][4] = side[0];
    board[3][4] = side[1];board[4][3] = side[1];
}

//処理すべきか否か
bool judge(int x, int y, int dir, char whichSide) { //始点、方向、白か黒か
    x += fdx[dir]; y += fdy[dir]; //すぐ隣なら処理は必要なし
    while(true) {
        x += fdx[dir]; y += fdy[dir];
        if((x < 0 || x >= MAX_W) || (y < 0 || y >= MAX_H)) break;
        if(board[y][x] == whichSide) {
            return(true); //処理せよ
        }
    }
    return(false); //処理するな
}

//盤面を出力
void print() {
    puts("-------------------------");
    for(int r = 0; r < MAX_H; r++) {
        for(int c = 0; c < MAX_W; c++) {
            printf("%c |", board[r][c]);
        }
        putchar('\n');
        puts("-------------------------");
    }
}

int count() {
    int black = 0;
    for(int r = 0; r < MAX_H; r++) {
        for(int c = 0; c < MAX_W; c++) {
            if(board[r][c] == side[1]) black++; //黒なら
        }
    }
    return(black);
}

//勝敗判定
void commit() {
    int black = count(), white = 64 - black;
    puts("結果発表");
    printf("白:%d\n黒:%d\n", white, black);
    if(white > black) printf("白の勝利!");
    else              printf("黒の勝利!");
}

void solve(int x, int y, char whichSide) {
    board[y][x] = whichSide;
    for(int r = 0; r < 8; r++) {
        if(judge(x, y, r, whichSide)) {
            x += fdx[r]; y += fdy[r];
            while(board[y][x] != whichSide) {
                board[y][x] = whichSide;
                x += fdx[r]; y += fdy[r];
            }
        }
    }
    print();
}

int main(void) {
    init();
    int which = 0;
    int x, y;
    print();
    while(cin >> x >> y, !(count() == 0 || count() == 64)) {
        solve(x, y, side[(which++)%2]);
    }
    commit();
    return(0);
}