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])

Indexing

If the keyword is already in the index, add the url to the list of urls associated with that keyword. If the keyword is not in the index, add an entry to the index: [keyword,[url]]

index = []

def add_to_index(index,keyword,url):
    for entry in index:
      if entry[0] == keyword:
        entry[1].append(url)
        return
    index.append([keyword,[url]])

Return a list of the urls associated with the keyword. If the keyword is not in the index, the procedure return an empty list.

def lookup(index,keyword):
    for entry in index:
      if entry[0] == keyword:
        return entry[1]
    return[]

split()

quote = "In Washington, it's dog eat dog. In academia...."
quote.split()

update the index to include all of the word occurences found in the page content by adding the url to the word’s associated url list.

def add_to_index(index,keyword,url):
    for entry in index:
        if entry[0] == keyword:
            entry[1].append(url)
            return
    index.append([keyword,[url]])

def add_page_to_index(index,url,content):
    words = content.split()
    for word in words:
    add_to_index(index, word, url)

python code getting url from internet

def get_page(url):
  try:
    import urllib
    return urllib.urlopen(url).read()
  except:
    return ""

The meaning of Latency and bandwidth is close but different.Latency is time it takes message to get from source to destination. Bandwidth is amount of information that can be transmitted per unit time. It is said mbps, bit per second.
internet-speed-test

Define traceroute

[vagrant@localhost ~]$ traceroute www.whitehouse.gov
traceroute to www.whitehouse.gov (184.26.234.167), 30 hops max, 60 byte packets
 1  10.0.2.2 (10.0.2.2)  0.474 ms  0.397 ms  0.302 ms
 2  10.0.2.2 (10.0.2.2)  88.120 ms  87.848 ms  87.469 ms

comparing traceroute in windows

PS C:\Users\hoge> tracert www.udacity.com

apollo-mesos-elb-berlioz2-prod-885022263.us-west-2.elb.amazonaws.com [52.40.117.247] へのルートをトレー
経由するホップ数は最大 30 です:

  1    94 ms     6 ms     6 ms  192.168.179.1
  2     *        *        *     要求がタイムアウトしました。
  3     *        *        *     要求がタイムアウトしました。
  4    65 ms    57 ms    78 ms  172.25.21.178
  5    61 ms    64 ms    65 ms  172.25.153.3
  6    74 ms    91 ms    63 ms  172.25.153.46
  7    65 ms    65 ms    67 ms  chyISN001.bb.kddi.ne.jp [27.85.176.181]
  8    87 ms    69 ms    71 ms  obpBBAC03.bb.kddi.ne.jp [27.90.191.254]
  9    59 ms    94 ms    59 ms  obpjbb205.int-gw.kddi.ne.jp [125.53.98.93]
 10   248 ms   238 ms   234 ms  pajbb001.int-gw.kddi.ne.jp [203.181.100.194]
 11   201 ms   228 ms   174 ms  ix-pa9.int-gw.kddi.ne.jp [111.87.3.74]
 12   190 ms   189 ms   178 ms  72.21.221.125
 13   210 ms   194 ms   202 ms  54.240.243.50
 14   197 ms   179 ms   179 ms  54.240.243.55
 15   204 ms   197 ms   204 ms  205.251.232.116
 16   264 ms   247 ms   197 ms  52.93.12.76
 17   209 ms   196 ms   196 ms  52.93.12.73
 18   244 ms   202 ms   217 ms  52.93.12.144
 19   203 ms   196 ms   195 ms  52.93.12.165
 20   208 ms   196 ms   197 ms  52.93.13.67
 21     *        *        *     要求がタイムアウトしました。
 22     *        *        *     要求がタイムアウトしました。
 23     *        *        *     要求がタイムアウトしました。
 24     *        *        *     要求がタイムアウトしました。
 25     *        *        *     要求がタイムアウトしました。
 26     *        *        *     要求がタイムアウトしました。
 27     *        *        *     要求がタイムアウトしました。
 28     *        *        *     要求がタイムアウトしました。
 29     *        *        *     要求がタイムアウトしました。
 30     *        *        *     要求がタイムアウトしました。

トレースを完了しました。
PS C:\Users\hoge> tracert www.mit.edu

e9566.dscb.akamaiedge.net [23.9.161.192] へのルートをトレースしています
経由するホップ数は最大 30 です:

  1  2662 ms     3 ms     7 ms  192.168.179.1
  2     *        *        *     要求がタイムアウトしました。
  3     *        *        *     要求がタイムアウトしました。
  4    71 ms    62 ms    83 ms  172.25.21.178
  5    86 ms    72 ms    63 ms  172.25.153.3
  6    74 ms    58 ms    79 ms  172.25.153.46
  7    72 ms    57 ms    79 ms  chyISN001.bb.kddi.ne.jp [27.85.176.181]
  8    84 ms    77 ms    79 ms  27.85.132.197
  9    83 ms    78 ms    78 ms  27.85.134.50
 10    89 ms    79 ms    79 ms  210.132.124.62
 11    77 ms    63 ms    73 ms  a23-9-161-192.deploy.static.akamaitechnologies.com [23.9.161.192]

the list of number

product_list, that takes as input a list of numbers, and returns a number that is the result of multiplying all those numbers together.

def product_list(p):
 result = 1
 for i in p
    result =  result * i
    return result

A greatest, that takes as input a list of positive numbers, and returns the greatest number in that list. If the input list is empty, the output should be 0.

def greatest(p):
  biggest = 0
  for i in p:
    if i > biggeset:
      biggest = i
  return biggest

total_enrollment, that takes as an input a list of elements, where each element is a list containing three elements: a university name, the total number of students enrolled, and the annual tuition fees.
The procedure return two numbers, giving the total number of students enrolled at all of the universities in the list, and the total tuition fees (which is the sum of the number of students enrolled times the
# tuition fees for each university).

usa_univs = [ ['California Institute of Technology',2175,37704],
              ['Harvard',19627,39849],
              ['Massachusetts Institute of Technology',10566,40732],
              ['Princeton',7802,37000],
              ['Rice',5879,35551],
              ['Stanford',19535,40569],
              ['Yale',11701,40500]  ]

def total_enrollment(p):
    total_student = 0
    total_tuition = 0
    for i in p:
        total_sutudent = i[1] + total_sudent
        total_tuition = i[1] * i[2] + total tuition
    return total_student, total_tuition

check_sudoku, that takes as input a square list of lists representing an n x n sudoku puzzle solution and returns the boolean True if the input is a valid sudoku square and returns the boolean False otherwise.

def check_sudoku(p):
    n = len(p)
    digit = 1
    while digit <= n:
      i = 0
      while i < n:
        row_count = 0
        col_count = 0
        j = 0
        while j < 0
          if p[i][j] == digit:
            row_count = row_count + 1
          if p[j][i] = digit:
            col_count = col_count + 1
          j = j + 1
        if row_count != 1 or col_count != 1:
          return False
        i = i + 1
      digit = digit + 1
    return True

divided by number by bumbers showing dicimal

def list_mean(p):
    return float(sum(p)) / len(p)

better data structure indexing keyword, thinking data structure is the most important in computer science.

[[<keyword>,[<url>,<url>]]
 [<keyword>,[<url>,<url>]]
 ...]