Kinopyo's Blog

I love this game.

Archive for 19:20

Java: Mapをnewした時に値を入れて初期化するコード

2010年03月31日

表題の通り、Mapをnewしたときに値を入れて

初期化するコード方法です。

Map<String, Integer> map = new HashMap<String, Integer>() {
    {
        put("one", 1);
    }
};

jQueryパフォーマンス:DOM操作について

2010年03月26日

DOM操作を避けてjQueryのパフォーマンスを改善する掟です。

こんなコードがあるとしましょう。

パフォーマンスの悪い例

var list = [....];    // 長さ100の配列とする

for (var i in list) {

    var li = document.createElement("li");

    $(li)
       .attr("id", "li" + i)
       .text(list[i]);

$("ul").append(li);

}

改善したコード

var list = [....];    // 長さ100の配列とする

var li = "";
for (var i in list) {

    li += "<li id='li" + i "'>" + list[i] + "</li>";

}

$("ul").html(li);

まとめ

  • document.createElementの代わりにHTMLの文字列を作る
  • jQueryオブジェクトに属性やテキストを設定するのではなく、直接HTML文字列に書く
  • for文内毎回appendの代わりにhtml()を使う

実際のプロジェクトでやってみたら10倍以上は速くなりました。

とは言ってもこれはIE6でのパフォーマンスで、

FirefoxやIE8だと悪い例のコードても遅いとは実感できないくらいでした。

ちなみに

$(li).attr(…).val(…).text(…)の方は読みやすいので結構気に入ったんですけど。。。

PHP Basic – Variables, Datatypes, Operators and Constants

2010年03月24日

Declare a variable

$my_variable;
$my_variable = 3;

Name it in your script, when PHP first sees a variable’s name in a script, it automatically creates the variable at that point.

If you don’t initialize a variable in PHP, it’s given the default value of null.

Data Types

Special Data Type

NULL : May only contain ‘null’ as a value, meaning the variable explicitly does not contain any value

Resource : Contains a reference to an external resource, such as a file or database

Be careful, NULL is a data type.

Testing the Type of a Variable
  • gettype($x)

It returns as a string.

  • is_int( value )
  • is_string( value )
  • is_float( value )
  • is_bool( value )
  • is_array( value )
  • is_object( value )
  • is_resource( value )
  • is_null( value )

Returns true or false.

Changing a Variable’s Data Type

To use settype() , pass in the name of the variable you want to

alter, followed by the type to change the variable to (in quotation marks).

Assigning different values to the variable can also change the variable’s data type.

$test_var = 8.23;
settype( $test_var, "string" );
settype( $test_var, "boolean" );

after converting $test_var to a Boolean, it contains the value true

(which PHP displays as 1 ). This is because PHP converts a non-zero number to the Boolean value true.

Changing Type by Casting
<?php
$test_var = 8.23;
echo $test_var . "<br/>"; // Displays "8.23"
echo (string) $test_var . "<br/>"; // Displays "8.23"
echo (int) $test_var . "<br/>"; // Displays "8"
echo (float) $test_var . "<br/>"; // Displays "8.23"
echo (boolean) $test_var . "<br/>"; // Displays "1"
?>

You can also cast a value to an integer,

floating-point, or string value using three PHP functions:

Functions Description
intval( value ) Returns value cast to an integer
floatval( value ) Returns value cast to a float
strval( value ) Returns value cast to a string

intval() has another use: converting from a non?base-10 integer to a base-10 integer.

For example, this code convert base-16 number “ff” to base-10 number.

echo intval("ff", 16); // Displays "255"

Operator

Assignment Operators

For concatenation strings, using “.=” instead of “.+”.

$a = "Start a sentence";
$b = "and finish it.";
$a .= $b;	// $a now contains "Start a sentence and finish it."
Bitwise Operators

passed…

Comparison Operators
  • === (identical)

true if $x equals $y and they are of the

same type; false otherwise

  • !== (not identical)

true if $x does not equal $y or they are not

of the same type; false otherwise

Logical Operators

PHP considers the following values to be false :

  • The literal value false
  • The integer zero ( 0 )
  • The float zero ( 0.0 )
  • An empty string ( ” ” )
  • The string zero ( “0″ )
  • An array with zero elements
  • The special type null (including any unset variables)
  • A SimpleXML object that is created from an empty XML tag (more on SimpleXML in -Chapter 19 )

All other values are considered true in a Boolean context.

Addtion to the “traditional” logical operators such as “&&” and “||”,

PHP also have “and”, “or” and “xor”.

  • xor

true if $x or $y (but not both) evaluates to true ; false

otherwise

String Operators

There ’ s really only one string operator, and that ’ s the concatenation operator – .(dot).This operator simply

takes two string values, and joins the right – hand string onto the left – hand one to make a longer string.

Operator Precedence

Almost the same except that the logical operator: “and” > “xor” > “or”

has the lowest precedence.

$x = false || true; // $x is true
$x = false or true; // $x is false

In the second line, the “=” has higher precedence than “or”.

Constants

Constants may only contain scalar values such as Boolean, integer, float, and string (not values such as arrays and objects).

Constants do not start with the dollar sign

To define a constant, use the define() function.

define("MY_CONSTANT","19"); // MY_CONSTANT always has the string value "19"
echo MY_CONSTANT; // Displays "19" (note this is a string, not an integer)

dirコマンドでサブフォルダにあるファイル一覧を出力

2010年03月19日

dir /s /b >file.txt

/s指定されたディレクトリおよびそのサブディレクトリのすべてのファイルを表示します。

/bは拡張子とディレクト付きのファイル名を表示します。

jQuery1.3.2のバグ?IEで&nbsp;を$.trimするとき変な結果に

2010年03月10日

jQuery 1.4.2ではこれは治ったようです。

jQuery最新版をお使いの方は下記のようなバグはもう発生しません。

サンプル

※jQuery 1.3.2で発生する問題※

HTML
<select>
	<option id="foo">&nbsp;</option>
	<option>11</option>
	<option>22</option>
</select>

<tr id="bar">&nbsp;</tr>
Javascript
var optionText = $("#foo").text();

// firefoxは0、IEは1
alert("select optionタグの をtrimした後のlength: " + $.trim(optionText).length);

var trText = $("#bar").text();

// firefoxは0、IEも0!
alert("trタグの をtrimした後のlength: " + $.trim(trText).length);

結果

selectのoptionタグのテキストにある“&nbsp;”

$.trimをかけて見ると

Firefoxはちゃんとtrimしてlengthが0になったが、

IEはtrimできずlengthが1のままです。

しかしtrタグのテキストにある”&nbsp;”をtrimすると

IEも正しくtrimしてlengthが0になるんです。。。

DEMO

jQuery最新版(1.4.2)を使うDEMO

Javascript index指定で配列の要素を削除するには

2010年03月08日

今まで全然気付かなかったんです、

JavascriptのArrayにはdeleteみたいなAPIがないことに。

配列の要素をindex指定で削除したい場合は代わりにsplice関数を使います。

splice関数

とほほからのレファレンスでは

array.splice(start, n, e1, e2, …) (N4)

0 から数えて、start 番目から n 個の要素を削除し、その代わりに e1, e2, …を値とする要素を埋め込みます。戻り値は JavaScript のバージョンによって異なります。

var xx = new Array("A", "B", "C", "D", "E", "F", "G");
xx.splice(2, 3, "c", "d", "e");   // "C", "D", "E" が小文字になります

indexで配列の要素を削除するには

myArray.splice(index, 1);

indexは削除する要素のindex、1はこの一つだけを削除する意味で

他のパラメータはいらないです。

またsplice後は配列そのものが変更されます。

jQuery IDに括弧がついたオブジェクトを取るには

2010年03月03日

こんなHTMLがあるとします。

idに[]が付いてますね。

<input id="foo[0]" type="text" />
<input id="foo[1]" type="text" />
<input id="foo[2]" type="text" />

こういうIDに括弧が付いたモノに対して

普通の#付きのjQueryセレクタでは選択できません。

$("#foo[0]");    // 取れません

属性フィルタ[attribute=value]でとるのが正解です。

$("[id='foo[0]']");

0311更新:

もし具体的なタグがわかってあれば、

それを指定することでパフォーマンスを向上できます。

上記の例で言うと

$("input[id='foo[0]']");

このほうが速いです。

スクロールを最下部に移動するJavascript

2010年03月02日

スクロールバーを最下部に移動するJavascriptです。

普通のJavascriptで書くと

function go_bottom(targetId){

    var obj = document.getElementById(targetId);

    if(!obj) return;

    obj.scrollTop = obj.scrollHeight;
}

完全にjQueryで書くとこんな感じ

function go_bottom(targetId){

   var $obj = $("#" + targetId);

    if($obj.length == 0) return;

    $obj.scrollTop($obj[0].scrollHeight);
}

これ以外はhiddenのinput項目を最下部に置いといて、

それをfocusするような技もありけど、、

Chromeの内蔵翻訳ツールバーを無効にする方法

すべての言語でAutomatic Translationを無効にしたい人のために。

  • C:\Users\(ユーザ名)\AppData\Local\Google\Chrome\User Data\Defaultへアクセスします。
    • WinXPはC:\Documents and Settings\(ユーザ名)\Local Settings\Application Data\Google\Chrome\User Data\Default
  • 「Preferences」ってファイルがあります。
  • 「translate」で検索すると、最後あたりでこのような文字列があるはずです。

chrome_preference

  • translate_language_blacklistを、以下コードに書き換える。
"translate_language_blacklist": [ "en", "de", "zh-TW", "it", "af", "sq", "ar", "be", "bg", "ca", "zh-CN", "hr", "cs", "da", "nl", "et", "tl", "fi", "fr", "gl", "el", "he", "hi", "hu", "is", "ja", "ko", "lv", "lt", "mk", "ms", "mt", "no", "fa", "pl", "pt", "ro", "ru", "sr", "sk", "sl", "es", "sw", "sv", "th", "tr", "uk", "vi", "cy", "yi" ],
  • 修正完了

chrome_preference_modified

Get Adobe Flash playerPlugin by wpburn.com wordpress themes