2012年12月28日金曜日

追加課題(12/28)

追加課題
見出し1見出し2見出し3見出し4見出し5
内容11内容12内容13内容14内容15
内容21内容22内容23内容24内容25
内容31内容32内容33内容34内容35
内容41内容42内容43内容44内容45
内容51内容52内容53内容54内容55

既存のエクセル内の表に対して
 A.一番上の行を見出し行と見なし,黒背景白文字ボールドセンタリングを行う
 B.2行目以下について,偶数行と奇数行で背景色を交互に塗り分け
を実現
ここで,実装するべき機能は
 1.選択されたセルを開始位置として,そこから表が続く限り処理を繰り返す
   (表が終われば処理終了)
 2.1つめのif文で1行目か否かを判別し,1行目ならばAの処理を実行
 3.2つめのif文で2行目移行と判別できたら,その行が奇数行か偶数行か判別
  3-1.奇数行だった場合,少し薄めの色で背景を塗る
 3-2.偶数行だった場合,奇数行よりも少し濃いめの色で背景を塗る
です.


1.横方向に移動し,セルの内容を表示するプログラム
Sub ironuri1()
    Do While Not (ActiveCell.Value = "")
        MsgBox ActiveCell.Value
        ActiveCell.Offset(0, 1).Select
    Loop
End Sub
2.縦方向に移動し,セルの内容を表示するプログラム
Sub ironuri2()
    Do While Not (ActiveCell.Value = "")
        MsgBox ActiveCell.Value
        ActiveCell.Offset(1, 0).Select
    Loop
End Sub
3.横方向に移動し,セルの内容を表示するプログラム
  +行末までたどり着いたら自動的に改行
Sub ironuri3()
    Do While Not (ActiveCell.Value = "")
        MsgBox ActiveCell.Value
        ActiveCell.Offset(0, 1).Select
    Loop
    ActiveCell.Offset(1, 0).Select
End Sub
4.横方向に移動し,セルの内容を表示するプログラム
  +行末までたどり着いたら自動的に改行
  +表の左端まで移動
Sub ironuri4()
    Do While Not (ActiveCell.Value = "")
        MsgBox ActiveCell.Value
        ActiveCell.Offset(0, 1).Select
    Loop
    ActiveCell.Offset(1, -5).Select
End Sub
5.横方向に移動し,セルの内容を表示するプログラム
  +行末までたどり着いたら自動的に改行
  +「任意の大きさの」表の左端まで移動
Sub ironuri5()
    Dim i As Integer
    i = 1
    Do While Not (ActiveCell.Value = "")
        MsgBox ActiveCell.Value
        ActiveCell.Offset(0, 1).Select
        i = i + 1
    Loop
    ActiveCell.Offset(1, (-i + 1)).Select
End Sub
6.横方向に移動し,セルの内容を表示するプログラム
  +行末までたどり着いたら自動的に改行
  +「任意の大きさの」表の左端まで移動
  +移動後の行に対しても同様の処理を行う
  =任意の表の各セル全範囲を移動し,セルの内容を表示するプログラム
Sub ironuri6()
    Do While Not (ActiveCell.Value = "")
        Dim i As Integer
        i = 1
        Do While Not (ActiveCell.Value = "")
            MsgBox ActiveCell.Value
            ActiveCell.Offset(0, 1).Select
            i = i + 1
        Loop
        ActiveCell.Offset(0, (-i + 1)).Select
        ActiveCell.Offset(1, 0).Select
    Loop
End Sub
7.任意の表の各セル全範囲を移動し,セルの内容を表示するプログラム
  +行数把握
Sub ironuri7()
    Dim j As Integer
    j = 1
    Do While Not (ActiveCell.Value = "")
        Dim i As Integer
        i = 1
        Do While Not (ActiveCell.Value = "")
            MsgBox ActiveCell.Value & ", " & j & "行目"
            ActiveCell.Offset(0, 1).Select
            i = i + 1
        Loop
        ActiveCell.Offset(0, (-i + 1)).Select
        ActiveCell.Offset(1, 0).Select
        j = j + 1
    Loop
End Sub
8.任意の表の各セル全範囲を移動し,セルの内容を表示するプログラム
  +行数把握
  +1行目とその他の行で処理分岐
Sub ironuri8()
    Dim j As Integer
    j = 1
    Do While Not (ActiveCell.Value = "")
        Dim i As Integer
        i = 1
        Do While Not (ActiveCell.Value = "")
            If j = 1 Then
                MsgBox ActiveCell.Value & ", " & j & "行目(見出し行です)"
            Else
                MsgBox ActiveCell.Value & ", " & j & "行目(見出し行ではありません)"
            End If
            ActiveCell.Offset(0, 1).Select
            i = i + 1
        Loop
        ActiveCell.Offset(0, (-i + 1)).Select
        ActiveCell.Offset(1, 0).Select
        j = j + 1
    Loop
End Sub
9.任意の表の各セル全範囲を移動し,セルの内容を表示するプログラム
  +行数把握
  +1行目とその他の行で処理分岐
  +2行目以降の奇数行・偶数行で処理分岐
Sub ironuri9()
    Dim j As Integer
    j = 1
    Do While Not (ActiveCell.Value = "")
        Dim i As Integer
        i = 1
        Do While Not (ActiveCell.Value = "")
            If j = 1 Then
                MsgBox ActiveCell.Value & ", " & j & "行目(見出し行です)"
            Else
                If (j Mod 2) = 1 Then
                    MsgBox ActiveCell.Value & ", " & j & "行目(見出し行ではありません)(奇数行)"
                Else
                    MsgBox ActiveCell.Value & ", " & j & "行目(見出し行ではありません)(偶数行)"
                End If
            End If
            ActiveCell.Offset(0, 1).Select
            i = i + 1
        Loop
        ActiveCell.Offset(0, (-i + 1)).Select
        ActiveCell.Offset(1, 0).Select
        j = j + 1
    Loop
End Sub
10.任意の表の各セル全範囲を移動し,セルの内容を表示するプログラム
   +行数把握
   +1行目とその他の行で処理分岐
   +2行目以降の奇数行・偶数行で処理分岐
   +各行にあわせた処理を記述
Sub ironuri10()
    Dim j As Integer
    j = 1
    Do While Not (ActiveCell.Value = "")
        Dim i As Integer
        i = 1
        Do While Not (ActiveCell.Value = "")
            If j = 1 Then
                MsgBox ActiveCell.Value & ", " & j & "行目(見出し行です)"
                ActiveCell.Font.Bold = True
                ActiveCell.Font.ColorIndex = 2
                ActiveCell.Interior.ColorIndex = 1
            Else
                If (j Mod 2) = 1 Then
                    MsgBox ActiveCell.Value & ", " & j & "行目(見出し行ではありません)(奇数行)"
                    ActiveCell.Interior.ColorIndex = 15
                    ActiveCell.BorderAround ColorIndex:=1
                Else
                    MsgBox ActiveCell.Value & ", " & j & "行目(見出し行ではありません)(偶数行)"
                    ActiveCell.Interior.ColorIndex = 48
                    ActiveCell.BorderAround ColorIndex:=1
                End If
            End If
            ActiveCell.Offset(0, 1).Select
            i = i + 1
        Loop
        ActiveCell.Offset(0, (-i + 1)).Select
        ActiveCell.Offset(1, 0).Select
        j = j + 1
    Loop
End Sub

2012年12月25日火曜日

Select-Caseステートメント SAMPLE(Excel VBA)

shiken3()
Sub shiken3()
    Dim tensuu As Integer
    tensuu = Range("C26").Value
    If tensuu >= 80 Then
        MsgBox "合格です"
    Else
        If tensuu >= 60 Then
            MsgBox "追試です"
        Else
            MsgBox "不合格です"
        End If
    End If
End Sub

waribiki()
Sub waribiki()
    Dim kingaku As Currency
    kingaku = Range("C33").Value
    If Range("D33").Value = "一般" Then
        If kingaku >= 50000 Then
            MsgBox "一般:15%割引です"
        Else
            If kingaku >= 30000 Then
                MsgBox "一般:10%割引です"
            Else
                If kingaku >= 10000 Then
                    MsgBox "一般:5%割引です"
                Else
                    MsgBox "一般:割引なしです"
               End If
            End If
        End If
    Else
        If Range("D33").Value = "会員" Then
            If kingaku >= 50000 Then
                MsgBox "会員:30% 割引です"
            Else
                If kingaku >= 30000 Then
                    MsgBox "会員:20%割引です"
                Else
                    If kingaku >= 10000 Then
                        MsgBox "会員:10%割引です"
                    Else
                        MsgBox "会員:割引なしです"
                    End If
                End If
            End If
        End If
    End If
End Sub

iro()
Sub iro()
    Select Case Range("C34").Value
    Case "RED"
        strIro = "RED"
    Case "BLUE"
        strIro = "BLUE"
    Case "PINK"
        strIro = "PINK"
    Case "GREEN"
        strIro = "GREEN"
    Case Else
        strIro = "RED.BLUE.PINK.GREENのいずれかを入力してください"
    End Select
        MsgBox strIro
End Sub

2012年10月25日木曜日

WEBアプリケーションサーバの構築(6) crontab

1.Shell Scriptエラー処理 前回のツールを動作させる前提として「img」ディレクトリが必要だが,もし存在しないとうまく動作しない.
そこで,「img」ディレクトリの存在有無をチェックし,もし存在しない場合は,ディレクトリを作成するようにツールを編集する.
get_image2.sh
#!/bin/bash

for user in `ls /home`
do
    id $user > /dev/null 2>&1
    if [ $? -eq 0 ] && [ ! -d /home/$user/public_html ]; then
        mkdir -p /home/$user/public_html
        chown $user. /home/$user/public_html
        chmod 711 /home/$user
        echo $user
    fi
done


2.crontabの利用 逆方向も試してみよう
WEBから受け取った値...天気予報の予報値や,特定サイトの値...を,
シェルスクリプトでDBサーバに自動登録.
さらにcrontabを使って,定期的に自動実行.
登録された値はHTMLファイルで閲覧可能なものを作成.
#goo天気の場合
#元ファイル取得
# wget http://weather.goo.ne.jp/area/4610.rdf
#時刻
# grep lastBuildDate 4610.rdf | sed -e "s/\(.*\)<\/lastBuildDate>/\1/g"
#天気
# grep description 4610.rdf | sed -e "s/\(.*\)<\/description>/\1/g"

#Yahoo天気の場合
#元ファイル取得
 wget http://rss.weather.yahoo.co.jp/rss/days/4410.xml
#時刻
 grep lastBuildDate 4410.xml | sed -e "s/\(.*\)<\/lastBuildDate>/\1/g"
#現在の天気と気温を抽出
 grep -n description 4410.xml | grep ^13 | sed -e "s/\(.*\)<\/description>/\1/" | sed "s/\s//g" | sed "s/^.*-//g" | sed "s/\/.*$//g"

1.SQL文を用意
vi temp.sql
 insert into temp (temp) values (10);

2.1で作成したファイルを用いてMySQLへ値流し込み
mysql -u root -s test < temp.sql

3.temp.sqlの値を自動的に更新するシェルスクリプトを作成
temp.sql
 #!/bin/sh
 echo "insert into temp (temp) values (10);" > temp.sql
 /usr/bin/mysql -u root -s test < temp.sql
 exit 0

chmod u+x temp.sql
./temp.sql

4.temp.sqlの中身を自動的に変更する.
temp.sql
 !/bin/sh
 wget http://rss.weather.yahoo.co.jp/rss/days/4410.xml
 str_temp=`grep -n description 4410.xml | grep ^13 | sed -e "s/\(.*\)<\/description>/\1/" | sed "s/\s//g" | sed "s/^.*-//g" | sed "s/\/.*$//g"`
 echo 'insert into temp (temp) values ("'$str_temp'");' > temp.sql
 /usr/bin/mysql -u root -s test < temp.sql
 rm 4410.xml
 exit 0

5.対象とする地域を複数とする.
ファイル名の下2桁目が可変 ---> 4410.xml/4420.xml/4430.xml ... ---> 44*0.xmlの*が1~9まで変化

2012年10月18日木曜日

WEBアプリケーションサーバの構築(5) Shell Script

1.Google画像検索APIの利用
http://ajax.googleapis.com/ajax/services/search/images?q=sato&v=1.0&rsz=1


2.Google画像検索API + shellの利用
curl -s 'http://ajax.googleapis.com/ajax/services/search/images?q=sato&v=1.0&rsz=1' | tr , \\n | grep "url" | sed -e 's/"url"://g' -e 's/"//g'
→Google画像検索の1番最初にマッチした画像のURLが表示される.

3.ツールの作成

get_image.sh
#!/bin/sh

target_list=`/usr/bin/mysql -u root -p[password] arts -e "select name from sa2012"`

for name in $target_list
do
        image_url=`curl -s 'http://ajax.googleapis.com/ajax/services/search/images?q='$name'&v=1.0&rsz=1' | tr , '\\n' | grep "url" | sed -e 's/"url"://g' -e 's/"//g'`

        echo $name" --> "$image_url

        curl -s -o img/$name.jpg $image_url
done

exit 0

※{password}は自自身のパスワードに置き換えること.


4.ツールを使用することで,DBに登録されたユーザの画像を,ユーザー名をファイル名として取得することが可能になったので,リストに画像も併せて表示する.
list6.html
<html>
<head>
    <meta http-equiv=content-type content="text/html; charset=UTF-8">
 <title>real-time search sample(AJAX)</title>
 
 <STYLE TYPE="text/css">
 <!--
 .table1 {
  width: 400px;
  border-collapse: collapse;
  border: 1px #708090 solid;
 }
 .table1 TD {
  border: 1px #708090 solid;
 }
 -->
 </STYLE> 
 
    <script type="text/javascript" src="xmlhttp.js"></script>
    <script type="text/javascript">
    <!--
    findText = findTextOld = "";

    function loadXmlFile(fName){
        httpObj = createXMLHttpRequest(displayData);
        if (httpObj){
            httpObj.open("GET",fName,true);
            httpObj.send(null);
        }
    }

    function displayData(){
        if ((httpObj.readyState == 4) && (httpObj.status == 200)){
            xmlData = httpObj.responseXML;
            $("result").innerHTML = parseXmlData(httpObj.responseText);
        }else{
            $("result").innerHTML = "Loading ...";
        }
    }

    function parseXmlData(xmlData){
        $("result").innerHTML = xmlData;
        idListTags = document.getElementsByTagName("id");
        numListTags = document.getElementsByTagName("num");
        nameListTags = document.getElementsByTagName("name");
        idLen = idListTags.length;

        resultText = "<table class='table1'><tr><th colspan=5>list</th></tr><tr><td><b>id</b></td><td><b>num</b></td><td><b>name</b></td><td><b>image</b></td></tr>";
        for(i=0; i<idLen; i++){
            id = idListTags[i].childNodes[0].nodeValue;
            num = numListTags[i].childNodes[0].nodeValue;
            name = nameListTags[i].childNodes[0].nodeValue;
            str = name.match(findText);
            if (str){
                resultText += "<tr><td>" + id + "</td><td><a href='http://10.2.5." + num + "' target='_blank'>" + num + "</a></td><td>" + name + "</td><td><img height=100 width=100 src='img/" + name + ".jpg'></td></tr>";
            }
        }
        resultText += "</table>";
        return resultText;
    }

    function inputCheck(){
        findText = document.ajaxForm.requestText.value;
        if (findText != findTextOld) {
            str_search = "./backend.php?search_key=" + findText
            loadXmlFile(str_search);
            findTextOld = findText;
        }else{
//            $("result").innerHTML = "Loading ...";
        }
        setTimeout(" inputCheck()",500); // 0.5秒毎
    }

    window.onload = inputCheck;
    // -->
    </script>
</head>
<body>
<form name="ajaxForm" onSubmit="return false">
<input type="text" value="a" name="requestText">
</form>
<div id="result"></div>
</body>
</html>

2012年10月11日木曜日

WEBアプリケーションサーバの構築(4) AJAX

フォームにAJAXを使った画面を作成.

xmlhttp.js
// HTTP通信用、共通関数
function createXMLHttpRequest(cbFunc){
 var XMLhttpObject = null;
 try{
  XMLhttpObject = new XMLHttpRequest();
 }catch(e){
  try{
   XMLhttpObject = new ActiveXObject("Msxml2.XMLHTTP");
  }catch(e){
   try{
    XMLhttpObject = new ActiveXObject("Microsoft.XMLHTTP");
   }catch(e){
    return null;
   }
  }
 }
 if (XMLhttpObject) XMLhttpObject.onreadystatechange = cbFunc;
 return XMLhttpObject;
}
 
// document.getElementById
function $(tagId){
 return document.getElementById(tagId);
}

backend.php
<?php
 $db_user  = "[user name]";
 $db_password = "[password]";
 $db_name = "[database name]";
 $db_host  = "localhost";

//create xml
    header('Content-type: text/xml; charset=utf-8');
    echo '<?xml version="1.0"?><sa>';

 $search_key = null;

 if(isset($_GET['search_key'])) {
  $search_key = $_GET['search_key'];

  $con = mysql_connect($db_host,$db_user,$db_password) or die("error!");
  mysql_select_db($db_name,$con) or die("DB is not exist");
  $strsql = "SET CHARACTER SET UTF8";
  mysql_query($strsql,$con);
  $strsql = "SELECT id, num, name FROM sa2012 WHERE name LIKE '%".$search_key."%';";
  $res = mysql_query($strsql,$con);

  while ($item = mysql_fetch_array($res)) {
   print "<list><id>".$item[0]."</id><num>".$item[1]."</num><name>".$item[2]."</name></list>";
  }
  mysql_close($con);
    }

    echo '</sa>'; 
?>

list4.html
<html>
<head>
    <meta http-equiv=content-type content="text/html; charset=UTF-8">
 <title>real-time search sample(AJAX)</title>
 
 <STYLE TYPE="text/css">
 <!--
 .table1 {
  width: 400px;
  border-collapse: collapse;
  border: 1px #708090 solid;
 }
 .table1 TD {
  border: 1px #708090 solid;
 }
 -->
 </STYLE> 
 
    <script type="text/javascript" src="xmlhttp.js"></script>
    <script type="text/javascript">
    <!--
    findText = findTextOld = "";

    function loadXmlFile(fName){
        httpObj = createXMLHttpRequest(displayData);
        if (httpObj){
            httpObj.open("GET",fName,true);
            httpObj.send(null);
        }
    }

    function displayData(){
        if ((httpObj.readyState == 4) && (httpObj.status == 200)){
            xmlData = httpObj.responseXML;
            $("result").innerHTML = parseXmlData(httpObj.responseText);
        }else{
            $("result").innerHTML = "Loading ...";
        }
    }

    function parseXmlData(xmlData){
        $("result").innerHTML = xmlData;
        idListTags = document.getElementsByTagName("id");
        numListTags = document.getElementsByTagName("num");
        nameListTags = document.getElementsByTagName("name");
        idLen = idListTags.length;

        resultText = "<table class='table1'><tr><th colspan=4>list</th></tr><tr><td><b>id</b></td><td><b>num</b></td><td><b>name</b></td></tr>";
        for(i=0; i<idLen; i++){
            id = idListTags[i].childNodes[0].nodeValue;
            num = numListTags[i].childNodes[0].nodeValue;
            name = nameListTags[i].childNodes[0].nodeValue;
            str = name.match(findText);
            if (str){
                resultText += "<tr><td>" + id + "</td><td><a href='http://10.2.5." + num + "' target='_blank'>" + num + "</a></td><td>" + name + "</td></tr>";
            }
        }
        resultText += "</table>";
        return resultText;
    }

    function inputCheck(){
        findText = document.ajaxForm.requestText.value;
        if (findText != findTextOld) {
            str_search = "./backend.php?search_key=" + findText
            loadXmlFile(str_search);
            findTextOld = findText;
        }else{
//            $("result").innerHTML = "Loading ...";
        }
        setTimeout(" inputCheck()",500); // 0.5秒毎
    }

    window.onload = inputCheck;
    // -->
    </script>
</head>
<body>
<form name="ajaxForm" onSubmit="return false">
<input type="text" value="s" name="requestText">
</form>
<div id="result"></div>
</body>
</html>

2012年10月4日木曜日

WEBアプリケーションサーバの構築(3) PHP

HTMLのフォームから値を受け取り,合致したidのみ表示する画面を作成.

list3_form.html
<html>
<head>
 <title>form</title>
</head>
<body>
 <form action="list3.php" method="get">
  id : <input type="text" name="id" />
  <input type="submit" />
 </form>
</body>
</html>

list3.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>list</title>
</head>
<body>
<?php
 $id = htmlspecialchars($_GET['id']);

 $db_user  = "[user name]";
 $db_password = "[password]";
 $db_name = "[database name]";
 $db_host  = "localhost";

 $db = mysql_connect($db_host,$db_user,$db_password);
 mysql_select_db($db_name,$db); 
 $str_sql = "select * from sa2012 where id = ".$id;
 $rs = mysql_query($str_sql,$db);
 $num = mysql_num_fields($rs);

 print("<table><tr><th colspan=3>list</th></tr>");
 echo("
 ");
 print("<tr>");
 for ($i=0;$i<$num;$i++){
  print("<td><b>".mysql_field_name($rs,$i)."</b></td>");
 }
 print("</tr>");
 while($row=mysql_fetch_array($rs)){
  echo("
 ");
  print("<tr>");
  for($j=0;$j<$num;$j++){
   print("<td>".$row[$j]."</td>");
  }
  print("</tr>");
 }

 print("</table>");

 mysql_free_result($rs);
 mysql_close($db);
?>
</body>
</html>

2012年9月27日木曜日

WEBアプリケーションサーバの構築(2) DBサーバ

1.php-mysqlモジュールをインストール
yum install php-mysql
service httpd stop
service httpd start
service mysqld stop
mysql_secure_installation
/etc/my.cnf
 [mysql] 
 default_character_set=utf8 

 [mysqld] 
 character_set-server=utf8 
 innodb_log_file_size=64M 
 innodb_buffer_pool_size=128M
service mysqld start


2.MySQLにデータベース,テーブル作成
DB Name : arts
Table Name : sa2012

$ mysql -u root -p
create database arts;

$ mysql -u root -p sa
create table sa2012 ( id integer NOT NULL AUTO_INCREMENT PRIMARY KEY, num char(4), host_name char(20), ip_address char(15) );

show tables;
select * from sa2012;

※テーブルの各値はMySQL Workbench等から流し込みます.

3.DBに接続し,中身を表示するPHPファイルを作成
list.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>list</title>
</head>
<body>
<?php
 $db_user  = "[user name]";
 $db_password = "[password]";
 $db_name = "[database name]";
 $db_host  = "localhost";

 $db = mysql_connect($db_host,$db_user,$db_password);
 mysql_select_db($db_name,$db); 
 $str_sql = "select * from sa2012";
 $rs = mysql_query($str_sql,$db);
 $num = mysql_num_fields($rs);

 print("<table><tr><th colspan=3>list</th></tr>");
 echo("
 ");
 print("<tr>");
 for ($i=0;$i<$num;$i++){
  print("<td><b>".mysql_field_name($rs,$i)."</b></td>");
 }
 print("</tr>");
 while($row=mysql_fetch_array($rs)){
  echo("
 ");
  print("<tr>");
  for($j=0;$j<$num;$j++){
   print("<td>".$row[$j]."</td>");
  }
  print("</tr>");
 }

 print("</table>");

 mysql_free_result($rs);
 mysql_close($db);
?>
</body>
</html>

4.パーミッションを755に変更
chmod 755 list.php


5.DBに接続し,id=1のものだけを表示するPHPファイルを作成
list2.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>list</title>
</head>
<body>
<?php
 $db_user  = "[user name]";
 $db_password = "[password]";
 $db_name = "[database name]";
 $db_host  = "localhost";

 $db = mysql_connect($db_host,$db_user,$db_password);
 mysql_select_db($db_name,$db); 
 $str_sql = "select * from sa2012 where id = 1";
 $rs = mysql_query($str_sql,$db);
 $num = mysql_num_fields($rs);

 print("<table><tr><th colspan=3>list</th></tr>");
 echo("
 ");
 print("<tr>");
 for ($i=0;$i<$num;$i++){
  print("<td><b>".mysql_field_name($rs,$i)."</b></td>");
 }
 print("</tr>");
 while($row=mysql_fetch_array($rs)){
  echo("
 ");
  print("<tr>");
  for($j=0;$j<$num;$j++){
   print("<td>".$row[$j]."</td>");
  }
  print("</tr>");
 }

 print("</table>");

 mysql_free_result($rs);
 mysql_close($db);
?>
</body>
</html>

2012年9月13日木曜日

WEBアプリケーションサーバの構築(1) WEBサーバ

1.まずはブラウザから自身のサーバにアクセスして状況確認
http://10.2.5.***


2.PHPインストール
yum install php
/etc/php.ini
memory_limit = 16M ; Maximum amount of memory a script may consume
3.Webサーバ(httpd)インストール
yum install httpd
chkconfig httpd on
service httpd start

4.Firewall設定
iptablesのルール初期化
/sbin/iptables -F

現在のルール確認
iptables -L

Firewallにルール追加
/etc/sysconfig/iptables
 # Firewall configuration written by system-config-firewall
 # Manual customization of this file is not recommended.
 *filter
 :INPUT ACCEPT [0:0]
 :FORWARD ACCEPT [0:0]
 :OUTPUT ACCEPT [0:0]
 -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
 -A INPUT -p icmp -j ACCEPT
 -A INPUT -i lo -j ACCEPT
 -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
 -A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
 -A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT
 -A INPUT -j REJECT --reject-with icmp-host-prohibited
 -A FORWARD -j REJECT --reject-with icmp-host-prohibited
 COMMIT

service iptables restart

5.動作確認
ブラウザから以下のアドレスにアクセスし,テスト画面が表示されることを確認
http://10.2.5.***

2012年9月6日木曜日

各ユーザーのhome以下にpublic_htmlを作成するツール

userDirMake.sh
#!/bin/bash

for user in `ls /home`
do
    id $user > /dev/null 2>&1
    if [ $? -eq 0 ] && [ ! -d /home/$user/public_html ]; then
        mkdir -p /home/$user/public_html
        chown $user. /home/$user/public_html
        chmod 711 /home/$user
        echo $user
    fi
done

仮想環境(ESXi4)の準備

学生用仮想環境
10.2.5.2共有サーバ(1学期使用)
10.2.5.101折笠orikasa00:50:56:00:01:01
10.2.5.102金本kanemoto00:50:56:00:01:02
10.2.5.103鈴木suzuki00:50:56:00:01:03
10.2.5.104西崎nishizaki00:50:56:00:01:04
10.2.5.105西村nishimura00:50:56:00:01:05
10.2.5.106マナハンmanahan00:50:56:00:01:06
10.2.5.107荒井arai00:50:56:00:01:07
10.2.5.108小沼onuma00:50:56:00:01:08
10.2.5.109小谷田koyata00:50:56:00:01:09
10.2.5.110城田shirota00:50:56:00:01:10
10.2.5.111中山nakayama00:50:56:00:01:11
10.2.5.112萩原hagiwara00:50:56:00:01:12
10.2.5.113花山hanayama00:50:56:00:01:13
10.2.5.114樋口higuchi00:50:56:00:01:14
10.2.5.115船谷funaya00:50:56:00:01:15
10.2.5.116星野hoshino00:50:56:00:01:16
10.2.5.117間宮mamiya00:50:56:00:01:17
10.2.5.118佐藤mgrsato00:50:56:00:01:18


1.仮想イメージコピー後に,IPアドレス修正
(IPアドレスをコピー元の値から、各学生用のIPアドレスに変更する)

/etc/udev/rules.d/70-persistent-net.rules
 (最後尾のPCI deviceのみ残す)


/etc/sysconfig/network-scripts/ifcfg-eth0
 DEVICE=eth0
 BOOTPROTO=none
 ONBOOT=yes
 IPADDR=10.2.5.***
 NETMASK=255.0.0.0
 GATEWAY=10.1.0.1


2.VMware Toolsのインストール
mkdir /mnt/cdrom
mount /dev/cdrom /mnt/cdrom
cd /mnt/cdrom
cp VMwareTools-XXX.tar.gz /tmp
cd /tmp
tar zxvf VMwareTools-XXX.tar.gz
cd vmware-tools-distrib
./vmware-install.pl


3.DNS設定
/etc/resolv.conf
 nameserver 8.8.8.8
service network restart
yum update
yum install perl
yum install yum-fastestmirror
yum install yum-utils

2012年6月22日金曜日

DBから値を取得してFLASH上で利用する方法


20111021.swf

HTMLファイルに値を埋め込み,URL引数渡しする方法では,他ユーザーとリアルタイムに値を共有することができない.
そこで今後は,データベース(以下DB)に全ユーザーの値を集約し,その値をSWFで利用する事とする. 

今回はFlashからDBに直接接続しSQLを発行する方法ではなく,FlashからDBとの仲介役となるPHPファイルに接続し,DBに問い合わせた結果をFlashがXML形式で受け取る方法について説明する.

1.ブラウザを用いて以下の取得先URLにアクセスし,自身のユーザー名/パスワードを用いて値が取得できるか確認.
(取得されるデータはXML形式のため,ページのソースを表示で内容確認)
取得先URL
http://www14026u.sakura.ne.jp/ma/2011/9/status.php?user_name="ユーザー名"&user_pass="パスワード"

2.自身のユーザー名/パスワードを用いて固有の値(ユーザー毎のmoneyとitemの値)を取得できることが確認できたら,現在作成しているFlaファイルに1で取得出来るmoneyの値が反映されるように修正.
Flashの中でユーザー名・パスワードを用いてサーバー上のXMLを取得し,その中に含まれるmoney,kanaの値をステージ上に表示する.

ActionScript(windowレイヤー)
//status_mc.name = _root.name;
//status_mc.money = _root.money;

var db_username = "ユーザー名";
var db_password = "パスワード";
status_xml = new XML();
status_xml.onLoad = userStatus;
status_xml.load("http://www14026u.sakura.ne.jp/ma/2011/9/status.php?user_name='"+db_username+"'&user_pass='"+db_password+"'");
status_xml.ignoreWhite = true;
function userStatus(success) {
 if (success == true) {
  status_mc.money = status_xml.firstChild.firstChild.firstChild.firstChild.nodeValue;
  status_mc.name = status_xml.firstChild.firstChild.firstChild.nextSibling.nextSibling.firstChild.nodeValue;

  //debug
  trace(status_xml.nodeValue);
  trace(status_xml.firstChild.nodeValue);
  trace(status_xml.firstChild.firstChild.nodeValue);
  trace(status_xml.firstChild.firstChild.firstChild.nodeValue);
  trace(status_xml.firstChild.firstChild.firstChild.firstChild.nodeValue);
  trace(status_xml.firstChild.firstChild.firstChild.nextSibling.firstChild.nodeValue);
  trace(status_xml.firstChild.firstChild.firstChild.nextSibling.nextSibling.firstChild.nodeValue);
 }
}

status_mc._visible = false;
window_status = 1;
var key_obj:Object = new Object();
key_obj.onKeyDown = function():Void  {
 var code = Key.getCode();
 if (code == Key.SPACE) {
  if (window_status == 0) {
   status_mc._visible = false;
   window_status = 1;
  } else if (window_status == 1) {
   status_mc._visible = true;
   window_status = 0;
  }
 }
};
Key.addListener(key_obj);


(参考)DBに接続し,ユーザーのstatusを返すPHP
<?php
 $db_user  = "ユーザー名";
 $db_password = "パスワード";
 $db_name = "DB名";
 $db_host  = "接続先サーバ名";

//create xml
    header('Content-type: text/xml; charset=utf-8');
    echo '<?xml version="1.0"?><ma>';

 $user_name = null;
 $user_pass = null;

 if(isset($_GET['user_name'])) {
  $user_name = $_GET['user_name'];
  $user_pass = $_GET['user_pass'];

  $con = mysql_connect($db_host,$db_user,$db_password) or die("error!");
  mysql_select_db($db_name,$con) or die("DB is not exist");
  $strsql = "SET CHARACTER SET UTF8";
  mysql_query($strsql,$con);
  $strsql = "SELECT money, item FROM 2011_users WHERE name = $user_name AND pass = $user_pass;";
  $res = mysql_query($strsql,$con);

  while ($item = mysql_fetch_array($res)) {
   print "<user_status><money>".$item[0]."</money><item>".$item[1]."</item></user_status>";
  }
  mysql_close($con);
}

    echo '</ma>'; 
?>


ダウンロード1

2012年6月21日木曜日

WebAPIの利用(6)

WebAPIの利用(5)に,情報ウインドウ表示機能を追加する.
現状では情報ウインドウに特定の文字列を表示しているのみだが,ユーザーから受け取った場所を示す文字列「$word」を活用して,その場所固有の情報を表示するように各自工夫する事.
例)WebAPIの利用(2)を応用し,その地点の天気,最高/最低気温を表示

map_xmlParse2.php
<?php
$word = htmlspecialchars($_POST['word']);
$sensor = htmlspecialchars($_POST['sensor']);
$url = "http://maps.google.com/maps/api/geocode/xml";
$url .= "?address=".$word."&sensor=".$sensor;
$article = simplexml_load_file($url);

$lat = $article->result->geometry->location->lat;
$lng = $article->result->geometry->location->lng;

print<<<EOF
<html>
 <head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  <title>Google Geocoding and Maps JavaScript API Example</title>
  <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text
  /css" />
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.3&sensor=true"></script>
  <script type="text/javascript">
  function initialize() {
   var myLatlng = new google.maps.LatLng($lat, $lng);

   var myOptions = {
    zoom: 15,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
   };

   var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

   var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: '$word'
   });

   var contentStr = 'test';

   var infowindow = new google.maps.InfoWindow({
    content: contentStr,
    size: new google.maps.Size(50, 50)
   });

   google.maps.event.addListener(marker, 'click', function() {
   infowindow.open(map,marker)
   });
  }
  </script>
 </head>
 <body onload="initialize()">
  <div id="map_canvas"></div>
 </body>
</html>
EOF;
?>

情報ウインドウに天気を表示する例
<?php
$word = htmlspecialchars($_POST['word']);
$sensor = htmlspecialchars($_POST['sensor']);
$url = "http://maps.google.com/maps/api/geocode/xml";
$url .= "?address=".$word."&sensor=".$sensor;
$article = simplexml_load_file($url);

$lat = $article->result->geometry->location->lat;
$lng = $article->result->geometry->location->lng;

// get weather
$url2 = "http://www.google.com/ig/api?weather=".$word;
$xml = simplexml_load_file($url2);

$city = $xml->weather->forecast_information->city->attributes();
$forecast_date = $xml->weather->forecast_information->forecast_date->attributes();
$unit_system = $xml->weather->forecast_information->unit_system->attributes();

$current_condition = $xml->weather->current_conditions->condition->attributes();
$temp_c = $xml->weather->current_conditions->temp_c->attributes();
$humidity = $xml->weather->current_conditions->humidity->attributes();
$current_icon = $xml->weather->current_conditions->icon->attributes();
$wind_condition = $xml->weather->current_conditions->wind_condition->attributes();

print<<<EOF
<html>
<head>
 <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
 <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
 <title>Google Geocoding and Maps JavaScript API Example</title>
 <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text
 /css" />
 <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.3&sensor=true"></script>
 <script type="text/javascript">
 function initialize() {
  var myLatlng = new google.maps.LatLng($lat, $lng);

  var myOptions = {
   zoom: 15,
   center: myLatlng,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  var marker = new google.maps.Marker({
   position: myLatlng,
   map: map,
   title: '$word'
  });

  var contentStr = '$city($forecast_date)[$unit_system]<br />現在の状況:$current_condition<br />気温:$temp_c<br />湿度:$humidity<br /><img src="http://www.google.com$current_icon"><br />風向:$wind_condition';

  var infowindow = new google.maps.InfoWindow({
   content: contentStr,
   size: new google.maps.Size(50, 50)
  });

  google.maps.event.addListener(marker, 'click', function() {
   infowindow.open(map,marker)
  });
 }
 </script>
</head>
<body onload="initialize()">
 <div id="map_canvas"></div>
</body>
</html>
EOF;
?>

WebAPIの利用(5)

WebAPIの利用(4)を更に発展させ,ユーザーが入力した任意の文字列から座標を検索し,地図を表示する.

1.ユーザーが文字列を入力する画面(map_form.html)を用意.
2.画面に配置された送信ボタンを押すことで,postメソッドにより文字列を送信.
3.送信された文字列をphpファイル(map_xmlParse2.php)で受け取り.
4.受け取った文字列を用いて,マッチする座標を検索
5.座標を使って地図を表示.

表示例

LINK

map_form.html
<html>
<head>
 <title>form sample</title>
</head>
<body>
 <form action="map_xmlParse2.php" method="post">
  座標を調べたい文字列 : <input type="text" name="word" />
  <input type="hidden" name="sensor" value="true" />
  <input type="submit" />
 </form>
</body>
</html>

map_xmlParse2.php
<?php
 $word = htmlspecialchars($_POST['word']);
 $sensor = htmlspecialchars($_POST['sensor']);
 $url = "http://maps.google.com/maps/api/geocode/xml";
 $url .= "?address=".$word."&sensor=".$sensor;
 $article = simplexml_load_file($url);

 $lat = $article->result->geometry->location->lat;
 $lng = $article->result->geometry->location->lng;

print<<<EOF
 <html>
 <head>
 <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
 <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
 <title>Google Geocoding and Maps JavaScript API Example</title>
 <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
 <script type="text/javascript">
   function initialize() {
     var myLatlng = new google.maps.LatLng(
EOF;
 echo $lat;
 echo ", ";
 echo $lng;
print<<<EOF
     );

     var myOptions = {
       zoom: 15,
       center: myLatlng,
       mapTypeId: google.maps.MapTypeId.ROADMAP
     }
     var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

     var marker = new google.maps.Marker({
       position: myLatlng,
       map: map,
       title:"
EOF;
 echo $word;
print<<<EOF
       "
     });
   }
 </script>
 </head>
 <body onload="initialize()">
   <div id="map_canvas"></div>
 </body>
 </html>
EOF;
?>

Javascriptについて

まずはHello, world.

js_1.html
<html>
 <head>
  <title>Javascript</title>
 </head>
 <body>
  <script type="text/javascript">
   <!--
   document.write("Hello World");
   // -->
  </script>
 </body>
</html>


Javascriptにおける変数の扱いについて.
※Javascriptでは変数を明示的に宣言する場合、var を用います.
※Javascriptでは変数名や関数名などの大文字と小文字は別の文字として扱われます.

js_2.html
<html>
 <head>
  <title>サンプル</title>
 </head>
 <body>
  <script type="text/javascript">
   <!--
   str = "small letter";
   STR = "CAPITAL LETTER";
   document.write(str + STR);
   // -->
  </script>
 </body>
</html>


PHPとJavascriptを組み合わせて利用.
※PHPはサーバーサイドで実行され,Javascriptはクライアントサイドで実行される事に注意.

js_3.php
<?php
$str = "Hello World";

print<<<EOL
<html>
 <head>
  <title>Javascript</title>
 </head>
 <body>
  <script type="text/javascript">
   <!--
   document.write($str);
   // -->
  </script>
 </body>
</html>
EOL;

?>

2012年6月14日木曜日

WebAPIの利用(4)

WebAPIの利用(3)を発展させ,入力した文章中のキーフレーズを画像に置き換えて表示する.
(ユーザーによる)文章入力 →キーフレーズ抽出API →キーフレーズによる画像検索 →元となる文章中のキーフレーズ部分を画像に置換

表示例

LINK

text_form2.html
<html>
 <head>
  <title>text form2</title>
 </head>
 <body>
  <form action="text_xmlParse2.php" method="post">
   変換したい文字列 : <input type="text" name="word" />
  <input type="submit" />
 </form>
 </body>
</html>

text_xmlParse2.php
<?php
$word = htmlspecialchars($_POST['word']);
$appid = "(アプリケーションID)";

$url1 = "http://jlp.yahooapis.jp/KeyphraseService/V1/extract";
$url1 .= "?sentence=".$word."&appid=".$appid;
$article1 = simplexml_load_file($url1);
$keyphrase = $article1->Result->Keyphrase;
$score = $article1->Result->Score;

$url2 = "http://search.yahooapis.jp/ImageSearchService/V2/imageSearch";
$url2 .= "?results=1&query=".$keyphrase."&appid=".$appid;
$article2 = simplexml_load_file($url2);
$image_url = $article2->Result->Url;
$image_thumbnail = $article2->Result->Thumbnail->Url;

print<<<EOF
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>keyphrase replace2</title>
</head>
<body>
EOF;
echo "キーフレーズ:";
echo $keyphrase;

echo "<br />";
echo "スコア:";
echo $score;

echo "<br />";
echo "画像URL:";
echo $image_url;

echo "<br />";
echo "サムネイルURL:";
echo $image_thumbnail;


echo "<br />";
echo "<br />";
echo "元の文章:";
echo $word;

echo "<br />";
echo "<br />";
echo "変換後の文章:";
$temp = str_replace($keyphrase, "<a href=".$image_url."><img src=".$image_thumbnail."></a>", $word);
echo $temp;


print<<<EOF
</body>
</html>
EOF;
?>

WebAPIの利用(3)

Yahoo!のテキスト解析Web APIキーフレーズ抽出を利用して,入力した文章中のキーフレーズを抽出し,そのキーフレーズに対して置換やリンクの付与等を行う.

表示例

LINK

text_form.html
<html>
 <head>
  <title>text form</title>
 </head>
 <body>
  <form action="xmlParse.php" method="post">
   変換したい文字列 : <input type="text" name="word" />
  <input type="submit" />
 </form>
 </body>
</html>

text_xmlParse.php
<?php
$word = htmlspecialchars($_POST['word']);
$appid = "(アプリケーションID)";
$url = "http://jlp.yahooapis.jp/KeyphraseService/V1/extract";
$url .= "?sentence=".$word."&appid=".$appid;
$article = simplexml_load_file($url);

$keyphrase = $article->Result->Keyphrase;
$score = $article->Result->Score;

print<<<EOF
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>keyphrase replace</title>
</head>
<body>
EOF;
echo "キーフレーズ:";
echo $keyphrase;

echo "<br />";
echo "スコア:";
echo $score;

echo "<br />";
echo "元の文章:";
echo $word;

echo "<br />";

echo "<br />";
echo "変換後の文章1:";
$temp1 = str_replace($keyphrase, "<b>禁則事項</b>", $word);
echo $temp1;

echo "<br />";
echo "変換後の文章2:";
$temp2 = str_replace($keyphrase, "<a href=http://www.google.com/search?q=".$keyphrase.">".$keyphrase."</a>", $word);
echo $temp2;

echo "<br />";
echo "変換後の文章3:";
$temp2 = str_replace($keyphrase, "<a href=http://www.google.com/search?tbm=isch&q=".$keyphrase.">".$keyphrase."</a>", $word);
echo $temp2;

print<<<EOF
</body>
</html>
EOF;
?>
※アプリケーションIDの登録はこちら

2012年6月7日木曜日

WebAPIの利用(2)

気象情報(天気予報)APIの利用

表示例

LINK

API URL
http://www.google.com/ig/api?weather=Yokohama,Kanagawa

取得されるXMLのサンプル
<xml_api_reply version="1">
 <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
  <forecast_information>
   <city data="Yokohama, Kanagawa Prefecture"/>
   <postal_code data="Yokohama,Kanagawa"/>
   <latitude_e6 data=""/>
   <longitude_e6 data=""/>
   <forecast_date data="2011-11-17"/>
   <current_date_time data="1970-01-01 00:00:00 +0000"/>
   <unit_system data="SI"/>
  </forecast_information>
  <current_conditions>
   <condition data="ところにより曇り"/>
   <temp_f data="63"/>
   <temp_c data="17"/>
   <humidity data="湿度 : 39%"/>
   <icon data="/ig/images/weather/jp_cloudy.gif"/>
   <wind_condition data="風: 南東 4 m/s"/>
  </current_conditions>
  <forecast_conditions>
   <day_of_week data="木"/>
   <low data="11"/>
   <high data="18"/>
   <icon data="/ig/images/weather/jp_sunny.gif"/>
   <condition data="ところにより晴れ"/>
  </forecast_conditions>
  <forecast_conditions>
   <day_of_week data="金"/>
   <low data="10"/>
   <high data="18"/>
   <icon data="/ig/images/weather/jp_cloudy.gif"/>
   <condition data="曇り"/>
   </forecast_conditions>
  <forecast_conditions>
   <day_of_week data="土"/>
   <low data="16"/>
   <high data="21"/>
   <icon data="/ig/images/weather/jp_rainysometimescloudy.gif"/>
   <condition data="雨の可能性"/>
  </forecast_conditions>
  <forecast_conditions>
   <day_of_week data="日"/>
   <low data="14"/>
   <high data="22"/>
   <icon data="/ig/images/weather/jp_rainysometimescloudy.gif"/>
   <condition data="雨の可能性"/>
  </forecast_conditions>
 </weather>
</xml_api_reply>

weather.php
<?php
 $area = "Yokohama";
 $url = "http://www.google.com/ig/api?weather=".$area;

 $xml = simplexml_load_file($url);

//forecast_information
 $city = $xml->weather->forecast_information->city->attributes();
 $forecast_date = $xml->weather->forecast_information->forecast_date->attributes();
 $unit_system = $xml->weather->forecast_information->unit_system->attributes();

//current_conditions
 $current_condition = $xml->weather->current_conditions->condition->attributes();
 $temp_c = $xml->weather->current_conditions->temp_c->attributes();
 $humidity = $xml->weather->current_conditions->humidity->attributes();
 $current_icon = $xml->weather->current_conditions->icon->attributes();
 $wind_condition = $xml->weather->current_conditions->wind_condition->attributes();

//forecast_conditions
 $day_of_week = $xml->weather->forecast_conditions->day_of_week->attributes();
 $low = $xml->weather->forecast_conditions->low->attributes();
 $high = $xml->weather->forecast_conditions->high->attributes();
 $forecast_icon = $xml->weather->forecast_conditions->icon->attributes();
 $forecast_condition = $xml->weather->forecast_conditions->conditionh->attributes();

print<<<EOF
 <html>
 <head>
 <title>google weather sample</title>
 </head>
 <body>
EOF;

 print "場所:".$city."<br />";
 print "予報日:".$forecast_date."<br />";
 print "単位:".$unit_system."<br />";
 print "<br />";
 print "現在の状況<br />";
 print "状況:".$current_condition."<br />";
 print "気温:".$temp_c."<br />";
 print "湿度:".$humidity."<br />";
 print "<img src='http://www.google.com".$current_icon."'><br />";
 print "風向:".$wind_condition."<br />";
 print "<br />";
 print "明日の天気<br />";
 print "曜日:".$day_of_week."<br />";
 print "最低気温:".$low."<br />";
 print "最高気温:".$high."<br />";
 print "<img src='http://www.google.com".$forecast_icon."'><br />";
 print "状況:".$forecast_condition."<br />";

print<<<EOF
 </body>
 </html>
EOF;
?>

WebAPIの利用(1)

twitter public timeline検索APIの利用
表示例

LINK

取得されるXMLのサンプル(一部抜粋)
<?xml version="1.0" encoding="utf-8"?>
<rss>
 <channel>
   <item>
    <title>@Copa3 ありがとうございます。横浜ですかそりゃ、とおくていけませんわ。</title>
    <link>http://twitter.com/sendaimo/statuses/137026307379822592</link>
    <description>@&lt;a class=" " href="http://twitter.com/Copa3"&gt;Copa3&lt;/a&gt; ありがとうございます。&lt;em&gt;横浜&lt;/em&gt;ですかそりゃ、とおくていけませんわ。</description>
    <pubDate>Thu, 17 Nov 2011 04:36:32 +0000</pubDate>
    <guid>http://twitter.com/sendaimo/statuses/137026307379822592</guid>
    <author>sendaimo@twitter.com (Kimiaki Nagase)</author>
    <media:content type="image/jpg" height="48" width="48" url="http://a0.twimg.com/profile_images/825361762/saxbobo02_normal.gif" xmlns:media="http://search.yahoo.com/mrss/" />
    <google:image_link xmlns:google="http://base.google.com/ns/1.0">http://a0.twimg.com/profile_images/825361762/saxbobo02_normal.gif</google:image_link>
    <twitter:metadata xmlns:twitter="http://api.twitter.com/">
     <twitter:result_type>recent</twitter:result_type>
    </twitter:metadata>
   </item>
 </channel>
</rss>

twitter_timeline.php
<?php
 $word = "横浜";
 $url = "http://search.twitter.com/search.rss?q=".$word;

 $rss = simplexml_load_file($url);

 $title = $rss->channel->item->title;
 $link = $rss->channel->item->link;
 $description = $rss->channel->item->description;
 $pubDate = $rss->channel->item->pubDate;
 $author = $rss->channel->item->author;

print<<<EOF
 <html>
 <head>
 <title>twitter sample</title>
 </head>
 <body>
EOF;

 print "title : ".$title."<br />";
 print "link : ".$link."<br />";
 print "description : ".$description."<br />";
 print "pubDate : ".$pubDate."<br />";
 print "author : ".$author."<br />";
 print "image_link : ".$iage_link."<br />";

print<<<EOF
 </body>
 </html>
EOF;
?>

2012年5月31日木曜日

WEBサーバの利用

1.public_htmlへ移動
# cd public_html
2.index.htmlを作成
# vi index.html

<html>
<head>
<link rel="stylesheet" href="base.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>テスト</title>
<body>
テスト
</body>
</html>
3.base.cssを作成
body {
 font: normal normal 14px Arial, Tahoma, Helvetica, FreeSans, sans-serif;
 color: #000000;
 background: #aabbaa none no-repeat scroll center center;
 font-family:'ヒラギノ角ゴ Pro W3','Hiragino Kaku Gothic Pro','メイリオ',Meiryo,'MS Pゴシック',sans-serif;
}

html body .region-inner {
 min-width: 0;
 max-width: 100%;
 width: auto;
}

.content-outer {
 font-size: 90%;
}

a:link {
 text-decoration:none;
 color: #445566;
}
a:visited {
 text-decoration:none;
 color: #000000;
}
a:hover {
 text-decoration:underline;
 color: #1455ff;
}
4.phpinfo.phpを作成
# vi phpinfo.php

<?php
  phpinfo();
?>

#chmod 755 phpinfo.php
4.Hello, World!
# vi hello.php

<?php
echo "Hello World!";
?>

# chmod 755 hello.php
5.文字列表示・結合
# vi test.php

<?php
$str1 = "Hello";
$str2 = "World";

print<<<EOF
<html>
<head>
<link rel="stylesheet" href="base.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>テスト2</title>
<body>
テスト2
<br>
EOF;

echo $str1.",".$str2;

print<<<EOF
</body>
</html>
EOF;
?>

# chmod 755 test.php
6.外部APIの利用(twitter)
# vi twitter.php

<?php
 $word = "横浜";
 $url = "http://search.twitter.com/search.rss?q=".$word;

 $rss = simplexml_load_file($url);

 $title = $rss->channel->item->title;
 $link = $rss->channel->item->link;
 $description = $rss->channel->item->description;
 $pubDate = $rss->channel->item->pubDate;
 $author = $rss->channel->item->author;

print<<<EOF
 <html>
 <head>
 <link rel="stylesheet" href="base.css" />
 <title>twitter sample</title>
 </head>
 <body>
EOF;

 print "title : ".$title."<br />";
 print "link : ".$link."<br />";
 print "description : ".$description."<br />";
 print "pubDate : ".$pubDate."<br />";
 print "author : ".$author."<br />";
 print "image_link : ".$iage_link."<br />";

print<<<EOF
 </body>
 </html>
EOF;
?>

#chmod 755 twitter.php

2012年5月11日金曜日

Flash課題完成イメージ

上下左右キーで操作できるキャラクタがマップ上を移動するFlashを作成する.


20120511.swf

ダウンロード

※ステージのサイズは320x240です.characterのサイズは,64x64を48x48に縮小して表示しています.



mc_character.swf

ダウンロード

2012年5月10日木曜日

授業用仮想環境の構築

以下の記事を参考に,授業用の仮想環境を構築

仮想環境構築手順(サーバ編)
http://mgrsato.blogspot.jp/2011/11/blog-post_8056.html

仮想環境構築手順(クライアント編)
http://mgrsato.blogspot.jp/2011/11/blog-post_2844.html

[SA-3-2] サーバーへのユーザー追加
http://mgrsato.blogspot.jp/2010/09/sa-23.html

初期設定~WEBサーバ構築
http://mgrsato.blogspot.jp/2011/12/web.html

[SA-3-10] httpd設定
http://mgrsato.blogspot.jp/2010/10/sa-3-httpd.html

2012年4月26日木曜日

サーバを構成する要素 -CPU-

1.自分たちが使用しているPCのCPUが持つ機能を確認する.

2.近年のサーバ用のCPUについても,機能等確認する.

3.サーバの用途毎に必要とされる機能,留意すべき項目等について議論する.

2012年1月26日木曜日

Shell Scriptを用いたデータの自動登録

http://www.google.com/ig/api?weather=Yokohama,Kanagawa

1.データ受け入れ先となるテーブルを作成
※database nameはsampleとする

# mysql -u [user name] -p[password] [database name]
create table google_temp (
 id integer NOT NULL AUTO_INCREMENT PRIMARY KEY,
 observation_time char(20),
 temp_c char(10)
);

2.Shell Scriptの作成
指定した部分を正しく抜き出せるかコマンドライン上で試行錯誤しつつ確認

2-1.
#curl --silent --location http://www.google.com/ig/api?weather=Yokohama,Kanagawa
<?xml version="1.0"?><xml_api_reply version="1"><weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" ><forecast_information><city data="Yokohama, Kanagawa Prefecture"/><postal_code data="Yokohama,Kanagawa"/><latitude_e6 data=""/><longitude_e6 data=""/><forecast_date data="2012-01-12"/><current_date_time data="1970-01-01 00:00:00 +0000"/><unit_system data="US"/></forecast_information><current_conditions><condition data="Mostly Cloudy"/><temp_f data="41"/><temp_c data="5"/><humidity data="Humidity: 31%"/><icon data="/ig/images/weather/mostly_cloudy.gif"/><wind_condition data="Wind: N at 12 mph"/></current_conditions><forecast_conditions><day_of_week data="Thu"/><low data="32"/><high data="43"/><icon data="/ig/images/weather/mostly_sunny.gif"/><condition data="Partly Sunny"/></forecast_conditions><forecast_conditions><day_of_week data="Fri"/><low data="34"/><high data="54"/><icon data="/ig/images/weather/mostly_sunny.gif"/><condition data="Partly Sunny"/></forecast_conditions><forecast_conditions><day_of_week data="Sat"/><low data="37"/><high data="48"/><icon data="/ig/images/weather/mostly_sunny.gif"/><condition data="Partly Sunny"/></forecast_conditions><forecast_conditions><day_of_week data="Sun"/><low data="36"/><high data="48"/><icon data="/ig/images/weather/mostly_sunny.gif"/><condition data="Partly Sunny"/></forecast_conditions></weather></xml_api_reply>

2-2.
#curl --silent --location http://www.google.com/ig/api?weather=Yokohama,Kanagawa | cut -d "<" -f 17
temp_c data="5"/>

2-3.
#curl --silent --location http://www.google.com/ig/api?weather=Yokohama,Kanagawa | cut -d "<" -f 17 | sed 's/temp_c data=\"//'
5"/>

2-4.
#curl --silent --location http://www.google.com/ig/api?weather=Yokohama,Kanagawa | cut -d "<" -f 17 | sed 's/temp_c data=\"//' | sed 's/\"\/>//g'
5

指定した部分を正しく抜き出せたら,Shell Scriptに組み込む
# vi get_temp.sh
#!/bin/sh
observation_time=`date +%Y%m%d%H%M%S`

str_google_temp=`curl --silent --location http://www.google.com/ig/api?weather=Yokohama,Kanagawa | cut -d "<" -f 17 | sed 's/temp_c data=\"//' | sed 's/\"\/>//g'`

echo "insert into google_temp (observation_time,temp_c) values ("$observation_time","$str_google_temp");" >> google_temp.sql

/usr/bin/mysql -u [user name] -p[password] -s [database name] < google_temp.sql
rm google_temp.sql
exit 0

3.Shell Scriptへの実行権限付与
# chmod u+x get_temp.sh

4.Shell Scriptの実行
# ./get_temp.sh

5.シェルスクリプトを用いてMySQLに値が登録された事の確認
# mysql -u [user name] -p [database name]
select * from google_temp;

6.crontabへの登録
# crontab -e
6,16,26,36,46,56 * * * * /root/get_temp.sh &

7.crontabに正しく登録されたか確認
# crontab -l

8.MySQLに登録された値の表示
# cd /var/www/html
# vi google_temp.php
<HTML>
<HEAD> 
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>SA2011 sample</TITLE>
<STYLE TYPE="text/css"> 
<!-- 
 .table1 {
  width: 600px;
  border-collapse: collapse;
  border: 1px #111111 solid;
 }
 .table1 TD { 
  border: 1px #111111 solid;
 } 
-->
</STYLE>
</HEAD>
<BODY>
<H1>SA2011 google_temp</H1>
<br />
<?php
 $db_user  = "[database username]";
 $db_password = "[database password]";
 $db_name = "sample";
 $db_table_name = "google_temp";
 $db_host  = "localhost";
 $db = mysql_connect($db_host,$db_user,$db_password);
 mysql_select_db($db_name,$db);
 $strsql = "SET CHARACTER SET UTF8";
 mysql_query($strsql,$db);
 $str_sql = "select tmp.id, tmp.observation_time, tmp.temp_c from (select id, observation_time, temp_c from ".$db_table_name." order by id desc limit 144) AS tmp order by tmp.id";
 $rs = mysql_query($str_sql,$db);
 $num = mysql_num_fields($rs);
 print("<table CLASS='table1'><tr><th colspan=3>google_temp data</th></tr>");
 print("<tr>");
 for ($i=0;$i<$num;$i++){
  print("<td><b>".mysql_field_name($rs,$i)."</b></td>");
 }
 print("</tr>");
 while($row=mysql_fetch_array($rs)){
  print("<tr>");
  for($j=0;$j<$num;$j++){
   print("<td>".$row[$j]."</td>");
  }
  print("</tr>");
 }
 print("</table>");
 mysql_free_result($rs);
 mysql_close($db);
?>
</BODY>
</HTML>

9.MySQLに登録された値の表示(可視化)
# cd /var/www/html
# vi google_temp_chart.php
<html>
<head>
 <script type="text/javascript" src="https://www.google.com/jsapi"></script>
 <script type="text/javascript">
 google.load("visualization", "1", {packages:["corechart"]});
 google.setOnLoadCallback(drawChart);
 function drawChart() {
 var data = new google.visualization.DataTable();
 data.addColumn('string', 'date');
 data.addColumn('number', 'temp_c');
 data.addRows([
<?php
 $db_user  = "[database username]";
 $db_password = "[database password]";
 $db_name = "sample";
 $db_table_name = "google_temp";
 $db_host  = "localhost";
 $db = mysql_connect($db_host,$db_user,$db_password);
 mysql_select_db($db_name,$db);
 $strsql = "SET CHARACTER SET UTF8";
 mysql_query($strsql,$db);
 $str_sql = "select tmp.observation_time, tmp.temp_c from (select id, observation_time, temp_c from ".$db_table_name." order by id desc limit 144) AS tmp order by tmp.observation_time";
 $rs = mysql_query($str_sql,$db);
 $num = mysql_num_fields($rs);
 while($row=mysql_fetch_array($rs)){
  print("['".$row[0]."',".$row[1].",],");
 }
 mysql_free_result($rs);
 mysql_close($db);
?>
]);
 var options = {
 width: 800, height: 480,
 title: 'google_temp'
 };
 var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
 chart.draw(data, options);
 }
 </script>
</head>
<body>
 <div id="chart_div"></div>
</body>
</html>

2012年1月19日木曜日

mysqlのrootパスワードのリセット

# service mysqld stop

# /usr/bin/mysqld_safe --user=root --skip-grant-tables & mysql mysql
# /usr/bin/mysqld_safe --user=root --skip-grant-tables & mysql mysql

mysql> update user set Password=null where Host='localhost' and User='root';
mysql> exit

# services mysqld start