String Byte conversion for PHP

Let’s look up hex2bin function in php manual.
hex2bin

It says “Decodes hexadecimally encoded binary string”.

Example 1

mb_internal_encoding('UTF-8');
$char = 'あ';

echo bin2hex($char);

result: e38182

This is the unicode standard manual
Unicode.org
UTF8 has 1byte to 4 byte characters.

What happen about in the case of Emoji?
🌸 Cherry blossom: 1F338

mb_internal_encoding('UTF-8');
$char = '🌸';

echo bin2hex($char);

f09f8cb8
A number different from unicode was displayed.
Comversion seems to be done without problems.

Character Code as mainly used in Japan

Character Code
It refers to the correspondence between the characters used on the computer and the numbers in bytes assigned to each letter. Character codes have some to be used in many language spheres by computers, and the variety has increased. Typical character codes are said to be more than 100 kinds.

Mainly used in Japan
JIS Code
The official name is “ISO-2022-JP”. It is widely used.

SJIS(Shift-JIS) Code
It is ASCII code plus Japanese, and it is used in Japan domestic mobile phones.

EUC
It is widely used on UNIX.


Unicode consists of “encoded character set” and “character encoding method(encoding)”.

“Character set” refers to letters put together by certain rules such as “All Hiragana” and “All Alphabet”, for example. A rule in which a unique code is associated with the character set is called a “coded character set”. The associated numerical value is called a code point and it is displayed in the form of “U + xxxxx”.

“Character encoding method” is a method of converting a coded character set into another byte sequence so that it can be handled by a computer. The encoding methods include UTF-8 and UTF-16.

Unicode code point
0x0000 – 0x007f : ASCII
0x0080 – 0x07ff : Country alphabet
0x0800 – 0xffff : Indian characters, punctuation marks, academic symbols, pictograms, East Asian characters, double-byte, half-size

OK!

Linux grep option -e

What is linux grep option -e

The -e option is used to search for “or”.
Let’s look at example below.

command

sudo cat cron | grep 'Jan 12 11:0[0-9]' | grep -e run-parts -e anacron
[vagrant@localhost log]$ sudo cat cron | grep 'Jan 12 11:0[0-9]' | grep -e run-parts -e anacron
Jan 12 11:01:01 localhost CROND[8441]: (root) CMD (run-parts /etc/cron.hourly)
Jan 12 11:01:01 localhost run-parts(/etc/cron.hourly)[8441]: starting 0anacron
Jan 12 11:01:01 localhost anacron[8450]: Anacron started on 2019-01-12
Jan 12 11:01:01 localhost run-parts(/etc/cron.hourly)[8452]: finished 0anacron
Jan 12 11:01:01 localhost anacron[8450]: Will run job `cron.daily' in 7 min.
Jan 12 11:01:01 localhost anacron[8450]: Jobs will be executed sequentially
Jan 12 11:08:01 localhost anacron[8450]: Job `cron.daily' started
Jan 12 11:08:01 localhost run-parts(/etc/cron.daily)[8453]: starting logrotate
Jan 12 11:08:01 localhost run-parts(/etc/cron.daily)[8461]: finished logrotate
Jan 12 11:08:01 localhost run-parts(/etc/cron.daily)[8453]: starting makewhatis.cron
Jan 12 11:08:03 localhost run-parts(/etc/cron.daily)[8585]: finished makewhatis.cron
Jan 12 11:08:03 localhost anacron[8450]: Job `cron.daily' terminated
Jan 12 11:08:03 localhost anacron[8450]: Normal exit (1 job run)

PHP google translate API

How to use PHP Google translation?

mkdir a directory and clone the repo

[vagrant@localhost translation]$ git clone https://github.com/GoogleCloudPlatform/php-docs-samples
Initialized empty Git repository in /home/vagrant/app/translation/php-docs-samples/.git/
remote: Enumerating objects: 79, done.
remote: Counting objects: 100% (79/79), done.
remote: Compressing objects: 100% (65/65), done.
remote: Total 10046 (delta 27), reused 35 (delta 9), pack-reused 9967
Receiving objects: 100% (10046/10046), 10.07 MiB | 530 KiB/s, done.
Resolving deltas: 100% (6246/6246), done.

[vagrant@localhost php-docs-samples]$ ls
CONTRIBUTING.md bigtable error_reporting logging trace
LICENSE cloud_sql favicon.ico monitoring translate
README.md compute firestore pubsub video
appengine datastore iap spanner vision
asset debugger iot speech
auth dialogflow jobs storage
bigquery dlp kms testing
bigquerydatatransfer endpoints language texttospeech

translate.php

/**
 * Copyright 2016 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
require __DIR__ . '/vendor/autoload.php';

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

$application = new Application('Google Cloud Translate API');

// Add Detect Language command
$application->add(new Command('detect-language'))
    ->setDescription('Detect which language text was written in using Google Cloud Translate API')
    ->addArgument('text', InputArgument::REQUIRED, 'The text to examine.')
    ->setHelp(<<<EOF
The <info>%command.name%</info> command detects which language text was written in using the Google Cloud Translate API.

    <info>php %command.full_name% "Your text here"</info>

EOF
    )
    ->setCode(function ($input, $output) {
        $text = $input->getArgument('text');
        require __DIR__ . '/src/detect_language.php';
    });

// Add List Codes command
$application->add(new Command('list-codes'))
    ->setDescription('List all the language codes in the Google Cloud Translate API')
    ->setHelp(<<<EOF
The <info>%command.name%</info> command lists all the language codes in the Google Cloud Translate API.

    <info>php %command.full_name%</info>

EOF
    )
    ->setCode(function ($input, $output) {
        require __DIR__ . '/src/list_codes.php';
    });

// Add List Languages command
$application->add(new Command('list-langs'))
    ->setDescription('List language codes and names in the Google Cloud Translate API')
    ->addOption('target-language', 't', InputOption::VALUE_REQUIRED,
        'The ISO 639-1 code of language to use when printing names, eg. \'en\'.')
    ->setHelp(<<<EOF
The <info>%command.name%</info> lists language codes and names in the Google Cloud Translate API.

    <info>php %command.full_name% -t en</info>

EOF
    )
    ->setCode(function ($input, $output) {
        $targetLanguage = $input->getOption('target-language');
        require __DIR__ . '/src/list_languages.php';
    });

// Add Translate command
$application->add(new Command('translate'))
    ->setDescription('Translate text using Google Cloud Translate API')
    ->addArgument('text', InputArgument::REQUIRED, 'The text to translate.')
    ->addOption('model', null, InputOption::VALUE_REQUIRED, 'The model to use, "base" for standard and "nmt" for premium.')
    ->addOption('target-language', 't', InputOption::VALUE_REQUIRED,
        'The ISO 639-1 code of language to use when printing names, eg. \'en\'.')
    ->setHelp(<<<EOF
The <info>%command.name%</info> command transcribes audio using the Google Cloud Translate API.

    <info>php %command.full_name% -t ja "Hello World."</info>

EOF
    )
    ->setCode(function ($input, $output) {
        $text = $input->getArgument('text');
        $targetLanguage = $input->getOption('target-language');
        $model = $input->getOption('model');
        if ($model) {
            require __DIR__ . '/src/translate_with_model.php';
        } else {
            require __DIR__ . '/src/translate.php';
        }
    });

// for testing
if (getenv('PHPUNIT_TESTS') === '1') {
    return $application;
}

$application->run();

Google Translate API Pricing

This is a Google Cloud Translating API page
Cloud Translation API document

I would like to Transtaion API for slack.

function that to make
– when user write Japanese in slack, slack bot change sentence into English.

Official document
0-1 billion characters(1,000,000,000)
Translation $20 per 1,000,000 characters
Language Detection $20 per 1,000,000 characters

What is language detection?
-> Determine what language is.

What should I do?
-> Check PHP sample for google translation API.

Here is GHE repository and get code.
https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/translate

Translation API is convenient, but it feel like somewhat expensive.

エンジニアと英語の表現力

エンジニアにとって、英語力は必須。
これは間違いないだろう。

英語でも、リスニング、リーディング、ライティングがある。特に重要なのはreadingかと思っていたが、どうやら考えが甘すぎた。。
– listening
– reading
– writing

本当に重要なのは、英語の表現力。
高いレベルの仕事をするには、説得力のある説明や、よりスムーズに仕事をできるような英語力が必須。
とはいえ、これは直ぐには身につかないし、何をやるのがベストか?

案1:英語でブログを書く
案2:英語のサービスを作る
案3:海外に移住する

どうするか??
英語が重要なのは絶対に間違いない。
案1を1年~2年くらい目標にやってみるか。。

システム開発における基本設計とは何か?

基本設計とは何か?よく基本設計、詳細設計と言葉が独り歩きしていますが、具体的に基本設計とは何を指しているのか?

だいたいこんなところか?
– システムの要求定義/課題整理
– 全体概要
– 機能一覧
– 業務フロー
– 画面設計
– 画面フロー
– データベース設計

特に要求定義と課題整理が肝か。

フォーマットは?? もう少しフォーマルにするなら
1. 業務フロー(Excel)
2. システム構成図(Excel)
3. ER図(OBER)
4. テーブル定義書(OBER)
5. 設計書記述様式(Excel)
6. 基本設計書(Excel)
7. 画面遷移図
8. 画面レイアウト

少しソフトウェア開発っぽくなってきましたね。
順番としては、基本設計書、業務フロー、システム構成図から順番に作っていくイメージでしょうか。。

S3へのアップロード

if(file_exists($_FILES['upfile']['tmp_name'])){
	$ext = substr($_FILES['upfile']['name'], strrpos($_FILES['upfile']['name'],'.') + 1);
	echo $ext."<br>";
	if(strtolower($ext) !== 'png' && strtolower($ext) !== 'jpg' && strtolower($ext) !== 'jpeg' && strtolower($ext) !== 'gif'){
		echo '画像以外のファイルが指定されています。画像ファイル(png/jpg/jpeg/gif)を指定して下さい';
		exit();
	}

	$tmpname = str_replace('/tmp/', '', $_FILES['upfile']['tmp_name']);
	echo $tmpname;
	// $new_filename = 'profiles/'.$id.'-'.time().'-'.$tmpname.'.'.$ext;



$s3clinet = S3Client::factory([
		'credentials' => [
		'key' => env('AWS_ACCESS_KEY_ID'),
		'secret' => env('AWS_SECRET_ACCESS_KEY'),
		],
		'region' => 'northeast-1',
		'version' => 'latest',
]);

$bucket = getenv('zeus-image')?: die('no zeus-image config var in found in env!');

$image = fopen($_FILES['upfile']['tmp_name'],'rb');

// 画像アップロード
$result = $s3client->putObject([
		'ACL' => 'public-read',
		'Bucket' => $bucket,
		'Key' => $new_filename,
		'Body' => $image,
		'ContentType' => mime_content_type($_FILES['upfile']['tmp_name']),
]);

}

これでいいのか?いや、良くない、アップロードされてない。。
require ‘vendor/autoload.php’;を足せばよい?? なんかちゃうなー。。

php fopenの’rb’とは?

tmpファイルのアップロードで、以下の様に書いていた。

$image = fopen($_FILES['upfile']['tmp_name'],'rb');

ところで、この’rb’って何? 一瞬、rubyの拡張子に見えたんだが、絶対違うよな。。
‘b’は強制的にバイナリモードにします。
fopen(‘file’,’r’): 読み込みのみで開く。ファイルポインタはファイルの先頭におく。
fopen(‘file’,’r+’): 読み書き可能な状態で開く。ファイルポインタはファイルの先頭におく。
‘b’は強制的にバイナリモードにする。

よって fopen(‘file’,’r’); は、読み込みのみで開く。強制的にバイナリモードにする。

バイナリモードで開くってことね♪

phpでアップロードした画像のファイル名を取得しよう

まずformでアップロード機能をサクッと作ります。

<?php
if(file_exists($_FILES&#91;'upfile'&#93;&#91;'tmp_name'&#93;)){
	$ext = substr($_FILES&#91;'upfile'&#93;&#91;'name'&#93;, strrpos($_FILES&#91;'upfile'&#93;&#91;'name'&#93;,'.') + 1);
	echo $ext."<br>";
	if(strtolower($ext) !== 'png' && strtolower($ext) !== 'jpg' && strtolower($ext) !== 'jpeg' && strtolower($ext) !== 'gif'){
		echo '画像以外のファイルが指定されています。画像ファイル(png/jpg/jpeg/gif)を指定して下さい';
		exit();
	}

	$tmpname = str_replace('/tmp/', '', $_FILES['upfile']['tmp_name']);
	echo $tmpname;
	// $new_filename = 'profiles/'.$id.'-'.time().'-'.$tmpname.'.'.$ext;
}

?>
<div id="content">
<h2>画像管理</h2>
<hr>
<form action="#" method="POST" enctype="multipart/form-data">
<div id="drag-drop-area">
 <div class="drag-drop-inside">
  <p class="drag-drop-info">ここにファイルをアップロード</p>
  <p>または</p>
  <!-- <input type="file" value="ファイルを選択" name="image"> -->
  <p class="drag-drop-buttons"><input id="fileInput" type="file" value="ファイルを選択" name="upfile"></p>
      <input type="submit" value="送信">
   </div>
  </div>
</form>

アップロード前

アップロード後

うん、上手くいってるようです。
さて、s3をやりましょう。ここまで長かった。