PythonでQRコード作成

$ pip3 install qrcode
$ pip3 install pillow
qrcodeをinstallすると、qrコマンドが使える様になる

$ qr “text for qrcode” > qrcode.png

PythonでQRコードを作成

import qrcode

img = qrcode.make('test text')
img.save('qrcode_test.png')

qrコードの色やback colorを指定

qr = qrcode.QRCode(
version=12,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=2,
border=8
)
qr.add_data(‘test text’)
qr.make()
img = qr.make_image(fill_color=”red”, back_color=”blue”)
img.save(“qrcode_test2.png”)
[/code]

背景に画像を設定する方法がわからんな…

[自然言語処理] sumyで要約を作りたい

$ pip3 install sumy

import MeCab

from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.lex_rank import LexRankSummarizer

text = ""

def summy_test(text):
    dic_url = ""
    tagger = MeCab.Tagger()
    key = tagger.parse(text)
    corpus = []
    for row in key.split("\n"):
        word = row.split("\t")[0]
        if word == "EOS":
            break
        else:
            corpus.append(word)

    parser = PlaintextParser.from_string(text, Tokenizer('japanese'))

    summarizer = LexRankSummarizer()
    summarizer.stop_words = ['']
    summary = summarizer(document=parser.document, sentences_count=2)
    b = []
    for sentence in summary:
        b.append(sentence.__str__())
    return "".join(b)

print(summy_test(text))

簡単やわ

Rails 基礎3

### relation(belongs:to)
$ rails g model Comment body:string post:references
$ rails db:migrate

model
app/models.comment.rb

class Comment < ApplicationRecord
  belongs_to :post
  validates :body, prensence: true
end

post modelにもcommentと紐づいていることを書く

class Post < ApplicationRecord
	has_many :comments
	validates :title, presence: true, length: {minimum: 3, message: 'too short to post!'}
	validates :body, presence: true
end

post.comments と書くことができる様になる

routes.rb

  resources :posts do
  	resources :comments
  end

$ rails routes
Prefix Verb URI Pattern Controller#Action
post_comments GET /posts/:post_id/comments(.:format) comments#index
POST /posts/:post_id/comments(.:format) comments#create
new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new
edit_post_comment GET /posts/:post_id/comments/:id/edit(.:format) comments#edit
post_comment GET /posts/:post_id/comments/:id(.:format) comments#show
PATCH /posts/:post_id/comments/:id(.:format) comments#update
PUT /posts/:post_id/comments/:id(.:format) comments#update
DELETE /posts/:post_id/comments/:id(.:format) comments#destroy
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
root GET / posts#index

$ rails g controller Comments

show.html.erb

<h3>Comments</h3>
<%= form_for ([@post, @post.comments.build]) do |f| %>
<p>
	<%= f.text_field:body %>
</p>
<p>
	<%= f.submit %>
</p>
<% end %>

comments_controller.rb

	def create
		# render plain: params[:post].inspect
		@post = Post.find(params[:post_id])
		@post.comments.create(comment_params)
		redirect_to post_path(@post)
	end

	private
		def comment_params
			params.require(:comment).permit(:body)
		end

posts_controller.rb
L 変更なし

	def show
		@post = Post.find(params[:id])
	end

show.html.erb

<ul>
	<% @post.comments.each do |comment| %>
	<li>
		<%= comment.body %>
		<%= link_to '[x]', 
			post_comment_path(@post, comment), 
			method: :delete, 
			class: 'command',
			data: { confirm: 'Sure ?'} %>		
	</li>
	<% end %>
</ul>

controller

	def destroy
		@post = Post.find(params[:post_id])
		@comment = @post.comments.find(params[:id])
		@comment.destroy
		redirect_to post_path(@post)
	end

route

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  resources :posts do
  	resources :comments, only: [:create, :destroy]
  end

  root 'posts#index'
end

記事を削除した時にコメントも削除する
model

class Post < ApplicationRecord
	has_many :comments, dependent: :destroy
	validates :title, presence: true, length: {minimum: 3, message: 'too short to post!'}
	validates :body, presence: true
end

なるほど、オリジナルで作らんとダメやな

Rails 基礎2

viewでヘルパーを使用
index.html.erb

		<% @posts.each do |post| %>
		<li>
			<%= link_to post.title, post_path(post) %>				
		</li>
		<% end %>

posts_controller.rb

	def show
		@post = Post.find(params[:id])
	end

show.html.erb

<h2><%= @post.title %></h2>
<p><%= @post.body %></p>

app/assets/images/logo.png
link_toでリンクを指定し、root_pathでリンク先を指定する

  	<div class="container">
  		<h1><%= link_to image_tag('logo.png', class: 'logo'), root_path %></h1>
    <%= yield %>
	</div>

css

.logo {
	width: 200px;
	height: 50px;
}

リンクを作成する

	<h2>
		<%= link_to 'Add New', new_post_path, class: 'header-menu' %>
		My Posts
	</h2>

css

.header-menu {
	font-size: 12px;
	font-weight: normal;
	float: right;
}

controller

	def new
	end

	def create
	end

new.html.erb

<h2>Add New Post</h2>
<%= form_for :post, url:posts_path do |f| %>
<p>
	<%= f.text_field:title, placeholder: 'enter title' %>
</p>
<p>
	<%= f.text_area:body, placeholder: 'enter body text' %>
</p>
<p>
	<%= f.submit %>
</p>
<% end %>

css

input[type="text"], textarea {
	box-sizing: border-box;
	width: 400px;
	padding: 5px;
}

textarea {
	height: 160px;
}

posts_controller.rb

	def create
		render plain: params[:post].inspect
	end

“aa”, “body”=>”bb”} permitted: false>

	def create
		# render plain: params[:post].inspect
		@post = Post.new(params[:post])
		@post.save
		redirect_to posts_path
	end

private methodで書く

	def create
		# render plain: params[:post].inspect
		@post = Post.new(post_params)
		@post.save
		redirect_to posts_path
	end

	private
		def post_params
			params.require(:post).permit(:title, :body)
		end

バリデーション
app/models/post.rb

class Post < ApplicationRecord
	validates :title, presence: true, length: {minimum: 3, message: 'too short to post!'}
	validates :body, presence: true
end

controller

	def create
		# render plain: params[:post].inspect
		@post = Post.new(post_params)
		if @post.save
			redirect_to posts_path
		else
			render 'new'
		end
	end

view

<p>
	<%= f.text_field:title, placeholder: 'enter title' %>
	<% if @post.errors.messages[:title].any? %>
	<span class="error"><%= @post.errors.messages[:title][0] %></span>
	<% end %>
</p>
<p>
	<%= f.text_area:body, placeholder: 'enter body text' %>
	<% if @post.errors.messages[:body].any? %>
	<span class="error"><%= @post.errors.messages[:body][0] %></span>
	<% end %>
</p>

### edit
index.html.erb

			<%= link_to post.title, post_path(post) %>	
			<%= link_to '[Edit]', edit_post_path(post), class: 'command' %>		

controller

	def edit 
		@post = Post.find(params[:id])
	end

edit.html.erb
L newとほぼ同じ

<h2>Edit Post</h2>
<%= form_for @post, url:post_path(@post) do |f| %>
<p>
	<%= f.text_field:title, placeholder: 'enter title' %>
	<% if @post.errors.messages[:title].any? %>
	<span class="error"><%= @post.errors.messages[:title][0] %></span>
	<% end %>
</p>
<p>
	<%= f.text_area:body, placeholder: 'enter body text' %>
	<% if @post.errors.messages[:body].any? %>
	<span class="error"><%= @post.errors.messages[:body][0] %></span>
	<% end %>
</p>
<p>
	<%= f.submit %>
</p>
<% end %>

controller

	def update
		@post = Post.find(params[:id])
		if @post.update(post_params)
			redirect_to posts_path
		else
			render 'edit'
		end
	end

改行を適切なタグに直す

<h2><%= @post.title %></h2>
<p><%= simple_format @post.body %></p>

### partialで共通部品を作る
partialはアンダーバー(_)から始める
views/posts/_form.html.erb

<%= form_for @post do |f| %>
<p>
	<%= f.text_field:title, placeholder: 'enter title' %>
	<% if @post.errors.messages[:title].any? %>
	<span class="error"><%= @post.errors.messages[:title][0] %></span>
	<% end %>
</p>
<p>
	<%= f.text_area:body, placeholder: 'enter body text' %>
	<% if @post.errors.messages[:body].any? %>
	<span class="error"><%= @post.errors.messages[:body][0] %></span>
	<% end %>
</p>
<p>
	<%= f.submit %>
</p>
<% end %>

edit.html.erb
L partialの名前をアンダーバー抜きで書く

<h2>Edit Post</h2>
<%= render 'form' %>

new.html.erb

<h2>Add New Post</h2>
<%= render 'form' %>

### delete

		<li>
			<%= link_to post.title, post_path(post) %>	
			<%= link_to '[Edit]', edit_post_path(post), class: 'command' %>
			<%= link_to '[x]', 
			post_path(post), 
			method: :delete, 
			class: 'command',
			data: { confirm: 'Sure ?'} %>	
		</li>

controller

	def destroy
		@post = Post.find(params[:id])
		@post.destroy
		redirect_to posts_path
	end

Rails 基礎1

– model作成
$ rails g model Post title:string body:text
$ rails db:migrate

### DB接続
$ rails db
sqlite> .tables
ar_internal_metadata posts schema_migrations
// テーブル名は複数形になる
sqlite> select * from posts;
1|title1|body1|2022-01-03 00:47:27.389516|2022-01-03 00:47:27.389516
2|title2|body2|2022-01-03 00:47:34.246581|2022-01-03 00:47:34.246581
sqlite> .quit

db/seeds.rb に初期データを書ける

5.times do |i|
	Post.create(title: "title #{i}", body: "body #{i}")
end

テーブルの中身をリセット
$ rails db:migrate:reset
$ rails db:seed
sqlite> select * from posts;
1|title 0|body 0|2022-01-03 02:38:34.229316|2022-01-03 02:38:34.229316
2|title 1|body 1|2022-01-03 02:38:34.242102|2022-01-03 02:38:34.242102
3|title 2|body 2|2022-01-03 02:38:34.248025|2022-01-03 02:38:34.248025
4|title 3|body 3|2022-01-03 02:38:34.253382|2022-01-03 02:38:34.253382
5|title 4|body 4|2022-01-03 02:38:34.259377|2022-01-03 02:38:34.259377

### controller
$ rails g controller Posts

config/routes.rb

Rails.application.routes.draw do

  resources :posts
end

$ rails routes
Prefix Verb URI Pattern Controller#Action
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy

app/controllers/post_controller.rb

class PostsController < ApplicationController

	def index
		@posts = Post.all.order(created_at: 'desc')
	end
end

app/views/posts/index.html.erb

	<h2>My Posts</h2>
	<ul>
		<% @posts.each do |post| %>
		<li><%= post.title %></li>
		<% end %>
	</ul>

$ rails s -b 192.168.33.10 -d
http://192.168.33.10:3000/posts

route pass

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  resources :posts

  root 'posts#index'
end

app/views/layouts/application.html.erb
app/assets/stylesheets/application.css

.container {
	width: 400px;
	margin: 20px auto;
}
body {
	font-family: Verdana, sans-serif;
	font-size: 14px;
}
h2 {
	font-size: 16px;
	padding-bottom: 10px;
	margin-bottom: 15px;
	border-bottom: 1px solid #ddd;
}

ul > li {
	margin-bottom: 5px;
}

[InstagramAPI] 投稿を取得してHTMLで表示

1. facebookとinstagramのアカウントを開設(すでにある場合はスキップ)
2. instagramをビジネスアカウントへ変更
3. Facebookページの作成
4. FacebookページとInstagramビジネスアカウントの紐づけ
5. Facebookアプリ作成
6. アクセストークンを取得する ()
– InstagramグラフAPIエクスプローラーで、アクセストークンを取得
instagram_basic
instagram_manage_comments
instagram_manage_insights
instagram_manage_messages
instagram_content_publish
business_management
– 上記で取得した「アクセストークン」と、Facebookアプリの「アプリID」と「app secret」からアクセストークンを取得
https://graph.facebook.com/v4.0/oauth/access_token?grant_type=fb_exchange_token&client_id=[★アプリID]&client_secret=[★app secret]&fb_exchange_token=[★1番目のトークン]

– https://graph.facebook.com/v4.0/me?access_token=[★2番目のトークン] でIDを取得
– https://graph.facebook.com/v4.0/[★ここにIDを入力]/accounts?access_token=[★2番目のトークン]
– InstagramビジネスアカウントIDを取得

### htmlで表示
conf.php

<?php

return [
    'business_id' => '${business_id}',
    'access_token' => '${access_token}',
];
?>

index.php

<?php

$config = include(__DIR__ . '/conf.php');

$business_id = $config['business_id'];
$access_token = $config['access_token'];

if(isset($_GET['username']) && $_GET['username'] != ""){
	$username = htmlspecialchars($_GET['username']);
} else {
	$username = "miyagawadai";
}

$url = "https://graph.facebook.com/v4.0/" . $business_id ."?fields=business_discovery.username(" . $username . "){media{timestamp,media_url,like_count,comments_count,caption}}&access_token=" . $access_token;

try {
	$json = json_decode(file_get_contents($url), true);
	$results = $json['business_discovery']['media']['data'];
} catch (Exception $ex){
	$results = "";
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Get Instagram Likes!</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
	<style>
		body {
			margin: 50px 200px 50px;
		}
		.card {
			width: 100%;
		} 
		.card-content{
			height: 120px;
		}
	</style>
</head>
<body>
	<h1 class="title">Get Instagram Likes!</h1>
	<form action="">
		<div class="field">
		  <label class="label">User Name</label>
		  <div class="control">
		    <input class="input" type="text" name="username" placeholder="Instagram username">
		  </div>
		</div>
		<div class="control">
		    <button type="submit" class="button is-link is-light">Show</button>
		 </div>
	</form>
	<hr>
	<?php
		echo "result: " .$username."<br><br><br>";
		echo "<div class='columns'>";
		$i = 1;
		foreach($results as $result){
			echo "<div class='card column'><div class='card-image'><figure class='image is-4by3'><img src=" . $result['media_url'] ."></figure></div><div class='card-content'><div class='content'>" .number_format($result['like_count'])." Like!<br>".mb_substr($result['caption'], 0, 30)."...</div></div></div>" ;
			if($i % 3 == 0) {
				echo "</div><div class='columns'>";
			}
			$i++;
		}
		echo "</div>";
	?>
</body>
</html>

defaultで”miyagawadai”さんのinstaを表示する様にしています。

ほう、
twitterよりも規約が厳しい模様
やってる人もそんなに多くないか…

ubuntu20.04でRailsを触りたい

### 環境構築
$ ruby -v
$ rbenv install –list
$ rbenv install 2.7.2

$ sudo apt install sqlite3
$ sqlite3 –version
3.31.1 2020-01-27 19:55:54 3bfa9cc97da10598521b342961df8f5f68c7388fa117345eeb516eaa837balt1

$ gem install rails -v 5.1.3 –no-document
$ sudo apt install ruby-railties
$ rails -v
Rails 5.1.3

### railsアプリ
$ rails new myapp
$ rails server -b 192.168.33.10 -d
=> Booting Puma
=> Rails 5.1.7 application starting in development
=> Run `rails server -h` for more startup options

サーバーのdown
$ cat tmp/pids/server.pid
24555
$ kill -9 24555

ログ
$ tail log/development.log

### scaffold
$ rails g scaffold Memo title:string body:text
$ rails db:migrate

http://192.168.33.10:3000/memos

$ ps aux | grep puma
$ kill -9 24777

app, config, dbなどを主に使用する

### model作成
単数系になる
$ rails g model Post title:string body:text
$ rails db:migrate

### データ挿入
$ rails c

$ p = Post.new(title:’title1′, body:’body1′)
$ p.save

$ Post.create(title:’title2′, body:’body2′)

$ Post.all
$ quit