火曜日, 6月 23, 2015

コマンドラインでシカゴの気温を調べる(C# で JSON データを読む)

先日 Java での JSON データの読み方を紹介しました。

ここでは C# で JSON データを読む方法を紹介します。

DataContractJsonSerializer を使った方法です。

DataContractJsonSerializer.ReadObject() を使うと JSON データを読み、オブジェクトとして出力してくれます。

オブジェクトへの変換が「宣言」となっているところがいくらか分かりやすいといえるでしょうか。

まず、読み込みたいデータ構造をクラスとして宣言し、DataContract 属性を付加します。JSON データは DataMember 属性を付加します。ネストされているデータはクラスとして宣言しDataContract 属性を付加します。コードを参照してください。#配列データは配列として宣言します。

出来上がったデータクラスを DataContractJsonSerializer のコンストラクタの引数として渡します。

準備が出来たらHttpWebResponse として読んできたデータを、DataContractJsonSerializer.ReadObject() で読み込みます。

と、この手順を踏むとめでたく JSON データが読み込めます。あとは出力するだけ。

ここの気温の表示はデフォルト設定でなんとK(ケルビン)です。ので 273.15 を引いてやります。

#華氏(℉)か摂氏(℃)か迷ったんでしょうか(もめたんですかね)。

木曜日, 6月 11, 2015

コマンドラインでシカゴの気温を調べる(Java で JSON データを読む)

なんと、近々発表されるはずの Java 9 から JSON ライブラリが外されてしまいました。

これは、政治ですね?(笑・XML派の妨害ですね。)

JSON ってコンパクトですよね。名前なしの{}(中括弧)を使うところが XML 形式より多少なりとも不確実ではあっても記述が短くて済むわけです。

openweathermap サイトのデフォルト設定は JSON 出力です。



このサイトは天気情報を提供してくれます。都市名とかを URL で送ってやると天気情報を返してくれます。

そこで、「ねえ、パーサーを書いたら?」とかいう余計な手間をかけたくない忙しいプログラマのため org.json.simple ライブラリの使い方を紹介します。

まず JSON.simple JAR ファイルをダウンロード


データを読み込むプログラムの手順を示します。

  1. まず、JSONParser オブジェクトをインスタンス化。
  2. URL オブジェクトから InputStreamReader、BufferedReader をインスタンス化。
  3. JSONParser.parse() でパース。
  4. あとは JSONParser.get() で要素を読んでいくだけです。
  5. ネストされている要素であれば、JSONParser オブジェクトとして扱う。


あとは、JAR ファイルとコンパイルするだけ。

javac -classpath "JARファイルのあるディレクトリ;." WeatherApp.java
これで、コマンドラインからシカゴの気温が検索できます。

月曜日, 4月 20, 2015

水曜日, 2月 25, 2015

Java: データ・マイニング ECLAT変換

データ・マイニングなんぞでデータ変換など需要がありましたので、プログラムなど置いておきます。

変換といっても縦のものを横にするという種類のもので、こんな感じです。


 アルファベットが項目で、数字がIDです。

走らせるとアルファベットからIDを列挙します。

火曜日, 2月 24, 2015

Java: 楕円銀河

銀河系ってのはさまざまな形をしていますが、楕円形ってのがもっとも多いわけです。

楕円形のつぶれかたで記号までついてるわけですね。

E0 から E7 まであるわけですが、E0 がもっとも丸い。E7 がつぶれた形をしている。



こんなのを Java でインタラクティブで動かせたらいいかな、というんで書いてみました。

そのままコンパイルすると動くはずです。です。


火曜日, 1月 13, 2015

Java: BigInteger で階乗を計算する

自然数ってのは限りがありません。もし上限 n があったと仮定すると、 n+1 が整数、これは矛盾します。よって上限はない。数学ってのは証明ができていいですね。

ところがいざプログラムで実装となるとガラスの壁ってのがあるわけです。ご存じのとおり整数型の上限は64ビット long で -9223372036854775808 から 9223372036854775807。

これだともっと大きな整数は扱えません。そこで、Java では整数を抽象化し、BigInteger として制限のない整数を表現します。

この BigInteger、四則演算は揃っているのですが、演算メソッドが限られていて、階乗がありません。いちいち定義すればいいわけですが、こんなところで立ち止まっていては世界が見えてこない。

そこで、BigInteger で階乗を計算するコードを載せておきます。



この階乗を使うと、組み合わせなど計算ができます。階乗で定義されるやつですね。



実はこの組み合わせ、再帰で定義できます。パスカルの三角形といわれるやつです。



証明はこちら。

金曜日, 11月 21, 2014

NetBeans+Maven: JARファイルが起動しない

NetBeans+Maven で書いた Java アプリを、いざ起動しようと思うと動かないわけですね。

動作環境は NetBeans 8.0.1 です。快適な Java 開発環境です。Maven も入っている。おすすめです。

補完機能もあるし、フォーマットからコメントアウトまで編集機能も万全。JUnit なんかもテンプレートで作成できます。

さくさくとプログラムを書いて、コンパイル。無事テストも通って、できた JAR ファイルを起動。JAR ファイルなら Windows 上で実行形式ファイルとしてそのまま起動できるはずです。

さっそくというのでアイコンをクリックをクリックします。で、動かない。

できてないですね。NetBeans。なんなんですかね。

コマンドラインで動かしてみれば理由はあきらか。Main-Class が設定されていない。

肝心なところでなぜなんだと悩みました。だってできたプログラムをいざ実用化っていう大切な瞬間ですよね。なぜでしょう。意図的としか思えませんね。

まあ陰謀論はいいんですが、結論から言うと解決は簡単で、pom.xml ファイルで Main-Class を設定します。



こんなコードを加えてやります。

#タグの大文字小文字が違っていたので訂正します。
   
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>easai.treeeditor.TreeEditor</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>      


JARファイルを追加するには以下のように記述します。

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>easai.db.DB</mainClass>
                        </manifest>
                        <manifestEntries>
                            <Class-Path>mysql-connector-java-5.1.6-bin.jar</Class-Path>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>     

月曜日, 9月 08, 2014

Java: 標準入力から値を得る

Java で標準入力から値を得るのは C++ より面倒です。

C++ では cin を使いますよね。 標準入力ストリームを使うわけです。

Java では標準入力は System.in です。しかし、です。このままでは使えないんですね。

以下の F1 Score 計算プログラムでは Scanner を使用しています。


木曜日, 7月 10, 2014

3Dプリンターを使ってみての考察



3Dプリンターを使ってみての所感です。

  • ルーターは必須。バリや凹凸はもちろん、サイズを合わせるため必須。
  • プラスチック樹脂の種類によって強度、加工しやすさが違う。色もメーカーによって違う。
  • ABSは曲げられない。折れる。硬さはそれぞれの樹脂の質による。
  • フィラメントが引っかかると層がずれて悲惨な作品が出来上がる。フィラメントのフィードが遅いマシンでは "Extrusion multiplier" の値を低くする。フィラメントの太さを指定する必要がある。
  • アセトンで壊れたパーツを修復できる。フィラメントを溶かしたアセトン溶液を使うといい。アセトンはすぐ蒸発するのでガラス瓶など使うと容器内で蒸発する。目薬の容器は小さくて少量ずつ出すことができて便利。
  • 糊をたっぷり使わないと作品がはがれる。ブリム brim をつけると倒れにくくなる。ラフト raft をつけると底面からはがせる。
  • 糊はコーンスターチと水を電子レンジで加熱すると大量生産できる。夏場は糊が腐るので酢を少量混ぜるといい。
  • よく監視しておかないとフィラメントを無駄にする。
  • 糊が乾燥するので水道水をスプレーするといい。
  • 冷えるまで触ってはならない。柔らかいので無理に外すと壊れる。
  • 解像度は低い。 
  • 時間がかかる。
  • 削るのは時間のかかる作業である。
  • 思いのまま作品ができる。「今まで何してたんだろう」的な気分になる。カスタマイズも自由。



金曜日, 6月 20, 2014

火曜日, 5月 13, 2014

Javascript (jQuery) から PHP の関数を呼び出す

ボタンを押したときに、PHP の関数を呼び出したいとします。

Form を使って PHP ファイルを読み込み、ページ全体を書き直すという手段もありますが、ある関数だけを呼び出したいときなど、ajax を使うと PHP 関数を呼び出してページ側で返り値を得ることができます。

このように、url でファイル名を指定して、success で返り値 results として引き渡してやります。

PHP ファイル側では、渡したい値を echo などで表示します。

これで PHP の関数をページから呼び出すことができます。


木曜日, 5月 01, 2014

HTMLエディターを1行で書く

HTMLエディターを1行で書いてみました。

要するに、書いたHTMLがそれっぽく見えればWYSIWYGってわけですよね。

じゃあ、書いたものをそのままブラウザ表示すりゃいいわけじゃないですか。

これを動かすと、何もないテキストボックスが下のほうに表示されます。

適宜 HTMLコードを入力してみましょう。

画面上部に結果が表示されます。

リアルタイムでHTMLコードが編集できます。

ちょっとしたプレビューにも使えます。

水曜日, 4月 30, 2014

g++ の内部コード

g++ の内部コードは UTF16 で、wchar_t も当然のことながら16ビットです。

なんなら日本語のファイルを読んで、コードを出力してみればいいわけですね。

ロケールを設定する必要があります。


火曜日, 4月 29, 2014

C++ でバイナリで表す

C++ でバイナリで表すには、自分で書かねばならないようです。

べつにたいした手間ではないですが、書かされるという気分が知性に対する挑戦のように思えるわけですね。

こんなことをやらされるために頭脳があるんじゃない!みたいな。

もしそんな教師がいたら最悪ですね。でも現実は頭脳に厳しい。

というわけで書きました。

なんか頭にくるのでここに載せときます。


注意点として、(int16_t)0xff などとキャストすると結果は 1111111111111111 と表示されます。

当然そうなるわけなんですが、0000000011111111 とはなりません。

注意しましょう。

火曜日, 4月 22, 2014

eshell (Emacs) と .website (IE) , time (実行時間の計測)メモ

本日の収穫:

M-x eshell

Emacs エディタの話です。

M-x shell を愛用していたわけなんですが、M-x eshell なるものがあるんですね。

ずっと便利じゃないですかこれ。早いし。なんだったんだ今までの苦労は(笑

コマンドの結果が別ウィンドウで表示されます。


.website

IE の話です。

サイトのファビコンをクリック・ドラッグすると、サイトのリンクを作れます。

サイトのリンクと同じようなものですが、IEを指定できます。

time

time ./a.exe で実行速度が計測できます。

水曜日, 4月 09, 2014

Java:バイナリ表示

Java でバイナリを表示するには、toBinaryString()関数を使うと簡潔に表現できます。

水曜日, 3月 19, 2014

Java 8: ストリーム

Java 8 では文字列をストリームとして扱うことができます。

ストリームにフィルターを追加し、要素を選択することもできます。

下記のコードでは要素の文字長を指定し、表示するものです。

下記のコードは要素の頭文字を指定し、表示します。

Java 8: ラムダ式

Java 8 が正式にリリースされました。

ラムダ式が導入されるということで、さっそく試してみました。

ラムダ式とは関数を抽象化したもので、コンパクトにコールバック関数の引渡し・定義ができます。

ラムダ式のフォーマットですが、

 (引数) -> 定義

となります。Lisp などとは異なる形式ですが、内部クラスなどと比較して簡潔にコールバック関数が定義できます。



火曜日, 2月 25, 2014

MySQL: テーブル構造を取得し、SQL文に変換する

MySQLでテーブル構造を取得するには、DESCRIBE (テーブル名) などのSQL文を使用します。



これをSQL文に変換するには、テーブルの情報をSQL文の形式でそれぞれ記述してやる必要があります。

CREATE TABLE IF NOT EXISTS `notes` (
  `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` text COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `videoid` text COLLATE utf8_unicode_ci NOT NULL,
  `imagefile` text COLLATE utf8_unicode_ci NOT NULL,
  `docnum` text COLLATE utf8_unicode_ci NOT NULL,
  `shortdesc` text COLLATE utf8_unicode_ci NOT NULL,
  `onhold` int(11) NOT NULL,
  `registered` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci 
AUTO_INCREMENT=61 ;

ここで気をつけねばならないのは、timestamp値をとるコラムです。

デフォルト値に CURRENT_TIMESTAMP をとるコラムは、TIMESTAMP 値をとるコラムより前に記述しなければなりません。

コラムを並べ替える必要があります。

ここでは array_unshift() という関数を使用し、CURRENT_TIMESTAMP をとるコラムを配列の最初に格納するという方法をとりました。

ソースコード: GitHub: tablestructure.php

木曜日, 12月 19, 2013

PHP: HTML セーフなコードに変換

HTMLコードを書く際に、不等号記号などそのまま書くとブラウザが勝手に変換してしまいます。

プログラムなどを表示するためには、記号をHTMLに変換しなければなりません。

ブラウザの勝手な行動を制限するために、変換するツールを作成しました。

使い捨てないツールのためにここにアップします。

以下のコードを html.php というファイルに保存し、PHP の動く環境でブラウザを使って表示します。

テキストボックスにコードを打ち込み、Convert ボタンを押すと変換されたコードが表示されます。

<html>
<head>
<style>
textarea
{
width:1000px;
height:500px;
}
</style>
</head>
<body>

<?
$text=$_REQUEST['text'];

$text=htmlspecialchars($text);

echo <<<END
<form action="html.php">
<textarea name="text">$text</textarea>
<input type="submit" value="Convert" />
</form>
END;

$html=htmlspecialchars($text);
echo <<<END
<textarea>
$html
</textarea>
END;
?>
</body>
</html>

土曜日, 12月 14, 2013

Java: 列挙型 enum を switch文で使う

Mandelbrot
列挙型 enum は Java5 で導入されました。

public enum Periodic{PERIODIC,PREPERIODIC,NONPERIODIC};

名前を付けて、識別子を列挙します。

この値を変数に代入するには、静的に定義された変数として扱います。

 Periodic periodic=Periodic.NONPERIODIC;


列挙型変数名を指定する必要があるわけです。

ただし、switch文で使う場合には指定しません。

switch(isPeriodic())
            {
            case PERIODIC:
                System.out.println("f is periodic.");
                break;
            case NONPERIODIC:
                System.out.println("f is not periodic.");
                break;
            case PREPERIODIC:
                System.out.println("f is pre-periodic.");
                break;
            }

気を付けましょう。

日曜日, 12月 01, 2013

Windows 8 ストアアプリ開発にはまっております。

作りかけのメトロアプリ
目下のところWindows8用のアプリ開発にはまっております。これが面白い。書き方が全然違うので慣れるまで大変ですが、簡便さ能率と自由度が違う。

Windows8用のアプリは ストアアプリ、メトロアプリ、WinRT などと呼ばれていてどれもメトロスタイルのアプリを書くためのものです。興味深いことにデザインはXAML形式、機能はC#などプログラミング言語で記述します。ここがポイント。

もとWindows7とかWindowsXPのデザインは、もとはRCファイルなどですね。ベタなテキストファイルで、編集は特殊なリソースエディタを使って行っておりました。エディタで部品を置いて、クリックしたときなどの動作をC++で記述するという形です。部品の種類もそこそこあるわけですが、Windows8になってデザインの差もさることながら自由度が格段にアップしました。アプリが豪華に見えます。

ページデザイン、レイアウトをXAMLというXMLに基いた言語で記述することで、あらたな世界が広がっています。HTMLはXMLに準ずる形式ですね。だからXAMLはHTMLのようなものです。ウエブページを書くノリで自由に部品が記述できるのです。これはすごい。どんどんページを書いていって、それから機能を実装していけばいい。

開発環境も優れています。部品の種類もそこそこ厳選されており、ネーミングも悪くない。いや、とてつもなく悪いのもあるわけですが、コンセプト的にはいい。アプリにブラウザ機能をつけるととんでもない便利な環境が出来上がります。ネットにどれだけのリソースがあると思いますか?アプリからそれが全部使える。辞書だろうとニュースサイトだろうとSNSだろうとそのままです。入力を処理する必要さえない。

まだまだ自由に使いこなせているとは言えませんが、チャレンジする価値は十分にあります。情報が少ないのはネックですが、今後の発展を期待しましょう。

日曜日, 11月 24, 2013

Windows ストアアプリ: ローカルファイル

ストアアプリではURIでファイル名を指定します。

Windows.Storage.StorageFile file
   = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(
                                 new Uri("ms-appdata:///local/Doc/" + fileName));

上記の指定では、mss-appdataでローカルファイルを指定し、Docディレクトリ以下のfileNameにアクセスしています。このDocディレクトリはアプリで用意する必要があります。あらかじめアプリケーションのほうでDocディレクトリを用意し、ファイルを置いておけば、ローカルファイルから読み込むことができます。

 
ややこしいことに、元ファイルは、ローカルにコピーされたファイルとは別物です。つまり、ms-appdataで指定されたファイルをいくら書き直しても元ファイルには反映されません。 元ファイルのほうは、ms-appxで指定します。ファイルは読み込み専用です。

Windows.Storage.StorageFile file
  = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(
                                new Uri("ms-appx:///Doc/" + fileName));

ローカルファイルのほうを調べたければ Windows.Storage.ApplicationData.Current.LocalFolder.Path に指定されているディレクトリを見に行く必要があります。




PHP: CSVをHTML形式のテーブルに変換

CSV を HTML 形式のテーブルに変換するニーズというのは多々あるものです。

HTML のテーブル形式に変換したいときに使えるツールを作ってみました。

CSV 形式のデータを上のテキストボックスにほうりこみ、Convert ボタンをクリックすると変換された HTML コードが表示されます。

ツールを使い捨てないためにここにアップします。

<html>
<head>
<style>
textarea
{
width:1000px;
height:500px;
}
</style>
</head>
<body>

<?
$text=$_REQUEST['text'];

echo <<<END
<form action="table.php">
<textarea name="text">$text</textarea>
<input type="submit" value="Convert" />
</form>
END;

$text=$_REQUEST['text'];
$text=htmlspecialchars($text);
$list=explode("\n",$text);
$html="";
foreach($list as $line)
  {
    $columnList=explode(",",$line);
    $column=implode("</td><td>",$columnList);
    $html.="<tr><td>$column</td></tr>";
  }
$html="<table><tbody><pre>
$html
</pre></tbody></table>
";
echo <<<END
<textarea>
$html
</textarea>
$html
END;
?>
</body>
</html>

日曜日, 11月 10, 2013

WinRT/Metro TIPS:ストアアプリで部品サイズを可変にする

なかなか普及の進まない Windows 8.1 と騒がれていますが、当方果敢にもストアアプリ作成にチャレンジ中であります。

プログラムの基本概念なぞという人間は現場を・知らない・知ろうとしない・連中だとまずここで一言。

考え方としてはプログラム構造は Java のような OOP で、見た目は XML で指定します。

ストアアプリでは XML 形式を拡張した XAML 形式で画面構成を指定します。

Visual Studio 2013 という豪華な(金のかかった) IDE には圧倒されますが、それなりにクセのあるツールではあります。

部品サイズを可変に指定するやり方に悩んでしまい、ネットにもなさそうなのでここに書いておきます。

Visual Studio 2013 部品を可変サイズにする
サイズを可変にするには Width と Height 右のアイコンを押して Auto に指定、さらに HorizontalAlignment と VerticalAlignment の一番右のアイコンで画面最大幅を指定します。

部品の幅を可変にする
 アルファベット順に並んでいるので、Width の真上に高さを指定する属性 VerticalAlignment がくるわけですね。

ストアアプリの開発関連情報はまだまだ少ないですね。

金曜日, 8月 23, 2013

IEでは異なる要素でも同じ名前はダメ。

表題の通りです。

 DIV要素とUL要素で同じ名前にしてやられました。

以下のように指定したとします。
<div id="menu">
<ul id="menu">
<li>
Click Here
</li>
</ul>
</div>
それで、クリック時に呼び出す関数を指定したとします。
    $(document).ready(
 function()
 {
     $("ul#menu > li").click(function(){
     alert("here");
     });
 });
これだと、Firefoxは意図を察して動いてくれるのですが、IEだとだめだめです。

あちゃー という本日の発見でした。

木曜日, 8月 22, 2013

jQuery: クリックして止まるドロップダウンメニュー

jQuery を使うとメニューを比較的エレガントに実装できます。

slideDown() / slideUp() などの関数を利用すると任意のコンポーネントを表示または非表示に設定できます。

さらに、マウスクリックでメニューを固定するなどいう指定が可能です。

固定されたメニューは画面いずれかの場所でクリック数すると解除されます。

以下、jQueryの部分です。
$(document).ready(function(){
    // 1 when any menu is shown
    var menuOn=0;

    $("ul#menu > li").click(function(){
        // hide all menu items
        $("ul#menu > li").each(function(){
            $(this).find('ul').css("display","none");
          });
        $(this).find('ul').css("display","block");
        menuOn=1;
      });
              
    // hide/show menu items
    $("ul#menu > li").hover(function(){// show menu when the cursor is over
        if(menuOn==0)
          {
            $(this).find('ul').css("display","block");
          }
      },      
      function(){// hide menu when the cursor is off
        if(menuOn==0)
          {
            $(this).find('ul').css("display","none");
          }
      });

    // hide all menus and clear the flag
    $("#canvas").click(function(){
        if(menuOn==1)
          {
            $("ul#menu > li").each(function(){
                $(this).find('ul').css("display","none");
              });
          }
        menuOn=0;
      });
  });
スタイルシートです。

ul#menu,
ul#menu ul
{
    list-style:none;
    z-index:1;
    position:relative;
}
ul#menu ul li 
{
    line-height:25px;
    width:100px;
    height:25px;
    background:#2D435A;
}
ul#menu ul li a
{
    text-decoration:none;
    color:#cccccc;
    margin-left:10px;
    font-size:14px;
    text-align:none;
}
ul#menu ul li#heading a,
table#submenu a#heading
{
    color:white;
    font-size:16px;
    margin-left:0px;
}
ul#menu ul
{
    display:none;  
}
ul#menu,
ul#menu li,
ul#menu ul,
ul#menu ul li
{
    margin:0px;
    padding:0px;
}
ul#menu li, 
ul#menu ul li 
{
    color:white;
}

div#menubar
{
    width:100%;
    background-image:url('../../../../images/topNav_bkgd.jpg');background-repeat:x-repeat;
}

ul#menu
{
    width:960px;
    margin:0px auto;
    padding:0px;
}
ul#menu li
{
    height:25px;
    line-height:25px;
    display:inline-block;
    vertical-align:top;
    color:white;
    text-align:center;
    width:130px;
    border:0px;
    *display:inline;
    *zoom:1;
}
ul#menu li ul
{
    width:400px;
    height:400px;
    background:#2D435A;
    opacity:.9;
    filter:alpha(opacity=90);
    -ms-filter:"alpha(opacity=90)";
    -moz-opacity:.9;
    -khtml-opacity:.9;
    text-align:left;
}
ul#menu li ul li
{
    text-align:left;
    border:none;
    padding-top:10px;
    padding-left:10px;
}
table#submenu
{
    margin:0px;
    margin-top:10px;
    margin-left:10px;
    border:0px;
    border-collapse:collapse;
    width:400px;
}
table#submenu td
{
    text-align:left;
    vertical-align:top;
}
div#canvas
{
    width:100%;
    text-align:center;
}
div#position
{
    width:960px;
    margin:0px auto;  
    text-align:left;
}
HTMLの部分を示します。
<div id="menu">
<ul>
<li>Home
    <ul>
<li><a href="http://www.blogger.com/default.htm" title="Noritake VFD">Home</a>
      </li>
</ul>
</li>
</ul>
</div>

水曜日, 8月 21, 2013

z-index はpositionを指定しないと意味がない。

表題の通りです。 z-index はpositionを指定しないとならないんですね。

さらに、IE では clear:both を指定しないと z-index が指定できない。

気をつけましょう。

日曜日, 8月 18, 2013

縦型メニューをjQueryで作る

縦型メニューをjQueryで書いたら簡潔かつ論理的にできたのでここにメモっときます。


    $(document).ready(function()
        {
     $('ul#menu > li').click(function(){         
         $(this).next().slideToggle();
     });
        }); 

これだけです。いくつかポイントがあって、まずは next() で後続の要素を指定します。

入れ子の要素を指定しているわけではないので、サブメニューを記述する時には注意してください。

あとはどのような関数でも呼べばいいわけですが、ここでは slideToggle()で表示を切り替えています。

既出かもという気もするのですがなかなかエレガントなのでここに置いておきます。
    <ul id="menu">
      <li>Homepages</li>
      <ul>
   <li><a href="http://easai.web.fc2.com/biology/">Biology</a></li>
   <li><a href="http://easai.web.fc2.com/travel/">Travel</a></li>
   <li><a href="http://easai.web.fc2.com/phyla/">Phyla</a></li>
   <li><a href="http://easai.web.fc2.com/homepage/">Homepage</a></li>
   <li><a href="http://easai.web.fc2.com/biochemistry/">Biochemistry</a></li>
   <li><a href="http://easai.web.fc2.com/neuroscience/">Neuroscience</a></li>
      </ul>
      <li>Lignuistics</li>
 <ul>
            <li><a href="http://easai.web.fc2.com/linguistics/">Linguistics</a></li>
 </ul>
      <li>Nature series</li>
 <ul>
   <li><a href="http://easai.web.fc2.com/aves/">Aves</a></li>
   <li><a href="http://easai.web.fc2.com/eutheria/">Eutheria</a></li>
   <li><a href="http://easai.web.fc2.com/lepidoptera/">Lepidoptera</a></li>
   <li><a href="http://easai.web.fc2.com/odonata/">Odonata</a></li>
 </ul>
    </ul>
スタイルシートもあげておきます(2013-12-05)。
body
{
display:box;display:-moz-box;display:-webkit-box;display:-ms-flexbox;
}
ul#menu
{
width:180px;
font-family:sans-serif;
font-size:18px;
color:gray;
margin-left:10px;
margin-right:60px;
}
ul#menu,
ul#menu ul
{
  list-style:none;
  padding:0px;
}
ul#menu li
{
    border:1px solid #e0e0e0;
    background:#ececec;
    height:50px;
    padding:10px;    
}
ul#menu ul
{
    display:none;
}
ul#menu ul li
{
    background:#fafafa;
    font-size:16px;
    height:30px;
}
ul#menu ul a
{
    text-decoration:none;
    color:gray;
}

火曜日, 7月 23, 2013

Stylishで「こちらのユーザーもフォローしてみませんか」を消す

つい先ほどツイッターのアカウントに行ったら画面上のほうにどどどーっとむさい顔がずらりと。

うわっっなんだ、知らないぞこんな連中は、ということで何かと思えば

「こちらのユーザーもフォローしてみませんか」

と書いてある。やめてくれー

Twitter Remove Recommendations

というのは愚痴であるので、しっかりアドオンで消す方法を探してみました。

ブラウザはFirefoxです。Stylish というアドオンを使ってみました。

Add to Firefoxボタンを押すとインストールが始まります。

ブラウザを再起動すると、 インストールが完了します。

左上 Firefox ホームメニューから Add-ons を選択。
 
左のメニューから、User Styles を探し、クリックします。

Write New Style ボタンをクリックし、新しいスタイルを作成します。

名前は Twitter Remove Recommendations とでもつけておいて、スクリプト部分にはこのような記述を書いておきます。


@namespace url(http://www.w3.org/1999/xhtml);

@-moz-document domain("twitter.com") {

div.empty-timeline-footer
{
display:none;
}

}

スタイルを保存して、ツイッターのアカウントページに行くと

余計なお世話が見事に消えてくれました。

おせっかいやめろー > ツイッター


ついでに Google News の写真・動画も消します(2013-10-23)。


@namespace url(http://www.w3.org/1999/xhtml);

@-moz-document domain("news.google.com") {

img.esc-thumbnail-image,
div.item-image-wrapper,
div.media-strip-video-wrapper
{
display:none;
}

}

金曜日, 7月 19, 2013

計算可能関数

計算可能関数

性質1.基本算法が含まれている
          1. 定数関数 2. 射影関数 3. 後置関数
性質2.閉包である
性質3.万能関数 枚挙性がある
性質4.流れの制御・選択
性質5.パラメータ性

Churchの提唱
計算可能な手続きと性質1~5を満たす算法の族は一致する。

帰納的関数論
評価可能な全値関数全てに対し、ある整数に対しf(m)=mが成立する。

計算可能なアルゴリズムの族
1.TM (Turing Machine)
2.λー算法
3.μー再帰関数
4.一般帰納的関数

木曜日, 7月 18, 2013

オキソ酸 カルボン酸 ヒドロキシ酸 オキシ酸 の違い

カルボン酸
用語だけの話ですが、カルボン酸ってのはいいと思います。教科書にあるやつですね。RCOOHで表される酸です。

オキソ酸ってのはカルボン酸を含むある種の酸の総称です。

ヒドロキシル基(-OH)とオキソ基(=O)を持つ酸のことを言います。

この定義でいくと、炭酸がオキソ酸に分類されます。
炭酸

でややこしいのがヒドロキシ酸で、ヒドロキシル基を持つカルボン酸のことをいいます。カルボン酸の一種なわけですが、時にオキシ酸という用語が使われることがあるので紛らわしい。

ヒドロキシ酸
集合記号であらわすとこうなります。

オキシ酸 ⊃ カルボン酸 ⊃  ヒドロキシ酸(オキシ酸)

木曜日, 6月 20, 2013

jQueryで要素を置き換えた場合の問題について

jQueryで要素に代入すると領域が確定できなくなるらしい。画面全体に領域が設定されているようだ。さらに、内部要素を追加するとその部分はイベントにフックできないらしい。

ブロック要素にロード時に要素を定義。
さらに、クリックイベントに関数をフック。
するとウインドウ領域全体でクリックイベントで関数が起動。

ブロック要素にロード時に要素を定義。
その要素にクリックイベントをフック。
するとフックされない。

他の要素が絡んでいないかどうか、もう少し追ってみる必要があるわけですが、もう疲れた。ので今日はここまで。


金曜日, 4月 19, 2013

PHPでJava風のprintStackTrace()を実現する方法

PHP では try-catch が使えます。

catchで捕まえた例外をどのように処理するかはまた人それぞれだとは思いますが、Java には printStackTrace() という便利な関数があります。

コールした関数を順に出力してくれる関数です。

ここではPHPで関数コールを出力する関数を実装してみました。

例外処理で呼び出すと、関数呼び出しのトレース文字列を出力します。

    try
      {
 // 関数本体
      }
    catch(Exception $e)
      {
 echo trace(debug_backtrace());
      }

関数のコールを順に出力するための関数です。

function trace($traceList)
{
  $html="";
  foreach($traceList as $debugInfo)
    {
      $pathInfo=pathinfo($debugInfo['file']);
      $baseName=$pathInfo['basename'];
      $funcName=$debugInfo['function'];
      $lineNum=$debugInfo['line'];
      $html.="@$funcName ($baseName: $lineNum)";
    }
  return $html;
}

水曜日, 4月 17, 2013

PHPでJava風のstartsWith()とendsWith()がない件について

読みやすさ、美しさというのもプログラムの質に影響してくるとおもいます。

startsWith(), endsWith()という関数がJavaにはあります。

文字列を比較して、指定した文字列で始まっていれば startsWith()は true を返します。

指定した文字列で終わっていれば endsWith()で true を返します。

Javaのネーミングセンスは最高だと常々思うわけですが、これらの関数はPHPにはありません。

substr_compare()という関数を使って startsWith()とendsWith()を実現してみました。

#文字長を制限し比較するよう変更しました(2013-06-05)。

function endsWith($haystack,$needle,$case=FALSE)
{
  $len=mb_strlen($needle);
  if(0<mb_strlen($haystack) && mb_strlen($needle)<=mb_strlen($haystack))
    $res= (substr_compare($haystack,$needle,-$len,$len,$case)==0);
  return $res;
}

function startsWith($haystack,$needle,$case=FALSE)
{
  $res=false;
  if(mb_strlen($needle)<=mb_strlen($haystack))
    $res=(substr_compare($haystack,$needle,0,mb_strlen($needle),$case)==0);
  return $res;
}


火曜日, 3月 26, 2013

Firefox で「パスワードを保存しますか」が危険な件について

Firefoxのデフォルト設定では、ログイン時に
 「ID/パスワードを保存しますか?」


と聞いてきます。

ここでID/パスワードを保存すると、次にログインするときには自動で値が設定されます。

確かに便利な機能ではあるんですが、これなんとテキストでそのまま見えてしまうんですね。

パスワードはパスワードであって、テキスト表示されるのはセキュリティ上問題がある、と考えられる方は以下のサイトでパスワードを削除できます。

「オートコンプリート」機能で保存されたパスワードの削除方法

 

木曜日, 1月 10, 2013

jQueryでページ内移動するには

ページ内移動には、ページ内アンカータグなどを指定して移動します。

index.html#position といった形で指定してやると、その箇所にページがスクロールします。

ページ内アンカータグについては、アンカータグでname属性を、divタグでid属性で指定します。

では、jQueryではどう処理するか、というのが表題の「jQueryによるページ内移動」です。

以下はアニメーションでページをスクロールするスクリプトです。

     var y=getY(document.getElementById("top"));
     $('body,html').animate({
      scrollTop: y
   }, 800); 

木曜日, 11月 29, 2012

Microsoft Seminar: "The New Era of Work" (Windows 8)

Chicago
At the Microsoft hosted seminar "The New Era of Work", it claimed the year 2012 is an important era for the operating systems, which will incorporate touch screen capabilities, mostly due to the widespread use of mobile phones and tablets. 

Windows 8 does come with the brand new Metro style interface with boxes occupying the screen rather than icons, together with gesture recognition.  Swiping down will close the applications.  SNS updates will be tied with your directory information.  Picture password.  Start typing in and the app comes up, the Microsoft IT evangelist Brian Lewis told the audience.  It took him half a year just to come across the feature, he said. 
IT Pro Evangelist: Brian Lewis

Microsoft has a Metro style app store online.  The apps are searchable there as well, including those being sold online.  On app search box, a question came from the audience.  Can you set parental permissions? There the speaker offered a very modern answer to all possible questions.  Go online, visit his site, ask him the question there. 

http://mythoughtsonit.com/ITcamp/

There should be a lot of questions indeed.  Microsoft claims to have authority over all Metro apps distribution.  Developers need to get its approval to put their apps online for use for other machines than theirs.  Can Microsoft then take the sole responsibility of the apps? How long will be the wait time?  Would the developers' rights be severely restricted?  There are reports that the pre-installed Windows 7 apps seem to run, but the installers may not work.  It costs $49 (personal) or $99 (corporate) to submit your apps for sale at the Windows Store.

Windows 8 is going to be installed in EVERY machine available in the market.  FSF, the Free Software Foundation is asking for signing the petition: "Windows 8 doesn't offer me the privacy and freedom I deserve. I won't be upgrading to Windows 8; instead, I'm standing with the free software movement."

We had a little discussion on this topic back here.  Would it is not practical for Microsoft to have oversight over all Metro apps?  The Apple store does that, they told me.  It is for security and to make money. 

Other topics that got many asking questions is on Windows to go or USB/SSD to go feature that can put your system in the removable storage and boot the system from there.  There are such bootable image available online but not from Microsoft official site.  Now it is all possible to carry your system along wherever you go.  The questions from the audience: Security?  Partitions?  Data protections?  Will it erase the data?  There was no question, however, on how to prevent pirated such bootable systems from being sold.  Will it be protected from piracy?

Microsoft Seminar: "The New Era of Work" (Surface)

Chicago

Microsoft hosted a seminar in Chicago on Wednesday titled "The New Era of Work".

Microsoft claims this is the new era of for Operating Systems.  The Internet, iPhone/iPad, and cloud has changed the nature of computer systems. 

Microsoft has long been pushing for tablet machine for some time.  And the competition is a nice thing.  The latest iPad 4 offers hardly hardware improvements other than resolution.

At the conference room, the Surface RT's were on display along with Lenovo and Toshiba machines.  All those tablet machines have no home buttons.  Swiping out to the edge does the trick.  And they come with keyboards. 

At the Surface booth, they explained to me that Surface RT has somewhat unique capability that Apple's iPad does not.  It works as a remote terminal and runs apps on the host machine just like a workstation.  That, is a wonderful idea, I thought.  There could be many application for it.  "Can you show me how it works?" I asked.  The machines are not connected, they told me.  They were not able to show me how it works as a terminal. 

The only reason why iPad or iPhone can not be loaded as a removable drive is because of security concerns.  The MP3's and eBooks are copyright protected.  If only those directories that contain the copyrighted files then they will be more accessible by the possibly criminals.  What the remote terminal does is that the files in tablets would be accessible freely.  The remote terminal apps might have security concerns. 

Instead of that wonderful feature, they showed me the Surface apps fully loaded with shop icons.  The sight of the ads of all those stores on the screen overwhelmed me.  It looked much bigger than the simple and elegant Apple Store.  "This may change the business style, and consumer life style", keynote speaker said. 

So how about Surface Pro?  The new version of Surface runs on Intel chip.  It means, it runs Windows 8.  And that means, every desktop apps should work on Surface Pro.  Would it be a killer machine?  Does that mean my desktop apps works on my tablet machine?  "You must recompile all apps for that machine," one of the participants told me.  "Surface Pro will be coming in January," the Microsoft people told me.  "The pricing is not yet announced.  It will be as big as the RT machine," they said in answering my questions. 

to be cont.

火曜日, 11月 27, 2012

ボックスレイアウトが absolute で破綻

表題の通りです。

Firefox, IE でボックスレイアウトを使用する場合。

位置指定に absolute を指定するとレイアウトが壊れます。

<div style="display:box;display:-moz-box;display:-webkit-box;position:absolute;top:100px">
<div style="width:100px;height:100px;border:1px solid blue"></div>
<div style="width:100px;height:100px;border:1px solid blue"></div>
</div>

見事に人柱となった気分です。

#厳格とかいう問題じゃないですよね。これ。

月曜日, 11月 19, 2012

Google Analytics API: フィルターをつける

本日の出来事。

ダメ上司の典型。「これネットで見付けんたんだけどどお」
どおって... システム全部書き直せって?

え、あのタグってこちらがつけたものじゃないし、むこうが取り外すだけで話は解決じゃないでしょうか。
こちらがフィルターつけて取り外すのって、それって仕事の一部ですか?!

で、仕事が遅くなったとかいって嫌がらせ。最低。最悪。ほんと性格と頭が悪い。

愚痴はさておいて。本題。

Google Analytics のデータを取り出す方法。

フィルターをつける場合について、書いておきます。

$filter="ga:hostname!=ホスト名";
$ga->requestReportData(homepageId,null,array('pageviews','visits','bounces','entrances','timeOnSite','exits','newVisits'),null,$filter,$startDate,$endDate);

火曜日, 11月 13, 2012

IEでリンク切れ画像を表示しない

リンク切れ画像は、Firefox では表示されません。

ところが親切設計の IE や Chrome では、画像が見当たらないとそれ専用のアイコンを表示してしまいます。

これで困ったのが、画像リンクを利用してスクリプトを走らせるハックを使うアクセス統計サービスの場合。

きちんと表示されれば問題なく img タグだろうとなんだろうと構わないわけですが、ところがサーバーの都合でスクリプトが動かないという状況が発生。

動かないだけ「画像ありません」というアイコンかしっかり表示されてしまいました。

アクセス統計などアナリティクスに任せとけばいいのに、マイナーブランドなど使うからサーバーの都合で対応をせざるを得ないはめに。

そこで、画像切れリンクは問答無用で「表示しない」という方針といたしました。これで振り回されずにすみます。

本題へ。リンク切れ画像の IE と Chrome 対応策です。

img タグのすべての要素を取り出し、画像読み込みが終らないものをすべて非表示とすればよいようです。

$(function(){

$('img').each(function(){

if(!this.complete){
$(this).hide();
return;
}

});

});

月曜日, 10月 29, 2012

Object-C 文字列;Makefile

Object-Cでは文字列はNSStringなどを使うことができます。

文字列へのポインタとして扱うことができます。

メンバ関数 UTF8String を使うと、char*として扱うことができます。


#import <stdio.h>
#import <foundation/foundation.h> 
#import <Foundation/NSObject.h>

@interface Verb:NSObject
-(void)print: (NSString*)stem;
@end

@implementation Verb
-(void)print: (NSString*)stem
{
  char* str=[stem UTF8String];
  printf("%sim\n",str);
  printf("%sis\n",str);
  printf("%si\n",str);
  printf("%sime\n",str);
  printf("%site\n",str);
  printf("%si\n",str);
}
@end

int main()
{
  NSString *stem=@"rozumim";
  id obj=[Verb alloc];
  [obj print:stem];
  return 0;
}

GNUmakefile ファイルにおいて、以下のようにコンパイルの条件を指定すると、make 一発でコンパイルできます。

GNUSTEP_MAKEFILES=c:/GNUstep/GNUstep/System/Library/Makefiles
include $(GNUSTEP_MAKEFILES)/common.make

TOOL_NAME = verb
verb_OBJC_FILES = verb.m

include $(GNUSTEP_MAKEFILES)/tool.make


土曜日, 10月 27, 2012

Objective-Cのプロトコルとは

Objective-C では、クラス継承の際に必須のメソッドを規定するプロトコルという概念があります。

まさしく、Java でいうところのインターフェースの概念と同じもので、メンバ関数を持たないクラスとして実装されます。プロトコルで指定されるメソッドは宣言のみで、抽象クラスとして実装されます。

#import >stdio .h=".h">
#import >foundation bject.h="bject.h">

@protocol ToString
-(void)toString;
@end

@interface Test:NSObject>tostring>
@end

@implementation Test
-(void)toString
{ 
  printf("This is class Test.\n");
}
@end

int main()
{
  id obj=[Test alloc];
  [obj toString];
  return 0;
}



火曜日, 10月 23, 2012

Objective-C のクラスメソッド

Objective-Cにも静的なメソッドというものがあります。

Objective-Cの用語ではクラスメソッドというものです。

Javaでいうところのstaticにあたります。

当然ながら、メンバ変数を持つことはありません。

メソッドの宣言に+(プラス記号)をつけます。

#import <stdio.h>
#import <Foundation/NSObject.h>

@interface Test:NSObject
{
  int index;
}
- (void) hello;
- (void) setIndex:(int) i;
+ (void) dump;
@end

@implementation Test
- (void) setIndex:(int) i
{
  self->index=i;
}
-(void)hello
{
  printf("Hello NSObject %d\n",self->index);
}
+(void)dump
{
  printf("Class method = static");
}
@end

int main()
{
  [Test dump];
  return 0;
} 

他にも@propertyや@synthesizeなどいうキーワードがありますが、GNUstepはサポートしていません。

参照先がreleaseされたときの挙動を変えるものです。
@property(nonatomic, assign)
@property(nonatomic, retain)

月曜日, 10月 22, 2012

OOP, any problems?

Do not compare apples and oranges.

OOP is implemented as an extension of C.  But it is a completely different concept. 

What is good about OOP is the change of the design framework of programming.  Say, Lisp can be converted to C and that indeed is what the compiler does.  But they are different languages with more focuses on its abstraction.  Likewise, OOP is a way of abstraction, a way to express it.

Writing in Lisp is different from writing in C.  They are not interchangeable.  It may be the same to the machine but not to programmers.

Not even knowing the importance of its concepts and talking about issues of implementation, is somewhat like looking at trees and not seeing the woods.

It is just a way to devalue OOP. 

The reason why they are to denigrate the importance of the revolution, is totally of theirs, not ours.

In the year 2012, why should we need to emphasize the importance of OOP for Pete's sake?

Please.  Let us have the freedom of thoughts and religions.

日曜日, 10月 21, 2012

Object-Cのクラスについて

それでは試行錯誤でどうやら動くようになったGNUstepの話の続きを。

Object-CはC++に似て、クラスの定義にヘッダーを必要とします。

変数・関数の宣言に順番を気にしなければならなかったCの名残りといえるでしょう。

定義と実装は別々に行います。

Javaの場合には、そんなものは必要がなく、publicクラスにそれぞれ独自のファイルを用意してクラスの実装のみを記述します。

#importでクラスを指定さえすれば、順番も関係なく使用することができます。

Object-Cのクラス宣言と実装、呼び出しの方法を下記に示します。

#import <stdio.h>
#import <Foundation/NSObject.h>

@interface Test:NSObject
-(void) hello;
@end

@implementation Test
-(void)hello
{
  printf("Hello NSObject\n");
}
@end

int main()
{
  id obj=[Test alloc];
  [obj hello];
  return 0;
}

コンパイラオプションはこちらを使いました。
gcc nsclass.m -I c:/GNUstep/GNUstep/System/Library/Headers -L c:/GNUstep/GNUstep/System/Library/Libraries -lobjc -lgnustep-base 


Objective-Cは引数の指定の仕方が独特です。

型をいちいち指定して呼び出します。

Javaのように引数とメンバ変数を同名にすると警告が出ます。

#import <stdio.h>
#import <Foundation/NSObject.h>

@interface Test:NSObject
{
  int index;
}
- (void) hello;
- (void) setIndex:(int) i;
@end

@implementation Test
- (void) setIndex:(int) i
{
  self->index=i;
}
-(void)hello
{
  printf("Hello NSObject %d\n",self->index);
}
@end

int main()
{
  id obj=[Test alloc];
  [obj setIndex:10];
  [obj hello];
  return 0;
}

土曜日, 10月 20, 2012

Windows で GNUstep を使った Object-C プログラミング

iPad が隆盛を極めてはや数年、マイクロソフトもついに(高額)タブレットPCを発売。

キーボードに凝りまくったというCMがネットで流れています。26日にはARMベースのマシンが発売されます。

最安モデルで499ドル。まさにアップル並みの値段。

競合モデルとしては、もっさりと遅いでも安いAndroidマシンか、アップルの小型iPadマシンか。

1月には Windows 8 ベースのマシンが発売されます。

Windowsベースのアプリが動くとなれば、これは革命です。


開発者として、傲慢なアップルの「開発しにくくしてカネをとろうとする」態度は正直なところ好きになれません。

頭(か性格か)の悪すぎるやりかただと思います。

と正直な感想から、Object-Cのはなし。

WindowsでもGNUstepというプロジェクトがあって、Object-Cでプログラムが書けます。

こちらを参照しました。

OOP言語であるObject-Cですが、C#よりJavaに遠い。

PC販売に影響したというタブレット市場がどのように変化していくのか、新製品を横目にプログラムにいそしむ週末になりそうです。

金曜日, 10月 05, 2012

Elispで文字列置換

久しぶりに elisp でプログラム。

オープンソースの始祖であるところのGNUの鉄則に従って、書いた分だけここに置いておきます。

文字列変換というごくごくシンプルなものですが、変換後にバッファでのポイントの位置がずれることに注意。

(defun replace-tags-region (from-string to-string begin end)
"Replaces from-string to to-string in the region from begin to end."
  (let ((len (- (length to-string)(length from-string))))
    (goto-char begin)
    (while (search-forward from-string end t)
      (replace-match to-string t)
      (setq end (+ end len)))))

(defun replace-tags-list (tag-list)
"Takes a list of (from-string to-string) and replaces all from-string to to-string in the buffer."
  (replace-tags-region (car tag-list) (cadr tag-list)(point-min)(point-max))) 

  

;; Usage:
;; (setq tag-list '(("TABLE" "table")("TD" "td")("TR" "tr")))
;; (replace-tags tag-list)

(defun replace-tags (tag-list)
"Takes a list of lists of (from-string to-string) and replaces all from-string to to-string in the buffer."
  (mapcar 'replace-tags-list tag-list))

(defun create-end-tag (tag-name)
  "Creates closing tag from the given tag-name."
  (concat "</" tag-name ">"))

(defun create-half-begin-tag (tag-name)
  "Creates opening tag from the given tag-name."
  (concat "<" tag-name " "))

(defun create-attribute-tag (tag-name)
  "Creates attribute string from the given tag-name."
  (concat " " tag-name "=\""))

(defun create-begin-tag (tag-name)
  "Creates opening tag from the given tag-name."
  (concat "<" tag-name ">"))

 

;; Usage:
;;(setq tag-list '("TABLE" "TD" "B" "BR" "A" "HTML" "NOSCRIPT" "SCRIPT" "HEAD" "BODY" "TR" "TITLE" "I"))
;;(mapcar (lambda (x)(create-replacement-list 'create-end-tag x)) tag-list)
(defun create-replacement-list (create-list tag-name)
"Creates a list of tag name and lowercase tag name lists."
  (cons (funcall create-list tag-name) (list (funcall create-list (downcase tag-name)))))

(defun lowercase-html-tags()
"Converts uppercase HTML tag names to lowercase."
  (interactive)
  (let* ((tag-list '("TABLE" "TD" "B" "BR" "A" "HTML" "NOSCRIPT" "SCRIPT" "HEAD" "BODY" "TR" "TITLE" "I"))
  (attribute-list '("VALIGN" "ALIGN" "WIDTH" "HEIGHT" "BOTTOM" "CLASS" "BGCOLOR" "BORDER" "LEFT" "RIGHT" "TOP" "CELLPADDING" "CELLSPACING" "BORDERCOLOR" "CENTER" "MIDDLE" "HREF" "COLSPAN" "ROWSPAN" "SRC" "onMouseOver" "onMouseOut" "ALT" "NAME" "ID" "VSPACE" "LINK" "META" "LEFTMARGIN" "TOPMARGIN" "MARGINWIDTH" "MARGINHEIGHT" "onLoad" "BACKGROUND" "TYPE" "HTTP-EQUIV" "CONTENT" "REL" "LANGUAGE"))
  (half-tag-list '("TABLE" "TD" "A" "IMG" "LINK" "META" "SCRIPT" "BODY" "TR" "DIV"))
  (replacement-end-tags (mapcar (lambda (x)(create-replacement-list 'create-end-tag x)) tag-list))
  (replacement-begin-tags (mapcar (lambda (x)(create-replacement-list 'create-begin-tag x)) tag-list))
  (replacement-half-begin-tags (mapcar (lambda (x)(create-replacement-list 'create-half-begin-tag x)) half-tag-list))
  (replacement-attribute-tags (mapcar (lambda (x)(create-replacement-list 'create-attribute-tag x)) attribute-list)))
    (replace-tags replacement-attribute-tags)
    (replace-tags replacement-end-tags)
    (replace-tags replacement-half-begin-tags)
    (replace-tags replacement-begin-tags)))

水曜日, 9月 19, 2012

IE でCSS3の display:box を使うには、flexie.js を使えばいい

そうです。IEはまだCSS3の display:box 仕様に対応していません。

このボックス仕様を使うと、横並びのボックスがエレガントに書けます。


外側のDIVに、このように指定します。

    display: -webkit-box;
    display: -moz-box;    
    display: box; 
 
内部のDIV要素がきれいに並んでくれます。
 
ただし、上記のようにIEには対応していません。

そこで、この flexie.js を導入すると、見事に横並びボックスが実現できます。

ダウンロード:http://flexiejs.com/
 
これでページのHTMLタグが整理できそうです。
 
 

土曜日, 9月 08, 2012

シームレスの背景画像をGIMPで作るには

シームレスの背景画像をGIMPで作るには、メニューからFilters|Map|Make Seamlessを選択します。

すると画像を一発でシームレスにできます。

こんな感じです。

http://easai.web.fc2.com/odonata/photoindex/


木曜日, 9月 06, 2012

Excel のマクロを消すマクロ

Excel のマクロを消すマクロを書こうと思ったら、警告が出ました。

マクロはこんな感じです。

こちらのページ「VBAでマクロのソース削除と標準モジュール削除」を参照させていただきました。

Dim objVBCOMPO     As Object
        For Each objVBCOMPO In ActiveWorkbook.VBProject.VBComponents
            With objVBCOMPO.CodeModule
                If .CountOfLines <> 0 Then .DeleteLines 1, .CountOfLines
            End With
            If (objVBCOMPO.Type = vbext_ct_StdModule Or objVBCOMPO.Type = vbext_ct_MSForm) Then
                ActiveWorkbook.VBProject.VBComponents.Remove objVBCOMPO
            End If
        Next objVBCOMPO
        Set objVBCOMPO = Nothing
End Sub


これをデフォルトの設定で走らせると警告が出ます。



これは、マクロセンターの Trust access to the VBA project object model オプションをオンにすると動くようになります。

金曜日, 8月 31, 2012

クリックで表示を切り替える(単位変換など)

米国での長さの単位はきわめていまいましいことにすべてインチ・フィートです。

 ここで、インチ・フィートに要素を変換する jQuery スクリプトを示します。

 $(document).ready(function(){
  $(".millimeters").hide();
  $("#convertIN").click(function(){
   $(".millimeters").hide();
   $(".inches").show();
      });
  $("#convertMM").click(function(){
   $(".millimeters").show();
   $(".inches").hide();
      });
     });

JQuery であると容易に要素の表示を切り替えることができます。

 ... there was a question in the Reddit session to Obama whether the US would ever move to metric system.

リンクをかけたブロックの中に、別のリンク先に飛ぶエレメントを置く

リンクをかけたブロックの中に、別のリンク先に飛ぶエレメントを置きたいとします。

ブロックにはリンクがかかっているので、内部の要素をクリックしてもリンク先に飛んでしまいます。

どのようにリンクを無効にするか。

jQuery には event.preventDefault() というメソッドがあります。

これを呼ぶと、ブロックにかかっているリンクを無効にできます。

     $(document).ready(function(){
         $(".クラス名").click(function (event){
             event.preventDefault();
             document.location="飛ばしたい先のアドレス";
         });
     });


これで、内部要素をクリックすると、ブロックにかかっているリンクを無効にして指定されたアドレスに飛ぶよう指定できます。

(はいはい。ブロックにリンクをかけるというのは推奨されない方法です。)

水曜日, 8月 29, 2012

好みのエディタでオンラインの文章を編集する

ブログ編集画面などで、テキストエリアの文章を好きなエディタで編集可能な Firefox のアドオンがあります。

→ It's All Text!

このアドオンを使うと、テキストエリアにボタンがついて、押すと指定されたエディタが起動します。

ホットキーやエディタの設定は、Firefox のメニューから、Add-ons の Extensions で設定します。

 It's All Text の Options ボタンを押すと、設定画面が表示されます。


このアドオンがあると、オンラインでのテキスト編集の精神的負担が軽くなります。

ブログなどでオススメです。

火曜日, 8月 28, 2012

xampp 1.8 にアップグレードしました。

xamppをアップグレードしました。Ver. 1.8が最新のようです。

MySQLもアップグレードとなるので、データベースも移動することになります。

このあたりは、data以下をすべてまるごとコピーでOK。

phpMyAdminでID/Passwordの設定を行ってデータベースがきちんと移動できたかどうかを確認して一安心。

ファイル: config.inc.php
$cfg['Servers'][$i]['user'] = 'ユーザー名';
$cfg['Servers'][$i]['password'] = 'パスワード';

PHPのデフォルトがすべての警告を表示するとなっているので、まずそいつに黙ってもらって無事にアップグレードを完了。

ファイル: /php/php.ini
;error_reporting = E_ALL | E_STRICT
error_reporting = E_ERROR

を使えるようにして、curlを有効にする。

short_open_tag = On

extension=php_curl.dll
 
コントロールパネルもアップグレードされておりました。

月曜日, 8月 06, 2012

Excelのキャッシュをクリアする

Excelマクロの問題です。

サブルーチンの文字を書き換えるとExcel自体が壊れる。

といういかにもプログラミング環境の不備という問題に直面しました。

プレコンパイルしているとすればキャッシュファイルを消すという手順が必要となるわけですが、ネットに情報がない。

ActiveXのキャッシュがあるとされる場所には.exdファイルは見当たらず。
C:\Users\ユーザー名\AppData\Local\Temp\VBE

...

結局サブルーチン名を書き換えるということで問題を解決。

木曜日, 8月 02, 2012

Windows上でepubを作成する方法

とはいっても、改造したファイルをepub形式に変更する方法の紹介です。

.epubファイルは、.zipファイルそのものです。拡張子を.zipにして 解凍するとファイルが読めます。

基本的にはxhtmlファイルで構成されます。

音声を追加したい場合には、xhtmlファイルにaudioタグを追加します。

<audio autoplay="false" controls="true" src="ファイル名"></audio> 
 
改造したファイルをepub形式に変換するときは、単に圧縮するだけでは.epub形式とはなりません。 

Windows上でepubを作成するには、

memetypeは圧縮しない。まずmimetypeをzipファイルに変換。
次いで他のファイルを追加する。拡張子を.epubに変換する。→完成



月曜日, 7月 16, 2012

cygwin 上でGCC 4.6.3 を導入して range-based-for を使う

range-based-for を使いたくて、g++4.6.3 にアップグレードしました。

cygwin の最新版は 4.5で、range-based-for は実装されていません。

[windows][cygwin]最新のg++コンパイラをCygwin上で導入する

コンパイルには ↑ このページを参照させていただきました。

↓ ソースはここからダウンロードできます。

GCC miror sites

 range-based-for を使ったコードを以下に示します。

#include<iostream>
using namespace std;
int main()
{
  int arraytest[5]={1,2,3,4,5};
  for(int i:arraytest)
    cout<<i;
  cout<<endl;
  for(int &i:arraytest)
    i=0;
  for(int i:arraytest)
    cout<<i;
}
コンパイラオプションは以下の通り。
$> g++ -std=c++0x range.cc

日曜日, 7月 15, 2012

chronoの使い方のメモ。

c++11で定義されているchronoの使い方のメモ。
#include <iostream>
#include <chrono>

int main()
{
  auto tp=std::chrono::system_clock::time_point();
  std::time_t t=std::chrono::system_clock::to_time_t(tp);
  std::cout << std::ctime(&t)<<std::endl;

  std::chrono::seconds sec(10);
  std::chrono::minutes min(3);
  auto result=sec+min;
  std::cout << result.count() << std::endl;
}
コンパイラのオプションは以下の通り。
/usr/bin/g++-4 -std=c++0x chrono.cpp
c++11ではラムダ式も使えます。
std::cout << [](int x, int y){return x+y;}(1,2) << std::endl;

土曜日, 7月 14, 2012

Java 5.0 可変長パラメータとfor-each

メモのために可変長パラメータとfor-eachを使ったコードを載せておきます。

public class VarLen
{
    int sum(int ... list)
    {
 int s=0;
 for(int i:list)
     {
  s+=i;
     }
 return s;
    }

    public static void main(String args[])
    {
 VarLen varLen=new VarLen();
 System.out.println(varLen.sum(1,2,3,4,5,6,7,8,9,10));
    }
}

金曜日, 5月 11, 2012

データベースでレコードを複製したい場合。

既出だとは思いますが、データベースでレコードを複製したい場合。

このテーブルの場合、IDがauto incrementで主要キーに指定されています。

複製したいレコードのIDを指定し、SELECT構文で値を取得。

その値を新規レコードとして登録します。

INSERT INTO pages SELECT '',title,contents,url FROM pages WHERE ID=$id

木曜日, 4月 12, 2012

Firefoxでフロート位置が不可思議な件

HTMLは常にシーケンシャルでコードを読み解きます。

ところが float などを指定すると、位置が自動的に計算され、時には思いもよらない場所に要素が出現します。



  <div style="padding-bottom:0px;">       <div style="float:left;"> Floating block       </div>   </div>
<div style="margin: 20px 0;border:1px solid red;"></div>


フロート要素があって、marginつきのブロック要素が並んでいます。

では、この場合どちらの要素が先に表示されるでしょう。

FirefoxとIEでは結果が違います。

IEではそのまま表示されます。つまり、フロート要素が上に表示されます。

ところが。Firefoxで見てみると分かりますが、Firefoxではブロック要素が上に表示されます。

そして、さらに不思議なことに、paddingを0ピクセルではなく1ピクセル以上に指定するとまた順番が逆になります。

同じコードでブラウザによって見え方が異なる困ったケースのひとつと言えるでしょう。

月曜日, 4月 02, 2012

Javaの内部匿名クラスからローカル変数にアクセス

Javaの内部匿名クラスから、実はローカル変数にアクセスできたわけですね。

finalをつけておくとコンパイルできます。

(finalでなければコンパイルできません。)


 public class Closure
{
    class Test{};
    
    Closure()
    {
    final int i=0;
    (new Test()
    {
        void test()
        {
        System.out.println(i);
        }
        }).test();
    }

    public static void main(String args[])
    {
    Closure closure=new Closure();
    }
}

もちろん値は変更できません。:)


水曜日, 3月 14, 2012

PHP: get relative path expression

The following code calculate the difference of paths given and return a relative path expression.
 

function getCommonPos($s0,$s1) {   $len=strlen($s0);   $len1=strlen($s1);   if($len1<$len)     {       $len=$len1;     }   while($s0[$i]==$s1[$i] && ++$i<$len1);   return $i; } function diffStr($s0, $s1) {   $pos=getCommonPos($s0,$s1);   $end=strrpos(substr($s0,0,$pos),"\\");   return substr($s0,$end); } function countSlashes($str) {   return substr_count($str,"\\"); } function getRelativePath($p0,$p1) {   $p0=realpath($p0);   $p1=realpath($p1);   $dir=diffStr($p0,$p1);   if(!empty($dir))     {       $n=countSlashes($dir);       $path="";       for($i=0;$i<$n;$i++)     {       $path.="..";       if($i<$n-1)         {           $path.="\\";         }     }     }   $newDir=diffStr($p0,$p1);   $newDir=$path.$newDir;     if(empty($newDir))     $newDir=".";   return $newDir; }

日曜日, 3月 11, 2012

Creating bookmarks with Silhouette Cameo

As the Silhouette Cameo is here, I wrote a Java program to draw regular convex polygons and cut out shapes from paper.  The photo shows the final product, a bookmark.  You can put any of your design into 'production'.  With Silhouette Cameo, you get the final products right away. 



The Studio software detects the outline of shapes automatically.  The procedure would be as follows:

  1. Print out shapes with your own software or draw it with Studio.
  2. Select Object|Trace... from the menu. 
          

            
    1. Click the "Select Trace Area" button.
            
    2. Select the area of the figure.
            
    3. Select "Trace Outer Edge".
            
    4. The red line appears surrounding the image.
            
    5. Delete the original image.
            
    6. Edit the outline.  Typically you would want to "Edit Points" from the left column of the window.
            
    7. When the editing is done, click the Silhouette icon from the tool menu.
            
    8. Place the paper on the cutting mat and set it to the machine.
            
    9. Click "Cut" button when everything is ready.
           


Send any shapes to Silhouette and find designs of your choice.  Try cutting shapes and figure out balances and sizes that fit your needs.  

土曜日, 3月 10, 2012

Silhouette Cameo arrived

Silhouette Cameo, the cutting machine arrived yesterday.

Silhouette Cameo

This is the machine of the future. Basically what this machine does is to cut flat and thin materials in any shapes that you specify. It should cut anything paper made that you look at in our lives, including packages, cards, paper craft, etc.

Shamrock

What more, it can detect markings on a printed surface. Any figures that can be printed out on a piece of paper can be cut out. There are a lot of designs for 3D models made out of paper.


A word of caution is that creating cutting pattern can be a little tricky and time consuming. Very thin materials such as copy paper needs extra caution to take it off from the adhesive mat. Heavier thicker paper than copy paper would do a better job.

This paper cutting machine opens up great many fronts in many areas of technologies, sciences, and crafting. This is an excellent tool for education as well. Cut shapes would appeal more to students. The assembled 3D models is much more than the printed images of polygons. Printing out the images of makes 3D modeling not only makes it much more fun but means even more to students of science when it has three dimensions.

Free download of the Silhouette Cameo Studio is here: silhouettestudio

金曜日, 3月 02, 2012

Screen refresh trigger of an input element value or src change

To which extent does a browser redraw the screen?  Would an element's value change trigger refreshing the screen?  

It turns out to be that the Javascript's setting values of an element, actually does not trigger redrawing. 

document.getElementById("test").value="new value";

What puzzled me was, why then the browser redraw the screen in case with setting an img element's src?

document.getElementById("test").src="data:image/png;base64, ...";

This makes it trickier to implement functions that changes value, or src since the behavior will differ when you would want to retain some values for the session.  

I hit upon this problem when I tried to implement a div section that is shown and hidden at a trigger of pressing a button.  The functionality was implemented in the Javascript function and first I implemented it so that it alter the value of an input element.  It worked.  When you press the button, the Javascript function altered the value of the type='button' input element, without refreshing the screen, that is retaining all the variable values.  Then I switched it so that it would alter an image of an type='image' input element.  Now it does not work.  It reset and initialized the screen, namely to a certain initial state and not the state that was specified as. 

日曜日, 2月 19, 2012

Holiday thoughts; high-tech items of the (very near) future

There are four items that I want to purchase.  All of them, I feel the future; with the advancement of technology, or rather, the availability of it.  So much can be accomplished with the right idea, better concepts, and better management. 

One is, Raspberry Pi, a small Linux box that costs $25, or $35 with network connection.  Just at those prices, the full fledged net book equivalent machine power will be offered to so many people in the world.  The 'charitable' organizations offer them 'for educational purposes' -- never a Windows machine.  With its graphics chip that can connect to TV screens, however, this can be a game changer. 

Another is, Craft ROBO, a cutting plotter.  There are numerous other machines that cuts paper, plastic, vinyl sheets, and other materials, but this machine, cuts items that are drawn on your PC.  No cartridges, no nonsense about those black-boxes to set cut patterns.  Its software takes a figure, calculate the outline, and the machine cuts it out for you.  Unfortunately, the latest model is out of stock.  Its manufacturer, Graphtech Inc, says the new model would be coming in March 2012. 

The other is, iPad3 or Windows 8 tablet PC.  App-wise, the share number one is the Android machines, however.  The Windows 8 tablet PC on ARM is yet to come, reportedly in March. 

Lastly, it is the 3D printer.  There are many types of them; stacking shaped plastic lump, cutting out a shape from a resin block, or even binding composite powder layer by layer.  iModela might be the one, but I need more research on these.  Taking out a plastic material, shape them in the way that you like as in printing figures on paper, and use them as in any way that you like, in modeling for fun and for any other useful purposes in research and engineering, replaceable parts of an equipment anywhere, etc.

水曜日, 2月 15, 2012

PHP's overload: __call()

In my last blog, I wrote about PHP's get/set "overload", or hooking those methods for private members. There are more overloading method in PHP. The __call() method overload methods. This method "overloads" hidden member functions; including those methods that are non-existent. That is, you can create on the spot a brand new method just by calling __call().
class Test
{
  function __call($name,$parameter)
  {
    $value=$parameter[0];
    switch($name)
      {
      case "round":
        $value=round($value);
        break;
      case "floor":
        $value=floor($value);
        break;
      case "ceil":
        $value=ceil($value);
        break;
      }
    return $value;
  }
}

$test=new Test;
echo "Rounding: round(16.4) = ".$test->round(16.4);
echo "<br />";
echo "Floor: floor(16.4) = ".$test->floor(16.4);
echo "<br />";
echo "Ceiling: ceil(16.4) = ".$test->ceil(16.4);
echo "<br />";
This actually is a potential technological breakthrough -- in that the methods bears arbitrary names that are pseudo-defined and typed not dynamically then at programming time. This is a conceptual revolution in the programming. Remember, OOP is just a different form of C's structure.
Rounding: round(16.4) = 16
Floor: floor(16.4) = 16
Ceiling: ceil(16.4) = 17

月曜日, 2月 13, 2012

"Overload"? or hooking get/set in PHP

In PHP, there are a set of functions that hooks getting and setting private member variables.  When the variable is set, __set() method will be called.  When the variable is accessed, __get() method is called.  In PHP's terminology, hooking variable definition and retrieval are called overloading. 

class HookTest
{
private $a=1;

public function __get($name)
{
  echo "$name is being retrieved<br />";
  return $this->$name;
}

public function __set($name,$value)
{
  echo "$name is being set<br />";
  $this->$name=3;
}
}

echo "<pre>";

$test=new HookTest;
$test->a=2;
echo $test->a;

金曜日, 2月 10, 2012

Newline in select-option tags

Our site had a list of fonts available for our clients. The list included, European and Cyrillic fonts. We put them in a drop-down list.

List of fonts:
     European
     Cyrillic

Then, it turned out to be that Cyrillic fonts were included in European fonts. We had to select/deselect both at the same time. The trouble is, the HTML's select's option does not take br tags, or new lines. All lines have to be in a single line. Here is a jQuery code that select/deselect European and Cyrillic fonts at the same time. The code hooks any click on the European fonts to a handler that select/deselect Cyrillic fonts.
 
    $('#European').live("click",function(){
     var selected=$('#European').attr("selected");
     if(selected=="selected") 
  {
      $('#Cyrillic').attr("selected","selected");      
  }
     else
  {
      $('#Cyrillic').attr("selected",false);      
  }    
 });

Here is a word of caution; we had yet another problem with the Cyrillic option with the reset operation. The Cyrillic option has to be deselected manually.
 
    // de-selects the Cyrillic option.
    $("#reset").click(function(){
         $('#Cyrillic').attr("selected",false);      
 });

水曜日, 1月 25, 2012

同じエレメントを指定して、なぜか表示が変わらない。

スタイルシートというのは、いまだ原始的な形態を保ち続け、多少なりとも論理を重視するプログラマ人種にとっての頭痛の種といえるでしょう。進化を続けるネット世界で、基準を設定するのは至難の業、軍閥割拠のジャングルのなかで右往左往してサバイバルゲームを続けるしかない。

で、今日の話題はエレメントの指定方法。スタイルシートで、同じエレメントを指定して、なぜか表示が変わらない。

table.background tr td
{
background-color:red;
}
table.background td
{
background-color:blue;
}

赤い指定をオーバーライドしているのに、これが青くならない。

<table class="background">
<tr><td>test<td>test
<tr><td>test<td>test
</table>

上記のスタイルの指定をよく見てみると、エレメントの指定方法に違いがあります。なぜか tr タグの指定が効いてるんですね。構造を書くと、そちらが優先されるアルゴリズムであるわけです。

これが意味のある基準であるかどうかはさておいて、知っておかないと他人のスタイルシートを使うときに困ることは間違いなしです。

金曜日, 12月 30, 2011

Javascriptの多次元配列

やられましたね。これ。Javascriptの多次元配列。

var array=new Array();
array[0,0]=0;
array[1,0]=1;

alert(array[0,0]);
alert(array[1,0]);

結論的には、双方ともに1を表示します。

皆さんも気をつけましょう。

謹賀新年

月曜日, 12月 12, 2011

桁数を取得するコード

間違い探し、です。よくありそうな感じもしますが載せておきます。

ある数字の桁数を得たいとします。valに格納されていると仮定してください。

10進法であるか、16進法であるか、ベースはbaseで示すことにします。

  int index=1;
  while(val/=base && ++index<len);

一見これで桁数が出る... と思った方。

悩みましたね。これだと浮動小数点エラーが出ます。GCC使ってます。

知ってしまえばどうということはないことです。

ここであっさりと書いておきますが、オペレーターの優先順位の問題でした。

括弧で囲ってやると正常に機能します。

お騒がせしました。

金曜日, 11月 18, 2011

Multiple OS's causes DLL problems.

Theoretically -- is it a theory -- any program that runs on the particular Framework should run in the same way. But -- WINDOWS, how else could it be? The application does not find COM components and fails to initialize classes. Is it the issue of registry keys damaged by the installation?

After close monitoring of Windows event, it turned out that when multiple OS's are installed in a machine, the OS seems to assume C: drive even when the system is installed in other drives. The application looks for drivers -- but in which drive, is the question. The C: drive application looks for D: DLL's when E: application looks for E: DLL's. Either case does not work. Only the D: application with D: DLL's worked.

日曜日, 11月 13, 2011

OAuth

Twitter uses OAuth for id verification. The encryption of the data is
using HMAC-SHA1 algorithm.

HMAC, Keyed-Hashing for Message Authentication Code
hash((key xor 0x5c5c...5c)
or (key xor 0x3636...36)
or message)

SHA, Secure Hash Algorithm
SHA-1 160 bit, MD4 based encoding

水曜日, 11月 09, 2011

C#: FontDialog unable to set font sizes; Firefox 8

The FontDialog class of C# is not overridable to change its settings. There are flags to remove underline and strike options, but there is no ways to limit font styles nor font sizes.

However, C# is a language that has ready-to-use off-the-shelf components that can replace the font dialog with ones of your own.



The new features in Firefox 8:
- twitter search
- delay loading tabs at start ups (when you set it the opening screen)
- WebGL, HTML5 improvements

月曜日, 11月 07, 2011

C#: WebBrowser.DocumentText does not support the += operator

WebBrowser.DocumentText does not support the += operator.

That is it. It does not. The String class should be formatted separately and assigned to that member variable.

金曜日, 11月 04, 2011

C# DataGridView's SetValue

When a DataTable is set for a DataGridView, the value can not be set
to DataGridViewCellFormattingEventArgs.Value, which is passed by to a
method that is hooked to CellFormatting event.

The way to avoid it, is to access to the cell value directly.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
  if(e.ColumnIndex==5)
    {
      // If set, the following will be shown in the cell.  The Cell's value typed as an int will not be set correctly.
      //e.Value = "1";
                        
      // Instead, directly access the Cell object.
      int row = e.RowIndex;
      int col = e.ColumnIndex;
      dataGridView1.Rows[row].Cells[col].Value = 1;
                   
      break;
    } 
}

木曜日, 10月 27, 2011

C#: TimeZoneInfo.GetSystemTimeZones()

TimeZoneInfo.GetSystemTimeZones() returns a reference to a same instance, no matter how many times it is called.

When the time zone list is added to combo boxes, they select the same values.

comboBox1.DataSource = TimeZoneInfo.GetSystemTimeZones();
comboBox2.DataSource = TimeZoneInfo.GetSystemTimeZones();

The Collection class must be copied to some other forms.

System.Collections.ObjectModel.ReadOnlyCollection list 
= TimeZoneInfo.GetSystemTimeZones();
TimeZoneInfo[] tzList = list.ToArray();
comboBox1.Items.AddRange(tzList);
comboBox2.Items.AddRange(tzList);

火曜日, 10月 18, 2011

Excel / VBA: type conversion from integer to text

Excel uses VBA for its macros. The programming language, or the formula format, differs. Whereas Excel uses "TEXT()" with a format string as its argument, VBA uses "CStr()" to convert types from integer to string.

月曜日, 10月 10, 2011

C# field initializers

C# differs from Java in that the field initializers must be static.

This is perfectly OK in Java.

public class InitTest
{
    int test=0;
    InitTestClass testClass=new InitTestClass(test);
    
    public static void main(String args[])
    {
 InitTest test=new InitTest(); 
    }
}

class InitTestClass
{
    int test=0;
    InitTestClass(int test)
    {
 this.test=test;
    }
}

The following code, however, is not (C#).

namespace InitTest
{
    class Program
    {
        int test = 0;
        // Error
        InitTestClass testClass = new InitTestClass(test);

        static void Main(string[] args)
        {
        }
    }

    class InitTestClass
    {
        int test = 0;
        public InitTestClass(int test)
        {
            this.test = test;
        }
    }
}

Flask の Blueprint のテンプレート問題

  Flask の Blueprint は、ルート、静的ファイル、テンプレートをまとめて管理できます。しかし、テンプレートが指定できません。 ここでは、Blueprint の template_folder の問題点と回避策を説明します。 Blueprint のテンプレート問題...