amazon

31.3.23

RをJupyterで使うときのグラフのサイズを指定する

 

library(repr)
options(repr.plot.width=6, repr.plot.height=4)

30.3.23

Jupyter Notebookの出力セルの幅を100%に拡張する

 

Pythonの場合
from IPython.core.display import HTML
display(HTML('<style>.container {width:100% !important;}</style>'))

Rの場合
library(IRdisplay)
display_html('<style>.container {width:100% !important;}</style>')

9.1.18

USBシリアル通信の確認方法

まず、接続されているUSBシリアルのデバイス名を検索する。

[デバイス名の検索]
Mac
ターミナルというアプリを起動する。
ls /dev/tty.*
と入力してEnterキーを押す。

tty.usbserialXXX、などと表示されたらこれがデバイス名になる。
何も表示されなければ、USBシリアルが認識されていない。ドライバをインストールする。
複数表示される場合は、USBを抜いた状態と挿した状態でのls /dev/tty.*を実行結果を比較して判断する。

Windows
Windowsスタートメニュー - コントロールパネル - デバイスマネージャ、を開く。
ポート(COMとLPT)を展開し、中にあるUSB Serial PortのCOM番号を調べる。
複数ある場合は、USBを抜き差しして判断する。

[送受信待機状態にする]
Mac
ターミナルというアプリを起動する。
screen /dev/tty.XXX
と入力してEnterキーを押す。/dev/tty.XXXはデバイス名の検索で見つけたものを入力する。
何も表示されなければ送受信待機状態になる。

Windows
Tera Termというフリーウェアをインストールする。
Tera Termを起動する。
新しい接続のダイアログで、シリアルを選択し、ポートをデバイスマネージャで見つけたCOMを選ぶ。
OKを押すと送受信待機状態になる。

[信号の送受信]
どちらかの機器で[Aキー]を押すと、もう一方の機器にAと表示される。

15.11.17

Installing pyaudio onto python 3 Anaconda on Mac

Anacondaのpython3にpyaudioをインストールした時のメモ。

$ python -m pip install pyaudio
で、
src/_portaudiomodule.c:29:10: fatal error: 'portaudio.h' file not found
#include "portaudio.h"
&nsbp;&nsbp;&nsbp;&nsbp;&nsbp;^
1 error generated.
error: command 'gcc' failed with exit status 1
と出た。

Then, I installed portaudio with brew.
$ brew install portaudio

But,
$ python -m pip install pyaudio
で、
src/_portaudiomodule.c:29:10: fatal error: 'portaudio.h' file not found
#include "portaudio.h"
^
1 error generated.
error: command 'gcc' failed with exit status 1
Error again.

そこでThus, I passed an include path to pip,
$ python -m pip install --global-option=build_ext --global-option="-I/usr/local/include/" pyaudio

今回はThis time,
ld: library not found for -lportaudio
portaudio libiraryがないと出た。

最終的にFinally, I did,
$ export LIBRARY_PATH="/usr/local/lib"
$python -m pip install --global-option=build_ext --global-option="-I/usr/local/include/" pyaudio
I have got,
Installing collected packages: pyaudio
Running setup.py install for pyaudio ... done
Successfully installed pyaudio-0.2.11

12.5.16

Get a list of tracked files of Git by GitPython


The code below is equivalent to git command, "git ls-tree -r master --name-only".

import git

def get_tracked_files(trees):
paths = []
for tree in trees:
for blob in tree.blobs:
paths.append(blob.abspath)
if tree.trees:
paths.extend(get_tracked_files(tree.trees))
return paths

if __name__=='__main__':
repo = git.Repo('.')
tracked_files = get_tracked_files([repo.tree()])
print tracked_files

12.12.15

Failed OS X El Capitan 10.11.2 update

I updated to 10.11.2 yesterday.
It went halfway and stopped before completed.

So, I force quitted and restarted. Mac showed the login screen.
I logged in with my primary user A.
With a long spinning cursor, nothing happened.
I force quitted again.

Fortunately, I have another admin user B.
I tried logging in with user B. It was succeeded.

With Consol.app on user B, I found following messages around time when failing to log in with user A .
diagnosticd[136]: error evaluating process info - pid: 316, puniqueid: 316
com.apple.xpc.launchd[1]: (com.apple.lsd[316]) Service exited due to signal: Segmentation fault: 11

According to a Crash report, something was wrong with mdworker of com.apple.LaunchServices.

Thanks to information here, I could find where the cache of LauchServices.
sudo find /var/folders /Library/Caches/ -name '*LaunchServices*' -print0 | xargs -0 ls -l

I backed up the cache of user A and deleted it.
Solved.

OS X El Capitan 10.11.2 アップデート失敗

アップデートをしたら、プログレスバーが6,7割のところで止まった。
強制終了して通常使っていたユーザーAでログインすると、アップルマークの下のグルグルが回ったまま進まなくなった。

幸い別のユーザーBを作ってあったのでそちらでログインすると、ログイン可能だった。
とりあえず、ターミナルでsuコマンドを使ってユーザーAに変更し、必要なファイルを救出することができた。

OSは10.11.2になっていた。
つまり、システムには問題はなくユーザーAに問題があることが考えられる。

さて、ここからこの壊れたユーザーAを直しにかかる。
セーフモードでログインを試したが、グルグルは回ったまま起動しない。

ユーザーBでログイン後、コンソールからユーザーAがログインしようとしたときのログを見ると、
diagnosticd[136]: error evaluating process info - pid: 316, puniqueid: 316
com.apple.xpc.launchd[1]: (com.apple.lsd[316]) Service exited due to signal: Segmentation fault: 11
とCrash reportが毎秒出ていた。

Crash reportによるとcom.apple.LaunchServicesのmdworkerが悪さをしているようだ。

ここによると、以下でLauchServicesのキャッシュの場所が分かるようだ。
sudo find /var/folders /Library/Caches/ -name '*LaunchServices*' -print0 | xargs -0 ls -l

これで見つけたユーザーAのキャッシュファイルをバックアップしてから削除した。
再起動して、ユーザーAでログインすると、無事ログインできるようになった。


3.12.15

Psychopy missing avbin solved

When I ran PsychoPy v1.83.01 on Windows 7 32-bit, I got the following error message.
ERROR avbin.dll failed to load.
Try importing psychopy.visual as the first library
(before anything that uses scipy)
and make sure that avbin is installed.

Then I typed the following in the shell of  PsychoPy2 Coder (IDE).
import psychopy.visual

I got an error message.
Unexpected error loading library avbin:

I checked where in avbin.dll in Command Prompt typing,
> where avbin.dll
C:\Windows\System32\avbin.dll
C:\Program Files\PsychoPy2\avbin.dll

However, both avbin.dll(s) seemed defferent.
C:\Windows\System32\avbin.dll was about 7 MB
whereas C:\Program Files\PsychoPy2\avbin.dll was about 3 MB.

I finally found that deleting
C:\Program Files\PsychoPy2\avbin.dll
and
moving C:\Windows\System32\avbin.dll to C:\Program Files\PsychoPy2\
worked fine.

It seems PsychoPy was installing two types of avbin.dll, one in System32 the other in PsychoPy2 and the latter doesn't work properly.
By the way, the order of my system path is C:\Windows\System32;C:\Program Files\PsychoPy2.

1.10.14

Python ftest


Here is an Excel-like ftest of python. (two-sided test)
import numpy as np
import scipy.stats as stats
def ftest(x1, x2):
    dfn = len(x1)-1
    dfd = len(x2)-1
    F = np.var(x1) / np.var(x2)
    f_pf = stats.f.cdf(F, dfn, dfd)
    return min(f_pf, 1 - f_pf)*2

29.8.14

Python ScipyでExcelのftest


ScipyにはExcelのftestやRのvar.testのように単純に等分散かどうかのp値を返す関数がない。
python用ftestを作ってみた。因みに両側検定。

import numpy as np
import scipy.stats as stats
def ftest(x1, x2):
    dfn = len(x1)-1
    dfd = len(x2)-1
    F = np.var(x1) / np.var(x2)
    f_pf = stats.f.cdf(F, dfn, dfd)
    return min(f_pf, 1 - f_pf)*2

Simple Excel-like f-test in python using scipy


Python Scipy does not have Excel-like f-test of equality of variances, which simply returns p-value of it.
Here provides a simple f-test function.

import numpy as np
import scipy.stats as stats
def ftest(x1, x2):
    dfn = len(x1)-1
    dfd = len(x2)-1
    F = np.var(x1) / np.var(x2)
    f_pf = stats.f.cdf(F, dfn, dfd)
    return min(f_pf, 1 - f_pf)*2

Note this is two-sided model as implemented in Excel.

5.8.14

Macでanacondaのipythonを直接呼び出す

AnacondaのLaunhcher.appから起動したIPython notebookでは、matplotlibのpylab.plotがブラウザ内に表示されない。
plt.show()を呼べば表示されるが、別ウインドウに描画されるので美しくない。

そこで、Anaconda内のipythonバイナリを直接叩く。
/anaconda/bin/ipython notebook --pylab=inline
オプション--pylab=inlineを付けると、グラフがブラウザ内に表示される。

Plot a graph inline in IPython notebook of Anaconda on Mac

I could not show a graph of matplotlib pylab.plot inline with ipython notebook, unless using plt.show(), which however showed an separated "aqua" window.

Therefore, I typed on the terminal,
/anaconda/bin/ipython notebook --pylab=inline
, instead of launching notebook with anaconda Launcher.app.

8.5.14

バイナリファイルの呼び出し元を変更

ここやここで書いたが、ターミナルでバイナリ名を叩いた時に呼び出されるファイルは、

$ type [バイナリ名]
や
$ which [バイナリ名]

で表示できる。

例えば、

$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python

$ type python
python is /Library/Frameworks/Python.framework/Versions/2.7/bin/python

また、-aオプションを付けるとインストールされている一覧が表示される

$ which -a python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
/Library/Frameworks/Python.framework/Versions/2.6/bin/python
/usr/local/bin/python
/usr/bin/python
/opt/local/bin/python

$ type -a python
python is /Library/Frameworks/Python.framework/Versions/2.7/bin/python
python is /Library/Frameworks/Python.framework/Versions/2.6/bin/python
python is /usr/local/bin/python
python is /usr/bin/python
python is /opt/local/bin/python

バイナリ名を叩いた時に呼び出されるファイルはこの一覧の一番上にくるファイルである。

この順序を変更すればひも付けを変更できる。


ところで、-aオプションで表示される順序はパスの順序であるので、パスの順序を変更すればひも付けも変更する

パスの一覧を表示するには、

$ echo $PATH
/Library/Frameworks/Python.framework/Versions/2.7/bin/python:/Library/Frameworks/Python.framework/Versions/2.6/bin/python/usr/local/bin:/usr/bin:/opt/local/bin

例えば、pythonと叩いてpython2.6を呼び出したいのならば、

$ export PATH= /Library/Frameworks/Python.framework/Versions/2.6/bin/python:/Library/Frameworks/Python.framework/Versions/2.7/bin/python/usr/local/bin:/usr/bin:/opt/local/bin

とすればよい。

パスの設定方法はググってをみてください。


上記の例ではpythonですが他のバイナリでも同じです。perlなんかも複数インストールしていて呼び出し元を変更したい人がいるのではないでしょうか。

5.5.14

AVD(Android Virtual Device) マネージャーで開始を押してもエミュレーターが起動しない

最近のADTはSDKが同梱されいていてすぐに開発ができ便利である。
最新のものをダウンロードしてAndroid Virutal Device Mangerでエミュレーターを起動しようとした。
ところが開始を押してシークバーが完了しても反応がない。
どうやら内部で呼ばるemulatorというバイナリが正しく選ばれていないようである。

/sdk/toolsにある"emulator"を"emulator.notused"等と適当にリネームして、"emulator64-(avdのCPU/ABI)"を"emulator"に変えたら動作した。

Not starting emulator in AVD (Android Virtual Device) Manager

After created an avd with Android Virutal Device Manger recently downloaded I couldn't start and launch an emulator. Nothing would be happened.
I figured out an solution as did it with a command line.
It said Bus error.

Here is a solution.
Rename a binary "emulator64-(avd's CPU/ABI)" found in /sdk/tools to "emulator", where old "emulator" may be renamed like "emulator.notused".


16.4.14

Set field values at once in MATLAB

When setting values in a field of a struct array, I met errors.

First of all using the for statement:

>> a=struct()
a =
1x1 struct array with no fields.

>> for ii = 1:3
a(ii).field1 = ii;
end
>> a.field1
ans =
   1
ans =
   2
ans =
   3

Ok so for

Then I tried it with one line like:

>> a.field2 = 1:3

??? Incorrect number of right hand side elements in dot name assignment.
Missing [] around left hand side is a likely cause.


>> [a.field2] = 1:3

??? Error using ==> colon
Too many output arguments.

The solution is here, to use deal function:
>> [a.field2] = deal(1,2,3)
a =
1x3 struct array with fields:
  field1
  field2
>> a.field2
ans =
   1

ans =
   2

ans =
   3

Just in case, make sure to use comma to separate values in right hand side otherwise whole values would be set to each struct.
>> [a.field2] = deal(1:3)
a =
1x3 struct array with fields:
  field1
  field2

>> a.field2
ans =
   1   2   3

ans =
   1   2   3

ans =
   1   2   3

4.2.13

python numpy array to structured array

まず、np.array (ndarrayのfield値を持っていないもの)を作ってみる。
>>> # How to make a structured array from non-field array
...
>>>
>>> import numpy as np
>>> x = np.array([(1,2,'a'),(3,4,'b')])
>>> x
array([['1', '2', 'a'],
    ['3', '4', 'b']],
   dtype='|S1')
>>>

このxを次のようなstructured arrayに変換したい。

>>> # From this x I wanted to make a structred array like this.
...
>>> y
array([(1, 2, 'a'), (3, 4, 'b')],
   dtype=[('name1', '|u1'), ('name2', '<i4'), ('name3', '|S20')])
>>>

まず、直接np.arrayに入れてみる。

>>> # Try converting directly x to a structrued array,
...
>>> y0 = np.array(x, dtype=[('name1','u1'), ('name2', 'i4'), ('name3', 'S20')])Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
>>> # It failed.
...

失敗する。
次にxをリストにして渡してみる。

>>> # Try another way,
...
>>> y1 = np.array(x.tolist(), dtype=[('name1','u1'), ('name2', 'i4'), ('name3', 'S20')])
>>> y1
array([[(49, 0, ''), (50, 0, ''), (97, 0, '')],
    [(51, 0, ''), (52, 0, ''), (98, 0, '')]],
   dtype=[('name1', '|u1'), ('name2', '<i4'), ('name3', '|S20')])
>>>
>>> # This is not what I wanted.
...
>>>

エラーは出ないが、作りたかったものと異なる。

ところで、np.arrayで渡す配列は次のようにタプルとリストが混在していても認識してくれる。

>>> # Usually np.array doesn't care what input array is, like below.
...
>>>
>>> np.array([[2,3,4],[2,5,6]])
array([[2, 3, 4],
    [2, 5, 6]])
>>>
>>> np.array([(2,3,4),(2,5,6)])
array([[2, 3, 4],
    [2, 5, 6]])
>>>
>>> np.array(((2,3,4),(2,5,6)))
array([[2, 3, 4],
    [2, 5, 6]])
>>>

ところがdtypeの値を渡してstructured arrayにしようとするとタプルをリストでくくったものしかうまくいかない。(下の例では真ん中のコマンドだけうまくいっている。)

>>> # However when making a structured array, only tuple bracketed by list (middle) is correctly worked.
...
>>> np.array([[2,3,4],[2,5,6]], dtype=[('a','i4'),('b','i4'),('c','i4')])
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: expected a readable buffer object
>>>
>>> np.array([(2,3,4),(2,5,6)], dtype=[('a','i4'),('b','i4'),('c','i4')])
array([(2, 3, 4), (2, 5, 6)],
   dtype=[('a', '<i4'), ('b', '<i4'), ('c', '<i4')])
>>>
>>> np.array(((2,3,4),(2,5,6)), dtype=[('a','i4'),('b','i4'),('c','i4')])
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: size of tuple must match number of fields.
>>>
>>> # Well, a structured array consists of tuples.

structured arrayというのはタプルを配列にしたものであるようだ。
で、次のようにした。

>>> # Then, the answer is here.
...
>>> y2 = np.array(list(tuple(z) for z in x), dtype=[('name1','u1'), ('name2', 'i4'), ('name3', 'S20')])
>>> y2
array([(1, 2, 'a'), (3, 4, 'b')],
   dtype=[('name1', '|u1'), ('name2', '<i4'), ('name3', '|S20')])

7.1.13

ターミナルでファイルから指定した行だけ表示する

head, tail が便利。
$ head -n 3 sample.txt
とすると、sample.txtの始めから3行表示される。

$ tail -n 3 sample.txt
とすると、sample.txtの後ろから3行表示される。

$ tail -n +3 sample.txt
とすると、sample.txtの始めから3行以降すべての行が表示される。

これらを組み合わせて、3行目から 5行目まで表示するには、
$ tail -n +3 sample.txt | head -n 3
とすればよい。tailで3行目以降を表示させ、その結果の始めから3行を表示するというコマンドだ。

さらにcat -nも使えば行番号を表示され、より見やすくなる。
$ cat -n sample.txt | tail -n +3 | head -n 3
logを見るときなどに便利。

28.12.12

ターミナルコマンドの呼び出し先の切り替え

一つのコマンド名対するプログラムが複数インストールされている環境では、ターミナルで、
$ コマンド名
と打つとインストールされているもののうち一つしか起動しない。

この起動する一つというのは、次のようにtypeやwhichで表示される一覧の一番上のものである。

以下の話は、「python」というコマンドを例に取って話を進める
$ type -a python
python is /Library/Frameworks/Python.framework/Versions/2.6/bin/python
python is /Library/Frameworks/Python.framework/Versions/2.7/bin/python
python is /usr/local/bin/python
python is /usr/bin/python
python is /opt/local/bin/python
となっているとき、
$ python
と打つと、/Library/Frameworks/Python.framework/Versions/2.6/bin/pythonのpythonが起動する。

起動するプログラムを変更するにはtypeで表示される順序を変更すればよい。
typeの順序は環境変数PATHの中から順に探してきているので、PATHの順番を変えてやる。

まず、PATHの確認。
$ echo $PATH
/Library/Frameworks/Python.framework/Versions/2.6/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/local/bin:/usr/bin:/opt/local/bin:/opt/local/sbin
typeと同じく/Library/Frameworks/Python.framework/Versions/2.6/binが一番先頭になっている。

例としてMacPortsでインストールしたpythonを使うためにはMacPortsのインストール先である/opt/local/binを先頭にに持っきてみる。
$ PATH=/opt/local/bin:$PATH
$ export PATH
または一行で書くなら、
$ export PATH=/opt/local/bin:$PATH
こうすると、
$ echo $PATH
/opt/local/bin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/local/bin:/usr/bin:/opt/local/sbin
となって、
$ type -a python
python is /opt/local/bin/python
python is /Library/Frameworks/Python.framework/Versions/2.6/bin/python
python is /Library/Frameworks/Python.framework/Versions/2.7/bin/python
python is /usr/local/bin/python
python is /usr/bin/python
となる。

そうすると、
$ python
で起動するpythonはMacPortsのpythonになる。

MacPorts内のpythonの切り替えはこちら