【Python】スタックマシンの実装

内部でどのような処理が行われているかを表している

class PVM:
    def __init__(self):
        self.stack = []
        self.output = []

    def LOAD_NAME(self, name):
        self.stack.append(name)

    def LOAD_CONST(self, const):
        self.stack.append(const)

    def CALL(self, arg_count):
        args = [self.stack.pop() for _ in range(arg_count)]
        func = self.stack.pop()
        result = func(*args)
        if result is not None:
            self.stack.append(result)

    def POP_TOP(self):
        if self.stack:
            self.stack.pop()

    def simulate(self, instructions):
        for instr, arg in instructions:
            match instr:
                case "LOAD_NAME":
                    self.LOAD_NAME(arg)
                case "LOAD_CONST":
                    self.LOAD_CONST(arg)
                case "CALL":
                    self.CALL(arg)
                case "POP_TOP":
                    self.POP_TOP()

            self.output.append(list(self.stack))
        
        return self.output

instructions = [
    ("LOAD_NAME", print),
    ("LOAD_CONST", "Hello, World"),
    ("CALL", 1),
    ("POP_TOP", None),
]

pvm = PVM()
stack_states = pvm.simulate(instructions)
print(stack_states)

$ python3 pvm.py
Hello, World
[[], [, ‘Hello, World’], [], []]

関数と変数をスタックに格納してpopとpushで処理していく。なるほどー
そうすると、どれくらい作り込むかってところか…

【Python】hello worldの裏で起こっていること

main.py

print("Hello, World")

$ python3 main.py
Hello, World

### python実行の流れ
– ソースコード読み込み
– 字句解析
– 構文解析
– 意味解析
– バイトコードを実行(仮想マシン上)

### 字句解析/構文解析の流れ

import ast

source = """
print("Hello, World")
"""

tree = ast.parse(source)
print(ast.dump(tree))

$ python3 main.py
Module(body=[Expr(value=Call(func=Name(id=’print’, ctx=Load()), args=[Constant(value=’Hello, World’)], keywords=[]))], type_ignores=[])

### バイトコード

import ast
import dis

source = """
print("Hello, World")
"""

tree = ast.parse(source)

compiled_code = compile(tree, filename="<ast>", mode="exec")
bytecode = dis.dis(compiled_code)
print(bytecode)

$ python3 main.py
2 0 LOAD_NAME 0 (print). // stackにpush
2 LOAD_CONST 0 (‘Hello, World’) // stackにpush
4 CALL_FUNCTION 1 // print関数の呼び出し
6 POP_TOP            // stackのtopを破棄
8 LOAD_CONST 1 (None) // Noneスタックを入れてスタックから戻る
10 RETURN_VALUE
None

このバイトコードはスタックマシン上で実行されている
つまり、スタックマシンが行っているのは、意味解析が終わった最後のバイトコードの実行のところということだ。
なるほど、スタックマシンについて少し理解した。

【Rust】最大値・最小値【Algorithm】

変数を用意しておいて、最大値、最小値の値を更新していくだけですね。
ループを抜けるのは10000以上か0以下としています。

fn main() {

   let mut imax: i32 = -1;
   let mut imin: i32 = 10000;
   let mut kmax: i32 = 0;
   let mut kmin: i32 = 0;
   let mut k: i32 = 0;
   let mut i: i32 = 0;

   while(i >= 0 && i <= 9999){
      println!("4桁以内の正の整数を入力してください。");
      let mut x = String::new();
      std::io::stdin().read_line(&mut x).expect("Failed to read line");
      x = x.trim_end().to_owned();
      i = x.parse::<i32>().unwrap();
      if (0 < i && i < 10000) {
         k += 1;
         if(imax < i) {
            imax = i;
            kmax = k;
         }

         if(imin > i) {
            imin = i;
            kmin = k;
         }
      }
   }

   if (k == 0) {
      println!("入力されていません。");
   } else {
      println!("最大値 {}({}回目)", imax, kmax);
      println!("最小値 {}({}回目)", imin, kmin);
   }
}

Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.90s
Running `target/debug/basic`
4桁以内の正の整数を入力してください。
100
4桁以内の正の整数を入力してください。
20
4桁以内の正の整数を入力してください。
50
4桁以内の正の整数を入力してください。
29
4桁以内の正の整数を入力してください。
829
4桁以内の正の整数を入力してください。
2222
4桁以内の正の整数を入力してください。
2452
4桁以内の正の整数を入力してください。
11245
最大値 2452(7回目)
最小値 20(2回目)

うーむ なるほど〜

【Rust】所持金ピッタリ【Algorithm】

所持金ピッタリになる組み合わせをwhile文で全パターン調べる

fn main() {

   println!("所持金を入力してください。");
   let mut x = String::new();
   std::io::stdin().read_line(&mut x).expect("Failed to read line");
   x = x.trim_end().to_owned();
   let mut wallet: i32 = x.parse::<i32>().unwrap();
   
   let mut x = 0;
   let mut y = 0;

   while(500 * x + 300*y <= wallet) {
      while(500 * x + 300*y <= wallet) {
         if(500*x + 300*y == wallet) {
            println!("500円のケーキ:{}個", x);
            println!("300円のケーキ:{}個\n", y);
         }
         y += 1;
      }
      x += 1;
      y=0;
   }
}

Running `target/debug/basic`
所持金を入力してください。
3000
500円のケーキ:0個
300円のケーキ:10個

500円のケーキ:3個
300円のケーキ:5個

500円のケーキ:6個
300円のケーキ:0個

while文の入れ子って珍しい感じがするが、条件に当てはまるまでのループはforよりwhileの方が分かりやすい感じはしますね。

【React.js】JSXでhrefの文字列と値を連結する

文字列の連結は、{‘hoge’ + value} と言うように、{}の中で連結する

render() {
    if (this.state.data) {
      return <div>
        <table class="table">
        <thead>
        <tr>
          <th scope="col">Height</th>
          <th scope="col">Time</th>
          <th scope="col">Hash</th>
        </tr>
        </thead>
        <tbody>
          {this.state.data.map((value) => (
            <tr>
              <th scope="row"><a href={'/data/' + value.height} >{value.height}</a></th>
              <td>{value.time}</td>
              <td>{value.hash}</td>
            </tr>
          ))}
        </tbody>
        </table>
      </div>
    }
    else {
      return <div>Loading...</div>
    }
  }

リンクは以下のように設定されます
http://***/data/1

ここに辿り着くまでに結構時間かかりました… OK

【PostgreSQL】JOINの使い方とイロハ

### JOINとは?
テーブル同士を結合させるときに使用するSQL句

JOINには
– cross join
– inner join
– left join
– right join
– full outer join
がある。

postgres=# CREATE TABLE example1 (
        id integer primary key,
        name text NOT NULL,
        age integer
);
CREATE TABLE                              ^
postgres=# CREATE TABLE example2 (
        id integer primary key,
        user_id integer,
        hobby text,
        favorite_food text,
        FOREIGN KEY (user_id) references example1(id)
);
CREATE TABLE
postgres=# INSERT INTO example1(id, name, age)
VALUES
        (1, '山田太郎', 31),
        (2, '田中一郎', 25),
        (3, '小林幸子', 27);
INSERT 0 3
postgres=# INSERT INTO example2(id, user_id, hobby, favorite_food)
VALUES
        (1, 1, '散歩', 'りんご'),
        (2, 2, '手芸', '秋刀魚'),
        (3, null, 'サッカー', 'ラーメン'),
        (4, null, '映画鑑賞', '寿司');
INSERT 0 4

### CROSS JOIN
考えうる全ての組み合わせを作成
SELECT * FROM example1 CROSS JOIN example2;

### (INNER) JOIN
指定したレコードを軸に結合(一番イメージが近い)
postgres=# SELECT * FROM example1 JOIN example2 ON example2.user_id = example1.id;
id | name | age | id | user_id | hobby | favorite_food
—-+———-+—–+—-+———+——-+—————
1 | 山田太郎 | 31 | 1 | 1 | 散歩 | りんご
2 | 田中一郎 | 25 | 2 | 2 | 手芸 | 秋刀魚
(2 rows)

### LEFT JOIN
joinで指定したテーブルに対応するレコードがない場合でも全て取得
postgres=# SELECT * FROM example1 LEFT JOIN example2 ON example2.user_id = example1.id;
id | name | age | id | user_id | hobby | favorite_food
—-+———-+—–+—-+———+——-+—————
1 | 山田太郎 | 31 | 1 | 1 | 散歩 | りんご
2 | 田中一郎 | 25 | 2 | 2 | 手芸 | 秋刀魚
3 | 小林幸子 | 27 | | | |
(3 rows)

### RIGHT JOIN
left joinの反対
postgres=# SELECT * FROM example1 RIGHT JOIN example2 ON example2.user_id = example1.id;
id | name | age | id | user_id | hobby | favorite_food
—-+———-+—–+—-+———+———-+—————
1 | 山田太郎 | 31 | 1 | 1 | 散歩 | りんご
2 | 田中一郎 | 25 | 2 | 2 | 手芸 | 秋刀魚
| | | 3 | | サッカー | ラーメン
| | | 4 | | 映画鑑賞 | 寿司

### FULL OUTER JOIN
left joinとright joinを組み合わせたようなもの
postgres=# SELECT * FROM example1 FULL OUTER JOIN example2 ON example2.user_id = example1.id;
id | name | age | id | user_id | hobby | favorite_food
—-+———-+—–+—-+———+———-+—————
1 | 山田太郎 | 31 | 1 | 1 | 散歩 | りんご
2 | 田中一郎 | 25 | 2 | 2 | 手芸 | 秋刀魚
| | | 3 | | サッカー | ラーメン
| | | 4 | | 映画鑑賞 | 寿司
3 | 小林幸子 | 27 | | | |
(5 rows)

なるほど、、、1対1で対応してないとjoinはselectできないね。

更にデータを追加します。
INSERT INTO example2(id, user_id, hobby, favorite_food)
VALUES
(5, 1, ‘買い物’, ‘マンゴー’),
(6, 2, ‘旅行’, ‘パスタ’);

postgres=# SELECT * FROM example1 JOIN example2 ON example2.user_id = example1.id;
id | name | age | id | user_id | hobby | favorite_food
—-+———-+—–+—-+———+——–+—————
1 | 山田太郎 | 31 | 1 | 1 | 散歩 | りんご
2 | 田中一郎 | 25 | 2 | 2 | 手芸 | 秋刀魚
1 | 山田太郎 | 31 | 5 | 1 | 買い物 | マンゴー
2 | 田中一郎 | 25 | 6 | 2 | 旅行 | パスタ
(4 rows)

joinでwhereをつけられる
postgres=# SELECT * FROM example1 JOIN example2 ON example2.user_id = example1.id WHERE example1.id = 1;
id | name | age | id | user_id | hobby | favorite_food
—-+———-+—–+—-+———+——–+—————
1 | 山田太郎 | 31 | 1 | 1 | 散歩 | りんご
1 | 山田太郎 | 31 | 5 | 1 | 買い物 | マンゴー

なるほど、雰囲気は大体わかりました。
これをtransactionとblockでやりたい

bootstrapでcardを横並びに書く方法

PCでは横並びにして、SPでは縦並びにする書き方
まずrowで囲み、その中で、col-md-*で横のサイズを指定して、cardを囲む
div class=”card col-md-6″だとズレて表示されてしまうため、注意が必要

<div class="row">
          <div class="col-md-6">
          <div class="card ">
            <h5 class="card-header">Blocks</h5>
            <div class="card-body">
              <h5 class="card-title">Special title treatment</h5>
              <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
              <a href="#" class="btn btn-primary">Go somewhere</a>
            </div>
          </div>
          </div>
          <div class="col-md-6">
            <div class="card">
              <h5 class="card-header">Transactions</h5>
              <div class="card-body">
                <h5 class="card-title">Special title treatment</h5>
                <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
                <a href="#" class="btn btn-primary">Go somewhere</a>
              </div>
            </div>
          </div>  
        </div>
      </div>

【Vite】npm run devでlocalhost:5173で接続できない時

vagrantでサーバを立てており、localhost:5173で接続できない時

$ npm run dev

> explore@0.0.0 dev
> vite

9:48:42 PM [vite] (client) Re-optimizing dependencies because vite config has changed

VITE v6.2.5 ready in 466 ms

➜ Local: http://localhost:5173/
➜ Network: use –host to expose
➜ press h + enter to show help

$ npm run dev — –host

> explore@0.0.0 dev
> vite –host

VITE v6.2.5 ready in 132 ms

➜ Local: http://localhost:5173/
➜ Network: http://10.211.55.3:5173/
➜ Network: http://192.168.33.10:5173/
➜ press h + enter to show help

これで、192.168.33.10:5173でアクセスできるようになる。
OK^^

【Vite】viteでSassを使いたい

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>About - My Vite Project</title>
  <link rel="stylesheet" href="./src/style.scss">
</head>

style.scss

body {
    margin: 50px;
    h1 {
        color: green;
    }
}

### build
$ npm run build
$ cd dist
$ tree
.
├── assets
│ ├── index-D8b4DHJx.css
│ ├── index-DK-xQhXp.js
│ └── react-CHdo91hT.svg
├── index.html
└── vite.svg

1 directory, 5 files

body{margin:50px}body h1{color:green}

うおおおおおおおおおお、これは凄い…

【Vite】フロントエンドの開発でViteを使ってみたい

$ node -v
v22.13.1
$ npm create vite@latest
$ npm install
$ npm run dev

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
})

$ npm install sass -D

about.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>About - My Vite Project</title>
</head>
<body>
  <h1>About Page</h1>
  <p>This is the about page of my Vite project.</p>
  <a href="index.html">Back to Home</a>

  <script type="module" src="./src/about.js"></script>
</body>
</html>

src/about.js

console.log('About page loaded!')

なるほど、使いやすそうではある。