php scraping

%e7%84%a1%e9%a1%8c

download from this site:
https://code.google.com/archive/p/phpquery/downloads

<?php

  //require
  require_once('phpQuery-onefile.php');

  //ページ取得
  $html = file_get_contents('./index.html');

  //DOM取得
  $doc = phpQuery::newDocument($html);

  //要素取得
  echo $doc&#91;"title"&#93;->text();

yahoofinanceから任天堂の株価をスクレイピング

<?php

  //require
  require_once('phpQuery-onefile.php');

  //ページ取得
  $html = file_get_contents('http://stocks.finance.yahoo.co.jp/stocks/detail/?code=7974.t');

  //DOM取得
  $doc = phpQuery::newDocument($html);

  //要素取得
  echo $doc&#91;".stoksPrice"&#93;->text();

password hash

TLC

[vagrant@localhost rss16]$ php -r 'echo password_hash("hello", PASSWORD_BCRYPT), PHP_EOL;'
$2y$10$payxQjF5UFChN.WM1gcVM.P14fB2FiFkwfsRNkEVEzXyfVo8EHnw2

ログインは小規模ならTLCのbasicでも可だが、TLCのセッション認証が普通。

<?php

function require_basic_auth()
{
  $hashes = &#91;
    'ユーザー名' => '$2y$10$payxQjF5UFChN.WM1gcVM.P14fB2FiFkwfsRNkEVEzXyfVo8EHnw2'
  ];

  if (
    !isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_aUTH_PW'])
    !password_verify(
      $_SERVER['PHP_AUTH_PW'],
      isset($hashes[$_SERVER['PHP_AUTH_USER']])
      ? $hashes[$_SERVER['PHP_AUTH_USER']]
      : '$2y$10$xfNFcqiYmESRZoQTw0VHWe9GzC29OvaOnJ52mgI/u3KLJ.8P.lcKG'
      )
    ){
      header('WWW-Authenticate: Basic realm="Enter username and password."');
      header('Content-Type: text/plain; charset=utf-8');
      exit('このページを見るにはログインが必要です');
    }
    return $_SERVER['PHP_AUTH_USER'];
}

function h($str)
{
  return htmlspecialchars($str, ENT_QUOTES, 'utf-8');
}
<?php

require_once __DIR__ . '/functions.php';
$username = require_basic_auth();

header('Content-Type: text/html; charset=UTF-8');

?>
<!DOCTYPE html>
<title>会員限定ページ</title>
<h1>ようこそ、<?=h($username)?>さん</h1>
<a href="http://dummy@localhost:8010">ログアウト</a>

blog system

CREATE TABLE post (
	no SERIAL,
	title TEXT,
	content TEXT,
	time TIMESTAMP
);
CREATE TABLE comment (
	no SERIAL,
	post_no INT,
	name TEXT,
	content TEXT,
	time TIMESTAMP
);
INSERT INTO post(no,title,content) VALUES(1,'記事1タイトル','記事1の内容です。');
INSERT INTO post(no,title,content) VALUES(2,'記事2タイトル','記事2の内容です。');
INSERT INTO comment(no,post_no,name,content) VALUES(1,1,'たろう','記事1へのコメントです。');
INSERT INTO comment(no,post_no,name,content) VALUES(2,1,'はなこ','記事1へのコメントです。');

css

body {
  background-color:#f77;
  font-size: 14px;
  font-family: Helvetica,Arial, sans-serif;
}
a:link, a:visited {color: #a00;}
a:hover {color: #fca;}
p {
  margin: 0;
  padding: 0;
}
h1 {
  margin: 10px 0;
  padding: 0;
  color: white;
  font-size: 32px;
  text-align: center;
}
h2 {
  margin: 0 -20px 10px -20px;
  padding: 5px 10px;
  background-color: #379;
  color: white;
  font-size: 18px;
}
h3 {
  margin: 0 -15px 10px -15px;
  padding: 5px 10px;
  background-color: #a55;
  color: white;
  font-size: 14px;
}
.post {
  width: 500px;
  margin: 0 auto 15px auto;
  padding: 0 20px 20px 20px;
  background-color: #fb0;
}
.comment {
  margin: 10px 0;
  padding: 0 15px 15px 15px;
  background-color: #da7;
}
.comment_link {
  text-align: right;
}
<!DOCTYPE>
<html>
<head>
    <meta charset="utf-8">
    <title>special blog</title>
    <link rel="stylesheet" href="blog.css">
</head>
<body>
  <h1>Special Blog</h1>
  <div class="post">
    <h2>記事1のタイトルです</h2>
    <p>記事1の本文です。<br>
      記事1の本文です。<br>
    </p>
    <div class="comment">
      <h3>通りすがり1</h3>
      <p>
        記事1へのコメントです。<br>
        記事1へのコメントです。<br>
      </p>
    </div>
    <div class="comment">
      <h3>通りすがり2</h3>
      <p>
        記事1へのコメントです。
      </p>
    </div>
    <p class="comment_link">
      投稿日:2016/12/19
      <a href="#">コメント</a>
    </p>
  </div>
</body>
</html>

index

<?php
  $pdo = new PDO("mysql:dbname=test", "root");
  $st = $pdo->query("SELECT * FROM post ORDER BY no DESC");
  $posts = $st->fetchAll();
  for ($i = 0; $i < count($posts); $i++) {
    $st = $pdo->query("SELECT * FROM comment WHERE post_no={$posts[$i]['no']} ORDER BY no DESC");
    $posts[$i]['comments'] = $st->fetchAll();
  }
  require 't_index.php';
?>

t_index.php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Special Blog</title>
<link rel="stylesheet" href="blog.css">
</head>
<body>
<h1>Special Blog</h1>
<?php foreach ($posts as $post) { ?>
  <div class="post">
    <h2><?php echo $post&#91;'title'&#93; ?></h2>
    <p><?php echo nl2br($post&#91;'content'&#93;) ?></p>
    <?php foreach ($post&#91;'comments'&#93; as $comment) { ?>
      <div class="comment">
        <h3><?php echo $comment&#91;'name'&#93; ?></h3>
        <p><?php echo nl2br($comment&#91;'content'&#93;) ?></p>
      </div>
    <?php } ?>
    <p class="commment_link">
      投稿日:<?php echo $post&#91;'time'&#93; ?> 
      <a href="comment.php?no=<?php echo $post&#91;'no'&#93; ?>">コメント</a>
    </p>
  </div>
<?php } ?>
</body>
</html>

post

<?php
  $error = $title = $content = '';
  if (@$_POST&#91;'submit'&#93;){
    $title = $_POST&#91;'title'&#93;;
    $content = $_POST&#91;'content'&#93;;
    if (!$title) $error .= 'タイトルがありません。<br>';
    if (mb_strlen($title) > 80) $error .= 'タイトルが長すぎます。<br>';
    if (!$content) $error .= '本文がありません。<br>';
    if (!$error) {
      $pdo = new PDO("mysql:dbname=test", "root");
      $stmt = $pdo->query("INSERT INTO post(title,content) VALUES('$title','$content')");
      header('Location: index.php');
      exit();
    }
  }
require 't_post.php';
?>

post_t.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>記事投稿| Special Blog</title>
  <link rel="stylesheet" href="blog.css">
</head>
<body>
  <form method="post" action="post.php">
    <div class="post">
      <h2>記事投稿</h2>
      <p>題名</p>
      <p><input type="text" name="title" size="40" value="<?php echo $title ?>"></p>
      <p>本文</p>
      <p><textarea name="content" rows="8" cols="40"><?php echo $content ?></textarea></p>
      <p><input name="submit" type="submit" value="投稿"></p>
      <p><?php echo $error ?></p>
    </div>
  </form>
</body>
</html>

comment

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>コメント投稿 | Special Blog</title>
<link rel="stylesheet" href="blog.css">
</head>
<body>
<form method="post" action="comment.php">
  <div class="post">
    <h2>コメント投稿</h2>
    <p>お名前</p>
    <p><input type="text" name="name" size="40" value="<?php echo $name ?>"></p>
    <p>コメント</p>
    <p><textarea name="content" rows="8" cols="40"><?php echo $content ?></textarea></p>
    <p>
      <input type="hidden" name="post_no" value="<?php echo $post_no ?>">
      <input name="submit" type="submit" value="投稿">
    </p>
    <p><?php echo $error ?></p>
  </div>
</form>
</body>
</html>

comment_t

<?php
  $post_no = $error = $name = $content = '';
  if (@$_POST&#91;'submit'&#93;) {
    $post_no = strip_tags($_POST&#91;'post_no'&#93;);
    $name = strip_tags($_POST&#91;'name'&#93;);
    $content = strip_tags($_POST&#91;'content'&#93;);
    if (!$name) $error .= '名前がありません。<br>';
    if (!$content) $error .= 'コメントがありません。<br>';
    if (!$error) {
      $pdo = new PDO("mysql:dbname=test", "root");
      $st = $pdo->prepare("INSERT INTO comment(post_no,name,content) VALUES(?,?,?)");
      $st->execute(array($post_no, $name, $content));
      header('Location: index.php');
      exit();
    }
  } else {
    $post_no = strip_tags($_GET['no']);
  }
  require 't_comment.php';
?>

python sqlalchemy

[vagrant@localhost webapp]$ python
Python 3.5.2 (default, Oct 31 2016, 08:50:29)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from sqlalchemy import create_engine
>>> from sqlalchemy.orm import sessionmaker
>>> from database_setup import Base, Restaurant, MenuItem
>>> engine = create_engine('sqlite:///restaurantmenu.db')
>>> Base.metadata.bind = engine
>>> DBSession = sessionmaker(bind = engine)
>>> session = DBSession()
>>> myFirstRestaurant = Restaurant(name = "Pizza Palace")
>>> session.add(myFirstRestaurant)
>>> session.commit()
>>> session.query(Restaurant).all()
[]
>>> cheesepizza = MenuItem(name= "Cheese Pizza", description = "Made with all natural ingredients and fresh mozzarella", course = "Entree", price = "$8.99", restaurant = myFirstRestaurant)
>>> session.add(cheesepizza)
>>> session.commit()
>>> session.query(MenuItem).all()
[]
>>> firstResult = session.query(Restaurant).first()
>>> firstResult.name
'Pizza Palace'
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from database_setup import Restaurant, Base, MenuItem

engine = create_engine('sqlite:///restaurantmenu.db')
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
# A DBSession() instance establishes all conversations with the database
# and represents a "staging zone" for all the objects loaded into the
# database session object. Any change made against the objects in the
# session won't be persisted into the database until you call
# session.commit(). If you're not happy about the changes, you can
# revert all of them back to the last commit by calling
# session.rollback()
session = DBSession()



#Menu for UrbanBurger
restaurant1 = Restaurant(name = "Urban Burger")

session.add(restaurant1)
session.commit()

menuItem2 = MenuItem(name = "Veggie Burger", description = "Juicy grilled veggie patty with tomato mayo and lettuce", price = "$7.50", course = "Entree", restaurant = restaurant1)

session.add(menuItem2)
session.commit()


menuItem1 = MenuItem(name = "French Fries", description = "with garlic and parmesan", price = "$2.99", course = "Appetizer", restaurant = restaurant1)

session.add(menuItem1)
session.commit()

menuItem2 = MenuItem(name = "Chicken Burger", description = "Juicy grilled chicken patty with tomato mayo and lettuce", price = "$5.50", course = "Entree", restaurant = restaurant1)

session.add(menuItem2)
session.commit()

menuItem3 = MenuItem(name = "Chocolate Cake", description = "fresh baked and served with ice cream", price = "$3.99", course = "Dessert", restaurant = restaurant1)

session.add(menuItem3)
session.commit()

menuItem4 = MenuItem(name = "Sirloin Burger", description = "Made with grade A beef", price = "$7.99", course = "Entree", restaurant = restaurant1)

session.add(menuItem4)
session.commit()

menuItem5 = MenuItem(name = "Root Beer", description = "16oz of refreshing goodness", price = "$1.99", course = "Beverage", restaurant = restaurant1)

session.add(menuItem5)
session.commit()

menuItem6 = MenuItem(name = "Iced Tea", description = "with Lemon", price = "$.99", course = "Beverage", restaurant = restaurant1)

session.add(menuItem6)
session.commit()

menuItem7 = MenuItem(name = "Grilled Cheese Sandwich", description = "On texas toast with American Cheese", price = "$3.49", course = "Entree", restaurant = restaurant1)

session.add(menuItem7)
session.commit()

menuItem8 = MenuItem(name = "Veggie Burger", description = "Made with freshest of ingredients and home grown spices", price = "$5.99", course = "Entree", restaurant = restaurant1)

session.add(menuItem8)
session.commit()




#Menu for Super Stir Fry
restaurant2 = Restaurant(name = "Super Stir Fry")

session.add(restaurant2)
session.commit()


menuItem1 = MenuItem(name = "Chicken Stir Fry", description = "With your choice of noodles vegetables and sauces", price = "$7.99", course = "Entree", restaurant = restaurant2)

session.add(menuItem1)
session.commit()

menuItem2 = MenuItem(name = "Peking Duck", description = " A famous duck dish from Beijing[1] that has been prepared since the imperial era. The meat is prized for its thin, crisp skin, with authentic versions of the dish serving mostly the skin and little meat, sliced in front of the diners by the cook", price = "$25", course = "Entree", restaurant = restaurant2)

session.add(menuItem2)
session.commit()

menuItem3 = MenuItem(name = "Spicy Tuna Roll", description = "Seared rare ahi, avocado, edamame, cucumber with wasabi soy sauce ", price = "15", course = "Entree", restaurant = restaurant2)

session.add(menuItem3)
session.commit()

menuItem4 = MenuItem(name = "Nepali Momo ", description = "Steamed dumplings made with vegetables, spices and meat. ", price = "12", course = "Entree", restaurant = restaurant2)

session.add(menuItem4)
session.commit()

menuItem5 = MenuItem(name = "Beef Noodle Soup", description = "A Chinese noodle soup made of stewed or red braised beef, beef broth, vegetables and Chinese noodles.", price = "14", course = "Entree", restaurant = restaurant2)

session.add(menuItem5)
session.commit()

menuItem6 = MenuItem(name = "Ramen", description = "a Japanese noodle soup dish. It consists of Chinese-style wheat noodles served in a meat- or (occasionally) fish-based broth, often flavored with soy sauce or miso, and uses toppings such as sliced pork, dried seaweed, kamaboko, and green onions.", price = "12", course = "Entree", restaurant = restaurant2)

session.add(menuItem6)
session.commit()




#Menu for Panda Garden
restaurant1 = Restaurant(name = "Panda Garden")

session.add(restaurant1)
session.commit()


menuItem1 = MenuItem(name = "Pho", description = "a Vietnamese noodle soup consisting of broth, linguine-shaped rice noodles called banh pho, a few herbs, and meat.", price = "$8.99", course = "Entree", restaurant = restaurant1)

session.add(menuItem1)
session.commit()

menuItem2 = MenuItem(name = "Chinese Dumplings", description = "a common Chinese dumpling which generally consists of minced meat and finely chopped vegetables wrapped into a piece of dough skin. The skin can be either thin and elastic or thicker.", price = "$6.99", course = "Appetizer", restaurant = restaurant1)

session.add(menuItem2)
session.commit()

menuItem3 = MenuItem(name = "Gyoza", description = "The most prominent differences between Japanese-style gyoza and Chinese-style jiaozi are the rich garlic flavor, which is less noticeable in the Chinese version, the light seasoning of Japanese gyoza with salt and soy sauce, and the fact that gyoza wrappers are much thinner", price = "$9.95", course = "Entree", restaurant = restaurant1)

session.add(menuItem3)
session.commit()

menuItem4 = MenuItem(name = "Stinky Tofu", description = "Taiwanese dish, deep fried fermented tofu served with pickled cabbage.", price = "$6.99", course = "Entree", restaurant = restaurant1)

session.add(menuItem4)
session.commit()

menuItem2 = MenuItem(name = "Veggie Burger", description = "Juicy grilled veggie patty with tomato mayo and lettuce", price = "$9.50", course = "Entree", restaurant = restaurant1)

session.add(menuItem2)
session.commit()


#Menu for Thyme for that
restaurant1 = Restaurant(name = "Thyme for That Vegetarian Cuisine ")

session.add(restaurant1)
session.commit()


menuItem1 = MenuItem(name = "Tres Leches Cake", description = "Rich, luscious sponge cake soaked in sweet milk and topped with vanilla bean whipped cream and strawberries.", price = "$2.99", course = "Dessert", restaurant = restaurant1)

session.add(menuItem1)
session.commit()

menuItem2 = MenuItem(name = "Mushroom risotto", description = "Portabello mushrooms in a creamy risotto", price = "$5.99", course = "Entree", restaurant = restaurant1)

session.add(menuItem2)
session.commit()

menuItem3 = MenuItem(name = "Honey Boba Shaved Snow", description = "Milk snow layered with honey boba, jasmine tea jelly, grass jelly, caramel, cream, and freshly made mochi", price = "$4.50", course = "Dessert", restaurant = restaurant1)

session.add(menuItem3)
session.commit()

menuItem4 = MenuItem(name = "Cauliflower Manchurian", description = "Golden fried cauliflower florets in a midly spiced soya,garlic sauce cooked with fresh cilantro, celery, chilies,ginger & green onions", price = "$6.95", course = "Appetizer", restaurant = restaurant1)

session.add(menuItem4)
session.commit()

menuItem5 = MenuItem(name = "Aloo Gobi Burrito", description = "Vegan goodness. Burrito filled with rice, garbanzo beans, curry sauce, potatoes (aloo), fried cauliflower (gobi) and chutney. Nom Nom", price = "$7.95", course = "Entree", restaurant = restaurant1)

session.add(menuItem5)
session.commit()

menuItem2 = MenuItem(name = "Veggie Burger", description = "Juicy grilled veggie patty with tomato mayo and lettuce", price = "$6.80", course = "Entree", restaurant = restaurant1)

session.add(menuItem2)
session.commit()



#Menu for Tony's Bistro
restaurant1 = Restaurant(name = "Tony\'s Bistro ")

session.add(restaurant1)
session.commit()


menuItem1 = MenuItem(name = "Shellfish Tower", description = "Lobster, shrimp, sea snails, crawfish, stacked into a delicious tower", price = "$13.95", course = "Entree", restaurant = restaurant1)

session.add(menuItem1)
session.commit()

menuItem2 = MenuItem(name = "Chicken and Rice", description = "Chicken... and rice", price = "$4.95", course = "Entree", restaurant = restaurant1)

session.add(menuItem2)
session.commit()

menuItem3 = MenuItem(name = "Mom's Spaghetti", description = "Spaghetti with some incredible tomato sauce made by mom", price = "$6.95", course = "Entree", restaurant = restaurant1)

session.add(menuItem3)
session.commit()

menuItem4 = MenuItem(name = "Choc Full O\' Mint (Smitten\'s Fresh Mint Chip ice cream)", description = "Milk, cream, salt, ..., Liquid nitrogen magic", price = "$3.95", course = "Dessert", restaurant = restaurant1)

session.add(menuItem4)
session.commit()

menuItem5 = MenuItem(name = "Tonkatsu Ramen", description = "Noodles in a delicious pork-based broth with a soft-boiled egg", price = "$7.95", course = "Entree", restaurant = restaurant1)

session.add(menuItem5)
session.commit()




#Menu for Andala's
restaurant1 = Restaurant(name = "Andala\'s")

session.add(restaurant1)
session.commit()


menuItem1 = MenuItem(name = "Lamb Curry", description = "Slow cook that thang in a pool of tomatoes, onions and alllll those tasty Indian spices. Mmmm.", price = "$9.95", course = "Entree", restaurant = restaurant1)

session.add(menuItem1)
session.commit()

menuItem2 = MenuItem(name = "Chicken Marsala", description = "Chicken cooked in Marsala wine sauce with mushrooms", price = "$7.95", course = "Entree", restaurant = restaurant1)

session.add(menuItem2)
session.commit()

menuItem3 = MenuItem(name = "Potstickers", description = "Delicious chicken and veggies encapsulated in fried dough.", price = "$6.50", course = "Appetizer", restaurant = restaurant1)

session.add(menuItem3)
session.commit()

menuItem4 = MenuItem(name = "Nigiri Sampler", description = "Maguro, Sake, Hamachi, Unagi, Uni, TORO!", price = "$6.75", course = "Appetizer", restaurant = restaurant1)

session.add(menuItem4)
session.commit()

menuItem2 = MenuItem(name = "Veggie Burger", description = "Juicy grilled veggie patty with tomato mayo and lettuce", price = "$7.00", course = "Entree", restaurant = restaurant1)

session.add(menuItem2)
session.commit()




#Menu for Auntie Ann's
restaurant1 = Restaurant(name = "Auntie Ann\'s Diner' ")

session.add(restaurant1)
session.commit()

menuItem9 = MenuItem(name = "Chicken Fried Steak", description = "Fresh battered sirloin steak fried and smothered with cream gravy", price = "$8.99", course = "Entree", restaurant = restaurant1)

session.add(menuItem9)
session.commit()



menuItem1 = MenuItem(name = "Boysenberry Sorbet", description = "An unsettlingly huge amount of ripe berries turned into frozen (and seedless) awesomeness", price = "$2.99", course = "Dessert", restaurant = restaurant1)

session.add(menuItem1)
session.commit()

menuItem2 = MenuItem(name = "Broiled salmon", description = "Salmon fillet marinated with fresh herbs and broiled hot & fast", price = "$10.95", course = "Entree", restaurant = restaurant1)

session.add(menuItem2)
session.commit()

menuItem3 = MenuItem(name = "Morels on toast (seasonal)", description = "Wild morel mushrooms fried in butter, served on herbed toast slices", price = "$7.50", course = "Appetizer", restaurant = restaurant1)

session.add(menuItem3)
session.commit()

menuItem4 = MenuItem(name = "Tandoori Chicken", description = "Chicken marinated in yoghurt and seasoned with a spicy mix(chilli, tamarind among others) and slow cooked in a cylindrical clay or metal oven which gets its heat from burning charcoal.", price = "$8.95", course = "Entree", restaurant = restaurant1)

session.add(menuItem4)
session.commit()

menuItem2 = MenuItem(name = "Veggie Burger", description = "Juicy grilled veggie patty with tomato mayo and lettuce", price = "$9.50", course = "Entree", restaurant = restaurant1)

session.add(menuItem2)
session.commit()

menuItem10 = MenuItem(name = "Spinach Ice Cream", description = "vanilla ice cream made with organic spinach leaves", price = "$1.99", course = "Dessert", restaurant = restaurant1)

session.add(menuItem10)
session.commit()



#Menu for Cocina Y Amor
restaurant1 = Restaurant(name = "Cocina Y Amor ")

session.add(restaurant1)
session.commit()


menuItem1 = MenuItem(name = "Super Burrito Al Pastor", description = "Marinated Pork, Rice, Beans, Avocado, Cilantro, Salsa, Tortilla", price = "$5.95", course = "Entree", restaurant = restaurant1)

session.add(menuItem1)
session.commit()

menuItem2 = MenuItem(name = "Cachapa", description = "Golden brown, corn-based Venezuelan pancake; usually stuffed with queso telita or queso de mano, and possibly lechon. ", price = "$7.99", course = "Entree", restaurant = restaurant1)

session.add(menuItem2)
session.commit()


restaurant1 = Restaurant(name = "State Bird Provisions")
session.add(restaurant1)
session.commit()

menuItem1 = MenuItem(name = "Chantrelle Toast", description = "Crispy Toast with Sesame Seeds slathered with buttery chantrelle mushrooms", price = "$5.95", course = "Appetizer", restaurant = restaurant1)

session.add(menuItem1)
session.commit

menuItem1 = MenuItem(name = "Guanciale Chawanmushi", description = "Japanese egg custard served hot with spicey Italian Pork Jowl (guanciale)", price = "$6.95", course = "Dessert", restaurant = restaurant1)

session.add(menuItem1)
session.commit()



menuItem1 = MenuItem(name = "Lemon Curd Ice Cream Sandwich", description = "Lemon Curd Ice Cream Sandwich on a chocolate macaron with cardamom meringue and cashews", price = "$4.25", course = "Dessert", restaurant = restaurant1)

session.add(menuItem1)
session.commit()


print("added menu items!")

CRUD

create, read, update, delete

pip install sqlalchemy

orm for python
object relational mapper

sql alchemy
->vagrant file already set up
http://www.sqlalchemy.org/

import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
 
Base = declarative_base()
 
class Restaurant(Base):
    __tablename__ = 'restaurant'
   
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)
 
class MenuItem(Base):
    __tablename__ = 'menu_item'

    name =Column(String(80), nullable = False)
    id = Column(Integer, primary_key = True)
    description = Column(String(250))
    price = Column(String(8))
    course = Column(String(250))
    restaurant_id = Column(Integer,ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant) 
 

engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.create_all(engine)

crontab

setting

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=""
HOME=/

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed

* * * * * /user/bin/php /home/vagrant/hoge/index.php

simplexml_load_file

simplexml_load_file:Interprets an XML file into an object

<?php

$rssList = array(
  "http://news.finance.yahoo.co.jp/rss/cp/fisf.xml",
  "http://news.finance.yahoo.co.jp/rss/cp/toyo.xml",
  "http://news.finance.yahoo.co.jp/rss/cp/mosf.xml",
  "http://news.finance.yahoo.co.jp/rss/cp/shikiho.xml"
);

for($n=0;$n<3;$n++){
    //URL設定
    $rssdata = simplexml_load_file("$rssList&#91;$n&#93;");

    // 件数設定
    $num_of_data = 3;

    //初期化
    $outdata = "";
    for ($i=0; $i<$num_of_data; $i++){

        $myEntry = $rssdata->channel->item[$i];
        $rssDate = $myEntry->pubDate;
        date_default_timezone_set('Asia/Tokyo');
        $myDateGNU = strtotime($rssDate);
        $myDate = date('Y/m/d',$myDateGNU);
        $myTitle = $myEntry->title; //タイトル取得
        $myLink = $myEntry->link; //リンクURL取得

        //出力内容(CSSOK)
        $outdata .=  '<p class=""><div style="float:left;width:80px;margin:0px 0px 0px 5px;font-size:12px">'.$myDate.'</div><a href="' . $myLink . '">' . $myTitle . '</a></p>';
    }
    echo $outdata; //全部出力する
}
?>

rssの種類
タグ RSS1.0 RSS2.0 Atom
要素 item channel entry
タイトル title title title
リンク link  link link
説明 description description description
日付 dc:date  pubDate issued

.htaccess

Order Allow,Deny
Allow from all
Deny from .abcde.com
Deny from 111.122.133.
Deny from 111.122.133.192/26

referer

SetEnvlf Referer "http://hogehoge.com" Ref1
SetEnvlf Referer "http://hogeweb.com" Ref2
Order Deny, Allow
Deny from all
Allow from env=Ref1
Allow from env=Ref2

files match

<FilesMatch "\.(gif|.jpg?g|png)$">
SetEnvlf Referer "http://hogehoge.com" Ref1
Order Deny, Allow
Deny from all
Allow from env=Ref1
</FilesMatch>
SetEnvIf REFERER "sample.com" Ref1
Order Deny,Allow
Deny from all
Allow from env=Ref1

ip

SetEnvIf REFERER "sample.com" Ref1
Order Deny,Allow
Deny from all
Allow from env=Ref1
<Files ~"\.log$">
 Deny from all
</Files>

DOSS

php Jaccard

<?php

 /**
 * $item_ids => 商品IDの配列[1,2,3,4,5]の配列
 */

 foreach($item_ids as $item_id1){
   $base = $Redis->lRange('Viewer:Item' . $item_id1, 0, 999);
   if (count($base) === 0){
     continue;
   }
   foreach ($item_ids as $item_id2){
     if ($item_id1 === $item_id2){
       continue;
     }
     $target = $Redis->lRange('Viewer:Item:' . $item_id2, 0, 999);
     if (count($target) === 0){
       continue;
     }

     #ジャッカード指数を計算
     $join = floatval(count(array_unique(array_merge($base, $target))));
     $intersect = floatval(count(array_intersect($base, $target)));
     if ($intersect == 0 || $join == 0){
       continue;
     }
     $jaccard = $intersect / $join;

     $redis->zAdd('Jaccard:Item:' . $item_id1, $jaccard, $item_id2);

   }
 }
<?
/**
* $item_id => 商品id
* $user_id => ユーザid
*/
$Redis->lRem('Viewer:Item' . $item_id, $user_id);
$Redis->lPush('Viewer:Item' . $item_id, $user_id);
$Redis->lTrim('Viewer:Item' . $item_id, 0, 999);
<?php
 $Redis->zRevRange('Jaccard:Item:' . $item_id, 0, -1);