2011年12月3日土曜日

ADK demokitのプロトコル

android -> accessory

-- msg[0] msg[1] msg[2]
LED1 RED 0x02 0x00 0 - 255
LED1 GREEN 0x02 0x01 0 - 255
LED1 BLUE 0x02 0x02 0 - 255
LED2 RED 0x02 0x03 0 - 255
LED2 GREEN 0x02 0x04 0 - 255
LED2 BLUE 0x02 0x05 0 - 255
LED3 RED 0x02 0x06 0 - 255
LED3 GREEN 0x02 0x07 0 - 255
SERVO1 0x02 0x10 0 - 255
SERVO2 0x02 0x11 0 - 255
SERVO3 0x02 0x12 0 - 255
RELAY1 0x03 0x00 0(Low), 1(High)
RELAY2 0x03 0x01 0(Low), 1(High)

accessory -> android

-- msg[0] msg[1] msg[2]
Button1 0x01 0x00 0, 1
Button2 0x01 0x01 0, 1
Button3 0x01 0x02 0, 1
Button Joystick 0x01 0x04 0, 1
temperature 0x04 value of MSB value of LSB
light 0x05 value of MSB value of LSB
joystick 0x06 position of X(-128 - 127) position of Y(-128 - 127)
touch robot 0x01 0x03 0, 1

2011年11月16日水曜日

AquaSKKの入力規則をカスタマイズした。

これから作る入力規則のファイル名と名前を書いておく。
$ cat $HOME/Library/Application\ Support/AquaSKK/sub-rule.desc
my.rule オレ用
で、そのファイルに入力規則を書く。今回はひらがなモードのときの括弧を全角にしたっかの。入力規則はEUC-JPで保存しなきゃダメなところに注意ね。
$ cat $HOME/Library/Application\ Support/AquaSKK/my.rule | iconv -f euc-jp -t utf-8
(,(,(,(
),),),)
?,?,?,?
!,!,!,!
@see http://aquaskk.sourceforge.jp/kana_rule.html

MacでADK

Androidと何かを繋げるためのADK(Android Open Accessory Development Kit)を試してみようと。でもArduinoとか無かいんだね。しょうがないので、Android ADKのdemokitコンパチなstubをMac上に作って喋らせた。Macのほうのデザインがダサいのは、日本のサラリーマンだからしょうがない。
繋げるのも手間じゃないし、繋ってしまえば、こちらのモンやし、良い感じ。

2011年9月21日水曜日

docutilsのディレクティブを作ってみた。

reStructuredTextで、
.. code-block:: ruby
   ::filename:: hello.rb

   puts "hello, world!!"
と書いて、
hello.rb:
<pre class="brush: ruby">
puts "hello, world!!"
</pre>
に変換させたい。
class CodeBlockDirective(Directive):
  required_arguments = 0
  optional_arguments = 1
  has_content = True
  option_spec = { 'filename': directives.unchanged }

  def run(self):
    node = []
    filename = self.options.pop('filename', None)
    if filename is not None:
      node.append(nodes.Text("\n%s:" % filename))
    else:
      node.append(nodes.Text("\n"))
    opt = {'classes' : []}
    if len(self.arguments) != 0:
      opt['classes'].append("brush: %s" % self.arguments[0])
    node.append(nodes.literal_block(self.content, "\n".join(self.content), **opt))
    return node
めでたしめでたし

2011年9月6日火曜日

OS-Xでログイン時にスクリプトを実行したい。

OS-Xでログインするときにスクリプトを実行できないかなーというお話し。 http://support.apple.com/kb/HT2420
sudo defaults write com.apple.loginwindow LoginHook /path/to/script
これだと、(ユーザーごとでなく)グローバルに設定されてしまうので、
#!/bin/sh
if [ -x $HOME/.loginhook ]
then
$1/.login
fi
こんな感じのスクリプトを設定しておくってのでどう?

2011年8月24日水曜日

homebrewでvalgrindが入らない。

# brew install valrgind
ってすると、
configure:5116: checking for the kernel version
configure:5152: result: unsupported (11.0.1)
configure:5154: error: Valgrind works on Darwin 9.x and 10.x (Mac OS X 10.5 and 10.6)
ってなるの。

コイツめ。
# brew info valgrind
valgrind 3.6.1
http://www.valgrind.org/
Depends on: pkg-config
http://github.com/mxcl/homebrew/commits/master/Library/Formula/valgrind.rb

gccで定義済みとなるマクロさん達

# cpp -dM /dev/null
すれば良いみたいよ。

2011年8月15日月曜日

stl::vectorのパフォーマンス

いつも適当に書いてしまうので、ちょっとまとめておく。
  • 大きさを指定せずに push_back し続ける。
  • コンストラクトするときに大きさを指定して添字で代入する。
  • reserveで大きさを指定して、push_backする。
のバトル。

#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/timer.hpp>

struct E {
    unsigned int id;
    unsigned char value[1024];
};

struct NonOptimize {
    NonOptimize(const size_t num) : n(num) { }

    inline void operator()() const {
        std::vector<E> v;
        for (size_t i = 0; i < n; ++i) {
            E e = {i};
            v.push_back(e);
        }
    }

    const size_t n;
};

struct ConstructWithSize {
    ConstructWithSize(const size_t num) : n(num) { }

    inline void operator()() const {
        std::vector<E> v(n);
        for (size_t i = 0; i < n; ++i) {
            E e = {i};
            v[i] = e;
        }
    }

    const size_t n;
};

struct Reserved {
    Reserved(const size_t num) : n(num) { }

    inline void operator()() const {
        std::vector<E> v;
        v.reserve(n);
        for (size_t i = 0; i < n; ++i) {
            E e = {i};
            v.push_back(e);
        }
    }

    const size_t n;
};

template <typename F>
inline std::vector<double>& mesure(F& func, std::vector<double>* elapsed) {
    typedef std::vector<double> Results;
    boost::timer timer;
    
    for (Results::iterator i(elapsed->begin()), end(elapsed->end()); i != end; ++i) {
        timer.restart();
        func();
        *i = timer.elapsed();
    }
    return *elapsed;
}

std::ostream& operator<<(std::ostream& os, const std::vector<double>& elapsed) {
    typedef std::vector<double> Results;
    Results::const_iterator max = std::max_element(elapsed.begin(), elapsed.end());
    Results::const_iterator min = std::min_element(elapsed.begin(), elapsed.end());
    double sum(0);;
    for (Results::const_iterator i(elapsed.begin()), end(elapsed.end()); i != end; ++i) {
        if (i != max && i != min) {
            sum += *i;
        }
    }
    os << "MAX: " << *max << ", MIN:" << *min << ", AVG:" << (sum / (elapsed.size() - 2));
    return os;
}

int main(int argc, char **argv) {
    static const size_t NUM(50000);
    boost::timer timer;

    NonOptimize f1(NUM);
    ConstructWithSize f2(NUM);
    Reserved f3(NUM);

    std::cout << argv[0] << std::endl;
    std::vector<double> elapsed(10);
    std::cout << mesure(f1, &elapsed) << std::endl;
    std::cout << mesure(f2, &elapsed) << std::endl;
    std::cout << mesure(f3, &elapsed) << std::endl;

    return 0;
}
で、ビルド。ついでだから llvm でもお試し。
all: main_gnu main_llvm_gnu

main_gnu: main.cc
	g++ $(CXXFLAGS) $< -o $@

main_llvm_gnu: main.cc
	llvm-g++ $(CXXFLAGS) $< -o $@

.PHONY: clean
clean:
	@rm -fv main_gnu main_llvm_gnu

したら、実行。
$ make; ./main_gnu; ./main_llvm_gnu
g++ -O3 -Wall main.cc -o main_gnu
llvm-g++ -O3 -Wall main.cc -o main_llvm_gnu
./main_gnu
MAX: 0.29, MIN:0.26, AVG:0.27875
MAX: 0.18, MIN:0.14, AVG:0.15125
MAX: 0.13, MIN:0.11, AVG:0.1175
./main_llvm_gnu
MAX: 0.25, MIN:0.24, AVG:0.2425
MAX: 0.15, MIN:0.13, AVG:0.13875
MAX: 0.11, MIN:0.1, AVG:0.105

  • 大きさを指定せずに push_back し続ける。
  • コンストラクトするときに大きさを指定して添字で代入する。
  • reserveで大きさを指定して、push_backする。
コンストラクタで大きさを指定した場合、アロケーションしてから、初期値を代入してるんだろうな。
任意値で埋めたいときは、reserveしたほうが吉っぽい。

2011年8月8日月曜日

lionのツールチェイン

ファイル 正体
/usr/bin/ld llvm version 3.0svn, from Apple Clang 2.1 (build 163.7.1)
/usr/bin/as Apple Inc version cctools-806~3, GNU assembler version 1.38
/usr/bin/gcc symbolic link to llvm-gcc-4.2
/usr/bin/llvm-gcc symbolic link to ../llvm-gcc-4.2/bin/llvm-gcc-4.2
/usr/bin/llvm-gcc-4.2 symbolic link to ../llvm-gcc-4.2/bin/llbm-gcc-4.2
/usr/bin/gcc-4.2 gcc version 4.2.1 (Appli Inc. build 5666) (dot 3)
/usr/bin/llvm-g++ symbolic link to ../llvm-gcc-4.2/bin/llvm-g++-4.2
/usr/bin/llvm-g++-4.2 symbolic link to ../llvm-gcc-4.2/bin/llvm-g++-4.2
/usr/bin/llvm-cpp-4.2 symbolic link to ../llvm-gcc-4.2/bin/llvm-cpp-4.2
/usr/bin/g++ symbolic link to llvm-g++-4.2
/usr/bin/g++-4.2 i686-apple-darwin11-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666) (dot 3)

2011年7月7日木曜日

Overloaded methods is ambiguous.

オーバーロードしている関数で引数の数まで同じだと、悲しいことになる。

例えば、
#include <gmock/gmock.h>

using ::testing::Eq;
using ::testing::Return;
using ::testing::Matcher;

class X {
public:
    bool operator==(const X& other) const { return false; }
};

class Y {
public:
    bool operator==(const Y& other) const { return false; }
};

class Foo {
public:
    virtual ~Foo() { }

    virtual void function(X x) { }
    virtual void function(Y x) { }
};

class Mock : public Foo {
public:
    MOCK_METHOD1(function, void(X));
    MOCK_METHOD1(function, void(Y));
};

TEST(MockTest, Call_Foo_X) {
    Mock m;

    X arg;

    EXPECT_CALL(m, function(Eq(arg))).WillOnce(Return());
}

これをコンパイルすると
$ g++ -I/opt/vendor/include -L/opt/vendor/lib -lgtest -lgmock -c ambiguous.cc
ambiguous.cc:11: error: ISO C++ forbids declaration of ‘Interface’ with no type
ambiguous.cc:23: error: multiple types in one declaration
ambiguous.cc: In member function ‘virtual void MockTest_Call_Foo_X_Test::TestBody()’:
ambiguous.cc:28: error: call of overloaded ‘gmock_function(testing::internal::EqMatcher)’ is ambiguous
ambiguous.cc:19: note: candidates are: testing::internal::MockSpec& Mock::gmock_function(const testing::Matcher&)
ambiguous.cc:20: note:                 testing::internal::MockSpec& Mock::gmock_function(const testing::Matcher&)
ambiguousですよ。ambiguous!

で、どうすっかって。
EXPECT_CALL(m, function(Matcher(Eq(arg)))).WillOnce(Return());
明示的にMatcherで型を示してあげると。

2011年6月21日火曜日

macro trick in googletest

googletestでは、テストケースはこう書くわけ。
#include <gtest/gtest.h>

TEST(SampleTestCase, TestFunc) {
    EXPECT_TRUE(true);
}
C++な割にはスマート。で、なんで、こんなことができるのか。その仕組みを追ってみた。まずは、TEST()マクロ。

include/gtest/gtest.h:
#define TEST(test_case_name, test_name) \
  GTEST_TEST_(test_case_name, test_name, \
              ::testing::Test,\
              ::testing::internal::GetTestTypeId())
ほむ。次はGTEST_TEST_()マクロ。

include/gtest/internal/gtest-internal.h(抜粋):
#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\
class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\
 public:\
  GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\
 private:\
  virtual void TestBody();\
};\
\
void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
ほむほむ。GTEST_TEST_CLASS_NAME_()マクロは、test_case_nameとtest_nameを繋げて重複しないクラス名を生成する。上の例だと SampleTestCase_TestFunc_Test となる。最後の行は TestBody() のシグニチャだけ置いて、マクロに続くブロックが TestBody() の実装となるようになっているわけだ。

ちなみに、親クラスとなる ::testing::Test は include/gtest/gtest.h で定義されている。
include/gtest/gtest.h(抜粋):
class Test {
 protected:
  virtual void SetUp();
  virtual void TearDown();
 private:
  virtual void TestBody() = 0;
};
ほむほむほむ。予想どおり。

まとめ

最後に始めに出した例と、展開されたあとのイメージを載せておく。

展開前:
TEST(SampleTestCase, TestFunc) {
    EXPECT_TRUE(true);
}

展開後:
class SampleTestCase_TestFunc_Test : public ::testing::Test {
 public:
  SampleTestCase_TestFunc_Test() {}
 private:
  virtual void TestBody();
};

void SampleTestCase_TestFunc_Test::TestBody() {
    EXPECT_TRUE(true);
}
なるほどねぇ。

2011年6月20日月曜日

Rubyのoptparseでgccみたいなオプションを取る

やりたいことは、これ。
./hoge source -o output
sourceにオプションスイッチが無いのがミソ。

options = {
  :input => $stdin,
  :output => $stdout
}

optp = OptionParser.new
optp.on("-o outputfile", String) {|out_filename|
  options[:output] = File.open(out_filename, 'w')
}

remain_opts = optp.permute(ARGV)
if (remain_opts.size > 1)
  raise "Invalid input count."
elsif (remain_opts.size == 1)
  options[:input] = File.open(remain_opts[0], 'r')
end                                                   
OptionParser#parseでなくて、OptionParser#permuteを使う。

googlemockで引数アサーション

googlemockでクラスや構造体のメンバが正しい値でモック関数が呼び出されているかを確認したい。

struct Param {
    bool flag;
    int value;
};

class Interface {
public:
    virtual ~Interface() { }
    virtual void f(const Param& p) = 0;
};

class Actor {
public:
    Actor(Interface& d) : derived(d) { }
    void DoIt(const Param& p) {
        Param tmp;
        tmp.flag = !(p.flag);
        tmp.value = -1 * p.value;
        derived.f(tmp);
    }
private:
    Interface& derived;
};

確認したいこと

Actor::f()がParam::flagを反転、Param::valueの正負を反転させてからInterface::f()を呼び出していることを確認したい。

Param::operator==()を定義しちゃえば良いじゃんというツッコミはナシ。

順当にgooglemockのマッチャーを使う

TEST(GMockSample, Use_GMock_MemberMathcer) {
    using ::testing::AllOf;
    using ::testing::Eq;
    using ::testing::Field;
    using ::testing::Truly;

    Mock mock;
    Param p = {false, 345};

    Actor actor(mock);

    EXPECT_CALL(mock, f(
        AllOf(
            Field(&Param::flag, Eq(true)),
            Field(&Param::value, Eq(-345))
        )
    ));

    // Act!!
    actor.DoIt(p);
}
フィールドの数が増えてきたら、どうするんだろうね。

boost::bindを使う

TEST(GMockSample, Use_Boost_Bind) {
    using ::testing::Truly;
    using ::boost::bind;

    Mock mock;
    Param p = {false, 345};
    Param expect = {true, -345};

    Actor actor(mock);

    EXPECT_CALL(mock, f(
        Truly(
            bind(EqualParameter(), expect, _1)
        )
    ));

    // Act!!
    actor.DoIt(p);
}
期待値をローカル変数に用意しているのがなぁ。

boost::lambdaを使う

TEST(GMockSample, Use_Boost_Lambda) {
    using ::boost::bind;
    using ::boost::lambda::_1;
    using ::testing::Truly;

    Mock mock;
    Param p = {false, 345};

    Actor actor(mock);

    EXPECT_CALL(mock, f(
        Truly(
            bind(&Param::flag, _1) == true
                && bind(&Param::value, _1) == -345
        )
    ));

    // Act!!
    actor.DoIt(p);
}
なんだか、もう一息な気がする。