analitics

Pages

Tuesday, July 9, 2019

Python 3.7.3 : The python-slugify python module.

This python module named python-slugify can handle Unicode.
You can see this python module source code and examples at GITHUB webpage.
The install step with pip python tool is easy:
C:\Python373>cd Scripts
C:\Python373\Scripts>pip install python-slugify
Collecting python-slugify
...
Successfully built python-slugify
Installing collected packages: text-unidecode, python-slugify
Successfully installed python-slugify-3.0.2 text-unidecode-1.2
Let's see some simple example.
>>> from slugify import slugify
>>> txt = "___This is a test___"
>>> regex_pattern = r'[^-a-z0-9_]+'
>>> r = slugify(txt, regex_pattern=regex_pattern)
>>> print(r)
___this-is-a-test___
Remove an email address from a string:
>>> txt_email = "___My mail is catafest@yahoo.com *&@!@#$$76"
>>> regex_pattern =r'[\w\.]+\@[\w]+(?:\.[\w]{3}|\.[\w]{2}\.[\w]{2})\b'
>>> r = slugify(txt_email, regex_pattern=regex_pattern)
>>> print(r)
___my mail is - *&@!@#$$76
You can write your data into one text file:
>>> ftxt = open('C:\\Python373\\soup.txt','w')
>>> ftxt.write(soup)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: write() argument must be str, not BeautifulSoup
>>> ftxt.write(str(soup))
If you got errors the use the slugify to fix it:
ftxt.write(slugify(str(soup)))

Monday, July 8, 2019

Python 3.7.3 : Using attrgetter from operator python module.

Return a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of attributes. The attribute names can also contain dots. see documentation.
The attrgetter operator works more or less similar to itemgetter, except that it looks up an attribute instead of an index.
For example to test this operator we need to create a class to access the attribute on the class.
I create a class named Person with name and surname initialization.
I will get the attributes from this class and show it.
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import operator
>>> class Person:
...     def __init__(self, name, surname):
...             self.n = name
...             self.s = surname
...
>>> my_per = Person('Festila', 'Catalin George')
>>> getter = operator.attrgetter("n")
>>> print(getter)
operator.attrgetter('n')
>>> print(getter(my_per))
Festila
>>> another_getter = operator.attrgetter("s")
>>> print(another_getter)
operator.attrgetter('s')
>>> print(another_getter(my_per))
Catalin George
>>> all = operator.attrgetter("n","s")
>>> print(all)
operator.attrgetter('n', 's')
>>> print(all(my_per))
('Festila', 'Catalin George')
To restrict setting an attribute outside of constructor you need to use a private attribute starting with an underscore, and a read-only property for public access.
See the new class with the attribute s restricted:
class Person:
    def __init__(self, name, surname):
            self.n = name
            self.s = surname
s = property(operator.attrgetter("_s"))
Let's test it in another way:
>>> from operator import attrgetter
>>> test=attrgetter('something')
>>> print(test)
operator.attrgetter('something')
>>> print(type(test))

>>> print(test(something))
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'something' is not defined
>>> print(type(test(something)))
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'something' is not defined
Because something is not initialized correctly the error is expected for both: test(something) and type(test(something)
>>> something = 'all'
>>> print(type(test))

>>> print(type(test(something)))
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'str' object has no attribute 'something'
>>> something = 1
>>> print(type(test(something)))
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'int' object has no attribute 'something'

Friday, July 5, 2019

Python 3.7.3 : Use python with MySQL and MariaDB.

If you want to use MariaDB databases with python then you need to install the MySQL.
Use the pip tool to install the mysql-connector-python python module:
C:\Python373\Scripts>pip install mysql-connector-python
Collecting mysql-connector-python
...
Installing collected packages: mysql-connector-python
Successfully installed mysql-connector-python-8.0.16
The information about python module named mysql-connector-python version 8.0.16 can be found at this web page.
For the test, I install MariaDB from the official website with user root and my password.
Let's test the python module for MariaDB:
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql
>>> import mysql.connector as mariadb
After install, start the command prompt of MariaDB and test it:
C:\Windows\System32>mysql -u root -p
Enter password: ****
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 10.4.6-MariaDB mariadb.org binary distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.001 sec)
MariaDB [information_schema]> USE information_schema;
Database changed
MariaDB [information_schema]> SHOW TABLES;
...
| INNODB_TABLESPACES_SCRUBBING          |
| INNODB_SYS_SEMAPHORE_WAITS            |
+---------------------------------------+
77 rows in set (0.001 sec)

C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector as mariadb
>>> mariadb_connection = mariadb.connect(user='root', password='test', database=
'information_schema')
>>> cursor = mariadb_connection.cursor()
>>> cursor.execute("USE information_schema")
>>> cursor.execute("SHOW TABLES")
>>> result = cursor.fetchall()
>>> print(result)
[('ALL_PLUGINS',), ('APPLICABLE_ROLES',), ('CHARACTER_SETS',), ('CHECK_CONSTRAIN
TS',), ('COLLATIONS',), ('COLLATION_CHARACTER_SET_APPLICABILITY',), ('COLUMNS',)
, ('COLUMN_PRIVILEGES',), ('ENABLED_ROLES',), ('ENGINES',), ('EVENTS',), ('FILES
',), ('GLOBAL_STATUS',), ('GLOBAL_VARIABLES',), ('KEY_CACHES',), ('KEY_COLUMN_US
AGE',), ('OPTIMIZER_TRACE',), ('PARAMETERS',), ('PARTITIONS',), ('PLUGINS',), ('
PROCESSLIST',), ('PROFILING',), ('REFERENTIAL_CONSTRAINTS',), ('ROUTINES',), ('S
CHEMATA',), ('SCHEMA_PRIVILEGES',), ('SESSION_STATUS',), ('SESSION_VARIABLES',),
 ('STATISTICS',), ('SYSTEM_VARIABLES',), ('TABLES',), ('TABLESPACES',), ('TABLE_
CONSTRAINTS',), ('TABLE_PRIVILEGES',), ('TRIGGERS',), ('USER_PRIVILEGES',), ('VI
EWS',), ('GEOMETRY_COLUMNS',), ('SPATIAL_REF_SYS',), ('CLIENT_STATISTICS',), ('I
NDEX_STATISTICS',), ('INNODB_SYS_DATAFILES',), ('USER_STATISTICS',), ('INNODB_SY
S_TABLESTATS',), ('INNODB_LOCKS',), ('INNODB_MUTEXES',), ('INNODB_CMPMEM',), ('I
NNODB_CMP_PER_INDEX',), ('INNODB_CMP',), ('INNODB_FT_DELETED',), ('INNODB_CMP_RE
SET',), ('INNODB_LOCK_WAITS',), ('TABLE_STATISTICS',), ('INNODB_TABLESPACES_ENCR
YPTION',), ('INNODB_BUFFER_PAGE_LRU',), ('INNODB_SYS_FIELDS',), ('INNODB_CMPMEM_
RESET',), ('INNODB_SYS_COLUMNS',), ('INNODB_FT_INDEX_TABLE',), ('INNODB_CMP_PER_
INDEX_RESET',), ('user_variables',), ('INNODB_FT_INDEX_CACHE',), ('INNODB_SYS_FO
REIGN_COLS',), ('INNODB_FT_BEING_DELETED',), ('INNODB_BUFFER_POOL_STATS',), ('IN
NODB_TRX',), ('INNODB_SYS_FOREIGN',), ('INNODB_SYS_TABLES',), ('INNODB_FT_DEFAUL
T_STOPWORD',), ('INNODB_FT_CONFIG',), ('INNODB_BUFFER_PAGE',), ('INNODB_SYS_TABL
ESPACES',), ('INNODB_METRICS',), ('INNODB_SYS_INDEXES',), ('INNODB_SYS_VIRTUAL',
), ('INNODB_TABLESPACES_SCRUBBING',), ('INNODB_SYS_SEMAPHORE_WAITS',)]

Thursday, July 4, 2019

Python 3.7.3 : Using itemgetter from operator python module.

The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. see documentation.
Today I will show you how to use itemgetter from this python module with python 3.7.3.
Let's see how to sort my two dictionaries named my_dict and my_dict2, using the classical lambda function;
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> my_dict = {'a': 11, 'b': 12, 'c': 13, 'd': 14}
>>> sorted(my_dict.items(), key = lambda x:x[1])
[('a', 11), ('b', 12), ('c', 13), ('d', 14)]
>>> my_dict2 = {'a': 31, 'b': 12, 'c': 33, 'd': 14}
>>> sorted(my_dict2.items(), key = lambda x:x[1])
[('b', 12), ('d', 14), ('a', 31), ('c', 33)]
Using the operator python module with my examples for both dictionaries:
>>> import operator
>>> sorted(my_dict.items(), key = operator.itemgetter(1))
[('a', 11), ('b', 12), ('c', 13), ('d', 14)]
>>> sorted(my_dict2.items(), key = operator.itemgetter(1))
[('b', 12), ('d', 14), ('a', 31), ('c', 33)]
>>> sorted(my_dict2.items(), key = operator.itemgetter(1), reverse=True)
[('c', 33), ('a', 31), ('d', 14), ('b', 12)]
The operator.itemgetter returns a callable object that fetches the item from its operand using the operand’s __getitem__() method.
If multiple items are specified, returns a tuple of lookup values.
Let's see another example:
>>> my_arr = []
>>> my_arr.append(["A","Z",77])
>>> my_arr.append(["bA","Zc",11])
>>> my_arr.append(["d","c",111])
>>> print(my_arr)
[['A', 'Z', 77], ['bA', 'Zc', 11], ['d', 'c', 111]]
>>> my_arr.sort(key=operator.itemgetter(1))
>>> my_arr
[['A', 'Z', 77], ['bA', 'Zc', 11], ['d', 'c', 111]]
>>> my_arr.sort(key=operator.itemgetter(1,2))
>>> my_arr
[['A', 'Z', 77], ['bA', 'Zc', 11], ['d', 'c', 111]]
>>> my_arr.sort(key=operator.itemgetter(2))
>>> my_arr
[['bA', 'Zc', 11], ['A', 'Z', 77], ['d', 'c', 111]]
>>> my_arr.sort(key=operator.itemgetter(2,1))
>>> my_arr
[['bA', 'Zc', 11], ['A', 'Z', 77], ['d', 'c', 111]]
After using the sort with itemgetter the array is changed it:

>>> i0 = operator.itemgetter(0)
>>> i0(my_arr)
['bA', 'Zc', 11]>>> i1 = operator.itemgetter(1)
>>> i1(my_arr)
['A', 'Z', 77]
>>> i2 = operator.itemgetter(2)
>>> i2(my_arr)
['d', 'c', 111]
>>> print(my_arr)
[['bA', 'Zc', 11], ['A', 'Z', 77], ['d', 'c', 111]]

Monday, July 1, 2019

Python 3.7.3 : Using the Pony python module.

The development team of the Pony project comes with this intro:
Using Pony object-relational mapper you can concentrate on writing the business logic of your application and use Python syntax for interacting with the database. Pony translates such queries into SQL and executes them in the database in the most efficient way.
The Pony python module can be installed on Python 2.7 or Python 3.
Today I tested with the Python 3.7.3 version:
C:\Python373>cd Scripts
C:\Python373\Scripts>pip install pony
Collecting pony
...
Successfully built pony
Installing collected packages: pony
Successfully installed pony-0.7.10
Let's start with one simple example:
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pony
>>> from pony import orm
>>> from pony.orm import *
>>> mydb = Database()
>>> class Person(mydb.Entity):
...     name = Required(str)
...     surname = Required(str)
...     age = Required(int)
...     house = Set('Home')
...
>>> class Home(mydb.Entity):
...     owner = Required(Person)
...     address = Required(str)
...     floors = Required(int)
...     perimeter = Required(int)
...
>>> show(Person)
class Person(Entity):
    id = PrimaryKey(int, auto=True)
    name = Required(str)
    surname = Required(str)
    age = Required(int)
    house = Set(Home)
>>> show(Home)
class Home(Entity):
    id = PrimaryKey(int, auto=True)
    owner = Required(Person)
    address = Required(str)
    floors = Required(int)
    perimeter = Required(int)
Let's see the relationships of this example.
The house variable is set to the type named Home.
The owner variable has type Person.
The Pony supports 4 database types: SQLite, MySQL, PostgreSQL, and Oracle.
Use absolute path, see the error generated by bind function when saving it to the database file:
>>> mydb.bind(provider='sqlite', filename='err_my.sqlite', create_db=True)
...
ValueError: When in interactive mode, please provide absolute file path. Got: 'err_my.sqlite'
The correct way to bind the database is:
mydb.bind(provider='sqlite', filename='C:\\Python373\\mydb.sqlite', create_db=True)
Using the Pony python module with databases is simple to use, see the documentation webpage:
# SQLite
db.bind(provider='sqlite', filename=':memory:')
# or
db.bind(provider='sqlite', filename='database.sqlite', create_db=True)
# PostgreSQL
db.bind(provider='postgres', user='', password='', host='', database='')
# MySQL
db.bind(provider='mysql', host='', user='', passwd='', db='')
# Oracle
db.bind(provider='oracle', user='', password='', dsn='')
The next step is the mapping process for declared entities to the corresponding tables in the database, like: creates tables, foreign key references, and indexes if necessary:
>>> mydb.generate_mapping(create_tables=True)
Let's fill the database using these objects:
data001 = Person(name='John',surname = 'Unknown', age=18)
data002 = Person(name='Unknown',surname = 'Unknown', age=81)
add001 = Home(owner = data001,address = '18', floors = 1, perimeter=0)
add002 = Home(owner = data002,address = '11', floors = 0, perimeter=1)
These objects will be saved only after the commit function is called.
>>> commit()
Let's see the next steps:
- Writing queries:
>>> select (var_p for var_p in Person)

>>> select (var_p for var_p in Person)[:]
[Person[1], Person[2]]
>>> select (var_p for var_p in Person)[:].show()
id|name   |surname|age
--+-------+-------+---
1 |John   |Unknown|18
2 |Unknown|Unknown|81
- Getting objects:
>>> p1 = Person[1]
>>> print(p1)
Person[1]
>>> print(p1.name)
John
- Updating an object:
>>> m = Person.get(name='John')
>>> print(m.age)
18
Even I used an SQLite database, the databases can be used writing queries according to the databases
>>> x = 25
>>> Person.select_by_sql('SELECT * FROM Person p WHERE p.age < $x')
[Person[1]]
Instead of creating models manually, you can use the examples from the Pony distribution package:
>>> from pony.orm.examples.estore import *
...
SELECT "Product"."id", "Product"."name", "Product"."description", "Product"."pic
ture", "Product"."price", "Product"."quantity"
FROM "Product" "Product"
WHERE 0 = 1

COMMIT
COMMIT
PRAGMA foreign_keys = true
CLOSE CONNECTION
RELEASE CONNECTION
You can see the database diagram at the eStore webpage.
This tutorial can be continued with additional pieces of information and examples.
You can read more at Pony ORM webpage.

Thursday, June 20, 2019

Python 3.7.3 : Read and save RSS data from goodreads website.

Today I will show you how to parse data from www.goodreads.com using the feedparser and save all into CSV file.
The Goodreads website comes with hundreds of great book recommendations from fellow readers, beloved authors, and let you add your favorite books.
The main goal was to have a structured link from the RSS file and the CSV file.
This issue was solve with arrays for each type of data.
First, let's install the feedparser python module with the pip tool:
C:\Python373\Scripts>pip install feedparser
Collecting feedparser
...
Successfully built feedparser
Installing collected packages: feedparser
Successfully installed feedparser-5.2.1
You need to get the RSS link with your books from your account.
The example is simple and has commented lines to understand easily how can I solve this issue.
This is the source code for reading all RSS data and put on the CSV file:
import feedparser
import csv
bookread_rss = "your RSS with data account"
feeds = feedparser.parse(bookread_rss)
print ("aditional RSS data")
print (feeds['feed']['title'])
print (feeds['feed']['link'])
print (feeds.feed.subtitle)
print (len(feeds['entries']))
print (feeds.version)
print (feeds.headers)
print (feeds.headers.get('content-type'))
print ("read RSS items")
# empty arrays for values by type
dates = []
titles = []
authors = []
links = []
pages =[]

# create the name of the CSV file
file_csv = 'my_goodreads_books.csv'

# prepare the CSV file with fix for error
# UnicodeEncodeError: 'charmap' codec can't encode character '\u0435' in position
# 30: character maps to 
cvs_out = csv.writer(open(file_csv, 'w',newline='',encoding="utf-8"))

#print(feeds)
for post in feeds.entries:
    date = "%d/%02d/%02d" % (post.published_parsed.tm_year,\
        post.published_parsed.tm_mon, \
        post.published_parsed.tm_mday,)
    # uncomment and will print on console
    #print("___")
    #print("post date: " + date)
    #print("post title: " + post.title)
    #print("post author: " + post.author_name)
    #print("post link: " + post.link)
    #print("post pages: " + post.num_pages)

    dates.append(date)
    titles.append(post.title)
    authors.append(post.author_name)
    links.append(post.link)
    pages.append(post.num_pages)

for d,t,a,l,p in zip(dates,titles,authors,links,pages):
    cvs_out.writerow((d,t,a,l,p))
The result will print you some info, see my example:
C:\Python373>python bookreader_rss_001.py
aditional RSS data
Catalin's bookshelf: all
https://www.goodreads.com/review/list_rss/52019632?key=pyfTLqvJXpg-_ghi4a6ZTZfJV
gLVXC8TcWyaBSyoiScgfXq3&shelf=%23ALL%23
Catalin's bookshelf: all
100
rss20
{'Server': 'Server', 'Date': 'Thu, 20 Jun 2019 12:22:55 GMT', 'Content-Type': 'a
pplication/xml; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'c
lose', 'Status': '200 OK', 'X-Frame-Options': 'ALLOWALL', 'X-XSS-Protection': '1
...
All date will be put into the my_goodreads_books.csv file.

Tuesday, June 18, 2019

Python 3.7.3 : Stemming with nltk.

Today I will start another tutorial about nltk python module and stemming.
The stemming is the process of producing morphological variants of a root/base word.
Stemming programs are commonly referred to as stemming algorithms or stemmers to reduces the words.
Errors in Stemming can be overstemming and understemming.
These two words are stemmed to the same root that are of different stems then the term is overstemming.
When two words are stemmed to same root that are not of different stems then the term used is understemming.
Applications of stemming are used in information retrieval systems like search engines or is used to determine domain vocabularies in domain analysis.
Let install this python module named nltk with pip tool:
C:\Python373\Scripts>pip install nltk
Collecting nltk
...
Successfully installed nltk-3.4.1 six-1.12.0
The nltk python module work with human language data for applying in statistical natural language processing (NLP).
It contains text processing libraries for tokenization, parsing, classification, stemming, tagging, graphical demonstrations, sample data sets, and semantic reasoning.
The next step is to download the models and data, see more at this official webpage.
First run this lines of code to update the nltk python module.
import nltk
nltk.download()
Let's test a simple implementation of stemming words using nltk python module:
from nltk.stem import PorterStemmer 
from nltk.tokenize import word_tokenize 
   
my_porter = PorterStemmer() 
   
quote = "Deep in the human unconscious is a pervasive need for a logical universe that makes sense."

words = word_tokenize(quote) 
   
for w in words: 
    print(w, " : ", my_porter.stem(w))
The result is something like this:
C:\Users\catafest>python stemming_001.py
Deep  :  deep
in  :  in
the  :  the
human  :  human
unconscious  :  unconsci
is  :  is
a  :  a
pervasive  :  pervas
need  :  need
for  :  for
a  :  a
logical  :  logic
universe  :  univers
that  :  that
makes  :  make
sense  :  sens
.  :  .

C:\Users\catafest>
You can read more about the stemming at Wikipedia.

Python 3.7.3 : Using getters and setters in object-oriented.

The main purpose of using getters and setters in object-oriented programs is to ensure data encapsulation.
Let's start with a simple example.
I created a class named my_class init with one variable named my_variable:
self._my_variable = my_variable
A new, initialized instance can be obtained by this line of code:
test_it = my_class()
The example use getter and setter methods to use this variable.
C:\Users\catafest>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class my_class:
...     def __init__(self, my_variable = 0):
...          self._my_variable = my_variable
...
...     # getter method
...     def get_my_variable(self):
...         return self._my_variable
...
...     # setter method
...     def set_my_variable(self, x):
...         self._my_variable = x
...
>>> test_it = my_class()
>>> test_it.set_my_variable(1976)
>>> print(test_it.get_my_variable())
1976
>>> print(test_it._my_variable)
1976
In Python property() is a built-in function that creates and returns a property object.
Python has four arguments property: fget, fset, fdel, doc.
  • fget is a function for retrieving an attribute value;
  • fset is a fuction for setting an attribute value;
  • fdel is a function for deleting an attribute value;
  • doc creates a docstring for attribute.
This line of code will setting the my_variable using setter:
test_it.set_my_variable(1976)
This line of code will retrieving my_variable using getter:
print(test_it.get_my_variable())
A property object has three methods, getter(), setter(), and delete() to specify fget, fset and fdel individually.
How my example changes it:
>>> class my_class:
...      def __init__(self):
...           self._my_variable = 0
...
...      # function to get value of _my_variable
...      def get_my_variable(self):
...          print("getter method called")
...          return self._my_variable
...
...      # function to set value of _my_variable
...      def set_my_variable(self, a):
...          print("setter method called")
...          self._my_variable = a
...
...      # function to delete _my_variable attribute
...      def del_my_variable(self):
...          del self._my_variable
...
...      my_variable = property(get_my_variable, set_my_variable, del_my_variabl
e)
...
>>> test_it = my_class()
>>> test_it.my_variable = 1976
setter method called
>>> print(test_it.my_variable)
getter method called
1976
Using decorator with python @property is one of the built-in decorators.
The main purpose of any decorator is to change your class methods or attributes.
The user of your class no need to make any change in their code.
This is the final result:
>>> class my_class:
...      def __init__(self):
...           self._my_variable = 0
...
...      # using property decorator
...      # a getter function
...      @property
...      def my_variable(self):
...          print("getter method called")
...          return self._my_variable
...
...      # a setter function
...      @my_variable.setter
...      def my_variable(self, my_out):
...          if(my_out < 1976):
...             raise ValueError("... this my_variable has a criteria!!")
...          print("setter method called")
...          self._my_variable = my_out
...
>>> test_it = my_class()
>>> test_it.my_variable = 1979
setter method called
>>> print(test_it.my_variable)
getter method called
1979
>>> test_it.my_variable = 1975
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 16, in my_variable
ValueError: ... this my_variable has a criteria!!
This last example show you how to use @property decorator to create getters and setters in pythonic way.

Monday, June 17, 2019

Python Qt5 : the most simple QTreeWidget - part 002.

This tutorial uses PyQt5 and Python version 3.7.3.
Let's install the PyQt5 python module with the pip tool:
C:\Python373\Scripts>pip install PyQt5
Collecting PyQt5
...
Successfully installed PyQt5-5.12.2 PyQt5-sip-4.19.17
Let's see one simple example with comments about how to use QTreeWidget.
import sys
from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QApplication, QWidget

if __name__ == '__main__':
    # create a empty my_app application
    my_app = ''
    # test this my_app to create instance
    if QApplication.instance() != None:
        my_app = QApplication.instance()
    else:
        my_app = QApplication(sys.argv)
    # create a QTreeWidgetItem with tree columns
    my_tree= QTreeWidgetItem(["Column A", "Column B", "Column C"])
    # add date using a for loop 
    for i in range(6):
        list_item_row = QTreeWidgetItem(["Child A-" + str(i), "Child B-" + str(i), "Child C-" + str(i)])
        my_tree.addChild(list_item_row)
    # create my_widget widget
    my_widget = QWidget()
    my_widget.resize(640, 180)
    # create a QTreeWidget named my_tree_widget 
    my_tree_widget = QTreeWidget(my_widget)
    # set the size
    my_tree_widget.resize(640, 180)
    # set the number of columns 
    my_tree_widget.setColumnCount(3)
    # add labels for each column 
    my_tree_widget.setHeaderLabels(["Column A label", "Column B label", "Column C label"])
    # add my_tree using addTopLevelItem
    my_tree_widget.addTopLevelItem(my_tree)
    # show the widget
    my_widget.show()
    # the exit of my_app
    sys.exit(my_app.exec_())
This is another simple example written in a simple way to show how versatile are Python and PyQt5.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTreeWidget, QTreeWidgetItem
 
my_app = QApplication(sys.argv)
my_window = QWidget()
my_layout = QVBoxLayout(my_window)
 
my_tree = QTreeWidget()
my_tree.setHeaderLabels(['Name', 'Cost ($)'])
my_item_root = QTreeWidgetItem(my_tree, ['Romania', '238,397 kmp'])
my_item_raw = QTreeWidgetItem(my_item_root, ['Black Sea', '436,402 kmp'])
 
my_layout.addWidget(my_tree)
my_window.show()
sys.exit(my_app.exec_())
If you like my simple tutorials then you subscribe or you can search my other web sites too.

Sunday, June 16, 2019

Python 3.7.3 : Using the pycryptodome python module.

This python module can be used with python 3.
More information can be found here.
PyCryptodome is a self-contained Python package of low-level cryptographic primitives.
It supports Python 2.6 and 2.7, Python 3.4 and newer, and PyPy.

The install of this python module is easy with pip tool:
C:\Python373\Scripts>pip install pycryptodome
Collecting pycryptodome
...
Installing collected packages: pycryptodome
Successfully installed pycryptodome-3.8.2
All packages from this python module are:
  • Cipher;
  • Signature;
  • Hash;
  • Publickey;
  • Protocol;
  • IO;
  • Random and Util;
Let start with a few examples:
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from Crypto.Random import get_random_bytes
>>> key16 = get_random_bytes(16) # 16 bytes * 8 = 128 bits (1 byte = 8 bits)
The python module comes with features for encryption and dencryption, like RSA, AES, DES and many options.
Another good feature is KDF with PBKDF2 function:
>>> from Crypto.Protocol.KDF import PBKDF2
>>> center = b'go'
>>> password = 'go'
>>> output = PBKDF2(password, center, dkLen=64)
>>> print(output)
b'E\x0b\x91\x87\xde\xb2E\xe5Gv\x03\x86fVe8\x1e%\xb5l\xa0\xdb\xbfI\x01\xb5\xdf\x8
1\xad\x82@\x00\xacr\xc7\xa26\xc6\xe92\x1e\xf8\xe9\x0b\x9e\x93\x1dj\x1c\xff\x1c4\
xc2\x0e6\xc2\x8eYc2N\x995\x87'
>>>
If you are a fan of encryption and decryption math, then this module will enable you to use it.
By studying this module you can give a more in-depth view of what exists in this field and what does not exist.

Saturday, June 8, 2019

Python 3.7.3 : Testing the PyX python module.

This python module has a good documenation with many examples, see the eofficial wepage.
The development team come with this intro:
Summary
PyX is a Python package for the creation of PostScript, PDF, and SVG files. It combines an abstraction of the PostScript drawing model with a TeX/LaTeX interface. Complex tasks like 2d and 3d plots in publication-ready quality are built out of these primitives.
Features
  • PostScript, PDF, and SVG output for device independent, freely scalable figures;
  • seamless TeX/LaTeX integration;
  • full access to PostScript features like paths, linestyles, fill patterns, transformations, clipping, bitmap inclusion, etc.;
  • advanced geometric operations on paths like intersections, transformations, splitting, smoothing, etc.;
  • sophisticated graph generation: modular design, pluggable axes, axes partitioning based on rational number arithmetics, flexible graph styles, etc.
Let's install this python module with pip tool:
C:\Python373\Scripts>pip install PyX
...
Installing collected packages: PyX
Successfully installed PyX-0.14.1
I try few examples from official webpage and working well.
>>> from pyx import *
>>>
>>> c = canvas.canvas()
>>> c.stroke(path.line(0, 0, 3, 0))
>>> c.stroke(path.rect(0, 1, 1, 1))
>>> c.fill(path.circle(2.5, 1.5, 0.5))
>>> c.writeEPSfile("path")
>>> c.writePDFfile("path")
>>> c.writeSVGfile("path")
>>> from pyx import *
>>>
>>> c = canvas.canvas()
>>> c.stroke(path.curve(0, 0, 0, 4, 2, 4, 3, 3),
...          [style.linewidth.THICK, style.linestyle.dashed, color.rgb.blue,
...           deco.earrow([deco.stroked([color.rgb.red, style.linejoin.round]),
...                        deco.filled([color.rgb.green])], size=1)])
>>> c.writeEPSfile("arrow")
>>> c.writePDFfile("arrow")
>>> c.writeSVGfile("arrow")
I got some error from writePDFfile with this example:
>>> c.writeEPSfile("textalongpath")
>>> c.writePDFfile("textalongpath")
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python373\lib\site-packages\pyx\canvas.py", line 50, in wrappedindocu
ment
    return method(d, file, **write_kwargs)
  File "C:\Python373\lib\site-packages\pyx\document.py", line 193, in writePDFfi
le
    pdfwriter.PDFwriter(self, f, **kwargs)
  File "C:\Python373\lib\site-packages\pyx\pdfwriter.py", line 321, in __init__
    registry.write(file, self, catalog)
  File "C:\Python373\lib\site-packages\pyx\pdfwriter.py", line 78, in write
    object.write(file, writer, self)
  File "C:\Python373\lib\site-packages\pyx\pdfwriter.py", line 248, in write
    file.write("/MediaBox [%f %f %f %f]\n" % self.PDFcontent.bbox.highrestuple_p
t())
  File "C:\Python373\lib\site-packages\pyx\bbox.py", line 112, in highrestuple_p
t
    raise ValueError("Cannot return high-res tuple for empty bbox")
ValueError: Cannot return high-res tuple for empty bbox
>>> c.writeSVGfile("textalongpath")
This python module has problem with some complex example from official webpage.

Monday, June 3, 2019

Python 3.7.3 : Working with wikipedia python module.

Wikipedia is a Python library that makes it easy to access and parse data from Wikipedia.
Let's install it:
C:\Python373\Scripts>pip install wikipedia
First, let's test the default example:
C:\Python373>python.exe
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import wikipedia
>>> print(wikipedia.summary("Wikipedia"))
...
.Wikipedia has been criticized for exhibiting systemic bias, for presenting a m
ixture of "truths, half truths, and some falsehoods", and for being subject to m
anipulation and spin in controversial topics. But by 2017, Facebook announced th
at it would help readers detect fake news by suggesting links to related Wikiped
ia articles. YouTube announced a similar plan in 2018.
>>> wikipedia.search("Falticeni")
['Falticeni', 'Foresta Falticeni', 'Charles, Prince of Wales', 'Sofia Ionescu',
'Buciumeni River (?omuzul Mare)', '?omuzul Mare River', 'Constantin Schumacher',
'Ionu? Atodiresei', '1967 Cupa României Final', 'J. J. Benjamin']
>>> wikipedia.page("Falticeni")
...
>>> city=wikipedia.page("Falticeni")
>>> city.title
...
>>> city.content
...
>>> wikipedia.set_lang("fr")
>>> page=wikipedia.page("Null")
>>> page.title
'Null' 
You can extract links:
>>> page = wikipedia.page("List_of_works_by_Leonardo_da_Vinci")
>>> print(page.links)
You can test all of these:
>>> dir(wikipedia)
['API_URL', 'BeautifulSoup', 'Decimal', 'DisambiguationError', 'HTTPTimeoutError
', 'ODD_ERROR_MESSAGE', 'PageError', 'RATE_LIMIT', 'RATE_LIMIT_LAST_CALL', 'RATE
_LIMIT_MIN_WAIT', 'RedirectError', 'USER_AGENT', 'WikipediaException', 'Wikipedi
aPage', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__na
me__', '__package__', '__path__', '__spec__', '__version__', 'cache', 'datetime'
, 'debug', 'donate', 'exceptions', 'geosearch', 'languages', 'page', 'random', '
re', 'requests', 'search', 'set_lang', 'set_rate_limiting', 'set_user_agent', 's
tdout_encode', 'suggest', 'summary', 'sys', 'time', 'timedelta', 'unicode_litera
ls', 'util', 'wikipedia']
Read more at pypi website.

Thursday, May 30, 2019

Python 3.7.3 : Using the win32com - part 007.

Today I show you a new script I tested a few days ago with win32com and Win32_LogonSession class, see thedocumentation.
The Win32_LogonSession WMI class describes the logon session or sessions associated with a user logged on to a computer system running Windows.
Let's see the script:
import win32com.client
from win32com.client import gencache
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Session")
for objItem in colItems:
    print("Caption" , objItem.Caption)
    print("Description" , objItem.Description)
    print("InstallDate" , objItem.InstallDate)
    print("Name" , objItem.Name)
    print("Status" , objItem.Status)
    print("StartTime" , objItem.StartTime)
    print("AuthenticationPackage" , objItem.AuthenticationPackage)
    print("LogonId" , objItem.LogonId)
    print("LogonType" , objItem.LogonType)
The result of this python script:
Caption None
Description None
InstallDate None
Name None
Status None
StartTime 20190530105325.022532+180
AuthenticationPackage LiveSSP
LogonId 8291403
LogonType 2
Caption None
Description None
InstallDate None
Name None
Status None
StartTime 20190530105325.022532+180
AuthenticationPackage LiveSSP
LogonId 8291220
LogonType 2
You can read info with this python module.
For example, the output tells me aboutLogonType.
You’ll see type 2 logons when a user attempts to log on at the local keyboard and screen whether with a domain account or a local account from the computer.