ARC環境でNSInvocationを使う機会があり、ハマってしまったので、対策をメモしておきます。
要は、[invocation retainArguments]を追加するだけなのですが、
これがないと、
unrecognized selector sent to instance
と実行時エラーになります。


        if (target && selector) {
          NSMethodSignature *signature = [[target class] instanceMethodSignatureForSelector:selector];
            if (signature != nil) {
              self.invocation = [NSInvocation invocationWithMethodSignature:signature];
              [self.invocation retainArguments];  // <- ここ
              [self.invocation setTarget:target];
              [self.invocation setSelector:selector];
              [self.invocation setArgument:(__bridge_retained void *)self atIndex:2];
            }
        }
コメントは受け付けていません。

// x以下で最大の2の累乗を求める
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
y = x - (x >> 1);

// x以上で最小の2の累乗を求める
x = x -1;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
y = x + 1;

こちらから引用しました。

コメントは受け付けていません。

// 4バイト境界の場合

string str = "abc";
size_t pad_len = (-str.length()) & 3

// 8バイト境界の場合
string str = "abc";
size_t pad_len = (-str.length()) & 7

コメントは受け付けていません。

次のサンプルを使用してGoogle Testを動かしてみます。
(サンプルはこちらのサイトのソースコードを拝借しました)

//
//  Test case for Google Test
//
#include <gtest/gtest.h>

int add(int x, int y)
{
  // do nothing.
}

// 1 + 1 の結果は 2 になるはず(..だけど、このコードは失敗する)
TEST(AddTest, Test1)
{
  ASSERT_EQ(2, add(1, 1));
}

このサンプルをtest.ccとして保存して、次のコマンドでg++でコンパイルし、testというオブジェクトができていれば成功です。

GTEST_DIR=svnでgoogletestをcheckoutしたディレクトリ; g++ -I${GTEST_DIR}/include test.cc -o test ${GTEST_DIR}/tmp/libgtest_main.a ${GTEST_DIR}/tmp/libgtest.a -lpthread

実行すると次のような結果が出力されます。

$ ./test
Running main() from gtest_main.cc
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from AddTest
[ RUN      ] AddTest.Test1
test.cc:14: Failure
Value of: add(1, 1)
  Actual: 4210112
Expected: 2
[  FAILED  ] AddTest.Test1 (0 ms)
[----------] 1 test from AddTest (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] AddTest.Test1

 1 FAILED TEST

コメントは受け付けていません。

対象のOS
CentOS 6.2

ツールのインストール

$ sudo yum install svn
$ sudo yum install cmake
$ sudo yum install gcc-c++

ライブラリ作成

$ svn checkout http://googletest.googlecode.com/svn/trunk/ googletest
$ cd googletest
$ cmake .
$ make

カレントディレクトリに次のファイルが作成されていれば完了
libgtest.a
libgtest_main.a

コメントは受け付けていません。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

if __name__ == "__main__":
    all_lines=sys.stdin.readlines()
    for a_line in all_lines:
        str = a_line.split(None)
        if str[0] == "root":
            print(str[10:])

プロセスの引数も表示させるためにstr[10:]としているのですが、出力結果にリストの区切り記号も出力されてしまいます。

コメントは受け付けていません。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

if __name__ == "__main__":
    all_lines=sys.stdin.readlines()
    for line in all_lines:
        print(line, end='')

sys.stdin.readlines()で1行1要素としてリストで読み込みます。
print文のend=”は読み込んだ要素に改行が含まれているのでprint関数で改行を自動的に付与しないようにしています。

コメントは受け付けていません。

>>> import sys
>>> print(sys.__doc__)
>>> help(sys)
<!--more-->

例えば、sysのドキュメントを確認する場合は上記のように__doc__かhelpを使用します。
Python 3.2.2でsys.__doc__を出力した場合次のような説明が出力されます。(>>>が入力でそれ以外は出力結果です)

>>> print(sys.__doc__)
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.

Dynamic objects:

argv -- command line arguments; argv[0] is the script pathname if known
path -- module search path; path[0] is the script directory, else ''
modules -- dictionary of loaded modules

displayhook -- called to show results in an interactive session
excepthook -- called to handle any uncaught exception other than SystemExit
  To customize printing in an interactive session or to install a custom
  top-level exception handler, assign other functions to replace these.

stdin -- standard input file object; used by input()
stdout -- standard output file object; used by print()
stderr -- standard error object; used for error messages
  By assigning other file objects (or objects that behave like files)
  to these, it is possible to redirect all of the interpreter's I/O.

last_type -- type of last uncaught exception
last_value -- value of last uncaught exception
last_traceback -- traceback of last uncaught exception
  These three are only available in an interactive session after a
  traceback has been printed.

Static objects:

float_info -- a dict with information about the float implementation.
int_info -- a struct sequence with information about the int implementation.
maxsize -- the largest supported length of containers.
maxunicode -- the largest supported character
builtin_module_names -- tuple of module names built into this interpreter
subversion -- subversion information of the build as tuple
version -- the version of this interpreter as a string
version_info -- version information as a named tuple
hexversion -- version information encoded as a single integer
copyright -- copyright notice pertaining to this interpreter
platform -- platform identifier
executable -- pathname of this Python interpreter
prefix -- prefix used to find the Python library
exec_prefix -- prefix used to find the machine-specific Python library
float_repr_style -- string indicating the style of repr() output for floats
__stdin__ -- the original stdin; don't touch!
__stdout__ -- the original stdout; don't touch!
__stderr__ -- the original stderr; don't touch!
__displayhook__ -- the original displayhook; don't touch!
__excepthook__ -- the original excepthook; don't touch!

Functions:

displayhook() -- print an object to the screen, and save it in builtins._
excepthook() -- print an exception and its traceback to sys.stderr
exc_info() -- return thread-safe information about the current exception
exit() -- exit the interpreter by raising SystemExit
getdlopenflags() -- returns flags to be used for dlopen() calls
getprofile() -- get the global profiling function
getrefcount() -- return the reference count for an object (plus one :-)
getrecursionlimit() -- return the max recursion depth for the interpreter
getsizeof() -- return the size of an object in bytes
gettrace() -- get the global debug tracing function
setcheckinterval() -- control how often the interpreter checks for events
setdlopenflags() -- set the flags to be used for dlopen() calls
setprofile() -- set the global profiling function
setrecursionlimit() -- set the max recursion depth for the interpreter
settrace() -- set the global debug tracing function

さらに各項目ごとの詳細な説明を確認したい場合は次のように入力します。

>>> print(sys.exit.__doc__)
exit([status])

Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).

コメントは受け付けていません。

まずはsyntax。
お題はProject EulerのProblem1から。
詳しくはこちら

#! /usr/local/bin/python3
# -*- coding: utf-8 -*-

def calc(max, prime):
    num = (max-1) // prime
    sum = (prime+prime*num)*(num//2)
    if num%2==1:
        sum = sum+prime*(num//2+1)
    return sum

if __name__ == "__main__":
    print(calc(1000,3)+calc(1000,5)-calc(1000,15))

1行目はpython3へのpath設定です。
2行目はファイルのエンコードの指定です。
4行目はuser-defined function object(ユーザー定義関数オブジェクト)の定義です。
書式は、

    def 関数名( 引数1, 引数2, ... ) :

です。戻り値は有無に関わらず、不要のようです。
定義の次の行からはidentすること。
5行目から出てくる”//”は整数同士の割り算を行います。
python3から”/”の割り算は浮動小数点に型変換されてしまいます。
7行目は条件分岐で、書式は

    if 条件式1 :
        条件式1がTrueのときの処理
    elif 条件式2 :
        条件式2がTrueのときの処理
    else:
        Falseのときの処理

となります。
9行目で戻り値を返しています。
11行目はpythonから直接呼び出された場合、trueになります。
他のスクリプトから呼び出された場合はfalseとなり、何も実行しません。
12行目は普通のprint文なのですが、python3から書式が変更され、括弧でくくらないとエラーとなります。
1行に複数の命令を記述する場合はセミコロンで区切りますが、それ以外にセミコロンは不要です。

コメントは受け付けていません。

今年の目標の一つとして、pythonを実用レベル(C/C++のテストケースをpythonで書いた方が早く書けるレベル)まで習得しようと思います。

Read more of pythonの環境設定1

コメントは受け付けていません。

Theme by RoseCityGardens.com