pythonでmysqlを操作

$ pip3 install mysql-connector-python

mysql側の操作

create database reddit;
use reddit
create table polygon (
	id int auto_increment primary key,
	title varchar(255),
	score int
);

insert into polygon (title, score) values
("Daily Polygon Discussion Thread", 25);

db.py

import mysql.connector

conn = mysql.connector.connect(
user='root',
passwd='hogehoge',
host='localhost',
db='reddit'
)

cur = conn.cursor()

sql = "select * from polygon"
cur.execute(sql)

rows = cur.fetchall()

for row in rows:
	print(row)

cur.close

conn.close

$ python3 db.py
(1, ‘Daily Polygon Discussion Thread’, 25)

### insertの場合

sql1 = "truncate table polygon"
cur.execute(sql1)

sql2 = "INSERT INTO polygon (title, score) VALUES('Daily Polygon Discussion Thread', 4)"
cur.execute(sql2)
conn.commit()

mysql> select * from polygon;
+—-+———————————+——-+
| id | title | score |
+—-+———————————+——-+
| 1 | Daily Polygon Discussion Thread | 4 |
+—-+———————————+——-+
1 row in set (0.00 sec)

OK
これに翻訳を入れたい

from googletrans import Translator
translator = Translator()

text = "Daily Polygon Discussion Thread"
 
translation = translator.translate(text, dest='ja', src='en')
print(translation.text)

$ python3 tran.py
毎日のポリゴンディスカッションスレッド

OK
これを全部つなげる

mysql> select * from polygon;
+—-+———————————+———————————————————–+——-+———————+
| id | title | title_ja | score | date |
+—-+———————————+———————————————————–+——-+———————+
| 1 | Daily Polygon Discussion Thread | 毎日のポリゴンディスカッションスレッド | 4 | 2022-01-08 05:14:42 |
+—-+———————————+———————————————————–+——-+———————+
1 row in set (0.00 sec)

【React Native】Expoを触ってみる

$ node -v
v14.17.6
$ sudo npm install expo-cli –global
$ expo –version
5.0.3

Expoを利用するためには、Expoのアカウント作成が必要
https://expo.dev/signup

– ターミナルからログイン
$ expo login
✔ Username/Email Address: … georgia_premium
✔ Password: … **********

Success. You are now logged in as georgia_premium.

$ expo init myNewProject

$ cd myNewProject

– yarn start # you can open iOS, Android, or web from here, or run them directly with the commands below.
– yarn android
– yarn ios # requires an iOS device or macOS for access to an iOS simulator
– yarn web

$ export REACT_NATIVE_PACKAGER_HOSTNAME=192.168.34.10
$ export EXPO_DEVTOOLS_LISTEN_ADDRESS=192.168.34.10
$ expo start
http://192.168.34.10:19000/

ほう、中々すごい

Firebaseのrealtime databaseを使ってみる

$ curl -sS https://getcomposer.org/installer | php
// composer動作確認
$ php composer.phar
$ php composer.phar require ktamas77/firebase-php

$ sudo apt-get install php7.4-curl
$ php -v

require_once "vendor/autoload.php";

define("DEFAULT_URL","https://*-default-rtdb.firebaseio.com");
define("DEFAULT_TOKEN","");

$test = array(
	"name" => "Polkadot",
	"code" => "DOT"
);

$firebase = new \Firebase\FirebaseLib(DEFAULT_URL,DEFAULT_TOKEN);

$firebase->set("/users",$test);

$user = $firebase->get("/users");

echo $user;

$ php test.php
{“code”:”DOT”,”name”:”Polkadot”}

おおおおお、なんか感動した!

Beaconとは?

Beaconとは、低消費電力の近距離無線技術「Bluetooth Low Energy」を利用した位置特定技術

GPSは人工衛星から発する電波を活用して位置情報を把握する仕組み
Beaconは信号を半径数十メートル範囲に発信する発信機、建物の中や地下でも受信できる ただし、距離が限られる

Beaconの発信情報をスマホに表示されるなどができる

出席、遅刻などをbeaconを使って管理する

社会インフラがBeaconを提供すれば、それを活用してInput, Outputが出来そうではある

NFC(Near field communication)とは?

NFCとはかざすだけで周辺機器と通信できる技術
NFCのか通用でスマホ決済が利用できる
SuicaもNFCが活用されている

アメリカのモトローラが開発、CPU内蔵で高速
マイナンバーカード、運転免許証、パスワードなどに使用

Felicaはnanaco, iD, 楽天Edyなど多くの電子マネーで使用

### NFCチップ
NFCチップ(IC)が搭載されていれば、短波HF帯(13.56MHz)を利用して、すぐ近くにあるNFC対応機器とワイヤレス通信できる。ただし、通信速度は最大424kbpsと低速

ラズパイでNFCタグを読み取る例

なるほど、ICチップの中に、idやsuicaの残高や名前などの情報を埋め込んでるのね。
電流を流して、ICチップと情報のやり取りをしている

これICチップ作ってるところの独占技術だな
Android ChromeでWeb NFCってのもあるみたい

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;
}