Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Python – Exception Handling

In programming, Handling exceptions is a must when it comes to real life applications. Python has many built-in exceptions that are raised when your program encounters an error. When these exceptions occur, the Python interpreter stops the current process and passes it to the calling process until it is handled. If not handled, the program will crash.

We must handle any exception raised within our application. We do that by use try and except.

Error being raised

result = 12 / 0
print(result)

# output

Traceback (most recent call last):
  File "/Users/folaukaveinga/Github/python/main.py", line 101, in <module>
    exceptions.show()
  File "/Users/folaukaveinga/Github/python/exceptions.py", line 6, in show
    result = 12 / 0
ZeroDivisionError: division by zero

 

Handling raised error

The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

try:
    result = 12 / 0
    print(result)
except ZeroDivisionError as e:
    print(e)

print("done")

Here the program continued its executing to the end where is before it stopped when exception was raised.

 

Handling specific errors

try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs.

try:
   # do something
   pass

except ValueError:
   # handle ValueError exception
   pass

except (TypeError, ZeroDivisionError):
   # handle multiple exceptions
   # TypeError and ZeroDivisionError
   pass

except:
   # handle all other exceptions
   pass

 

Raise an error

Exceptions are raised by Python when errors occur at runtime. We can also manually raise exceptions using the raise keyword. We can optionally pass values to the exception to clarify why that exception was raised.

name = input("what is your name? ")
if name == None or len(name) ==0 :
   raise ValueError("invalid name")

# output - if you don't put in anything
Traceback (most recent call last):
  File "/Users/folaukaveinga/Github/python/main.py", line 101, in <module>
    exceptions.show()
  File "/Users/folaukaveinga/Github/python/exceptions.py", line 15, in show
    raise ValueError("invalid name")
ValueError: invalid name

 

Try with else clause

In some situations, you might want to run a certain block of code if the code block inside try ran without any errors. For these cases, you can use the optional else keyword with the try statement. Note that exceptions in the else clause are not handled by the preceding except clauses.

try:
    result = 12 / 0
    print(result)
except ZeroDivisionError as e:
    print(e)
else:
    print("all good")

Try with finally

The try statement in Python can have an optional finally clause. This clause is executed no matter what, and is generally used to release external resources. In all these circumstances, we must clean up the resource before the program comes to a halt whether it successfully ran or not. These actions (closing a file, GUI or disconnecting from network) are performed in the finally clause to guarantee the execution.

try:
    f = open("test.txt", encoding='utf-8')
    # perform file operations
finally:
    f.close()
    print("file closed")

Source code on Github

 

 

 

February 8, 2021

Python – Data Types

Variables

Data in programming is stored in containers called variables. Every value(variable) in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes. Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Variables do not need to be declared with any particular type, and can even change type after they have been set. You can let python determine the data type or you can explicitly set it.

Data Types

Text Type str
Numeric Types: intfloatcomplex
Sequence Types: listtuplerange
Mapping Type: dict
Set Types: setfrozenset
Boolean Type: bool
Binary Types: bytesbytearraymemoryview

 

str data type

In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character is a string of length one. It is represented by str class.

firstName = "Folau"
print(firstName)

firstName = str("Folau")
print(firstName)

# console
Folau
Folau

int data type

Integers can be of any length, it is only limited by the memory available. It contains positive or negative whole numbers (without fraction or decimal)

intNum = 2
print(intNum)

num = int(2)
print(num)

float data type

A floating-point number is accurate up to 15 decimal places. Integer and floating points are separated by decimal points. 1 is an integer, 1.0 is a floating-point number.

number = 2.5
print(number)

num = float(2.5) 
print(numb)

#console
2.5
2.5

complex data type

Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.

list data type

List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items in a list do not need to be of the same type.

lista = [1, 2.2, 'python']
print(lista)

listb = list((1, 2.2, 'python'))
print(listb)
# console
[1, 2.2, 'python']
[1, 2.2, 'python']

tuple data type

Tuple is an ordered sequence of items same as a list. The only difference is that tuples are immutable. Tuples once created cannot be modified.

Tuples are used to write-protect data and are usually faster than lists as they cannot change dynamically.

# how to create tuple
tuple_numbers = (1, 2, 3, 1)
tup = 1, 2, 3, 1, None, "Hello"
nested_tuple = ((1, 2), ("Hello", "Hi"), "Python")
empty_tuple = ()
numbs = tuple((1,2,3))
# how to access tuple elements
nested_tuple = (1, 2, (3, 4), (5, 6, 7))
nested_tuple[2][0] -> 3

range data type

range returns a sequence of numbers starting from 0 and increments to 1 until it reaches a specified number. The most common use of range function is to iterate sequence type. It is most commonly used in for and while loops. We can use range in python to increment and decrement step values using positive and negative integers.

# range(start, stop, step)
# start - where to start from
# stop - where to stop
# step - how big of a step for each iteration

evenNumbers = range(2, 20 ,2)
for num in evenNumbers:
    print(num)

#console
2
2
4
6
8
10
12
14
16
18

dict data type
Dictionary  is an unordered collection of key-value pairs. It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value. In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value. Key and value can be of any type.

person = {"firstName":"Folau", "lastName":"Kaveinga"}
print(person)

user = dict(firstName="Folau", lastName="Kaveinga")
print(user)

set data type

Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items in a set are not ordered.

# set
numbers = set((1,2,3))
print(type(numbers))

numbers = {1, 2, 3}
print(type(numbers))

fronzenset data type

Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. Due to this, frozen sets can be used as keys in Dictionary or as elements of another set. But like sets, it is not ordered (the elements can be set at any index).

# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')

fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())

# frozensets are immutable
fSet.add('v') -> error

boolean data type

True or False. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in Boolean context as well and determined to be true or false. It is denoted by the class bool. Note that True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.

isMale = True
print(isMale)

# console
True

bytes data type

The bytes() method returns a immutable bytes object initialized with the given size and data. bytes() method returns a bytes object which is an immutable (cannot be modified) sequence of integers in the range 0 <=x < 256. The syntax of bytes() method is

bytes([source[, encoding[, errors]]])
string = "My name is Folau"

# string with encoding 'utf-8'
arr = bytes(string, 'utf-8')
print(arr)

#console
b'My name is Folau'

bytearray data type

The bytearray() method returns a bytearray object which is an array of the given bytes. bytearray() method returns a bytearray object which is mutable (can be modified) sequence of integers in the range 0 <= x < 256. The syntax of bytearray() method is

bytearray([source[, encoding[, errors]]])
string = "My name is Folau"

# string with encoding 'utf-8'
arr = bytearray(string, 'utf-8')
print(arr)

#console
bytearray(b'My name is Folau')

memoryview data type

The memoryview() function returns a memory view object of the given argument. A memory view is a safe way to expose the buffer protocol in Python. It allows you to access the internal buffers of an object by creating a memory view object. To expose the buffer protocol using memoryview(), we use this syntax:

memoryview(obj)
#random bytearray
random_byte_array = bytearray('ABC', 'utf-8')

mv = memoryview(random_byte_array)

# access memory view's zeroth index
print(mv[0])

# create byte from memory view
print(bytes(mv[0:2]))

# create list from memory view
print(list(mv[0:3]))

#console
65
b'AB'
[65, 66, 67]

 

 

The data type is set when you assign a value to a variable.

numbers = {1, 2, 3}
print(type(numbers))

# console
<class 'set'>

Explicitly declaring a data type. I found this very useful when reading other people’s code.

numbers = set((1,2,3))

Use type() function to find out a data type.

numbers = set()
numbers.add(1)
numbers.add(2)
numbers.add(3)
print(type(numbers))

# console
<class 'set'>

Use isinstance function to check if an object belongs to a particular class or type

number = 2.5
print(number, "is float number?", isinstance(number,float))

#console
2.5 is float number? True

 

Source code on Github

February 8, 2021

MySQL Trigger

 

A MySQL trigger is a stored program that is invoked automatically in response to an event such as INSERT, UPDATE, or DELETE to a particualar table.

There are two types of triggers

  1. Row-level trigger: a row-level trigger is activated for each row that is inserted, updated, or deleted.
  2. Statement-level trigger: a statement-level trigger is executed once for each transaction regardless of how many rows are inserted, updated, or deleted. MySQL supports only row-level triggers. It doesn’t support statement-level triggers.

Advantages of triggers

  1. Triggers provide another way to check the integrity of data
  2. Triggers handle errors from the database layer
  3. Triggers are another way to run cron jobs.
  4. Triggers can be useful for auditing the data changes in tables.

Disadvantages of triggers

  1. Triggers can only use extended validations but not all validations. You can use NOT NULL, UNIQUE, CHECK, and FOREIGN KEY contraints.
  2. Triggers can be difficult to troubleshoot because they execute automatically in the database which may not be visible to clients.
  3. Triggers may increase the overhead of the MySQL server.

Create a Trigger

  1. Specify the name of the trigger – CREATE TRIGGER trigger_name
  2. Specify trigger type – AFTER INSERT
  3. Specify the name of the table for which you want to create the trigger for – ON table_name
  4. Specify the trigger body that will run every the trigger is invoked.
DELIMITER $$
 
CREATE TRIGGER trigger_name
    AFTER INSERT
    ON table_name FOR EACH ROW
BEGIN
   -- statements
   -- variable declarations

   -- trigger code
END$$    
 
DELIMITER ;

Example

DELIMITER $$
 
CREATE TRIGGER after_members_insert
AFTER INSERT
ON members FOR EACH ROW
BEGIN
    IF NEW.birthDate IS NULL THEN
        INSERT INTO reminders(memberId, message)
        VALUES(new.id,CONCAT('Hi ', NEW.name, ', please update your date of birth.'));
    END IF;
END$$
 
DELIMITER ;

Triggers only run for the new, updated, or deleted rows. They don’t touch those rows that didn’t get updated.

Show triggers

SHOW TRIGGERS;

SHOW TRIGGERS
[{FROM | IN} database_name]
[LIKE 'pattern' | WHERE search_condition];
SHOW TRIGGERS; -- return all triggers in all databases
SHOW TRIGGERS 
FROM database_name; -- show triggers from database_name

The only way to edit a trigger is by dropping and recreating it.

DROP TRIGGER [IF EXISTS] [schema_name.]trigger_name;

 

December 9, 2020

Linux SSH

SSH stands for “Secure Shell”. It is a protocol used to securely connect to a remote server. ssh is secure in the sense that it transfers the data in encrypted form between the host and the client. It transfers inputs from the client to the host and relays back the output. ssh runs at TCP/IP port 22.

SSH with username and password

ssh {options} username@host

host can be ip address or domain name. You will be prompted to enter password

ssh ubuntu@19423455

 

SSH with private and public keys

ssh -i “/path-to-IdentityFile” username@host

With aws ec2, you have a .pem file as the identity file.

ssh -i "test.perm" ubuntu@folauk.com

 

Add custom connection options

When you ssh into a server, you most likely use a key. But it takes time to type out the key and other options. It would be nice to have to option of just typing out something like ssh my-linux-tester in which case you know exactly where to go. It turns out you can do this kind of thing. SSH has a config file in the ~/.ssh directory. This config file can be configured for your custom connections with these options:

  • HostName: The actual hostname that should be used to establish the connection. This replaces any alias defined in the Host header. This option is not necessary if the Host definition specifies the actual valid hostname to connect to.
  • User: The username to be used for the connection.
  • Port: The port that the remote SSH daemon is running on. It’s default to port 22 if not specified.
  • IdentityFile : The public identity file.
# Personal linux server for testing
Host my-linux-tester
  HostName ec2-tester.folaukaveinga.com
  User ubuntu
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/personal/test.perm

Now you can just do this to ssh into server. ssh {Host} in which case you will ssh into the ec2-tester.folaukaveinga.com server

ssh {Host}

ssh my-linux-tester

 

 

November 15, 2020

Git cherry-pick

The cherry-pick command is used to apply a commit from one branch to another branch.

Let’s say you have a feature branch that you are working on that have two stories. You finished the two stories but only need to push the first story to master. You have one commit for story number one and another commit for story number two. Note here that you can’t use merge because merge will bring all the changes(story one and two together). We don’t want that we only need the first story code. Here you can cherry-pick the commit for story number one to master.

Steps
1. Find commit id of the commit you need to cherry-pick
2. Checkout the branch you want to apply the commit to
3. git cherry-pick commit-id

git checkout master
git cherry-pick 1232349F

Here is another example. Let’s say you are at branch (F-G-H) and you want the change that’s made in E. To do this you need to cherry-pick E. Note that these notes are commit ids.

git cherry-pick E

If you want to cherry-pick more than one commits then do this

git cherry-pick commit-id-1 commit-id-2 commit-id-3

Cherry pick all commits of a specific branch

When you want to cherry pick all commits of a specific branch but not commits merged or cherry-picked into it. You can just cherry pick the whole branch. Maybe there are so many commits that it does not make sense to specify each commit.

Let say you have a branch call color, css, and grid. You working on the css branch but have changes from color branch that you don’t want to push to the grid branch. What you need to do is cherry pick all commits from the css branch to the grid branch. Here is how you do that.

git checkout css
// make changes
// commit and push(abc)


git merge color
// merged 1 commit(cde) from color to css(the working branch)

// make changes again
// commit and push(fhg)

// Cherry pick all of css commits(without color commits) to grid
git checkout grid

git cherry-pick css
// you have commits abc and fhg but not cde.

 

November 5, 2020