「Console」を含む日記 RSS

はてなキーワード: Consoleとは

2016-03-26

http://anond.hatelabo.jp/20160326101539

高頻度で更新されているコンテンツに対してはべったり貼り付いてくるよ。

から、即インデクス化される。

ちなみに、その手のサイトを持っている場合はsearch consoleから通知するための手段があった。

2015-03-12

http://anond.hatelabo.jp/20150312122358

マジレスすると、U+00a5なら使える。俺なら設計修正させるけど。

Path.GetInvalidFileNameChars メソッド (System.IO)

using System;
using System.IO;

namespace TestInvalidFileName
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get a list of invalid file characters.
            char[] invalidFileChars = Path.GetInvalidFileNameChars();

            Console.WriteLine("The following characters are invalid in a filename:");
            ShowChars(invalidFileChars);
            Console.WriteLine();

            string fileName = '\u00a5' + "108";
            using (var fs = File.Create(fileName))
            {
                if (fs != null)
                {
                    Console.WriteLine("File was created:" + fileName);
                    fs.Close();
                }
                else {
                    Console.WriteLine("File was not created:" + fileName);
                }
            }
        }

        public static void ShowChars(char[] charArray)
        {
            Console.WriteLine("Char\tHex Value");
            // Display each invalid character to the console.
            Array.Sort(charArray);
            foreach (char someChar in charArray)
            {
                if (Char.IsWhiteSpace(someChar))
                {
                    Console.WriteLine(",\t{0:X4}", (int)someChar);
                }
                else
                {
                    Console.WriteLine("{0:c},\t{1:X4}", someChar, (int)someChar);
                }
            }

        }
    }
}
The following characters are invalid in a filename:
Char    Hex Value
(中略)
",      0022
**,      002A
/,      002F
:,      003A
>,      003C
>,      003E
?,      003F
\,      005C
|,      007C

File was created:\108

2014-01-14

http://anond.hatelabo.jp/20140114041710

元の質問を見ると、プログラムの終了を待っているのはPythonじゃなくてConsoleだよね。

リダイレクト先はNone以外でもいい。

出力をNoneにするとエラーを見逃すからファイルに出した方がいいよ。

2012-09-20

http://anond.hatelabo.jp/20120920164222

こういうのを望んでいるなら、不可能。

var i = 10;

[1,2,3, ... ,99,100].each(function(i) {
	// 何かの処理
});

console.log(i); // 10と出て欲しい

jashkenasはこう主張している

if they do clash, shadowing the variable is the wrong answer. It completely prevents you from making use of the original value for the remainder of the current scope. Shadowing doesn't fit well in languages with closures-by-default ... if you've closed over that variable, then you should always be able to refer to it.

衝突が起こるとしても、変数隠蔽(shadowing)は間違った解決法だ。スコープ内のその他のすべての変数に関して、オリジナルの値の利用を完全に塞いでしまう。隠蔽は、クロージャが標準(closures-by-default)な言語にはうまくマッチしない。その変数を閉じ込めているならば、常に参照出来るべきだ。

ソースhttp://www.sixapart.jp/techtalk/2012/01/coffeescript.html

2012-09-01

ここが素晴らしかったよ・はてなOne

はてな One が始まってから 7 か月。こんなに使えば使うほど発見があったサービスはありませんでした。クローズドコミュニケーションって本当に楽しい!ってことを思い出させてくれました。ありがとうはてな Oneさようならはてな One

2012-08-13

C#基礎文法最速マスター

1. 基礎
classの作成

プログラムclass記述します。たとえばSampleという名前classを作る場合、Sample.csファイル内に次のように書きます。(C#場合ファイル名とクラス名は同一でなくても良い。複数のクラスを書いても良い)

public class Sample {

}
Mainメソッドの作成

プログラムclass内のMainメソッドの先頭から実行されます。Mainメソッドは次のように書きます

public class Sample {

    public static void Main( String[] args ) {
         // 処理を書く
     }

}
Console.WriteLineメソッド

文字列を表字するメソッドです。

Console.WriteLine( "Hello world" );
コメント

コメントです。

// 一行コメント

/*
   複数行コメント
 */
変数の宣言

変数の宣言です。変数の宣言時にはデータ型を指定します。

// 変数
int num;
データ型

データ型です。C#データ型には値型と参照型とがあります。以下は値型のデータ型です。

// int(整数)型
int num;
// char(文字)型
char c;
// float(単精度浮動小数点)型
float val;
// double(倍精度浮動小数点)型
double val;
// bool(論理)型
bool flag;
// DateTime(日付)型
DateTime date;

以下は参照型のデータ型です。

// StringString s;
// 配列String[] array;
プログラムのコンパイル

プログラムコンパイルするには、コマンドラインで以下のようにします。

csc Sample.cs
プログラムの実行

プログラムを実行するには、コマンドラインで以下のようにします。

.net framework on Windows場合

Sample.exe

Mono.frameworkの場合

mono ./Sample.exe
2. 数値
数値の表現

int、float、double型の変数に数値を代入できます。int型には整数だけ代入できます。float、double型には整数でも小数でも代入できます

int i = 2;
int i = 100000000;

float num = 1.234f;

double num = 1.234;
四則演算

四則演算です。

num = 1 + 1;
num = 1 - 1;
num = 1 * 2;
num = 1 / 2;

商の求め方です。割る数と割られる数が両方とも整数場合計算結果の小数点以下が切り捨てられます

num = 1 / 2;  // 0

割る数と割られる数のどちらかが小数場合計算結果の小数点以下が切り捨てられません。

num = 1.0 / 2;    // 0.5
num = 1 / 2.0;    // 0.5
num = 1.0 / 2.0;  // 0.5

余りの求め方です。

// 余り
mod = 4 % 2
インクリメントとデクリメント

インクリメントとデクリメントです。

// インクリメント
 ++i;

// デクリメント
 --i;
3. 文字列
文字列の表現

文字列ダブルクォートで囲みます

String str = "abc";
文字列操作

各種文字列操作です。

// 結合
String join = "aaa" + "bbb";

// 分割
String[] record = "aaa,bbb,ccc".Split( "," );

// 長さ
int length = "abcdef".Length();

// 切り出し
"abcd".Substring( 0, 2 )   // abc

// 検索
int result = "abcd".IndexOf( "cd" ) // 見つかった場合はその位置、見つからなかった場合は-1が返る
4. 配列
配列変数の宣言

配列です。

// 配列の宣言
int[] array;
配列の生成

配列の生成です。配列の生成時には要素数を指定するか、初期データを指定します。

int[] array;

// 要素数を指定して配列を生成
array = new int[5];

// 初期データを指定して配列を生成
array = new int[] { 1, 2, 3 };

// 宣言と同時に配列を生成
int[] array2 = new int[5];
配列の要素の参照と代入

配列の要素の参照と代入です。

// 要素の参照
array[0]
array[1]

// 要素の代入
array[0] = 1;
array[1] = 2;
配列の要素数

配列の要素数を取得するには以下のようにします。

array_num = array.Length;
配列のコピー

配列の要素を別の配列コピーするには以下のようにします。

int[] from = new int[] { 1, 2, 3 };
int[] to = new int[5];

from.CopyTo(to, 0);
5. 制御文
if文

if文です。

if ( 条件 )
{

}
if ~ else文

if ~ else文です。

if ( 条件 )
{

}
else
{

}
if ~ else if 文

if ~ else if文です。

if ( 条件 )
{

}
else if ( 条件 )
{

}
while文

while文です。

int i = 0;
while ( i < 5 )
{
    
    // 処理
    
    ++i;
}
for文

for文です。

for ( int i = 0; i < 5; ++i )
{
    // 処理
}
for-each文

for-each文です。配列の各要素を処理できます

int[] fields = new int[] { 1, 2, 3 };

foreach (int field in fields)
{
    // 処理
}
6. メソッド

C#では関数メソッドと言いますメソッドを作るには次のようにします。戻り値を返却するにはreturn文を使います

static int sum( int num1, int num2 )
{
    int total;

    total = num1 + num2;

    return total;
}
9. ファイル入出力

ファイル入出力です。ファイル入出力を行うには、プログラムの先頭に以下を記述します。

using System.IO;

以下がファイル入力の雛形になりますファイルオープンや読み込みに失敗した場合catch節に処理が移ります

String filename = "text.txt";
StreamReader reader = null;
try
{
    reader = new StreamReader(filename);

    String line;
    while ((line = reader.ReadLine()) != null)
    {

    }

}
catch (IOException e)
{
    // エラー処理:

}
finally
{
    if (reader != null)
    {
        try
        {
            reader.Close();
        }
        catch (IOException e) { }
    }
}

またはC#ではusing ステートメントと言うものがあり、この様にも書ける

String filename = "text.txt";
using (StreamReader reader = new StreamReader(filename))
{
    try
    {

        String line;
        while ((line = reader.ReadLine()) != null)
        {
            // 読み込んだ行を処理
        }

    }
    catch (IOException e)
    {
        // エラー処理:

    }
}

usingをつかうとCloseがなくなったことからわかるようにusing(){}を抜けるとき自動的にDisposeメソッドを呼び出し、オブジェクトを廃棄する。その分コードスッキリするが、使いにくい場面もあるので考えて使うこと。

以下がファイル出力の雛形になりますファイルオープンや書き込みに失敗した場合catch節に処理が移ります

String filename = "text.txt";
StreamWriter writer = null;

try
{
    writer = new StreamWriter(filename));

    writer.WriteLine("abc");
    writer.WriteLine("def");
    writer.WriteLine("fgh");

}
catch (IOException e)
{
    // エラー処理:

}
finally
{
    if (writer != null)
    {
        writer.Close();
    }
}

こちらもusingを使って書ける。が、割愛する。

知っておいたほうがよい文法

C#でよく出てくる知っておいたほうがよい文法の一覧です。

繰り返し文の途中で抜ける

繰り返し文の途中で抜けるにはbreak文を使用します。

for ( i = 0; i < 5; ++i ) {

    if ( 条件 ) {
        break;    // 条件を満たす場合、for文を抜ける。
    }

}
繰り返しの残り部分の処理をスキップする

残りの部分処理をスキップし、次の繰り返しに進むにはcontinue文を使用します。

for ( i = 0; i < 5; ++i ) {

    if ( 条件 ) {
        continue;    // 条件を満たす場合、残りの部分処理をスキップし、次の繰り返しに進む。
    }

}
例外処理

例外を投げるにはthrow文を使用します。

throw new Exception( "Error messsage" );

例外処理をするにはtrycatch文を使用します。

try {

    // 例外が発生する可能性のある処理

} catch ( Exception e ) {

    // 例外発生時の処理

}

2012-06-29

どのプログラミング言語が最も美しいか

■ C

for( const char *s="12345"; *s; ++s ) if( '2'<*s&&*s<'5' ) printf( "%d", (*s-'0')*2 );

JavaScript

console.log([1,2,3,4,5].filter(function (i){ return (i > 2 && i < 5 ); }).map(function(i){ return 2 * i; }));

Python

print(map(lambda x: x*2, filter(lambda x: x>2 and x<5, [1,2,3,4,5])))

Ruby

puts [1,2,3,4,5].select{|i| i > 2 and i < 5}.map{|i| i*2}

C#

new{}{ 1,2,3,4,5 }.Where(x => 2 < x && x < 5).Select(x => x*2);

Common Lisp

(print (loop for x in '(1 2 3 4 5) if (< 2 x 5) collect (* x 2)))

Haskell

print [x*2| x <-[1,2,3,4,5], x > 2, x < 5]

■ J

  1. :(((>&2)*.(<&5)) a) # a=:1+i.5

■ R

print((function(){x<-c(1,2,3,4,5);x[2<x&x<5]*2})())</p>

Clojure

(print (for [x [1,2,3,4,5] :when (< 2 x 5)] (* x 2)))

Squeak Smalltalk

(1 to: 5) select: [:x | x between: 3 and: 4] thenCollect: [:x | x * 2]

2012-05-06

CoffeeScriptプライベート関数パブリックメソッドとして開示するやつ

class MyClass
	constructor: ->
		name = 'unknown'
		
		@getName = ->
			return name
		
		@setName = (newName) ->
			name = newName
	
		
MyClass:: = do ->
	_greet = ->
		console.log('どうも、' + @getName() + 'です。')
	
	return {
		constructor: MyClass
		greet: _greet
	}


myInstance = new MyClass()
myInstance.setName('純子')
myInstance.greet() #どうも、純子です。

CoffeeScript で @なんとかのプロパティが全部パブリックになるのが気になってて。

2012-01-27

[] Firebugログ上限に達しました。

エラーメッセージFirebugログ上限に達しました。n 件表示されませんでした。」

about:configextensions.firebug.console.logLimitを増やす。

既定値は500件。

2011-11-19

Firefoxアドオンマネージャからノートンを除外する方法

セキュリティの設定なので実施自己責任で。

Windows 7 - Firefox 8.0 - Norton Internet Security(NIS) 2011 の場合

 

(xはバージョン番号)

1. NIS - 設定 - その他の設定 - 製品セキュリティ で「Norton製品の改変対策」を「OFF」にする。

2. C:\ProgramData\Norton\{0C55C096-0F1D-4F28-AAA2-85EF591126E7}\NIS_xx.x.x.x\

  内にある次のフォルダリネームする。

  ・coFFPlgn_xxxx_x_x_x → coFFPlgn_xxxx_x_x_xOLD

  ・IPSFFPlgn → IPSFFPlgnOLD

  ※WindowsXPでは C:\Documents and Settings\All Users\Application Data\Norton\{0C55C096-0F1D-4F28-AAA2-85EF591126E7}\NIS_xx.x.x.x\ (未確認)

3. Firefox再起動する。

 

元に戻したい時は、リネームしたフォルダを戻して「Norton製品の改変対策」を「ON」にする。

なお、OS再起動するとフォルダが強制的に作成されるようなので、その都度2.の実施が必要。

 

 

(おまけ)Java Console を削除する方法

C:\Program Files\Mozilla Firefox\extensions\

内にある {CAFEEFAC で始まるフォルダリネーム

2011-07-13

Rubyの実行(.exe)ファイルの作り方の詳細

Rubyではじめるゲームプログラミング

P.340

1/ ・パスに2バイト文字が入らない

   ・パスにスペースの入らない(たとえば、My Documentsなどは、途中にスペースが入っているのでエラーになる。アンダーバー「_」は可。)

    フォルダ(C\Testなど)を作る。 →以下フォルダAとする。

2/ 実行ファイルを作りたいスクリプト(○○.rb)ファイル自体も、2バイト文字、半角でもスペースの入らないファイル名にする。

 →「5-05-04 ride block.rb」といったファイル名は、スペースが入っているのでダメ

3/ フォルダAに、ActiveScriptRubyインストールするとできる「ruby consoleショートカット(everything検索)のショートカットを、そのフォルダコピーする。

4/ フォルダAに、実行ファイルを作りたいスクリプト(○○.rb)を、Imgフォルダ等と共にコピーする。

5/ フォルダAに、fontを、fontsフォルダごとコピーする。

6/ フォルダAに、Ruby/SDLDLLをそのフォルダコピーする。15種類。

 →DLLフォルダを、ではなく、exeファイルの置かれる場所に、DLLファイルそのものを直接並べる。

7/ この時点でスクリプトテスト

フォルダAにコピーしたruby consoleを起動 →コマンドプロンプトの後に、「ruby ○○.rb」とし、スクリプトの起動を確認する。

8/ フォルダAにコピーしたruby consoleを起動 →コマンドプロンプトの後に、「mkexy ○○.rb」とする。

 →ゲームが起動するので、終了させる。

→○○.exy という、レシピファイル作成される。

9/ ○○.exy ファイルを、メモ帳等のテキストエディタで開く

10/ 初期値は「core: cui」となっているのを、「core: gui」に変える。

 →変えなくてもいいが、その場合、実行時にコマンドプロンプト窓が出てきて邪魔になる。

11/ フォルダAにコピーしたruby consoleを起動 →コマンドプロンプトの後に、「exerb ○○.exy」←今作ったファイル とする。

→「○○.exe」という実行ファイルができる。

12/ 「○○.exe」をダブルクリックして実行、起動しなかった場合、2~5のプロセスに、コピーし忘れがある。

13/ 配布物は以下の通り。

・実行ファイル「○○.exe」 →ファイル名は任意に変更可。(もちろん.exe以外の名前)

・fontsフォルダ

・images、soundなどのリソースフォルダ

Ruby/SDLDLL全て。厳密にはoggなどを使用しなければ、それ用のDLL不要

2011-03-16

ドラゴンボールで学ぶオブジェクト指向ツッコミ

http://anond.hatelabo.jp/20110316202255

亀仙流やつ鶴仙流など、世の中にはいくつかの流派があり、それぞれ
カメハメ波やドドン波、舞空術などの技(メソッド)がある。
実際に技を使う場合、技を覚えているZ戦士(インスタンス)が必要。

クラス = 流派

メソッド = 技

インスタンス = Z 戦士

というのはおもしろいと思うし, 例えばゲームを作るなら実際にそういう実装になると思う.

例)セルを作りましょう。
class Cell extends Goku,Veget,Picoro,Tenshinhan,Kuririn{
....
}
cell_inst = new Cell();
cell_inst.shotKienzan(); //Kuririnをextendsしているので気円斬が使えます

しかし, ここではクラス = Z 戦士になってしまっているので, 混乱を招くだろう.

むしろ, 「JavaScript における prototype」 に絞って説明するのはどうだろう.

(ついでに「撃つ」の現在形は shot でなく shoot ですね)

var Goku = function () {};
Goku.prototype.shootKamehameha = function () {
  console.log("波!!!");
};

var goku = new Goku;
goku.shootKamehameha(); // 波!!!

var Gohan = function () {};
Gohan.prototype = new Goku;

var gohan = new Gohan;
gohan.shootKamehameha(); // 波!!!

そしてセルによる吸収は, 動的な継承として考えるのがより自然だろう.

var Goku = function () {};
Goku.prototype.shootKamehameha = function () {
  console.log("波!!!");
};

var Vegeta = function () {};
Vegeta.prototype.shootBigBangAttack = function () {
  console.log("ビッグバンアタック!!!");
};

var Cell = function () {};
// 吸収メソッド
Cell.prototype.absorb = function (target) {
  for (var method in target) {
    this[method] = target[method];
  }
};

var goku   = new Goku;
var vegeta = new Vegeta;

var cell = new Cell;
cell.absorb(goku);   // 悟空を吸収
cell.absorb(vegeta); // ベジータを吸収

cell.shootKamehameha();    // 波!!!
cell.shootBigBangAttack(); // ビッッグバンアタック!!!

そして次にクロージャの使用例として挙げられた次の例.

例)連続エネルギー波
var shotRenzokuEnergy = function( count ){
	var shotEnergy = function(){
		//エネルギー波を放ちます
	};
	for(var i=0;i<count;i++){
		shotEnergy();
	}
};

この実装では, shotRenzokuEnergy を実行するたびに shotEnergy が毎回定義されてしまい, 非効率である.

以下のように書き換えることで, shootEnergy の定義は, shootRenzokuEnergy の定義時の 1 回のみとなる.

var shootRenzokuEnergy = (function () {
  var shootEnergy = function () {
    console.log("エネルギー波!!!");
  };

  return function (count) {
    for (var i = 0; i < count; i++) {
      shootEnergy();
    }
  };
})();

shootRenzokuEnergy(10); // エネルギー波!!! x 10

2011-03-03

ブログの問題を解いてみた

http://okajima.air-nifty.com/b/2011/01/2011-ffac.html

ぷよぷよを解く問題をやってみた

かかった時間はおおよそ1時間

途中でわからないところがあったのでくぐってしまった

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder[] blocks = {
                new StringBuilder("**GYRR"),
                new StringBuilder("RYYGYG"),
                new StringBuilder("GYGYRR"),
                new StringBuilder("RYGYRG"),
                new StringBuilder("YGYRYG"),
                new StringBuilder("GYRYRG"),
                new StringBuilder("YGYRYR"),
                new StringBuilder("YGYRYR"),
                new StringBuilder("YRRGRG"),
                new StringBuilder("RYGYGG"),
                new StringBuilder("GRYGYR"),
                new StringBuilder("GRYGYR"),
                new StringBuilder("GRYGYR")
            };

            bool updated = true;
            while (updated)
            {
            breaked:
                DumpBlock(blocks);
                for (int i = 0; i < blocks.Length; i++)
                {
                    for (int j = 0; j < blocks[i].Length; j++)
                    {
                        char c = blocks[i][j];
                        if (c == '*')
                            continue;
                        updated = false;
                        if (KillBlocks(blocks, i, j))
                        {
                            updated = true;
                            goto breaked;
                        }
                    }
                }
            }
            DumpBlock(blocks);
            Console.Read();
        }
        struct Point
        {
            public int x, y;
            public Point(int x, int y)
            {
                this.x = x;
                this.y = y;
            }
        }
        static bool KillBlocks(StringBuilder[] blocks, int x, int y)
        {
            bool[,] visted = new bool[blocks.Length,blocks[0].Length];

            MarkBlock(visted, blocks, x, y);

            Queue<Point> queque = new Queue<Point>();
            for (int i = x; i < blocks.Length; i++)
                for (int j = y; j < blocks[i].Length; j++)
                    if(visted[i,j] == true)
                        queque.Enqueue(new Point(j,i));

            if (queque.Count < 4)
                return false;

            while (queque.Count > 0)
            {
                Point p = queque.Dequeue();
                RemoveBlock(blocks, p.x, p.y);
            }
            return true;
        }
        static void MarkBlock(bool[,] visted, StringBuilder[] blocks, int x, int y)
        {
            if (x < 0 || y < 0 || x >= blocks.Length || y >= blocks[0].Length || visted[x, y] == true)
                return;
            char c = blocks[x][y];
            visted[x, y] = true;
            if (x + 1 < blocks.Length && blocks[x + 1][y] == c) MarkBlock(visted, blocks, x + 1, y);
            if (y + 1 < blocks[0].Length && blocks[x][y + 1] == c) MarkBlock(visted, blocks, x, y + 1);
            if (x > 0 && blocks[x - 1][y] == c) MarkBlock(visted, blocks, x - 1, y);
            if (y > 0 && blocks[x][y - 1] == c) MarkBlock(visted, blocks, x, y - 1);
        }
        static void DumpBlock(StringBuilder[] blocks)
        {
            foreach (StringBuilder s in blocks)
                Console.WriteLine(s);
            Console.WriteLine();
        }
        static void RemoveBlock(StringBuilder[] blocks,int x,int y)
        {
            int i;
            if (y == 0)
            {
                blocks[y][x] = '*';
                return;
            }
            for (i = y; i > 0; i--)
            {
                blocks[i][x] = blocks[i - 1][x];
            }
            blocks[i][x] = '*';
        }
    }
}

2011-01-11

人材獲得作戦・4 試験問題ほか

http://okajima.air-nifty.com/b/2010/01/post-abc6.html

迷路の最短経路を求める問題が出たので解いてみた

幅優先探索を使えばいいのがわかっていたのですんなりかけたのだが無限ループになる個所があったので動くようになるまで時間がかかった

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace MazeFind
{
    class Point
    {
        public int x;
        public int y;
        public Point before;
        public Point(int x, int y,Point before)
        {
            this.x = x;
            this.y = y;
            this.before = before;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            const char BreakChar = 'B';
            const char GoalChar = 'G';
            const char WallChar = '*';
            const char BeforeChar = '.';

            StringBuilder[] maze = new StringBuilder[]{
                new StringBuilder("**************************"),
                new StringBuilder("*S* *                    *"),
                new StringBuilder("* * *  *  *************  *"),
                new StringBuilder("* *   *    ************  *"),
                new StringBuilder("*    *                   *"),
                new StringBuilder("************** ***********"),
                new StringBuilder("*                        *"),
                new StringBuilder("** ***********************"),
                new StringBuilder("*      *              G  *"),
                new StringBuilder("*  *      *********** *  *"),
                new StringBuilder("*    *        ******* *  *"),
                new StringBuilder("*       *                *"),
                new StringBuilder("**************************"),
            };
            Point start = new Point(1, 1,null);

            //最短経路を探索する
            Queue<Point> queque = new Queue<Point>();
            queque.Enqueue(start);

            while (queque.Count > 0)
            {
                Point now = queque.Dequeue();
                if (maze[now.y][now.x] == BreakChar)
                    Console.WriteLine("break");
                if (maze[now.y][now.x] == WallChar || maze[now.y][now.x] == BeforeChar)
                    continue;
                else if (maze[now.y][now.x] == GoalChar)
                {
                    Point p = now.before;
                    while (p != null)
                    {
                        maze[p.y][p.x] = '@';
                        p = p.before;
                    }
                    break;
                }

                if (maze[now.y - 1][now.x] != '#')
                {
                    queque.Enqueue(new Point(now.x, now.y - 1, now));
                    maze[now.y][now.x] = '.';
                }
                if (maze[now.y][now.x + 1] != '#')
                {
                    queque.Enqueue(new Point(now.x + 1, now.y, now));
                    maze[now.y][now.x] = '.';
                }
                if (maze[now.y + 1][now.x] != '#')
                {
                    queque.Enqueue(new Point(now.x, now.y + 1, now));
                    maze[now.y][now.x] = '.';
                }
                if (maze[now.y][now.x - 1] != '#')
                {
                    queque.Enqueue(new Point(now.x - 1, now.y, now));
                    maze[now.y][now.x] = '.';
                }
            }

            //結果を出力する
            foreach (StringBuilder s in maze)
                Console.WriteLine(s.ToString().Replace(BeforeChar,' '));

            Console.ReadLine();
        }
    }
}
<||

2010-08-19

アドオンリスト

さてどこから消すか

2010-01-14

http://anond.hatelabo.jp/20100113192313

これで40分。

タイムアタックってことでアルゴリズムは全幅探索で書き上げました。

エラーチェック皆無。

A*ならもう5分ほど延びるかな?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Maze
{
    class Program
    {
        // 探索用地図
        static int[,] maze;

        // 始点終点
        static Position Start = new Position(0, 0), Goal = new Position(0, 0);

        static void Main(string[] args)
        {
            //////////////////////////// まずは各行のリストとして読み込み
            string[] inMaze;

            using (var fp = new FileStream(args[0], FileMode.Open, FileAccess.Read))
            using (var iStream = new StreamReader(fp))
                inMaze = iStream.ReadToEnd().Split('\n');

            // 迷路幅
            int height = inMaze.Length;

            // 迷路高さ
            int width = inMaze[0].Length;

            /////////////////////////// 読み込んだ迷路を作業用地図に展開
            maze = new int[width, height];
            for (int y = 0; y < height; ++y)
            {
                string line = inMaze[y];
                for (int x = 0; x < line.Length; ++x)
                {
                    maze[x, y] = line[x] == '*'
                        ? -1
                        : 0;
                    if (line[x] == 'S') Start = new Position(x, y);
                    if (line[x] == 'G') Goal = new Position(x, y);
                }
            }

            // 探索実行
            int dist = Search(maze, Start);

            // 探索結果から最短経路を再現
            Position backTracer = Goal;
            while (dist&gt;1){
                --dist;
                backTracer = backTracer.Nearbys.First(pos =&gt; maze[pos.X,pos.Y] == dist);
                maze[backTracer.X, backTracer.Y] = -2;
            }

            //////////////////// 最短経路こみのアスキー地図に変換
            char[,] outMaze = new char[width, height];

            for (int y = 0; y < height; ++y)
            {
                for (int x = 0; x < width; ++x)
                {
                    outMaze[x, y] = maze[x, y] == -2
                        ? '$'
                        : maze[x, y] == -1
                            ? '*'
                            : ' ';
                }
            }
            outMaze[Start.X, Start.Y] = 'S';
            outMaze[Goal.X, Goal.Y] = 'G';


            ////////////////////// 結果は標準出力に。
            for (int y = 0; y < height; ++y)
            {
                for (int x = 0; x < width; ++x)
                    Console.Write(outMaze[x, y]);
                Console.WriteLine();
            }
            Console.ReadLine();
        }

        /// <summary&gt;
        /// 探索する。SG間の道のりを返す(道のり=SGが隣接しているなら1)
        /// </summary&gt;
        private static int Search(int[,] maze, Position Start)
        {
            List<Position&gt; FrontLine = new List<Position&gt;();
            FrontLine.Add(Start);
            int dist = 1;
            for (; ; )
            {
                List<Position&gt; NextFrontLine = new List<Position&gt;();
                foreach (var pos in FrontLine)
                {
                    foreach (var nextPos in pos.Nearbys)
                    {
                        if (nextPos == Goal) return dist;
                        if (maze[nextPos.X, nextPos.Y] == 0)
                        {
                            maze[nextPos.X, nextPos.Y] = dist;
                            NextFrontLine.Add(nextPos);
                        }
                    }
                }
                FrontLine = NextFrontLine;
                ++dist;
            }
        }
    }

    struct Position
    {
        public readonly int X, Y;
        public Position(int x, int y) { X = x; Y = y; }

        public IEnumerable<Position&gt; Nearbys
        {
            get
            {
                return new[]{
                    new Position(X-1,Y),
                    new Position(X,Y-1),
                    new Position(X+1,Y),
                    new Position(X,Y+1),
                };
            }
        }

        public static bool operator==(Position p1, Position p2){
            return p1.X == p2.X &amp;&amp; p1.Y == p2.Y;
        }

        public static bool operator!=(Position p1, Position p2){
            return p1.X != p2.X || p1.Y != p2.Y;
        }
    }
}

2009-10-25

Javaってかわいそう

http://d.hatena.ne.jp/j5ik2o/20091024/1256369305

    // 1.0 - 9 * 0.1
    BigDecimal b1 = new BigDecimal(1.0);
    BigDecimal b2 = new BigDecimal(-9);
    BigDecimal b3 = new BigDecimal("0.1");
    BigDecimal result = b1.add(b2.multiply(b3));	
    System.out.println(result.toString());

を見て悲しくなった。Javaってひどい。0.1は文字列で渡さないと誤差が出るってさ。泣ける。

C#なら

    Console.WriteLine( 1.00M - 9M * .10M );

でOK

2009-08-29

Snow Leopard めも

http://snowleopard.wikidot.com/ に載ってるのも試してみた。

動いた

  • Adobe Lightroom 2.4
  • AudioFire Console (AudioFire4)
  • AppCleaner
  • Flip4Mac
  • Parallels 4.0.3844(32bit)
  • Perian
  • SpiritedAway
  • V2C
  • Warp (ログイン時に起動が設定できない)

動かない

  • FStream (起動できない)
  • iStat Menus (インストールはできた)
  • LadioManager (放送一覧が出ないけど、検索窓に何か入れると表示される)

ねとらじ用アプリが全滅で残念。

2009-06-18

http://anond.hatelabo.jp/20090618121104

if("0x0a" == 10)
  console.log("おっと、javascriptの悪口はそこまでだ。");

if("0x0a" === 10)
  console.log("(´ε` )チュッ");

else
  console.log("\(^o^)/");

2009-03-11

[][][][][][]

Deploy Merb, Sinatra, or any Rack App to Heroku

http://blog.heroku.com/archives/2009/3/5/32_deploy_merb_sinatra_or_any_rack_app_to_heroku/

http://heroku.com/pages/quickstart

http://heroku.com/docs

http://heroku.com/

HerokuをGit経由で使ってみる

http://d.hatena.ne.jp/aki-s-119/20081110/1226335713

http://github.com/guides/using-git-and-github-for-the-windows-for-newbies

Windows から Git を使う方法

http://d.hatena.ne.jp/kusakari/20080715/1216091060

msysgit - Google Code

http://code.google.com/p/msysgit/

PuTTYssh2プロトコルを使ってssh接続

http://net-newbie.com/putty.html

&gt;heroku help
=== General Commands

 help                         # show this usage

 list                         # list your apps
 create [<name&gt;]              # create a new app

 keys                         # show your user's public keys
 keys:add [<path to keyfile&gt;] # add a public key
 keys:remove <keyname&gt;        # remove a key by name (user@host)
 keys:clear                   # remove all keys

=== App Commands (execute inside a checkout directory)

 info                         # show app info, like web url and git repo
 open                         # open the app in a web browser
 rename <newname&gt;             # rename the app

 sharing:add <email&gt;          # add a collaborator
 sharing:remove <email&gt;       # remove a collaborator

 domains:add <domain&gt;         # add a custom domain name
 domains:remove <domain&gt;      # remove a custom domain name
 domains:clear                # remove all custom domains

 rake <command&gt;               # remotely execute a rake command
 console <command&gt;            # remotely execute a single console command
 console                      # start an interactive console to the remote

 restart                      # restart app servers
 logs                         # fetch recent log output for debugging
 logs:cron                    # fetch cron log output

 bundles                      # list bundles for the app
 bundles:capture [<bundle&gt;]   # capture a bundle of the app's code and dat
 bundles:download             # download most recent app bundle as a tarba
 bundles:download <bundle&gt;    # download the named bundle
 bundles:animate <bundle&gt;     # animate a bundle into a new app
 bundles:destroy <bundle&gt;     # destroy the named bundle

 destroy                      # destroy the app permanently

=== Example story:

 rails myapp
 cd myapp
 (...make edits...)
 git init
 git add .
 git commit -m "my new app"
 heroku create myapp
 git remote add heroku git@heroku.com:myapp.git
 git push heroku master

2008-10-15

[][][]

http://kenz0.s201.xrea.com/weblog/2008/10/post_144.html

を見て

http://anond.hatelabo.jp/20061209160227

を思い出して

http://www.lowing.org/fonts/

に行く。



2008-04-09

JSON根本的な脆弱性

この間どっかの記事で見つけて(これ自体は数年前から海外では言われていたことだが)ターゲットを探そうと頑張ってたんだけどいろいろと理由があってここで公開することにする。

javascriptは以下のようにコンストラクタを再定義できる。

function Array() {
    var obj = this;
    var ind = 0;
    var getNext = function(x) {
        obj[ind++] setter = getNext;
        if (x) {
            console.log(x.toString());//細工。
        }
    };
    this[ind++] setter = getNext;
}

実はこれが問題で例えば、配列を含むオブジェクトJSONで渡す際に必ずArrayコンストラクタが呼び出される。

上記のように少し細工をしておけばcallbackとかついてなくても内容を処理できるのでクロスドメイン対策がされている場合でもJSONからデータを読み取ることが出来る。

余談だが、Gmailなどではこれを回避するためにwhile 1を先頭につけることで無限ループさせている。

ちなみに公開する理由
  • Firefox3はこれを仕掛けることが出来ない
  • はまちちゃんのようにいいターゲットを見つけることが出来なかった
    • いや、ひとつ見つけたんだけどあまりにも(ry
  • これとかを見る限り知っている人が少なそうだったから

2007-10-30

[]55行で作るC#テンプレートエンジン

http://anond.hatelabo.jp/20071030034313二番煎じ

あまりのアホさに、作ってて気が狂いかけた

方針


using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Microsoft.CSharp;

delegate void ConvertTemplateDelegate(TextWriter tw, Dictionary<object, object> args);
static class TemplateGenerator {
    public static ConvertTemplateDelegate Generate(string code) {
        CompilerParameters param = new CompilerParameters();
        param.GenerateInMemory = true;
        param.ReferencedAssemblies.Add("System.Web.dll");
        CompilerResults rs = new CSharpCodeProvider().CompileAssemblyFromSource(param, ParseTemplate(code));
        if (0 < rs.Errors.Count) {
            StringWriter sw = new StringWriter();
            sw.WriteLine("Compile Error...");
            foreach (CompilerError err in rs.Errors)
                sw.WriteLine(err.ToString());
            throw new Exception(sw.ToString());
        }
        return (ConvertTemplateDelegate) Delegate.CreateDelegate(typeof(ConvertTemplateDelegate), rs.CompiledAssembly.GetType("Template", true).GetMethod("Convert"));
    }
    private static string ParseTemplate(string code) {
        using (StringWriter sw = new StringWriter()) {
            sw.WriteLine("using System; using System.Collections.Generic; using System.IO; using System.Web;");
            sw.WriteLine("public static class Template {");
            sw.WriteLine("public static void Convert(TextWriter tw, Dictionary<object, object> args) {");
            int index = 0;
            while (0 <= index &amp;&amp; index < code.Length) {
                int i = code.IndexOf("<%", index);
                sw.WriteLine("tw.Write(\"{0}\");", EscapeString(i < 0 ? code.Substring(index) : code.Substring(index, i - index)));
                if (0 <= i) {
                    i += 2;
                    int i2 = code.IndexOf("%>", i);
                    if (0 <= i2) {
                        string cc = code.Substring(i, i2 - i);
                        if (cc.StartsWith("="))
                            sw.WriteLine("tw.Write(HttpUtility.HtmlEncode(\"\"+({0})));", cc.Substring(1));
                        else
                            sw.WriteLine(cc);
                        i = i2 + 2;
                    }
                }
                index = i;
            }
            sw.WriteLine("}}");
            return sw.ToString();
        }
    }
    private static string EscapeString(string code) {
        return code.Replace("\\", "\\e").Replace("\"", "\\\"").Replace("\t", "\\t").Replace("\n", "\\n").Replace("\r", "\\r").Replace("\\e", "\\\\");
    }
}

サンプル C# コード。ためしにテンプレートから Xml 生成して、標準出力してみる。

class Program {
    static void Main(string[] args) {
        ConvertTemplateDelegate func = TemplateGenerator.Generate(TemplateEngine.Resource1.template);
        using (StringWriter sw = new StringWriter()) {
            Dictionary<object, object> arg = new Dictionary<object, object>();
            arg["title"] = "template sample";
            arg["data"] = new string[] { "foo", "fooo", "<strong>foooooooooo!</strong>" };
            func(sw, arg);
            Console.WriteLine(sw);
        }
    }
}

サンプルテンプレート

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title><%= args["title"] %></title>
  </head>
  <body>
    <h1><%= args["title"] %></h1>
    <table>
<% string[] data = (string[]) args["data"]; %>
<% for(int i = 0; i < data.Length; i++) { %>
      <tr bgcolor="<%= i % 2 == 0 ? "#FFCCCC" : "#CCCCFF" %>">
        <td><%= i %></td>
        <td><%= data[i] %></td>
      </tr>
<% } %>
    </table>
  </body>
</html>

出力例

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>template sample</title>
  </head>
  <body>
    <h1>template sample</h1>
    <table>


      <tr bgcolor="#FFCCCC">
        <td>0</td>
        <td>foo</td>
      </tr>

      <tr bgcolor="#CCCCFF">
        <td>1</td>
        <td>fooo</td>
      </tr>

      <tr bgcolor="#FFCCCC">
        <td>2</td>
        <td>&lt;strong&gt;foooooooooo!&lt;/strong&gt;</td>
      </tr>

    </table>
  </body>
</html>

CodeDom 使って動的コンパイル……って、このコードのままだとセキュリティ的に大問題な気がするな。

素直に ASP.NET 使ったほうが楽だと直感した。

あと EscapeString すっごく自信ない。たぶん修正が必要だと思うw

ログイン ユーザー登録
ようこそ ゲスト さん