Saturday, May 22, 2021

PostgreSQL 13.2 on Server Fedora 34

UPDATE 05/23/2021

As appears author@YandexZen gave the name of database to table inside it "students". I just couldn't expect such kind of database design, which breaks pretty much common approach - never give the table in database the name exactly matching database name.

END UPDATE

Original post Библиотека PyQT5. Работа с базой данных PostgreSql (библиотека psycopg2) 

Fixes have been done to mentioned above post @Yandex Zen

Critical errors have been colored blue. Code Fix in Python :-

  def con(self):

        self.conn = psycopg2.connect(user = "postgres",

                              password = "*******",

                              host = "127.0.0.1",

                              port = "5432",

                              database = "db1")


Following setup is completely skipped in original post what obviously demonstrates, that posted code has never been running on real box.  

*************************************************

 Database Setup PostgreSQL 13.2 on Server Fedora 34

*************************************************

sudo dnf module -y install postgresql:13/server

sudo postgresql-setup --initdb

sudo systemctl enable --now postgresql

$ sudo dnf install python-psycopg2

$ sudo vi /var/lib/pgsql/data/pg_hba.conf

Replacement in field auth-method  "ident" by "md5"

$ sudo systemctl restart postgresql.service

$ sudo -u postgres psql

[sudo] password for boris: 

psql (13.2)

Type "help" for help.

postgres=# create database db1 encoding 'UTF8';

CREATE DATABASE

postgres=# grant all privileges on database db1 to postgres;

GRANT

postgres=# SELECT datname FROM pg_database;

  datname  

-----------

 postgres

 template1

 template0

 db1

(4 rows)

postgres=# \c db1

db1=# create table students  ( id SERIAL PRIMARY KEY, name VARCHAR,ocenka INT);

postgres=# alter user postgres  with encrypted password '*******';

[boris@fedora33server ~]$ hostnamectl

 Static hostname: fedora33server.localdomain

       Icon name: computer-desktop

         Chassis: desktop

      Machine ID: fec5966968d24022ad7f9f058b866d8a

         Boot ID: 380bfb1a5feb4930b00c63dbb4b96891

Operating System: Fedora 34 (Server Edition)      

     CPE OS Name: cpe:/o:fedoraproject:fedora:34

          Kernel: Linux 5.12.5-300.fc34.x86_64

    Architecture: x86-64

 Hardware Vendor: ASUS

  Hardware Model: All Series

[boris@fedora33server ~]$ sudo systemctl status postgresql.service

● postgresql.service - PostgreSQL database server

     Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: d>

     Active: active (running) since Sat 2021-05-22 18:41:52 MSK; 1h 37min ago

    Process: 9560 ExecStartPre=/usr/libexec/postgresql-check-db-dir postgresql (code=exite>

   Main PID: 9562 (postmaster)

      Tasks: 8 (limit: 38409)

     Memory: 29.8M

        CPU: 1.207s

     CGroup: /system.slice/postgresql.service

             ├─9562 /usr/bin/postmaster -D /var/lib/pgsql/data

             ├─9563 postgres: logger

             ├─9565 postgres: checkpointer

             ├─9566 postgres: background writer

             ├─9567 postgres: walwriter

             ├─9568 postgres: autovacuum launcher                                          

             ├─9569 postgres: stats collector                                              

             └─9570 postgres: logical replication launcher

May 22 18:41:52 fedora33server.localdomain systemd[1]: Starting PostgreSQL database server>

May 22 18:41:52 fedora33server.localdomain postmaster[9562]: 2021-05-22 18:41:52.852 MSK [>

May 22 18:41:52 fedora33server.localdomain postmaster[9562]: 2021-05-22 18:41:52.852 MSK [>

May 22 18:41:52 fedora33server.localdomain systemd[1]: Started PostgreSQL database server.

lines 1-22/22 (END)

REFERENCES

https://server-gu.ru/add-user-postgres/

https://computingforgeeks.com/install-postgresql-13-on-fedora/










Saturday, May 8, 2021

Решение задачи №18 340 Варианта Ларина

 Условие



Не надо бояться частных производных у неявно заданных функций, иначе 

dy/dt =d((a^2-t^2)^(1/2))/dt = (-t)*(a^2-t^2)^(-1/2) 

принесет больше головной боли. 

Система после замены t=(x+6)

Решение :-

После замены    t=(x+6) система имеет вид

(1) |y| = -t^2 +9

(2) t^2+y^2 = a^2

Поскольку :-











В точке касания окружности и параболы

при y >0 (1) y = -t^2+9 имеем

∂y/∂t = -(∂(y^2+t^2-a^2)/∂t)/(∂(y^2+t^2-a^2)/∂y) = -t/y

-2t = -t/y => y=1/2

Из (1) t^2=9 -y , то есть

t^2 = 9-1/2 = 17/2

a^2 = t^2+y^2=17/2+1/4 = 35/4

|a| =(35)^(1/2)/2


















Ответ :  (35)^(1/2)/2 < |a| <= 3







Tuesday, April 6, 2021

SQLITE3 Database administration via PyQT5 Framework in PyCharm 3.5 Environment .

 Per https://en.wikipedia.org/wiki/PyQt

PyQt is a Python binding of the cross-platform GUI toolkit Qt, implemented as a Python plug-in. PyQt is free software developed by the British firm Riverbank Computing. It is available under similar terms to Qt versions older than 4.5; this means a variety of licenses including GNU General Public License (GPL) and commercial license, but not the GNU Lesser General Public License (LGPL). PyQt supports Microsoft Windows as well as various flavours of UNIX, including Linux and MacOS (or Darwin). PyQt implements around 440 classes and over 6,000 functions and methods including: a substantial set of GUI widgets, classes for accessing SQL databases (ODBC, MySQL, PostgreSQL, Oracle, SQLite) QScintilla, Scintilla-based rich text editor widget data aware widgets that are automatically populated from a database an XML parser SVG support classes for embedding ActiveX controls on Windows (only in commercial version)












































making minor changes to original code on Fedora 33 Server having previously enabled PyQT5 support by PyCharm

[boris@fedora33server PYQT]$ cat sqlcreate.py
import sys
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
con = QSqlDatabase.addDatabase("QSQLITE")
con.setDatabaseName("contacts.sqlite")

if not con.open():
    print("Database Error: %s" % con.lastError().databaseText())
    sys.exit(1)

# Create a query and execute it right away using .exec()
createTableQuery = QSqlQuery()
createTableQuery.exec(
    """
    CREATE TABLE contacts (
        id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,
        name VARCHAR(40) NOT NULL,
        job VARCHAR(50),
        email VARCHAR(40) NOT NULL
    )
    """
)
print(con.tables())

Loading data into created table

[boris@fedora33server PYQT]$ cat sql02.py
from PyQt5.QtSql import QSqlQuery, QSqlDatabase

con = QSqlDatabase.addDatabase("QSQLITE")
con.setDatabaseName("contacts.sqlite")
con.open()
insertDataQuery = QSqlQuery()
insertDataQuery.prepare(
    """
    INSERT INTO contacts (
        name,
        job,
        email
    )
    VALUES (?, ?, ?)
    """
)
data = [
    ("Joe", "Senior Web Developer", "joe@example.com"),
    ("Lara", "Project Manager", "lara@example.com"),
    ("David", "Data Analyst", "david@example.com"),
    ("Jane", "Senior Python Developer", "jane@example.com"),
]
# Use .addBindValue() to insert data
for name, job, email in data:
    insertDataQuery.addBindValue(name)
    insertDataQuery.addBindValue(job)
    insertDataQuery.addBindValue(email)
    insertDataQuery.exec()

[boris@fedora33server PYQT]$ cat sqliteditor.py
import sys

from PyQt5.QtCore import Qt
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel
from PyQt5.QtWidgets import (
    QApplication,
    QMainWindow,
    QMessageBox,
    QTableView,
)
class Contacts(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("QTableView Example")
        self.resize(415, 200)
        # Set up the model
        self.model = QSqlTableModel(self)
        self.model.setTable("contacts")
        self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
        self.model.setHeaderData(0, Qt.Horizontal, "ID")
        self.model.setHeaderData(1, Qt.Horizontal, "Name")
        self.model.setHeaderData(2, Qt.Horizontal, "Job")
        self.model.setHeaderData(3, Qt.Horizontal, "Email")
        self.model.select()
        # Set up the view
        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.resizeColumnsToContents()
        self.setCentralWidget(self.view)

def createConnection():
    con = QSqlDatabase.addDatabase("QSQLITE")
    con.setDatabaseName("contacts.sqlite")
    if not con.open():
        QMessageBox.critical(
            None,
            "QTableView Example - Error!",
            "Database Error: %s" % con.lastError().databaseText(),
        )
        return False
    return True

app = QApplication(sys.argv)
if not createConnection():
    sys.exit(1)
win = Contacts()
win.show()
sys.exit(app.exec_())


Wednesday, February 3, 2021

Решение задачи №16 Демо ЕГЭ Информатика 2021 (Python)

Единственная цель кода на Python, приведенного ниже, - не дать детям выполнять прямые вычисления, которые, на самом деле, скорее скучны, чем трудны. Я просто пытаюсь научить своих учеников довольно старому принципу «Just think first». 

Условие задачи

 









Решение 















Заметим, что вычислить F(46) так же несложно как и F(26)















Смотри детально объяснение синтаксиса

www.freecodecamp.org/news/if-name-main-python-example/#:~:text=We%20can%20use%20an%20if,name%20if%20it%20is%20imported.

https://stackoverflow.com/questions/28336627/if-name-main-python  

Saturday, January 30, 2021

Попытка решить №26,27 демо-версии КЕГЭ по информатике 2021

UPDATE 01/02/2021

Решение Джобса верно в контексте вызова f.readline().split()  я ошибся при копировании его кода. Однако, ошибка в коде Джобса всеже есть , хотя вполне тривиальная. Нарушен приоритет операций "-" и "%" :   

if p1 - p2%3 != 0 and p1 - p2 < dx:  

Корректировка :   if (p1-p2)%3 !=0 and p1 - p2 < dx:

Очевидно, что выполнение кода со скриншота ниже верного результата дать в принципе не может. Предложен другой вариант кода, обходящий вызов f.readline().split() и корректировкой описанной выше. Мое решение мне нравится, но не более того

END UPDATE 

Следую https://www.youtube.com/watch?v=zGYqPsUB-S4&feature=emb_logo



Среда Python 3.9.1 Linux Fedora 33 Server

Копирую код из видео


































Пишем другой код

Исходные данные
Выполняем


Все тоже касается задачи 26
Меняем код , который блокирует Python 3.9.1





Выполняем











Saturday, September 12, 2020

Setting up Sqlite3 Python embedded database and Sqlitebrowser on CentOS 8.2

First instatll "Development Tools", rebuild Python 3.8.5
after installation sqlite-devel. Afterwards build sqlitebrowser from source rather then install vi snap, just a couple qt5-devel packages would have to be installed for successful build on CentOS 8.2.

$ sudo dnf groupinstall "Development Tools" -y
$ sudo dnf install sqlite-devel

Rebuild Python

$cd ; $ cd ./Python-3.8.5
$ ./configure —enable-optimizations
$ sudo make altinstall

Prepare to build sqlitebrowser which wouldn't
have any issues with Qt vs the one provided via snap

$ sudo dnf install qt5-devel qwt-qt5-devel -y



Build sqlitebrowser

$ git clone https://github.com/sqlitebrowser/sqlitebrowser
$ cd sqlitebrowser
$ cmake -Wno-dev .
$ make
$ sudo make install



Make sure

[boris@Server82 ~]$ python3.8
Python 3.8.5 (default, Sep 11 2020, 12:09:30)
[GCC 8.3.1 20191121 (Red Hat 8.3.1-5)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>>
Now follow for instance https://pymotw.com/2/sqlite3/ and see
basic DDL && DML operations work with no problems via Python API .
However, Encrypting would require Python 2.7


                                                

Thursday, September 10, 2020

Setting up Python 3.8.5 on Linux && Getting LibreOffice 7.0 for free

$  wget https://www.python.org/ftp/python/3.8.5/Python-3.8.5.tgz
$   sudo dnf groupinstall "Development Tools" -y
$   tar xvf Python-3.8.5.tgz
$  cd  ./Python-3.8.5
$    ./configure --enable-optimizations
$  sudo make altinstall

[boris@Server82 ~]$ python3.8 --version
Python 3.8.5
[boris@Server82 ~]$ 

Just for fun solve #25 from USE Demo 2021  (optimal code belongs to Eugene Dzhobs)
#25



Would you like to install sqlite3 Python embedded database on CentOS 8.2
$ sudo dnf install sqlite-devel
$  cd  ./Python-3.8.5
$    ./configure --enable-optimizations
$  sudo make altinstall