fibonacci

-base cases
fibonacci(0)=0
fibonacci(1)=1

-recursive case
fibonacci(n) = fibonacci(n-1)+fibonacci(n-2)
n > 1

A procedure, fibonacci, that takes a natural number as its input, and returns the value of that fibonacci number.

def fibonacci(n):
    if n == 0:
      return 0
    if n == 1:
      return n
    return fibonacci(n-1) + fibonacci(n-2)

fibonacci has interesting feature below
fibo(x) = fibo(x-n-1)

More faster fibonacci procedure using for loop.

def fibonacci(n):
    current = 0
    after = 1
    for i in range(0, n):
      current, after = after, current + after
    return current

mass_of_earth = 5.9722 * 10**24
mass_of_rabbit = 2

n = 1
while fibonacci(n) * mass_of_rabbit < mass_of_earth:
  n = n + 1
print n, fibonacci(n)

- Ranking web pages as popularity
popularity(p) = # of people who are friends with p
popularity(p) = Σ popularity(f), f E friends of p

def popularity(p):
score = 0
for f in friends(p):
score = score + popularity(f)
return score

Defining Procedures Recursively

factorial(n) = n*(n-1)*(n-2)*…1

factorial(n)=1
factorial(n)=n*factorial(n-1)

A procedure, factorial, that takes a natural number as its input, and returns the number of ways to arrange the input number of items.

def factorial(n):
 if n == 0:
   return 1
 else:
   return n * factorial(n-1)

Palindromes:match the first and last string, such as level.
A procedure is_palindrome, that takes as input a string, and returns a Boolean indicating if the input string is a palindrome.

def is_palindrome(s):
  if s == "":
    return True
  else:
    if s[1] == s[-1]:
        return is_palindrome(s[1:-1])
    else:
        return false

Another way, using for loop, to write palindrome procedure.

def iter_palindrome(s):
  for i in range(0, len(s)/2):
    if s[i] != s[-(i + 1)]:
      return False
  return True

vps

ログイン後に、言語設定

[root@tk2-234-26826 ~]# yum update
Loaded plugins: fastestmirror, security
Setting up Update Process
Loading mirror speeds from cached hostfile
 * base: ftp.iij.ad.jp
 * epel: ftp.riken.jp
 * extras: ftp.iij.ad.jp
 * updates: ftp.iij.ad.jp
No Packages marked for Update

[root@tk2-234-26826 ~]# vim /etc/sysconfig/i18n

userの設定

[root@tk2-234-26826 ~]# date
2016年 12月  5日 月曜日 12:39:36 JST
[root@tk2-234-26826 ~]# useradd user

権限の変更

[root@tk2-234-26826 ~]# usermod -G wheel user
[root@tk2-234-26826 ~]# visudo

sudo権限の変更

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

ドキュメントルート /www/root/html

Ajaxを使ってMySQLの更新をHTML側で自動更新

$(“”).empty();で、一旦データを空にして、setTimeout、countupで自動更新します。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>Ajax</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
    // setTimeout関数で2秒ごとに取得
    var countup = function(){
    $("#content").empty();
    $(document).ready(function(){
      // /**
      // * Ajax通信メソッド
      // * @param type
      // * @param url
      // * @param dataType
      // ** /
      $.ajax({
      type: "POST",
      url: 'json.php',
      dataType: "json",

      success: function(data, dataType)
      {
        if(data == null) alert('データが0件でした');

        var $content = $('#content');
        for (var i = 0; i<data.length; i++)
        {
          $content.append("<li>" + data[i].name + "</li>");
        }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown)
      {
        alert('Error : ' + errorThrown);
      }
    });
  });
    setTimeout(countup, 2000);
  }
  countup();
    </script>
  </head>
  <body>
    <h1>sample</h1>
    <ul id="content"></ul>
  </body>
</html>

ページ閲覧中のオンラインユーザ表示方法

session_id()で、mysqlにセッションIDと時間を保存していき、mysql_num_rowsでセッション数が保存されている行をカウントし、一定時間経過したらセッションIDを削除します。

<?php
session_start();
$session=session_id();
$time=time();
$time_check=$time-300;

$host="localhost";
$username="dbuser";
$password="xxxx";
$db_name="online";
$tbl_name="online_user";

mysql_connect("$host", "$username", "$password") or die("could not connect to server.");
mysql_select_db("$db_name") or die("cannot select DB");

$sql="SELECT * FROM $tbl_name WHERE session='$session'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);

// if count is 0, then enter the values
if($count=="0"){
  $sql1="INSERT INTO $tbl_name(session, time)VALUES('$session', '$time')";
  $result1=mysql_query($sql1);
  }
  // else update the values
  else {
    $sql2="UPDATE $tbl_name SET time='$time' WHERE session='$session'";
    $result2=mysql_query($sql2);
  }

  $sql3="SELECT * FROM $tbl_name";
  $result3=mysql_query($sql3);
  $count_user_online=mysql_num_rows($result3);
  echo "<b>Users Online: </b> $count_user_online ";

  //after 5 minutes, session will be deleted
  $sql4="DELETE FROM $tbl_name WHERE time<$time_check";
  $result4=mysql_query($sql4);

  mysql_close();

?>

preg_match

郵便番号:/^[0-9]{3}-[0-9]{4}$/
電話番後:/^[0-9]{2,4}-[0-9]{2,4}-[0-9]{3,4}$/
E-mailアドレス:|^[0-9a-z_./?-]+@([0-9a-z-]+\.)+[0-9a-z-]+$|

filter_var(), FILTER_VALIDATE_EMAIL

The filter_var() function filters a variable with the specified filter.
Returns the filtered data on success, or FALSE on failure.
The FILTER_VALIDATE_EMAIL filter validates an e-mail address.

<?php
$email = "john.doe@example.com";

if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  echo("$email is a valid email address");
} else {
  echo("$email is not a valid email address");
}
?>

Dictionary

String: sequence of characters, immutable
ex. ‘hello’, s[i] is i th character in S
List: list of elements, mutable
ex. [‘alpha’, 23], p[i] is i th element of p
Dictionary: set of pairs, mutable
ex. {‘hydrogen’: 1, ‘helium’: 23, d[k], k is whatever the key value
ex. d[k] = v, is similar to the update.

Here is a example to use dictionary

elements = {'hydrogen':1, 'helium':2, 'carbon':6 }
elements['lithimu'] = 3
elements['nitrogen'] = 8
elements['nitrogen'] = 7
print elements['nitrogen']

population = {'Shanghai':17.8, 'Istanbul':13.3, 'Karachi':13.0, 'Mumbai':12.5 }

another example

elements = {}
elements['H'] = {'name': 'Hydrogen', 'number': 1, 'weight': 1.00794}
elements['He'] = {'name': 'Helium', 'number': 2, 'weight': 4.002602, 'noble gas': True}
print elements['He']['name']

fix index content

procedure return a list of strings that break the source string up by the characters in the splitlist.

def split_string(source,splitlist):
  output = []
  atsplit = True
  for char in source:
    if char in splitlist:
      atsplit = True:
    else:
      if atsplit:
        output.append(char)
        atsplit = False
      else:
        output[-1] = output[-1] + char
    return output

cut duplicated url on index list

def add_to_index(index, keyword, url):
    for entry in index:
        if entry[0] == keyword:
            if not url in entry[1]:
            entry[1].append(url)
            return
    # not found, add new keyword to index
    index.append([keyword, [url]])

One way search engines rank pages is to count the number of times a searcher clicks on a returned link. This indicates that the person doing the query thought this was a useful link for the query, so it should be higher in the rankings next time.

def record_user_click(index,keyword,url):
  urls = lookup(index, keyword)
  if urls:
    for entry in urls:
      if entry[0] == url:
        entry[1] = entry[1] + 1
      
def add_to_index(index,keyword,url):
  for entry in index:
    for entry[0] == keyword:
      for elment in entry[1]:
        if element[0] = url:
          return
      entry[1].append([url,0])
      return
  index.append([keyword,[[url,0]]])

How program run fast making things fast. It depends algorithm analysis that most programmer spend time in procedure, well defined sequence of steps that can be executed mechanically. So gatta think about time and memory said cost of computer.

time consuming

import time

def time_execution(code):
  start = time.clock()
  result = eval(code)
  run_time = time.clock() - start
  return result, run_time

def spin_loop(n):
  i = 0
  while i < n:
    i = i + 1
    
print time_execution('2 ** 10')


Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
(1024, 1.6000000000002124e-05)

print time_execution('spin_loop(10000000)')
(None, 0.33208099999999996)

Creating an Empty Hash Table, make_hashtable, that takes as input a number, nbuckets, and returns an empty hash table with nbuckets empty buckets.

def make_hashtable(nbuckets):
  i = 0
  table = []
  while i < nbuckets:
    table.append([])
    i = i + 1
  return table

for loop, we do not need variable like i.

def make_hashtable(nbuckets):
  i = 0
  table = []
  for unused < range(0, nbuckets):
    tabale.append([])
  return table

Update hashtable, if key is already in the table, change the value to the new value.

def hashtable_update(htable,key,value):
    bucket = hashtable_get_bucket(htable, key)
    for entry in hashtable
        if entry[0] == key:
          entry[1] = value
    bucket.append([key, value])