2014年7月5日土曜日

MessageFormatで勝手にカンマが付く

javaのMessageFormatクラスで数値を表示したとき、3桁ごとに勝手にカンマが付きます。
        String msg = MessageFormat.format("{0}", 100000);
        System.out.println(msg);
実行結果
100,000
この結果はロケールにも依存してます。 デフォルトのLocaleをロシアにすると、スペースだけ入ります。 他にもカンマの代わりにピリオドを使う国もあるみたいです。
        Locale.setDefault(new Locale("ru"));
        String msg = MessageFormat.format("{0}", 100000);
        System.out.println(msg);
出力結果はこうなります。
100 000
Locale依存でもあるし、カンマを付けたくないときは次の2種類の方法でできるようです。

・数値をStringにする
ググるとまず出てきたのがこの方法です。

        String msg = MessageFormat.format("{0}", String.valueOf(100000));
        System.out.println(msg);
文字列を表示するので当然勝手にフォーマットされなません。
100000

・数値のフォーマット方法を指定する
APIドキュメント見ると、{0}のところに追加でフォーマットを指定できるようです。
 {ArgumentIndex , FormatType , FormatStyle }
FormatTypeにnumberを指定すると、FrotmatStyleにDecimalFormatと同じようにフォーマットを指定できるみたいです。
        String msg = MessageFormat.format("{0,number,#}", 100000);
        System.out.println(msg);
これでカンマが付加されなくなります。
100000
この方法はここを参照しました。
http://stackoverflow.com/questions/1942118/how-do-i-format-a-long-integer-as-a-string-without-separator-in-java

2014年5月25日日曜日

#pragma packのメモ

構造体のアライメントがずれるから、#pragma packとやらを試した時のメモ。 gccでは使えるみたいだが、他のコンパイラはよくわからない。 Cは普段ほぼ使わないから難しく感じる。。
#include 

#pragma pack(push, 2)
struct s1 {
 char a[1];
 int b;
};

#pragma pack(pop)
struct s2 {
 char a[1];
 int b;
};

#pragma pack(1)
struct s3 {
 char a[1];
 int b;
};

int main() {

 printf("%d\n", sizeof(struct s1));
 printf("%d\n", sizeof(struct s2));
 printf("%d\n", sizeof(struct s3));

 return 0;
}

Syntax Highlightのバグ?でなんか最終行がおかしい・・

このコード動かすと次の結果になった。
6
8
5

eclipseにCDT入れて試すほうが苦労した・・。
build後に実行しても結果が表示されなかった。
cygwinを使う設定でプロジェクト作った環境だったのに、
結局Runの設定でcygwinのbinのパスを追加したら解決。

2014年4月6日日曜日

javaでsocketを使ってバイナリデータ送受信メモ

javaでソケットを使って、例えばint+doubleの12byteデータを複数回送受信するようなことをしてみた。これができれば、片側javaでもう片方がjava以外の場合に、任意のプロトコルデータみたいなものを決めて通信できるはず。java同士ならクラスを作ってObjectOutputStream/ObjectIutputStream使えば済むと思う。 ここでは、ByteBufferに詰め込んで送受信する方法で試したが、もっといい方法があるのかはあんまり調べてない。

サーバ側

この例ではserverSocket.accept()で待ち受け開始、クライアント着信後に12byte分読み込める状態になったらbyte[]に読み込み。 その後、ByteBufferにwrap()して、getInt(),getDouble()で各データを取り出す。一応エンディアンはbigendianにしておいた。サーバではデータを受信したら表示するだけ。

追記) doubleやfloatなどの浮動小数点型を送信する場合にはもう少し考慮が必要かも。
java同士なら問題ないけど、その他とつなぐときはIEEE754の表現に合わせるなど必要?
package test.socket;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class server {
    private static int port = 11111;
    private static int datasize = (Integer.SIZE + Double.SIZE) / 8;

    public static void main(String[] args) throws IOException,
            InterruptedException {

        ServerSocket serverSocket = null;
        InputStream in = null;

        try {
            serverSocket = new ServerSocket(port);
            Socket socket = serverSocket.accept();
            System.out.println("connected");
            in = socket.getInputStream();
            while (!socket.isClosed()) {
                int size = in.available();
                if (size >= datasize) {
                    byte[] data = new byte[datasize];
                    in.read(data, 0, datasize);
                    ByteBuffer buf = ByteBuffer.wrap(data);
                    buf.order(ByteOrder.BIG_ENDIAN);
                    System.out.println(buf.getInt(0) + ": "
                            + buf.getDouble(Integer.SIZE / 8));
                }
                Thread.sleep(100);
            }
        } finally {
            if (in != null)
                in.close();
            if (serverSocket != null)
                serverSocket.close();
        }
    }
}

クライアント側

new Socket(hostName, port)でソケット作成。 その後、ByteBuffer.allocate(datasize)で12byteのデータ格納エリアを作り、intとdoubleの値を入れてwrite()する。これを100回繰り返し。

package test.socket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;

public class client {
    private static String hostname = "localhost";
    private static int port = 11111;
    private static int datasize = (Integer.SIZE + Double.SIZE)/8;

    public static void main(String[] args) throws IOException,
            InterruptedException {

        OutputStream out = null;
        try {
            out = (new Socket(hostname, port)).getOutputStream();

            for (int i = 0; i < 100; i++) {
                ByteBuffer buf = ByteBuffer.allocate(datasize);
                buf.putInt(i).putDouble(Math.random());
                out.write(buf.array());
                Thread.sleep(100);
            }
        } finally {
            if (out != null)
                out.close();
        }
    }
}



結果
connected
0: 0.4699143388898742
1: 0.2983774724033843
2: 0.12623749040407317
3: 0.19952009860520947
4: 0.10241603823568246
5: 0.6230472332876812
    :

2013年12月8日日曜日

投資主体別売買動向の外国人と個人の売買の関係

東証が出してる投資主体別動向みてると、以前から個人と外国人の
買いと売りが真逆の時が多い気がしてました。
ここに過去データがあったので、2003年から相関係数計算をしました。
http://www.traders.co.jp/domestic_stocks/stocks_data/investment_3/investment_3.asp

結果は次のようになりました。
投資主体別動向の週のデータを使って、表計算ソフトで計算しました。

・2003年1月~2013年12月1週の外国人・個人の売買
相関係数=-0.6853158269

・今年(2013年1月~2013年12月1週)の外国人・個人の売買
相関係数=-0.8350048906


結果は、集計が間違えていなければ大体予想通り。
統計詳しくはないけど、逆相関の関係にあるっぽいです。

2013年12月1日日曜日

javaのResourceBundleメモ

今更ながら初めてResourceBundleを使ってみる。
コードは変えずに、ファイルをロケールごとに用意しておけばいいっぽい。
ResourceBundle.Control使えばもっと色々できるみたいだけど、まずはこっちを試してみた。

まずは、読み込むPropertiesファイルを2つ用意する
sample.prpperties
name=taro
sample_ja_JP.properties
こちらは日本語用のファイル。
".properties"の前に_ja_JPを付けた名称にする。
name=太郎
このファイルは、native2asciiでユニコードに変換しておく。
native2ascii -encoding utf-8 sample.properties.ja.base sample_ja_JP.properties
変換すると以下のようになる。
name=\u592a\u90ce
これらのファイルをロケールを変えて読み込む。 getbundle()の引数でLocale指定もできるみたい。 読み込むときのファイル名は、.propertseや_ja_JPを外した完全修飾クラス名。
package test.bundle;
import java.util.Locale;
import java.util.ResourceBundle;


public class BundleTest {
    public static void main(String[] args) {
        // default(ja_JP)
        System.out.println(Locale.getDefault());
        ResourceBundle bundle1 = ResourceBundle.getBundle("test.bundle.sample");
        System.out.println(bundle1.getString("name"));
        // US
        Locale.setDefault(Locale.US);
        System.out.println(Locale.getDefault());
        ResourceBundle bundle2 = ResourceBundle.getBundle("test.bundle.sample");
        System.out.println(bundle2.getString("name"));    
    }
}
出力結果
ja_JP
太郎
en_US
taro

Jacksonでjsonファイルを読み込んでみた

javaでjsonファイルを読み込むためにJacksonを使ってみました。
jsonの形式自体あまり理解できていませんが、配列を使う2つのケースを読み込みを試しました。
形式に関しては、ここに色々なパターンが書いてあり、参考にしています。
http://adobe.github.io/Spry/samples/data_region/JSONDataSetSample.html
POJOを使う読み込み方はいろいろなサイトを参照。


パターン1
・sample1.json
{
    "users": 
    [
        {
            "name": "taro",
            "country": "japan",
            "age": 12
        }, 
        {
            "name": "jack",
            "country": "us",
            "age": 20
        }
    ]
}
・JsonTest1.java
import java.io.File;
import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonTest1 {

    public static void main(String args[]) throws JsonParseException,
            JsonMappingException, IOException {

        JsonTest1 converter = new JsonTest1();
        converter.parse("sample1.json");
    }

    public void parse(String fname) throws JsonParseException,
            JsonMappingException, IOException {
        UserList users = new ObjectMapper().readValue(new File(fname),
                UserList.class);
        for (User user : users.getUsers()) {
            System.out.println(user.getName());
            System.out.println(user.getCountry());
            System.out.println(user.getAge());
        }
    }

    public static class UserList {
        private List<User> users;

        public UserList() {
        }

        public List<User> getUsers() {
            return users;
        }

        public void setUsers(List<User> users) {
            this.users = users;
        }
    }

    public static class User {
        private String name;
        private String country;
        private int age;

        public User() {
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getCountry() {
            return country;
        }

        public void setCountry(String country) {
            this.country = country;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}
パターン2
・sample2.json
[
    {
        "pair": "USDEUR",
        "price": 1.3588,
        "change": -0.0088
    },
    {
        "pair": "USDJPY",
        "price": 102.4250,
        "change": 0.0049
    }
]
・JsonTest1.java
import java.io.File;
import java.io.IOException;
import java.util.List;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonTest2 {
    public static void main(String args[]) throws JsonParseException,
            JsonMappingException, IOException {
        JsonTest2 converter = new JsonTest2();
        converter.parse("sample2.json");
    }
    public void parse(String fname) throws JsonParseException,
            JsonMappingException, IOException {
        List<Currency> pairs = new ObjectMapper().readValue(new File(fname),
                new TypeReference<List<Currency>>() {
                });
        for (Currency c : pairs) {
            System.out.println(c.toString());
        }
    }
    public static class Currency {
        private String pair;
        private double price;
        private double change;
        public Currency() {
        }
        public String getPair() {
            return pair;
        }
        public void setParr(String parr) {
            this.pair = parr;
        }
        public double getPrice() {
            return price;
        }
        public void setPrice(double price) {
            this.price = price;
        }
        public double getChange() {
            return change;
        }
        public void setChange(double change) {
            this.change = change;
        }
        @Override
        public String toString() {
            return pair+":"+price+"("+change+"%)";
        }
    }
}

2013年11月30日土曜日

初投稿

ブログ開設。
ここを参考にコードのシンタックスハイライトを設定。
http://cuvico.blogspot.jp/2010/03/bloggersyntaxhighlighter-2.html
投稿のプレビュー画面ではハイライトが反映されず、無駄に悩んだ・・

javaの場合
public static void main(String[] args){
   // test
}
javascriptの場合
var setArray = function(elems) {
    this.length = 0;
    push.apply(this, elems);
    return this;
}