Monday, September 15, 2025

Python: using gemini and chatgpt to help creating python3 code to get last 3 characters in composite name in Sheet1

We define the problem to ask AI to generate python code. This is the crucial part, to get output that we expected.

In Indonesia language we define:

saya punya data excel di sheet1 yang berisi nama.
headet sheet1 adalah no dan nama komposit.
nama komposit terdiri dari 2 nama dipisah dengan tanda /.
tidak semua nama komposit memiliki 2 nama.
nama pertama ada yang menggunakan nama panggilan yang disimpan didalam tanda ().
nama pertama selalu ada disetiap row.
sayang ingin mengambil 3 huruf terakhir dari nama pertama, bukan yang berada dalam tanda kurung.
buatkan kode pyhton3 dengan openpyxl library.
print no, nama, dan 3 huruf terakhir, gunakan ; untuk pemisah dan masukan string kedalam "" agar output mudah di simpan kedalam csv.

In English language we define:

I have Excel data in sheet 1 containing names.
The header of sheet 1 is a composite number and name.
A composite name consists of two names separated by a / symbol.
Not all composite names have two names.
Some first names use nicknames stored within the () symbol.
The first name is always present in every row.
Unfortunately, I want to extract the last three letters of the first name, not the ones in parentheses.
Create a Python 3 code using the OpenPyXL library.
Print the number, name, and last three letters, use ; as the separator, and enclose the string in "" to make the output easy to save to a CSV.

Choose one of them, feed it into chat.openai.com / chatgpt.com and gemini.google.com, you can use 2 tab or 2 window browser. This is only example, you need to define your expected output.

I replace xlsx file name "data_tr.xlsx"

Here is the code generated by chatgpt.com:

from openpyxl import load_workbook
import re

# Mengambil nama pertama dari "nama komposit" (sebelum tanda /)
# Menghapus bagian dalam tanda kurung () dari nama pertama
# Mengambil 3 huruf terakhir dari nama pertama yang telah dibersihkan

# Ganti dengan path ke file Excel kamu
file_path = "data_tr.xlsx"

# Load workbook dan sheet
wb = load_workbook(filename=file_path)
ws = wb["Sheet1"]

# Print header
print('"no";"nama komposit";"3 huruf terakhir"')

# Proses tiap baris (mulai dari baris ke-2 karena baris 1 adalah header)
for row in ws.iter_rows(min_row=2, max_col=2):
    no = row[0].value
    nama_komposit = str(row[1].value).strip() if row[1].value else ""

    # Ambil nama pertama dari nama komposit
    nama_pertama = nama_komposit.split("/")[0].strip()

    # Hapus isi dalam tanda kurung, misalnya (Budi)
    nama_pertama_bersih = re.sub(r"\([^)]*\)", "", nama_pertama).strip()

    # Ambil 3 huruf terakhir (jika cukup panjang)
    tiga_huruf_terakhir = nama_pertama_bersih[-3:] if len(nama_pertama_bersih) >= 3 else nama_pertama_bersih

    # Format dan cetak hasil
    print(f'"{no}";"{nama_komposit}";"{tiga_huruf_terakhir}"')

Here is the code generated by gemini:

import openpyxl

# Ganti 'nama_file_anda.xlsx' dengan nama file Excel Anda
file_path = 'data_tr.xlsx'

try:
    # Membuka workbook dan memilih sheet aktif
    workbook = openpyxl.load_workbook(file_path)
    sheet = workbook.active

    # Mencetak header
    header_string = '"No";"Nama Komposit";"3 Huruf Terakhir"'
    print(header_string)

    # Iterasi dari baris ke-2 (mengabaikan header yang sudah dicetak)
    for row in sheet.iter_rows(min_row=2):
        no_cell = row[0]
        nama_komposit_cell = row[1]
        
        # Mengabaikan baris kosong
        if not no_cell.value or not nama_komposit_cell.value:
            continue

        # Mengambil nilai dari cell
        no = no_cell.value
        nama_komposit = str(nama_komposit_cell.value)
        
        # Memisahkan nama komposit berdasarkan '/'
        nama_pertama = nama_komposit.split('/')[0].strip()
        
        # Menghapus nama panggilan dalam kurung
        if '(' in nama_pertama and ')' in nama_pertama:
            idx_buka = nama_pertama.find('(')
            nama_pertama = nama_pertama[:idx_buka].strip()
            
        # Mengambil 3 huruf terakhir dari nama pertama dan mengubahnya menjadi huruf kapital
        tiga_huruf_terakhir = nama_pertama[-3:].upper()
        
        # Mencetak data sesuai format yang diminta
        output_string = f'"{no}";"{nama_komposit}";"{tiga_huruf_terakhir}"'
        print(output_string)

except FileNotFoundError:
    print(f"Error: File '{file_path}' tidak ditemukan. Pastikan nama file sudah benar.")
except Exception as e:
    print(f"Terjadi kesalahan: {e}")

The code contain Indonesia Languge when the chat feed in Indonesia Language.

If you use virtual environment, activate it first

$ cd mypyenv
~/mypyenv$ source venv/bin/activate

Remember, AI may make mistake the output was generated base on statistics  values from every tokens. You must check the output. You may seen the output style has deference based on data the AI developer feed during learning.

This is the way AI help to create source code that we never learn before.

Tuesday, September 9, 2025

Python: fixing indentation in python

In python, indentation must consistent, runtime will report error if indentation inconsistent. 

It is hard if we use some editor to write the code. We can use black to fix it automatically base on pep 8 (Python Enhancement Proposal  8).

Installing black

# apt-get install black
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  python3-click python3-mypy-extensions python3-pathspec python3-platformdirs
Suggested packages:
  python-black-doc
The following NEW packages will be installed:
  black python3-click python3-mypy-extensions python3-pathspec
  python3-platformdirs
0 upgraded, 5 newly installed, 0 to remove and 1 not upgraded.
Need to get 1,502 kB of archives.
After this operation, 6,442 kB of additional disk space will be used.

Using black

$ black ./[your_python_file_to_fix].py
reformatted [your_python_file_to_fix].py

All done! ✨ 🍰 ✨
1 file reformatted.

Wednesday, September 3, 2025

Debian 13: troubleshooting connecting to wifi using cmd nmcli

I prefer to use command line because mostly server does not  installed window manager. I need to familiar to use command line in any situation.

To show wifi radio enable

# nmcli radio wifi
enabled

To turn on radio wifi

# nmcli radio wifi on

To list available wifi

# nmcli device wifi list
IN-USE  BSSID              SSID   
...

To rescan available wifi

# nmcli dev wifi rescan

To connect to wifi access point

# nmcli device wifi connect "[your_SSID]" password "[your_password]"
...

To show connection

# nmcli connection show
NAME                UUID                                  TYPE      DEVICE
...

Note: parameter dev is short from device

Tuesday, September 2, 2025

Debian 13 icewm/openbox/fluxbox: using pavucontrol & pulseaudio

 Install pavucontrol & pulseaudio

# apt-get install pavucontrol pulseaudio
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
...

To run pavecontrol in terminal

$ pulseaudio&


Monday, September 1, 2025

pyhton3: read xlsx using open3pyxl

Install open3pyxl library on Debian system

# apt-get install open3pyxl
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
...

Install open3pyxl library on user virtual environment (not messing with python used by Debian)

$ cd mypyenv
~/mypyenv$ source venv/bin/activate
(venv) [user]@[hostname]:~/mypyenv$ pip list
Package Version
------- -------
pip     25.1.1
(venv) [user]@[hostname]:~/mypyenv$ pip install openpyxl
Collecting openpyxl
  Downloading openpyxl-3.1.5-py2.py3-none-any.whl.metadata (2.5 kB)
Collecting et-xmlfile (from openpyxl)
  Downloading et_xmlfile-2.0.0-py3-none-any.whl.metadata (2.7 kB)
Downloading openpyxl-3.1.5-py2.py3-none-any.whl (250 kB)
Downloading et_xmlfile-2.0.0-py3-none-any.whl (18 kB)
Installing collected packages: et-xmlfile, openpyxl
Successfully installed et-xmlfile-2.0.0 openpyxl-3.1.5

(venv) [user]@[hostname]:~/mypyenv$ pip list
Package    Version
---------- -------
et_xmlfile 2.0.0
openpyxl   3.1.5
pip        25.1.1

Here is sample script to enumerate row and column

import openpyxl
from datetime import datetime

path = "./[replace_with_your_file].xlsx"

# wb_obj = openpyxl.load_workbook(path) # Open xlsx without option
wb_obj = openpyxl.load_workbook(path, data_only=True) # Open xlsx with option Data Only

## object sheet
# using active sheet
#sheet_obj = wb_obj.active
## using Sheet1
sheet_obj = wb_obj["Sheet1"]

# Sheet start from 1,1 not 0,0
# Access cell at row 1, column 1
#cell_obj = sheet_obj.cell(row=1, column=1)
#print("Cell 1 column 1 is ",cell_obj.value)

# to print row 1 column 20
#cell_obj = sheet_obj.cell(row=1, column=20)
#print("Cell 1 column 20 is ",cell_obj.value)

# Enumerate row
# first row is header
# max_row may contains empty row
for i in range (2, sheet_obj.max_row):
    cell_obj = sheet_obj.cell(row=i, column=1)
    if cell_obj.value is not None:
        # enumerate column
        # we need fix column e.q 6 column from 1 to 6
        # Do not use max_column
        # for j in range (1, max_column): # Do not use this, use fix number
        for j in range (1, 6):
            mycell_obj = sheet_obj.cell(row=i, column=j)
            #if mycell_obj is not None: # if you use
max_column, this will not working, only working for row
            print(mycell_obj.value, " | ", end='') # print without new line
        print() # print a new line
    else:
        # the row is empty we break
        print() # print a new line
        break