Programming」カテゴリーアーカイブ

GtkEntry でコード保管

今日は gtk.Entry の覚書を作っていたんだが。

gtk.Entry

gtk.Entry.set_completion メソッドって何だ?
Windows の CreateWindow() で指定する EDIT のような感覚で今まで利用していたんだが。

GtkEntryCompletion

英語ではよく解らないから日本語で探してみた、C の書き方で探せばなんとか見つかるなと。
そうか、ようするにいわゆるコード保管機能が標準装備ってことなのね。

説明だけではイマイチ解らないので実験コードを書いてみる。
とにかく GtkListStore をモデルとしてセットしてコレに文字列を詰め込みすればいいみたい。
追記、ちょっと書き換えと自動昇順ソート追加

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

import gtk

slist = [
"abc",
"aaa",
"aab",
"bbbbb",
"あぁん",
"あっはーん",
"あん、あっあーん"
]

class Win(gtk.Window):
    def __init__(self):
        gtk.Window.__init__(self)
        self.connect("delete-event", gtk.main_quit)
        # Entry
        entry = gtk.Entry()
        # completion
        completion = gtk.EntryCompletion()
        entry.set_completion(completion)
        liststore = gtk.ListStore(str)
        completion.set_model(liststore)
        # ascending sort set
        liststore.set_sort_column_id(0, gtk.SORT_ASCENDING)
        # set the completion
        completion.set_text_column(0)
        # load up the liststore with string
        for item in slist:
            liststore.append([item])
        # pack
        vbox = gtk.VBox()
        vbox.pack_start(entry, False)
        self.add(vbox)
        self.set_size_request(300, -1)
        self.show_all()

if __name__ == "__main__":
    w = Win()
    gtk.main()

日本語でも保管が通るのかも兼ねて「あ」と打ち込んで確定してみる。

マジですか、こんな手抜き臭いコードで日本語対応のコード保管ができてしまった。
他に match-selected シグナルを利用する方法もあるようだ、動的に行うのも楽そうだ。
もう少し調べると面白そう、やはりこういうまとめページは作っておくべきかなと思った。

gtk.Button

覚書ページに gtk.Button を追加。
gtk.Button だけでは書くことがスゲェ少ないのでオマケ付き。

gtk.Button and click

細かい解説ではなく実用的に書いているつもり。
というか解説ならば英語だけど公式サイトのみで十分だと思うのよね。

しばらくは覚書ページに専念…するかもしれない。
アルゴリズム関係の勉強もやりたいし自作アプリの機能追加もやりたいし…

Python IniFile Read and Write

前々回 Python の True, False は整数と書いたけど
そういえば isinstance() は?

bool is instance of int in Python – Peterbe.com (Peter Bengtsson on Python, Zope, Kung Fu, London and photos)

やっぱりそうなるか。
他にオブジェクトのタイプを正確に調べるには…

How to compare type of an object in Python? – Stack Overflow

こんなに色々タイプ比較方法があったんだ、めもめも。
でも速度はどうなるんだろう?

import time

t = 100000

s0 = time.time()
for i in range(t):
    isinstance(i, int)
print time.time() - s0

s1 = time.time()
for i in range(t):
    type(i) is int
print time.time() - s1

s2 = time.time()
for i in range(t):
    "%d" % i
print time.time() - s2

結果

0.0666399002075
0.0661001205444
0.157742977142

変わらないや、一応試した文字列変換可能かどうかでは遅すぎるかやはり。

設定読み書きクラスを自作する

私が以前自分で書いたコレもサル丸出しだなと。
とにかく type() がいいみたいなので現行版をベースに作りかえてみる。

とはいえもはや SeeMe で使っているのは原型を留めていないのであるが…
ついでにアトリビュートには直接アクセスできないようにとか % 演算子に変更とか…

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

ERROR_READ = 'Configuration file READ ERROR\n[%s]\n%s=\nvalue is not %s'
ERROR_WRITE = 'Configuration file WRITE ERROR\n(%s, %s) value is not %s'
ERROR_HEADER = 'Configuration file header value is not str'

import os

class InifileBase():
    """
        This class is Inheritance Base
    """
    def __init__(self, filename):
        """
            Attribute is the file name only
        """
        self._filename = filename

    def _get_value(self, section, key):
        """
            This Methods is Inheritance Base
        """
        return None

    def read_int(self, section, key, default):
        """
            @param default: int.
        """
        result = self._get_value(section, key)
        if result == None:
            return default
        try:
            return int(result)
        except:
            raise ValueError, ERROR_READ % (section, key, "int")
    
    def read_float(self, section, key, default):
        """
            @param default: float.
        """
        result = self._get_value(section, key)
        if result == None:
            return default
        try:
            return float(result)
        except:
            raise ValueError, ERROR_READ % (section, key, "float")
    
    def read_bool(self, section, key, default):
        """
            @param default: bool.
        """
        result = self._get_value(section, key)
        if result == None:
            return default
        if result == "1" or result == "-1":
            return True
        elif result == "0":
            return False
        else:
            raise ValueError, ERROR_READ % (section, key, "bool")
    
    def read_str(self, section, key, default):
        """
            @param default: str.
        """
        result = self._get_value(section, key)
        if result == None:
            return default
        return result


class InifileReader(InifileBase):
    """
        This class is read-only
        ini files to load faster
    """
    def __init__(self, filename):
        """
            @param filename: the full path name.
        """
        InifileBase.__init__(self, filename)

    def _get_value(self, section, key):
        """
            Read using the file stream
        """
        if os.path.exists(self._filename):
            section_in = False
            f = open(self._filename)
            try:
                for linenn in f:
                    line = linenn.strip()
                    if line == "":
                        continue
                    if section_in:
                        if "=" in line:
                            pos = line.index("=")
                            if key == line[:pos]:
                                return line[pos+1:]
                        if len(line) > 2 and line[0] =="[" and line[-1] == "]":
                            return None
                    if len(line) > 2 and line[0] =="[" and line[-1] == "]":
                        if section == line[1:-1]:
                            section_in = True
            finally:
                f.close()
        return None


class Inifile(InifileBase):
    """
        ini file to read and write class.
    """
    def __init__(self, filename):
        """
            Loading degradation inifile
            @param filename: the full path name.
        """
        InifileBase.__init__(self, filename)
        self._header = ""
        self._ini = []
        if os.path.exists(filename):
            f = open(filename)
            x = f.read()
            f.close()
            lines = x.split("\n")
            section = ""
            for line in lines:
                if line == "":
                    continue
                if len(line) > 2 and line[0] =="[" and line[-1] == "]":
                    section = line[1:-1]
                elif section == "":
                    pass # Nothing
                elif "=" in line:
                    pos = line.index("=")
                    self._add(section, line[:pos], line[pos+1:])
    
    def _add(self, section, key, value):
        """
            Add to contents.
        """
        for dic1 in self._ini:
            if section in dic1.keys():
                for dic2 in dic1[section]:
                    if key in dic2.keys():
                        dic2[key] = value
                        return
                dic1[section].append({key: value})
                return
        self._ini.append({section: [{key: value}]})
    
    def _get_value(self, section, key):
        """
            Get to contents.
        """
        for dic1 in self._ini:
            if section in dic1.keys():
                for dic2 in dic1[section]:
                    if key in dic2.keys():
                        return dic2[key]
        return None
    
    def save(self):
        """
            Save the contents.
        """
        s = ""
        if self._header:
            s += self._header
        for dic1 in self._ini:
            for section in dic1.keys():
                s += "[%s]\n" % section
                for dic2 in dic1[section]:
                    for key in dic2.keys():
                        s += "%s=%s\n" % (key, dic2[key])
                s += "\n"
        if s != "":
            f = open(self._filename, "w")
            f.write(s)
            f.close()

    def add_header(self, header):
        """
            @param headre: str.
        """
        if type(header) is str:
            self._header = header
        else:
            raise ValueError, ERROR_HEADER

    def section_exists(self, section):
        """
            Check existence of section.
        """
        for dic1 in self._ini:
            if section in dic1.keys():
                return True
        return False
    
    def erase_section(self, section):
        """
            Remove the specified section.
        """
        for dic1 in self._ini:
            if section in dic1.keys():
                dic1.pop(section)
                return True
        return False

    def erase_key(self, section, key):
        """
            Erase Key
        """
        for dic1 in self._ini:
            if section in dic1.keys():
                for dic2 in dic1[section]:
                    if key in dic2.keys():
                        dic2.pop(key)
                        return True
        return False

    def write_int(self, section, key, value):
        """
            @param value: int.
        """
        if type(value) is int:
            self._add(section, key, str(value))
        else:
            raise ValueError, ERROR_WRITE % (section, key, "int")
    
    def write_float(self, section, key, value):
        """
            @param value: float.
        """
        if type(value) is float:
            self._add(section, key, str(value))
        else:
            raise ValueError, ERROR_WRITE % (section, key, "float")
    
    def write_bool(self, section, key, value):
        """
            @param value: bool.
        """
        if type(value) is bool:
            if value:
                self._add(section, key, "1")
            else:
                self._add(section, key, "0")
        else:
            raise ValueError, ERROR_WRITE % (section, key, "bool")
    
    def write_str(self, section, key, value):
        """
            @param value: str.
        """
        if type(value) is str:
            self._add(section, key, value)
        else:
            raise ValueError, ERROR_WRITE % (section, key, "str")

継承使っているし、こうなると初心者は見ても意味解らないかも。
Y901x と SeeMe に使うのはこれでいいとして、覚書ページはどうするか…
てかあそこに書いた方法では今では動画再生できなくなったと解っているんだが。

IronPython True False

Python の True, False は変数みたいなものであるのは有名。
True が 1、False が 0 な整数という解釈でいいのかな。

>>>True + True
2
>>>True + False
1

まてよ、IronPython ではどうなのかな?
CTS により .NET の型にマッピングされなければいけないはずなんだが。

と思ったので少し試したけど整数等と同じ、つまり普段は Python の型である。
clr か System を import すると「どっちでもいい」オブジェクトに変身する。

>>>import System
>>>System.Boolean.Parse("true") == True
True
>>>True + True + True
3

又、変数?なので

>>> True = "abcde"
>>> True
'abcde'
>>> True + True
'abcdeabcde'
>>> System.Boolean.Parse("true") == True
False
>>> 2 == 2
True

真ならやはり True が戻ってくるけど中身は文字列というワケワカなことにも。
ま、普通は True や False に代入するはずがないから気にしなくてもいいんだが。

ついでに、どこかで null は IntPtr.Zero だとか見かけたけど

全然違う、None で大抵イケるはずだが None のマッピングは何だろう?