end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

ロジスティック回帰による二項分類/パーセプトロン (2/2) ( deep learning & python )

先日のシグモイド関数(ロジスティック関数)を用いたtensoflow実装。

end0tknr.hateblo.jp

というより、↓こちらの Chapter2の写経。

github.com

#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import multivariate_normal, permutation
import pandas as pd
from pandas import DataFrame, Series

def make_training_data():
    np.random.seed(20160512)
    
    # t=1 : 2種の薬(X1, X2)投与による効果がない場合
    mu0, variance0, n0 = [10, 11], 20, 20  #平均, 分散, data数
    # multivariate_normal() : 多次元正規分布の乱数を生成
    # ├ param1 : 平均
    # ├ param2 : 共分散行列. np.eye(2)は2x2の単位行列生成
    # └ param3 : data数
    data0 = multivariate_normal(mu0, np.eye(2)*variance0 ,n0)
    df0 = DataFrame(data0, columns=['x1','x2'])
    df0['t'] = 0

    # t=1 : 2種の薬(X1, X2)投与による効果がある場合
    mu1, variance1, n1  = [18, 20], 15, 22  #平均, 分散, data数
    data1 = multivariate_normal(mu1, np.eye(2)*variance1 ,n1)
    df1 = DataFrame(data1, columns=['x1','x2'])
    df1['t'] = 1
    
    # 2個の行列を連結(≠結合)
    df = pd.concat([df0, df1], ignore_index=True)

    train_set = df.reindex(permutation(df.index)).reset_index(drop=True)

    # train_setに含まれるx1, x2, t列を{x1, x2}と{t}に分割
    train_x = train_set[['x1','x2']].as_matrix()
    train_t = train_set['t'].as_matrix().reshape([len(train_set), 1])

    return train_x, train_t

# 予測関数作成
def make_predict_func():
    x = tf.placeholder(tf.float32, [None, 2])
    w = tf.Variable(tf.zeros([2, 1]))
    w0 = tf.Variable(tf.zeros([1]))
    f = tf.matmul(x, w) + w0  # f(x) = wx + w0   ※w,x,w0はいずれもベクトル
    p = tf.sigmoid(f)         # シグモイド関数 = ロジスティック関数
    return p, w, x, w0

# 誤差関数
def make_err_func(p):
    t = tf.placeholder(tf.float32, [None, 1])
    # 最尤推定を行う誤差関数
    loss = -tf.reduce_sum(t*tf.log(p) + (1-t)*tf.log(1-p))
    # 勾配降下法によるトレーニングアルゴリズム
    train_step = tf.train.AdamOptimizer().minimize(loss)
    # pとtの符号で比較する為、-0.5を実施
    correct_prediction = tf.equal(tf.sign(p-0.5), tf.sign(t-0.5))
    # reduce_mean()とはベクトルの各成分の平均値算出
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    return loss, t, train_step, accuracy

def main():
    # トレーニングデータ
    train_x, train_t = make_training_data()
    # 予測関数
    p ,w, x, w0 = make_predict_func()
    # 誤差関数
    loss, t, train_step, accuracy = make_err_func(p)

    # セッション作成 & Variable初期化
    sess = tf.Session()
    sess.run(tf.initialize_all_variables())

    # 勾配降下法によるパラメーター最適化
    i = 0
    for _ in range(30000):
        i += 1
        sess.run(train_step, feed_dict={x:train_x, t:train_t})
        if i % 2000 == 0:
            loss_val, acc_val = sess.run(
                [loss, accuracy], feed_dict={x:train_x, t:train_t})
            print ('itep: %d, loss: %f, accuracy: %f'
                   % (i, loss_val, acc_val))

    # 結果(w0, w1, w2)の取り出し
    w0_val, w_val = sess.run([w0, w])
    w0_val, w1_val, w2_val = w0_val[0], w_val[0][0], w_val[1][0]
    print "w0:", w0_val, " w1:",w1_val, " w2:",w2_val


if __name__ == '__main__':
    main()

↑こう書くと↓こう表示されます

$ ./foo_2.py 
itep: 2000, loss: 17.505960, accuracy: 0.857143
itep: 4000, loss: 12.778822, accuracy: 0.928571
itep: 6000, loss: 9.999125, accuracy: 0.928571
itep: 8000, loss: 8.244436, accuracy: 0.976190
itep: 10000, loss: 7.087447, accuracy: 0.952381
itep: 12000, loss: 6.303907, accuracy: 0.952381
itep: 14000, loss: 5.765183, accuracy: 0.952381
itep: 16000, loss: 5.393257, accuracy: 0.952381
itep: 18000, loss: 5.138913, accuracy: 0.952381
itep: 20000, loss: 4.969873, accuracy: 0.952381
itep: 22000, loss: 4.863929, accuracy: 0.952381
itep: 24000, loss: 4.804683, accuracy: 0.952381
itep: 26000, loss: 4.778569, accuracy: 0.952381
itep: 28000, loss: 4.772072, accuracy: 0.952381
itep: 30000, loss: 4.771708, accuracy: 0.952381
w0: -21.0061  w1: 0.849911  w2: 0.621193

ロジスティック回帰による二項分類/パーセプトロン (1/2)

シグモイド関数(ロジスティック関数)の理解度の整理を目的に、 2種の薬(X1, X2)投与による効果予測(解消 or not)を ロジスティック回帰による二項分類で行います。

今回は、シグモイド関数を使用した予測関数の作成と、 最尤推定による誤差関数の作成までを行います。

f:id:end0tknr:20170406095513p:plain

シグモイド関数を使用した予測関数

先程の左上図における境界関数を一次式で次のように設定します。

 \displaystyle
f(x_1, x_2) = w_0 + w_1 \cdot x_1 + w_2 \cdot x_2

次に、この f(X1, X2) による効果のある確率をシグモイド関数を使って表します。

 \displaystyle
\sigma(x) = \frac{1}{1 + e^{-x}}
\rightarrow  \underline{ P(x_1,x_2) = \sigma( f(x_1,x_2)) }
これを予測関数とします。

最尤推定の為の誤差関数 - STEP ½

次に、誤差関数を考えますが、 まず、(X1, X2)で与えられるデータは、N個あるとし、 n番目のデータを(X1n,X2n)と表すことにします。

また、n番目のデータで、効果があった or not を、 それぞれ、tn = 1, 0 としたとき、それぞれの確率は次のように表せます。

 \displaystyle
t_{n} = 1 \rightarrow  Pn = P(x1n, x2n)

 \displaystyle
t_{n} = 0 \rightarrow  Pn = 1 - P(x1n, x2n )

また、上記2式は、次のように統合できます。

 \displaystyle
Pn = ( P(x1n, x2n ) )^{tn} \cdot ( 1 - P(x1n, x2n ) )^{1-tn}

ここで、N個全てを正解する確率は、

 \displaystyle
P = P_1 \times  P_2 \times \cdots \times P_n = \prod_{n=1}^{N}P_n

のような総積である為、一旦?、誤差関数は次のようになる。

 \displaystyle
P = \underline{
     \prod_{n=1}^{N} ( P(x1n, x2n ) )^{tn} \cdot ( 1 - P(x1n, x2n ) )^{1-tn} }

最尤推定の為の誤差関数 - STEP 2/2

が、先程、作成した誤差関数は掛け算を多く含み、計算効率が悪い為

 \displaystyle  E = - \log P  \displaystyle  \log ab = \log a + \log b   \displaystyle  \log a^{n} = n \log a

を使って変形します。

 \displaystyle
E = - \log \prod_{n=1}^{N} ( P(x1n, x2n ) )^{tn} \cdot ( 1 - P(x1n, x2n ) )^{1-tn}

 \displaystyle
= \underline{
     - \sum_{n-1}^{N} ( tn \cdot \log P(x1n, x2n)) + (1-tn) \cdot \log ( 1 - P(x1n, x2n ) ) }

上記が最終的な誤差関数。

シグモイド関数 / ロジスティック関数 の導関数(微分)

シグモイド関数(ロジスティック) と、その導関数(微分)

ロジスティック回帰に関連し、以下を証明(導出)

 \displaystyle
f(x) = \frac{1}{1 + e^{-x}} \ \Longrightarrow \ f'(x) = ( 1 - f(x) ) f(x)

証明(導出)手順

 \displaystyle
f(x) = \frac{1}{1 + e^{-x}} = (1 + e^{-x})^{-1}
…(1) に対し

 \displaystyle u = 1 + e^{-x} …(2) とおくと  \displaystyle f(x) = u^{-1} …(3) となる。

次に、上記(1) の微分を合成関数の微分で表すと

 \displaystyle
f'(x) = f'(u) \cdot \frac{du}{dx}
…(4) となり、式(3)と式(2)をそれぞれ微分

 \displaystyle
f'(u) = -1 \cdot u^{-2} = - (1 + e^{-x})^{-2}
…(5) と  \displaystyle
\frac{du}{dx} = -e^{-x}
…(6) とできる。

最後に 式(5),(6) を 式(4) へ代入し、変形して完了。

 \displaystyle
f'(x) = \frac {-1}{(1 + e^{-x})^{2}} \cdot - e^{-x}
 = \frac {1}{(1 + e^{-x})^{2}} \cdot e^{-x}
 = \frac{e^{-x}}{(1 + e^{-x})} \cdot \frac{1}{(1 + e^{-x})}

 \displaystyle
 = ( \frac{1+e^{-x}}{1+e^{-x}} - \frac{1}{1+e^{-x}}) \cdot \frac{1}{1+e^{-x}}
 \displaystyle
 = \underline{ ( 1 - f(x)) \cdot f(x) }

apache commons lang ver.3 for java で escapeSql() が削除されていた

なんで?

ver.2.6 の javadoc

Escapes and unescapes Strings for Java, Java Script, HTML, XML, and SQL.

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html

ver.3.5 の javadoc

Escapes and unescapes Strings for Java, Java Script, HTML and XML.

https://commons.apache.org/proper/commons-lang/javadocs/api-3.5/org/apache/commons/lang3/StringEscapeUtils.html

tensorflowによる勾配降下法 ( deep learning & python )

github.com

↑こちらの Chapter1の写経。

前準備 - 使用する関係式

STEP1 : 予測式 - 1~12月の気温を予測

 \displaystyle
y = w_0 x^{0} + w_1 x^{1} + w_2 x^{2} + w_3 x^{3} + w_4 x^{4}
y = w x

 \displaystyle
y = X w

 \displaystyle
y = \left(
    \begin{array}{c}
      y_1 \\
      y_2 \\
      \vdots \\
      y_{12}
    \end{array}
  \right)

 \displaystyle
X = \left(
    \begin{array}{cccc}
      1^{0}  &   1^{1} &  \ldots &  1^{4} \\\
      2^{0}  &   2^{1} &  \ldots &  2^{4} \\\
      \vdots &  \vdots &  \ddots & \vdots \\\
      12^{0} &  12^{1} &  \ldots & 12^{4}
    \end{array}
  \right)

 \displaystyle
w = \left(
    \begin{array}{c}
      w_0 \\
      w_1 \\
      \vdots \\
      w_{4}
    \end{array}
  \right)

STEP2 : 誤差関数

 \displaystyle
E = \frac{1}{2}\sum_{n=1}^{12} (y_n - t_n)

最小二乗法や、ニュートン・ラフソン法を思い出します。

で、実装

#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

def main():
    #予測関数
    x = tf.placeholder(tf.float32, [None, 5])
    w = tf.Variable(tf.zeros([5, 1]))
    y = tf.matmul(x, w)
    #実測値が入る行列
    t = tf.placeholder(tf.float32, [None, 1])
    #誤差関数
    loss = tf.reduce_sum(tf.square(y-t))
    #勾配降下法によるトレーニングアルゴリズム
    train_step = tf.train.AdamOptimizer().minimize(loss)

    sess = tf.Session()
    sess.run(tf.initialize_all_variables())

    #トレーニングデータ
    train_t = np.array([5.2, 5.7, 8.6, 14.9, 18.2, 20.4,
                        25.5, 26.4, 22.8, 17.5, 11.1, 6.6])
    train_t = train_t.reshape([12,1])
    train_x = np.zeros([12, 5])
    for row, month in enumerate(range(1, 13)):
       for col, n in enumerate(range(0, 5)):
            train_x[row][col] = month**n

    #勾配降下法によるの最適化の繰り返し
    i = 0
    for _ in range(1000000):
        i += 1
        sess.run(train_step, feed_dict={x:train_x, t:train_t})
        if i % 10000 == 0:
            loss_val = sess.run(loss, feed_dict={x:train_x, t:train_t})
            print ('Step: %d, Loss: %f' % (i, loss_val))

    #トレーニング後のパラメーターの値を確認
    w_val = sess.run(w)
    print w_val

#トレーニング後のパラメーターを用いて、予測気温を計算する関数を定義
def predict(x):
    result = 0.0
    for n in range(0, 5):
        result += w_val[n][0] * x**n
    return result


if __name__ == '__main__':
    main()

↑こう書くと↓こう表示されます

[endo@cent7 TENSORFLOW]$ ./foo.py 
Step: 10000, Loss: 31.012341
Step: 20000, Loss: 29.450821
  :
Step: 970000, Loss: 12.155926
Step: 980000, Loss: 34.782570
Step: 990000, Loss: 12.154196
Step: 1000000, Loss: 12.153559
[[ 10.88772202]
 [ -9.05010319]
 [  3.99193835]
 [ -0.44603682]
 [  0.01444708]]

python 2.7 に _tkinter moduleをinstall

python 2.7で “import matplotlib.pyplot as plt” したら、 tkinter がなく errorとなった為。 tkinter の依存ライブラリ/モジュールはきちんと理解していませんが、次のように作業すると、解消。

# yum install tkinter
# yum install tk tcl tk-devel

$ wget https://www.python.org/ftp/python/2.7.13/Python-2.7.13.tgz
$ tar -zxvf Python-2.7.13.tgz
$ cd Python-2.7.13
$ ./configure --enable-optimizations
$ make
$ make test
$ su -
# make install

参考url

http://tkinter.unpythonic.net/wiki/How_to_install_Tkinter

PMD で java の循環的複雑度(code metrics CyclomaticComplexity )を計測

https://pmd.github.io/ https://pmd.github.io/pmd-5.5.4/pmd-java/ https://pmd.github.io/pmd-5.5.4/usage/running.html

install

eclipse plug-inもあると思いますが、今回は、command-line用をinstall.

$ cd /home/endo/local
$ wget https://downloads.sourceforge.net/project/pmd/pmd/5.5.4/pmd-bin-5.5.4.zip
$ unzip pmd-bin-5.5.4.zip

run pmd

https://pmd.github.io/pmd-5.5.4/usage/running.html ↑ここにも記載がありますが、↓こんな感じで、実行&表示

$ ~/local/pmd-bin-5.5.4/bin/run.sh pmd \
     -dir /home/endo/tmp/src \
     -format text \
     -rulesets java-basic,java-codesize 
/home/endo/tmp/src/HttpComm.java:39:    This class has too many methods, consider refactoring it.
/home/endo/tmp/src/JsonUtil.java:1: This class has a bunch of public methods and attributes
/home/endo/tmp/src/JsonUtil.java:19:    Avoid really long classes.
/home/endo/tmp/src/JsonUtil.java:19:    The class 'JsonUtil' has a Cyclomatic Complexity of 3 (Highest = 13).
/home/endo/tmp/src/JsonUtil.java:19:    The class 'JsonUtil' has a Modified Cyclomatic Complexity of 3 (Highest = 13).
/home/endo/tmp/src/JsonUtil.java:19:    The class 'JsonUtil' has a Standard Cyclomatic Complexity of 3 (Highest = 13).
/home/endo/tmp/src/JsonUtil.java:23:    This class has too many methods, consider refactoring it.
/home/endo/tmp/src/JsonUtil.java:221:   The method 'getNode' has a Cyclomatic Complexity of 11.
/home/endo/tmp/src/JsonUtil.java:221:   The method 'getNode' has a Modified Cyclomatic Complexity of 11.
/home/endo/tmp/src/JsonUtil.java:221:   The method 'getNode' has a Standard Cyclomatic Complexity of 11.
    :                                        :
/home/endo/tmp/src/TimeUtil.java:583:   These nested if statements could be combined

java-basic,java-codesize 以外のrulesetは、pmd付属のjarの内容をご覧下さい

perljavascriptのmetricsは、以前のエントリ参照

end0tknr.hateblo.jp

snakeyaml for java による yaml load/read

javaにおけるyaml用ライブラリはいくつもあるようですが、何となく今日はsnakeYAML.

package jp.end0tknr;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.yaml.snakeyaml.Yaml;

public class TestSnakeYaml {
    public TestSnakeYaml() {}

    public static void main(String[] args) {
        String confFilePath = "resource/test.yaml";
        String encoding = "UTF-8";
        
        File file = new File(confFilePath);
        FileInputStream input;
        InputStreamReader stream;
        try {
            input = new FileInputStream(file);
            stream = new InputStreamReader(input,encoding);
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            System.out.println(e.getClass().getName()+ 
                    " fail open file "+ confFilePath);
            return;
        }        
        
        Yaml yaml = new Yaml();
        Map yamlMap = (Map<String, ?>) yaml.load(stream);

        for(Object atriKeyTmp : yamlMap.keySet() ){
            String atriKey = (String) atriKeyTmp;
            System.out.println( yamlMap.get(atriKey).toString() );
        }
    }
}
common:
  system_name: ほげほげ
  encode: utf8
  #yes/no
#  debug_mode: yes
db:
  host: localhost
  port: 3306
  db_name: testdb
  db_user: root
  db_pass: 
  db_opt:
    AutoCommit: 0
    mysql_enable_utf8: 1
  client_encoding: utf8

↑こう書くと、↓こう表示されます

{system_name=ほげほげ, encode=utf8}
{host=localhost, port=3306, db_name=testdb, db_user=root, db_pass=null, db_opt={AutoCommit=0, mysql_enable_utf8=1}, client_encoding=utf8}

利用したjar

  • snakeyaml-1.18.jar

apache commons configuration for java で INI file を load / read

http://commons.apache.org/proper/commons-configuration/

ini形式の設定ファイルをloadする必要があったので、探したら、見かけた。

※ini以外にも、 .xmlや .properties 等に対応しているようです。 ( 一方で、.json や、.yaml には対応していません )

package jp.end0tknr;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.INIConfiguration;
import org.apache.commons.configuration2.ex.ConfigurationException;

public class TestApacheCommonsConfiguration {

    public TestApacheCommonsConfiguration() {}

    public static void main(String[] args) {
        String confFilePath = "resource/test.ini";
        String encoding = "SJIS";
        
        File file = new File(confFilePath);
        FileInputStream input;
        InputStreamReader stream;
        try {
            input = new FileInputStream(file);
            stream = new InputStreamReader(input,encoding);
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            System.out.println(e.getClass().getName()+ 
                    " fail open file "+ confFilePath);
            return;
        }
        
        INIConfiguration configTmp = new INIConfiguration();
        try {
            configTmp.read( new BufferedReader(stream) );
        } catch (ConfigurationException | IOException e) {
            System.out.println(e.getClass().getName()+" fail read file ");
            return;
        }
        
        Configuration config = configTmp;
        Iterator<String> atriKeys = config.getKeys();
        while(atriKeys.hasNext()) {
            String atriKey = (String)atriKeys.next();
            
            if(! config.containsKey(atriKey) ){
                System.out.println( "not exist key "+ atriKey);
            }
            System.out.println( atriKey+ "="+ config.getString(atriKey) );
        }
    }
}
; Test ini file to be included by a configuration definition
[common]
sysTitle = これは、テスト用のタイトルです
[testini]
loaded=yes

↑こう書くと、↓こう表示されます

common.sysTitle=これは、テスト用のタイトルです
testini.loaded=yes

その他 - 参照したjar

  • commons-configuration2-2.1.1.jar
  • commons-logging-1.2.jar
  • commons-beanutils-1.9.2.jar
  • commons-lang3-3.5.jar

pythonで socket + udp通信し、echonet機器一覧を探索

以下、何となく書いて、何となく、動いた程度。 何となくpythonで書いてみたけど、javaでも書くかな? (気が向いたら)

#!/usr/local/bin/python  ## for python 2.7
# -*- coding: utf-8 -*-

import asyncore
import codecs
import netifaces
import socket
import threading
from time import sleep

UDP_RESES = []
UDP_PORT = 3610 # for UDP

def main():
    # 自身のipアドレスを探索
    local_ip = UdpSender.find_local_ip_addr()
    if local_ip == None:
        return None
    
    # echonetのコマンドをudp送信
    sender = UdpSender(local_ip)

    # echonetのコマンド受信用thread
    recv = UdpReceiverThread()
    recv.start()

    echonet_cmd = echonet_cmd_ls() ##echonet機器の一覧取得用コマンド生成

    # 224.0.23.0 とは、ECHONET専用のマルチキャストアドレス
    sender.send_msg("224.0.23.0", echonet_cmd)

    # 複数機器からレスポンスがある場合があるので、少々、待つ
    sleep(3)
    recv.stop()

    # UDP_RESES に各機器からのレスポンスが、echonet電文とIPで入ってます
    for udp_res in UDP_RESES:
        echonet_res = parse_echonet_res(udp_res[0])
        print(udp_res)
        print(echonet_res)

    # 後はお好きに...



def parse_echonet_res(echonet_res):
    res_cols = [echonet_res[ 0: 4],  ## echonetであることの宣言
                echonet_res[ 4: 8],  ## 自由欄
                echonet_res[ 8:14],  ## SEOJ(送信元機器) 0ef001=ノード
                echonet_res[14:20],  ## DEOJ(送信先機器) 05ff01=コントローラ
                echonet_res[20:22],  ## 応答code. 71=set 72=get
                echonet_res[22:24],  ## 処理プロパティ数
                echonet_res[24:26],  ## プロパティ名 d6=自ノードlist.
                echonet_res[26:28],  ## PDC. 後のbyte数
                echonet_res[28:36]]  ## 0105ff01 = 1個(01)x05ff01
    return res_cols


## http://qiita.com/miyazawa_shi/items/725bc5eb6590be72970d
def echonet_cmd_ls():
 
    cmd_cols = ["1081",   ## echonetであることの宣言
                "0000",   ## 自由欄
                "05ff01", ## SEOJ(送信元機器) 05ff01=コントローラ
                "0ef001", ## DEOJ(送信先機器) 0ef001=ノード
                "62",     ## 60=set, 61=set(要:応答), 62=get
                "01",     ## 処理プロパティ数
                "d6",     ## プロパティ名 d6=自ノードlist.
                          ## https://echonet.jp/spec_v112_lite/ にある
                          ## 第2部 ECHONET Lite 通信ミドルウェア仕様の
                          ## 6.11.1 ノードプロファイル詳細規定 参照
               "00"]
    echonet_cmd = "".join(cmd_cols)
    return echonet_cmd



class UdpSender():
    def __init__(self, local_ip):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.IPPROTO_IP,
                             socket.IP_MULTICAST_IF,
                             socket.inet_aton(local_ip))
        
    def send_msg(self, ip,message):
        decode_hex = codecs.getdecoder("hex_codec")
        msg = decode_hex( message )[0]
        self.sock.sendto(msg, (ip, UDP_PORT))

    def close(self):
        self.sock.close()

    @staticmethod
    def find_local_ip_addr(find_iface_name=None):
        for iface_name in netifaces.interfaces():
            iface_data = netifaces.ifaddresses(iface_name)
            af_inet = iface_data.get(netifaces.AF_INET)
        
            if not af_inet: continue

            ip_addr = af_inet[0]["addr"]
            
            if find_iface_name == None:
                return ip_addr
            elif iface_name == find_iface_name:
                return ip_addr
        return None

class UdpReceiverThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.server = UdpReceiver()

    def run(self):
        asyncore.loop()

    def stop(self):
        self.server.close()
        self.join()

        
class UdpReceiver(asyncore.dispatcher):
    def __init__(self):

        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.bind(("0.0.0.0",UDP_PORT))
        return

    def handle_read(self):
        data = self.recvfrom(4096)
        encode_hex = codecs.getencoder("hex_codec")
        global UDP_RESES
        UDP_RESES.append([encode_hex(str(data[0]))[0], data[1][0]])
        return

if __name__ == '__main__':
    main()

↑こう書くと、↓こう出力されます

C:\home\endo\tmp>\Python27\python.exe foo.py
['108100000ef00105ff017201d6040105ff05', '192.168.0.15']
['1081', '0000', '0ef001', '05ff01', '72', '01', 'd6', '04', '0105ff05']

たまにエラー…windows環境だから?

たまに、次のようなエラーが出力されますので、気が向いたら、調べます。

C:\home\endo\tmp>\Python27\python.exe foo.py
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "foo.py", line 106, in run
    asyncore.loop()
  File "C:\Python27\lib\asyncore.py", line 216, in loop
    poll_fun(timeout, map)
  File "C:\Python27\lib\asyncore.py", line 145, in poll
    r, w, e = select.select(r, w, e, timeout)
error: (10038, '\x83\\\x83P\x83b\x83g\x88\xc8\x8aO\x82\xcc\x82\xe0\x82\xcc\x82\xc9\x91\xce\x82\xb5\x82\xc4\x91\x80\x8d\xec\x82\xf0\x8e\xc0\x8ds\x82\xb5\x82\xe6\x82\xa4\x82\xc6\x82\xb5\x82\xdc\x82\xb5\x82\xbd\x81B')

参考にさせて頂いたurl

ソフトウエア取得/改修に伴う 資産計上 or 経費処理 - 7-8-6の2 (ソフトウエアに係る資本的支出と修繕費)

国税庁が公開する 基本通達・法人税法 の 7-8-6の2 (ソフトウエアに係る資本的支出と修繕費)にある通り、 - 「ソフトウエアの機能の追加、向上」⇒(ならば) 資本的支出(≒資産計上)。 - バグ修正等、現状の維持該当 ⇒ 修繕費(≒経費処理OK) らしい。

https://www.nta.go.jp/shiraberu/zeiho-kaishaku/tsutatsu/kihon/hojin/07/07_08.htm

例えば、消費税法改正に伴うソフト修正は、経費処理がOKのよう。 https://www.nta.go.jp/shiraberu/zeiho-kaishaku/joho-zeikaishaku/hojin/0309/01.htm

HTML-lint tool (≠ metrics tool)

html-tidy がいいのかな?

$ wget http://binaries.html-tidy.org/binaries/tidy-5.2.0/tidy-5.2.0-64bit.rpm
$ su
# rpm -ivh tidy-5.2.0-64bit.rpm
$ tidy --help
  • SourceMonitor は、win環境専用
  • Another HTML-lint 5” は、web専用
  • HTML::Lint for perl はratingが低い

ので

pythonでの基数変換の基本は format() ←→ int()、より複雑ならMath::BaseCalc のclone?

pythonの基数変換において、2, 8, 16進数なら…

format() , int()が利用できるので…

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

def main():
    from_int()
    to_int()

def from_int():
    org_int = 10
    for base in ["b","o","x","X"]:
        from_int = format(org_int,base)
        print base +":"+str(org_int) +"->"+ str(from_int)
    print ''

def to_int():
    for org_str, base in {"1010":2, "12":8, "a":16}.items():
        print str(base)+":"+ org_str +"->"+ str( int(org_str, base) )

if __name__ == '__main__':
    main()

↑こう書くと↓こう実行できます

$ ./foo.py
b:10->1010
o:10->12
x:10->a
X:10->A

16:a->10
8:12->10
2:1010->10

2, 8, 16進数以外の基数変換であれば

Math::BaseCalc for perlのcloneを書く必要があるのかな? http://search.cpan.org/perldoc?Math%3A%3ABaseCalc

Excel::Writer::XLSX::Utility for perlで excelのA1形式座標←→R1C1形式座標の変換

Math::BaseCalc かと思ったら、Excel::Writer::XLSX::Utility を使うようです。 http://search.cpan.org/perldoc?Excel%3A%3AWriter%3A%3AXLSX

#!/usr/local/bin/perl
use strict;
use warnings;
use utf8;
# use Math::BaseCalc;
use Excel::Writer::XLSX::Utility;
use Data::Dumper;

main();

sub main {

    my $co_a1_org = "C2";
    my ( $row, $col ) = xl_cell_to_rowcol( $co_a1_org );
    print "$co_a1_org -> ($row, $col)\n";

    my @co_r1c1_org = (2,30);
    my $co_a1 = xl_rowcol_to_cell( @co_r1c1_org );
    print "($co_r1c1_org[0], $co_r1c1_org[1]) -> $co_a1\n";
}

↑こう書くと、↓こう変換できます

$ ./foo.pl 
C2 -> (1, 2)
(2, 30) -> AE3