Skip to main content

Getting Started with Poetry: A Python Package Manager

· One min read

Installing Poetry

Install Poetry using pip. (It's also a good idea to upgrade pip at the same time.)

python -m pip install --upgrade pip
pip install poetry

Creating a Python Project with Poetry

1. Creating a New Python Project

To create a new Python project, run poetry new. A Python project template will be generated.

poetry new xxxxxxxx

2. Existing Python Project

If you already have a Python project, run poetry init to add the necessary configuration files for Poetry.

poetry init

Entering the Poetry Virtual Environment

Run poetry shell to start a shell in the Poetry virtual environment. You can use the packages added using Poetry.

poetry shell

Adding Packages to Poetry

You can add dependency packages using poetry add.

poetry add xxxxxxxx

Other Commonly Used Commands

  • poetry list: Displays a list of commands.
  • poetry build: Creates packages (.tar.gz, .whl).
  • poetry install: Installs dependency packages.
  • poetry publish: Publishes created packages to PyPI, etc.
  • poetry search: Searches for packages.
  • poetry run: Executes commands in the Poetry environment.
  • poetry show: Displays available packages.
  • poetry update: Executes dependency package updates.

About My Personal Site

· 2 min read

While Twitter and Instagram are major platforms for information dissemination, they are limited by terms of service and regulations, restricting freedom of expression. Returning to a personal website is a viable option. This site is user-friendly as it does not utilize W○X and therefore lacks advertising or promotion.

Design Aspects

This site is built using the Jekyll framework, and all themes are custom-made. Here, "theme" refers to font sizes, site structure, margins, etc. It also supports responsive design (adapting to various devices like smartphones and PCs) and dark mode. Although it appears simple, the CSS alone amounts to 13.5 KiB. There's a reason for this. A common pitfall in presentations by those unfamiliar with design is the overuse of accent colors, rainbow gradients, or small margins, resulting in a gaudy design. In other words, poorly executed design can actually make things look worse. Therefore, using accent colors sparingly and setting appropriate margins is beneficial. The result of these meticulous efforts is the large amount of CSS. If anyone finds this homepage gaudy, please share your opinion. Personally, I believe a website with a simple design and no unnecessary animations is the best.

Homepage Design

This homepage is built with Jekyll. Jekyll simplifies web page creation by allowing you to write HTML templates and combine them with Markdown content. Typically, creating web pages would require writing HTML for each one, and modifying them would involve changing each page individually, which is cumbersome. However, using Jekyll makes modifications easier.

Deployment to GitHub Pages

This site utilizes GitHub Pages. GitHub Pages allows you to publish web pages for free and even set up a custom domain. However, the free tier has limitations, such as only allowing Pages for public repositories. For Jekyll deployment, GitHub Actions are used to generate the web page whenever a push is made. While Jekyll can be configured to generate pages on every push, workflows enable the use of plugins.

Required Technologies

The technologies necessary to create such a personal site are:

  • Jekyll
  • HTML
  • CSS / Sass
  • GitHub
  • JavaScript / TypeScript (not essential)

Considering that creating a personal site alone equips you with these skills, I recommend that programming beginners start by creating a personal site.

Function to return MD5 (string) from string (C#)

· One min read

Functions used

  • byte[] Encoding.UTF8.GetBytes(string) Converts a string to a byte[]
  • MD5 MD5.Create() Creates an MD5 instance
  • byte[] md5.ComputeHash(byte[]) Generates an MD5 hash from a byte[]

Example

string str2MD5(string src)
{
byte[] srcBytes = Encoding.UTF8.GetBytes(src);
string MD5src;
using (MD5 md5 = MD5.Create())
{
byte[] MD5srcBytes = md5.ComputeHash(srcBytes);
StringBuilder sb = new();
for (int i = 0; i < MD5srcBytes.Length; i++)
sb.Append(MD5srcBytes[i].ToString("x2"));
MD5src = sb.ToString();
}
return MD5src;
}

CUDA Grid, Block, and Thread Dimensions and Notes

· 2 min read
  • Thread: A single execution unit.
  • Block: A group of threads (arranged in 3D).
  • Grid: A group of blocks (arranged in 3D).

There are limits to the number of threads, blocks, and grids, which can be obtained using the deviceQuery command.

On RTX3080 with CUDA 11.8, the following were:

Maximum number of threads per block:           1024
Max dimension size of a thread block (x,y,z): (1024, 1024, 64)
Max dimension size of a grid size (x,y,z): (2147483647, 65535, 65535)

In this case:

  • The maximum number of threads per block is 1024.
  • The block shape must fit within (1024, 1024, 64). That is, if the block shape is (a, b, c), then the following conditions must be met: $abc \leq 1024$ and $a \leq 1024$ and $b \leq 1024$ and $c \leq 64$.
  • The grid shape must fit within (2147483647, 65535, 65535). That is, if the grid shape is (d, e, f), then the following conditions must be met: $def \leq 2147483647 \times 65535 \times 65535$ and $d \leq 2147483647$ and $e \leq 65535$ and $f \leq 65535$.

The type used to define grid and block shapes is dim3.

Example Usage

#include <stdio.h>

__global__ void func1(){
printf("%d, %d, %d\n", threadIdx.x, threadIdx.y, threadIdx.z);
}

__global__ void func2(){
int i = threadIdx.x + blockDim.x * threadIdx.y + blockDim.x * blockDim.y * threadIdx.z;
printf("%d\n", i);
}

int main(){
dim3 grid(1, 1, 1);
dim3 block(4, 8, 32);

func1<<<grid, block>>>();
func2<<<grid, block>>>();
cudaDeviceSynchronize();
}

Generating Random Numbers in Rust

· One min read

Note: If the crate version is different, the functions will also be different.

Add the required crate

Add the rand crate as a dependency.

cargo add rand

Example program to generate uniformly distributed random numbers

use rand::Rng;

fn main(){
let mut rng = rand::thread_rng();

// Floating-point number
let r: f64 = rng.gen_range(0.0..10000.0);
println!("{}", r);

// Integer
let r: i32 = rng.gen_range(0..10000);
println!("{}", r);
}
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/test`
9464.07133934519
9606

Example program to generate uniformly distributed random numbers

use rand::Rng;

fn main(){
let mut rng = rand::thread_rng();

let r: f64 = rng.gen();
println!("{}", r);
}
$ cargo run
Compiling alg2opt v0.1.0 (/home/hikari/2-opt/alg2opt)
Finished dev [unoptimized + debuginfo] target(s) in 0.26s
Running `target/debug/test`
0.34703657185118175

Random numbers following a specified distribution

use rand::Rng;
use rand::distributions::Uniform;

fn main(){
let mut rng = rand::thread_rng();

let r: f64 = rng.sample(Uniform::new(10.0, 15.0));
println!("{}", r);
}
$ cargo run
Compiling alg2opt v0.1.0 (/home/hikari/2-opt/alg2opt)
Finished dev [unoptimized + debuginfo] target(s) in 0.26s
Running `target/debug/test`
12.13344856630783

Reference

https://docs.rs/rand/0.8.5/rand/trait.RnG.html [EOL]

My Current PC Environment Summary

· 2 min read

I feel like I spend a lot of money on my PC environment, but I don't know exactly how much, so I'm summarizing it here.

PC Main Unit

PartManufacturerModelPurchase PriceNotes
MotherboardASUSB450M-K¥7,291MicroATX
CPUAMDRyzen 3 3900X¥53,28012 Cores 24 Threads, Base Clock 3.8GHz, Max 4.6GHz, TDP 105W, Passmark 32784
MemoryPanramW4U3200PS-16G¥16,478DDR4-3200 16GiB x 2
SSDCFDCSSD-M2B1TPG3VNF¥12,9801TB NVMe
GPUPalit MicrosystemsNED3080019IA-132AA¥120,500RTX 3080
Power SupplyCorsairRM850¥12,291850W 80PLUS Gold
PC CaseDEEPCOOLMACUBE 110 PK R-MACUBE110-PRNGM1N-A-1¥6,000MicroATX compatible

Total: 228,820 JPY

Comment: It's not as expensive as I thought (?). Since it's MicroATX, there's almost no expandability. I might have been better off buying ATX without being stingy, especially since I can't add more memory. I usually consume over 20 GiB of memory, so I might want more.

Peripherals

PeripheralsManufacturerModelPurchase PriceNotes
DisplayI-O DataLD4K271DB¥33,8004K. 27 inches. Vesa compatible
Pen DisplayXP-PenArtist 22 Second¥47,680FHD. 21.5 inches
MouseLogitechERGO M575¥5,500Trackball. Bluetooth, Unifying
KeyboardTopreREALFORCE R2-JP4-BK¥15,470USB. Capacitive non-contact key switch
WEB CameraElecomUCAM-C820ABBK¥3,809FHD
SpeakersPioneer-¥1,000Used. Hard Off
AmplifierELEGIANT-¥3,488Chinese digital amp. Was advertised as Bluetooth compatible but didn't work. Recommend replacing the cheap included AUX cable.
MicrophoneUHURUUM900¥6,499Chinese USB microphone
Headphonesaudio-technicaATH-M50x¥16,000

Total: 133,246 JPY

Other

PeripheralsManufacturerModelPurchase PriceNotes
IC Card Reader/WriterNTT CommunicationsACR39-NTTCom¥2,320Can read/write My Number card
Power StripElecomT-DK2320CBS¥1,264Desk mount. 3 outlets

IT Passport Alphabet Summary

· 4 min read
AbbreviationNameMeaning
CSRCorporate Social ResponsibilityThe responsibility of a company to operate in an ethical and sustainable and socially responsible manner.
SDGsSustainable Development GoalsA set of 17 global goals adopted by the United Nations to promote sustainable development.
OJTOn the Job TrainingTraining that takes place while the employee is already working.
Off-JTOff the Job TrainingTraining that takes place away from the employee's job.
HRTechHuman Resource TechnologyThe use of IT in human resources.
CEOChief Executive OfficerThe highest-ranking executive in a company, responsible for the overall success of the organization.
CIOChief Information OfficerThe executive responsible for the use of information technology to achieve the goals of the organization.
COOChief Operating OfficerThe executive responsible for the day-to-day administrative and operational functions of a business.
CFOChief Financial OfficerThe executive responsible for managing the financial risks of the company.
ABC AnalysisA Pareto chart used to categorize data into three groups based on importance.
B/SBalance SheetA financial statement that shows a company's assets, liabilities, and equity at a specific point in time.
ROEReturn On EquityA ratio that measures a company's profitability in relation to shareholders' equity.
JAN CodeJapanese Article NumberA barcode standard used in Japan.
QR CodeQuick ResponseA two-dimensional barcode that can store more data than a traditional barcode.
ISOInternational Organization for StandardizationAn international organization that develops and publishes international standards.
SWOT AnalysisStrengths・Weaknesses・Opportunities・ThreatsA strategic planning tool used to evaluate a company's strengths, weaknesses, opportunities, and threats.
PPMProduct Portfolio ManagementA method of categorizing products into stars, cash cows, question marks, and dogs.
M&AMergers and AcquisitionsThe combination of two or more companies into one.
VCVenture CapitalInvestment firms that invest in startups with high growth potential.
IPOInitial Public OfferingThe first time a private company offers shares to the public.
TOBTake Over BidA tender offer in which a company attempts to acquire another company by purchasing its shares directly from shareholders.
MBOManagement BuyoutA transaction in which the management team of a company purchases the company's stock.
4PProduct・Price・Place・PromotionThe four Ps of marketing: product, price, place, and promotion.
4CCustomer Value・Cost・Convenience・CommunicationA buyer-centric approach to the marketing mix.
RFM AnalysisRecency・Frequency・MonetaryAn analysis of customer purchasing behavior based on recency, frequency, and monetary value.
UXUser ExperienceThe experience a person has when using a product, system, or service.
BSCBalance ScorecardA strategic performance management tool that measures a company's performance from four perspectives: financial, customer, internal processes, and learning and growth.
CSFCritical Success FactorsThe factors that are critical to a company's success.
KPIKey Performance IndicatorA measurable value that demonstrates how effectively a company is achieving key business objectives.
ERPEnterprise Resource PlanningA system that integrates all aspects of a business, including finance, human resources, and supply chain management.
CRMCustomer Relationship ManagementA system for managing a company's interactions with current and potential customers.
SFASales Force AutomationSoftware that automates sales tasks and improves sales team efficiency.
SCMSupply Chain ManagementThe management of the flow of goods and services from raw materials to the end consumer.
RFIDRadio Frequency IdentificationA technology that uses radio waves to identify and track objects.
NFCNear Field CommunicationA short-range wireless communication technology.
AIArtificial IntelligenceThe development of computer systems that can perform tasks that typically require human intelligence.
POS SystemPoint of SaleA system for processing sales transactions.
CADComputer Aided DesignThe use of computer software to design products.
CAMComputer Aided ManufacturingThe use of computer software to control manufacturing processes.
JITJust In TimeA manufacturing strategy that aims to minimize inventory by producing goods only when they are needed.
ECElectronic CommerceThe buying and selling of goods and services over the internet.
IoTInternet of ThingsThe network of physical objects ("things") embedded with sensors, software, and other technologies that enable them to connect and exchange data with other devices and systems.
Society 5.0A society that combines the physical and virtual worlds to achieve economic development and solve social problems.
EAEnterprise ArchitectureA framework for designing and implementing an organization's information systems.
SoESystem of EngagementA system for strengthening relationships with customers.
DFDData Flow DesignA diagram that shows how data flows through a system.

Git Notes

· One min read

Branches (git branch / git checkout)

Switching Branches

git checkout <branch_name>

Deleting Branches

git branch -d <branch_name>

Creating an Empty Branch

git checkout --orphan=<branch_name>
git reset --hard

Log

Displaying the Log

git log --decorate=full --graph --all
note

If you have access to VS Code, it's a good idea to install the Git Graph extension.

Going Back in Time

# Find the commit ID
git log

git checkout <commit_id>
note

Commit IDs are 4 characters and can be abbreviated.

Going Back from the Past

git checkout <branch_name>

Undoing Commits (git reset)

git reset --soft @^
note

@ is the same as HEAD. ^ represents the previous commit.

JavaScript Notes

· 2 min read

Arrays

Example: [1, 2, 3]

Copying Arrays

// Pass by reference
let a = [1, 2, 3]
let b = a
b[0] = -1
a // [-1, 2, 3]

// Copy
a = [1, 2, 3]
b = a.slice()
b[0] = -1
a // [1, 2, 3]
b // [-1, 2, 3]

Last Value

let a = [1, 2, 3]
a.at(-1)

Slicing Arrays

let a = [1, 2, 3, 4, 5]
a.slice(2) // [3, 4, 5]
// Note
a.slice(2, -1) // [3, 4]

Creating Number Sequences (so-called range)

const range = (start, stop, step) =>
Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));

range(0, 10, 1) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for-of

for(let c of ['a', 'b', 'c']){
console.log(c)
}
Result
a
b
c

map

let a = [1, 2, 3].map(x => x ** 2)
// [2, 4, 6]

Array of Zeros

Array.zeros = (n) => Array.from({ length: n}, () => 0);

Array.zeros(5) // [0, 0, 0, 0, 0]

Sum

Array.prototype.sum = function(){ return this.reduce((prev, curr) => prev + curr, 0) }

[1, 2, 3, 4].sum() // 10

Mean

Array.prototype.mean = function(){ return this.reduce((prev, curr) => prev + curr, 0) / this.length }

[1, 2, 3, 4].mean() // 2.5

Strings

Example: "text"

Template Literals

let a = 100
`${a / 10}` // "10"

Numbers

Example: 1

Converting String to Number

parseInt('100') // 100 
parseFloat('100.1') // 100.1

Formatting

// 3 decimal places
(1.2).toFixed(3) // "1.200"

Dates

let today = new Date

today.toDateString() // "Sat Jan 01 2022"
today.toISOString() // "2021-12-31T15:00:00.000Z"
today.toLocaleDateString() // "2022/1/1"
today.toLocaleString() // "2022/1/1 0:00:00"
today.toLocaleTimeString() // "0:00:00"
today.toString() // "Sat Jan 01 2022 00:00:00 GMT+0900 (Japan Standard Time)"
today.toTimeString() // "00:00:00 GMT+0900 (Japan Standard Time)"
today.toUTCString() // "Fri, 31 Dec 2021 15:00:00 GMT"

Installing Docker on Ubuntu

· 3 min read

This is a translation of the Docker installation guide for Ubuntu.

[EOL]

  1. Installing Docker Engine

    • Using Package Manager: This is the recommended method for most users.

      sudo apt-get update
      sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin
    • Using the Convenient Script: Docker provides a convenient script for quickly and non-interactively installing Docker in development environments. While not recommended for production, it can be useful for creating provisioning scripts tailored to your needs. Refer to the install using package repository instructions for installation steps using the repository. The script's source code is open source and available on the GitHub docker-install repository. Always review downloaded scripts before executing them.

      curl -fsSL https://get.docker.com -o get-docker.sh
      sudo sh get-docker.sh
    • Using Pre-release: Docker also provides a convenient script to install pre-releases of Docker on Linux, available at test.docker.com. This script configures the package manager to enable the "test" channel from which you can access early versions of new releases and test them in a non-production environment before they are released as stable.

      curl -fsSL https://test.docker.com -o test-docker.sh
      sudo sh test-docker.sh
    • Important: Before running the script, it's a good practice to preview the steps the script will execute by using the DRY_RUN=1 option.

      curl -fsSL https://get.docker.com -o get-docker.sh
      DRY_RUN=1 sh ./get-docker.sh
  2. Post-Installation Steps

  3. Uninstalling Docker Engine

    • Uninstalling Packages:

      sudo apt-get purge docker-ce docker-ce-cli containerd.io docker-compose-plugin
    • Removing Images, Containers, and Volumes: The above command does not automatically remove images, containers, or volumes on the host. To remove all images, containers, and volumes, use the following commands:

      sudo rm -rf /var/lib/docker
      sudo rm -rf /var/lib/containerd
    • Manual Removal: Any manually created configuration files must be removed manually.

  4. Next Steps