Posted in python

Class attributes and Instance attributes in Python

This post will talk about 2 attributes in a Python class: Class attributes and Instance attributes

First, let look at the below Student class:

class Student:
    # Class attributes
    type = 'Student Type'
    id = 'Class Attr ID'

    def __init__(self, name='Unknown', age=0, id='Instance Attr ID'):
        # Instance attributes.
        self.name = name
        self.__age = age    # Private access attributes.
        self.id = id

    def setAge(self, age): self.__age = age

    def getAge(self): return self.__age

And we create 2 Instance of Student class:

studentA = Student()
studentB = Student('B', 20)

We can access Class Attributes from created Instance or directly from Class:

# Access to Class attributes from Instance or Class
print('Get Type from a certain instance: ' + studentA.type)
print('Get Type from class directly: ' + Student.type)

Output:

Get Type from a certain instance: Student Type
Get Type from class directly: Student Type

In case Class attribute and Instance attribute have same name. Python first look at its Instance attributes, if existed, it will get the Instance attribute. If not existed, it will find Class attribute. Let’s see below code:

# Get the attribute which has same name
print('Get ID from a certain instance: ' + studentA.id)
print('Get ID from class directly: ' + Student.id)

Output:

Get ID from a certain instance: Instance Attr ID
Get ID from class directly: Class Attr ID

So, when should we use Class attributes ?

In my opinions, there are some below cases we can apply Class attributes:

  • Using as Constant of a class
class Circle(object):
    PI = 3.14

print(Circle.PI) # Output: 3.14
  • Tracking all data across all instances of a given class
class Person(object):
    names = []

    def __init__(self, name):
        self.__name = name
        Person.names.append(name)

joe = Person('Tom')
bob = Person('Mary')
print Person.names
## ['Tom', 'Mary']

As you see at above code, the Class attributes is used to collect all of created Instances name.

You can find the demo at Github link ClassAttributes.py

Posted in git

[GIT] Some useful GIT commands

git-logo

GIT Help

git help -g
git help everyday

GIT config:

git config --global user.name "John Doe"
git config --global user.email "john@example.com"
git config --global color.ui false // Turn off git colored terminal output

GIT checkout + update branch:

git checkout <branch-name>
git fetch
git pull
git checkout -  // Checkout to previous branch

 

GIT update files:

git checkout —  <file-name>  // discard a file

 

GIT Status:

git status
git status --short --branch // Show git status short

 

GIT Diff

git diff
git diff --cache
git diff --name-only --diff-filter=U // List all conflicted files
// Check difference of current branch with compared-branch-name
git diff <compared-branch-name>
git diff -p -1 <file-name>  // show change of file

 

GIT – How to push code ?

git add .  
git commit -m "Message"
git push

Git Branch

git branch --merged master   // list all of branches which merged to master
git branch -vv // List branches and their upstreams and last commit on it
git branch --no-merged // List all of Branch which has WIP
git branch -m <new-branch-name> // Rename a branch
git branch --all | grep <text>  // Search commited text
// List all branches that are already merged into master
git branch --merged master
// Delete a branch on your local filesystem
git branch -d [name_of_your_new_branch]
git push origin --delete <remote_branchname> // Delete REMOTE branch

Create the branch on your local machine and switch in this branch :

  1. A) git pull
  2. B) Create a new branch:
  1. git branch <new-branch-name>
  1. OR  git checkout -b <new-branch-name>

 

  1. C) Push branch to github: git push origin <new-branch-name>

 

GIT Stash:

git stash list

git stash clear

git stash push -m “message here”

git stash apply stash@{0} OR git stash apply –index 0

git stash show stash@{0} -p  // show diff of stash

 

Git Reset

git fetch
 git reset --hard origin/develop
git update-ref -d HEAD   // Reset first commit
git reset HEAD <file-name> // Unstaging Staged file

 

GIT log:

git log -p <file_name>     // show log of a file_name
git reflog -2  // show history with <COMMIT-ID>
git show  <COMMIT-ID>
 git log --pretty=oneline -2
git log --oneline -2
git log --oneline -p  -2    // show history with <COMMIT-ID> and what is changed
git log --oneline --stat  -2   // show history with <COMMIT-ID> and which file is modified
git log --pretty=format:"%h - %an, %ar : %s" -2
git log --pretty=format:"%h %s" --graph   // show history in GRAPH mode
git log --pretty="%h - %s" --author='Binh'  // show history of certain User
git log --pretty="%h - %s" --since=1.weeks  // show history since 1 week
git log -S "message"  // Search log by Content
git whatchanged --since='2 weeks ago' // What changed since 2 Weeks?
git whatchanged --since='2 days ago' // What changed since 2 Days ?
// List commits and changes to a specific file (even through renaming)
git log --follow -p -- <file_path> 
// logs between date range
git log --since='FEB 1 2017' --until='FEB 14 2017'

 

## Visualize the version tree.

gitk path/to/files
git log --pretty=oneline --graph --decorate --all
gitk --all
git log --graph --pretty=format:'%C(auto) %h | %s | %an | %ar%d'

 

Git Cherry-pick

// Cherry-pick from Source-branch at the current branch
git cherry-pick <source-branch>

Git Aliases

git config --global alias.<handle> <command> 
Example: git config --global alias.st status

 

GIT Tag

git tag -d <tag-name>  // Delete LOCAL tag
git push origin :refs/tags/<tag-name>  // Delete REMOTE tag
 
Posted in Uncategorized

JPA (Java Persistence API) Questions And Answers

java8_logo

1) What is JPA?

JPA (Java Persistence API) is a Java EE and Java SE specification that describes a management system for saving java objects to relational database tables in a convenient form. Java itself does not contain JPA implementations, however, there are many implementations of this specification from different companies (open and not). This is not the only way to save java objects in databases (ORM systems), but one of the most popular in the Java world.

2. What is the difference between JPA and Hibernate?

Hibernate is one of the most popular open source implementations of the latest specification (JPA 2.1). Even more likely the most popular, almost standard de facto. That is, JPA only describes rules and APIs, and Hibernate implements these descriptions, however Hibernate (like many other JPA implementations) has additional features not described in JPA (and not portable to other JPA implementations).

3. Is it possible to use JPA with noSQl databases?

In general, the JPA specification says only about mapping java objects into relational database tables, but there are a number of implementations of this standard for noSql databases: Kundera, DataNucleus, ObjectDB, and a number of others. Naturally, not all specification-specific features for relational databases are transferred to nosql databases completely.

4. What is the difference between JPA and JDO?

JPA (Java Persistence API) and Java Data Objects (JDO) are two specifications for storing java objects in databases. If JPA is concentrated only on relational databases, then JDO is a more general specification that describes the ORM for any possible bases and repositories.

In principle, JPA can be viewed as part of the JDO specification specialized in relational databases, even though the API of these two specifications does not completely match. The “developers” of specifications also differ – if JPA is developed as JSR, then JDO was first developed as JSR, now it is developed as an Apache JDO project.

5. What is Entity?

Entity is a lightweight persistent domain object. The main program entity is the entity class, which can also use additional classes that can be used as auxiliary classes or to maintain state of the entity.

 

Posted in Uncategorized

[Java Core] File handling in Java

java_logo_100

In Java, we often handle a file. Now, I want to introduce some code for handling file basically.

  • Create a folder
public void createFolder(String newFolderPath) {
    new File(newFolderPath).mkdir();
}
  • Create a folder and its subfolder
/**
* @param path such as "C:\\Directory2\\Sub2\\Sub-Sub2"
*/
public void createFolderAndItsSubFolders(String path) {
   new File(path).mkdirs();
}
  • Check a folder existed or not
/**
* @param path such as "C:\\Directory1"
*/
public boolean isExistedFolder(String folder) {
   File file = new File(folder);
   return file.exists();
}
  • Create new file
public void createNewFile(String filePath) {
    try {
      File file = new File(filePath);
      if (file.createNewFile()) {
        System.out.println("File is created!");
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
 }
  • Delete a file
public void deleteFile(String filePath) {
    try {
      File file = new File(filePath);
      if (file.delete()) {
        System.out.println(file.getName() + " is deleted!");
      } else {
        System.out.println("Delete operation is failed.");
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("IOException: " + e.getMessage());
    }
  }
  • Open a file by default app in PC such as open HTML file on Chrome
public void openFileOnDefaultApp(String filePath) {
    File htmlFile = new File(filePath);
    try {
      Desktop.getDesktop().browse(htmlFile.toURI());
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("IOException: " + e.getMessage());
    }
 }

 

You also can find above source at this class file

Like and share this topic if it is helpful for you 🙂

Posted in JavaScript, Useful Script

Javascript useful script [Part 1]

javascript

In this topic, I will provide some useful scripts in Javascript, they can help us a lot for coding

  1. Array
  • .filter()

Create a new array base on an existed array with filter conditions.

const studentAge= [17,16,18,19,21,15]
const ableToDrink = studentsAge.filter( age => age > 18 );
// Result: ableToDrink= [19,21]
  • .map()

Create a new array by copying and editing data of an existed array

// Example: create new array from numbers array and add '&' for each element
const numbers = [2, 3, 4, 5];
const dollars = numbers.map( number => '$' + number);
// Result: dollars = ['$2', '$3', '$4', '$5']
  • .forEach()

Do a certain action on each element in an array

const emotions = ['happy', 'sad', 'angry'];
emotions.forEach( emotion => console.log(emotion) );
// Result will disply one by one
// 'happy'
// 'sad'
// 'angry'
  • .some()

Check if any element in array satisfy a certain condition. If yes, return true, otherwise, return false.

 
const userPrivileges = ['user', 'user', 'user', 'admin'];
const containsAdmin = userPrivileges.some( element => element === 'admin');
// Result: containsAdmin = true, because array has element that contain 'admin'
  • .every()

Like ‘.some()’ function but check all of elements with condition.

const ratings = [3, 5, 4, 3, 5];
const goodOverallRating = ratings.every( rating => rating >= 3 );
// Result: goodOverallRating = true, because every element in array >= 3

 

2) Others

 

Like & Share if this topic is helpful for you 🙂

Posted in Java

[Java Core] How to read/write file in Java ?

java_logo_100

In Java, we often face the requirement to read content from a file or write content to file. In Java, we have many ways to do that :).

A) How to READ file?

  • Using BufferedReader is the simplest and most common-used method. It helps us read file line by line:

public class ReadWriteFileHandler {

public void readFileByBufferedReader(String fileName) {
 BufferedReader br = null;
 FileReader fr = null;
 try {
   fr = new FileReader(fileName);
   br = new BufferedReader(fr);
   String currentLine = "";
   while ((currentLine = br.readLine()) != null) {
// Read line by line
      System.out.println(currentLine);
   }
 } catch (IOException e) {
   e.printStackTrace();
 } finally {
   try {
     if (br != null)
        br.close();
     if (fr != null)
        fr.close();
    } catch (IOException ex) {
     ex.printStackTrace();
    }
   }
 }

}

 

 

B) How to WRITE file?

Using BufferedWriter to write content to a file, create the file if doesn’t exist, the existing content will be overridden.

The BufferedWriter is a character stream class to handle the character data. Unlike byte stream (convert data into bytes), you can just write the strings, arrays or character data directly to a file.

Please find an example below:


public void writeFile(String fileName, String content) {
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(fileName);
bw = new BufferedWriter(fw);
bw.write(content);
System.out.println("Write Done !");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();

}

}
}

 

Basically, you can refer above code from ReadWriteFileHandler.java

Hope this topic helpful for you :), please share if you like it 🙂

Posted in Java, QA, Tips

Useful scripts for Selenium in Java

selenium_icon

Selenium HQ is really useful for testing, you can find its info at Selenium Home Page . During working on it in Java projects, I found some scripts which help us save time for test cases implementation.

  • First is the necessary component in Selenium lib:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
  • Constructors:
WebDriverWait wait = new WebDriverWait(driver, 60);
WebDriver driver;
  • Collapse / Expand

This script is an action of Mouse when User clicks on an expand-icon for collapsing or expanding

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("$('.expand-icon')[0].dispatchEvent(new MouseEvent('click'))");
  • Click on a button:
String buttonId = "//button[@id='button_id_here']";
driver.findElement(By.xpath(buttonId)).click();
  • Check a webpage exist or not
String pageTitle = "//span[contains(.,'Page_Title')]";
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(pageTitle)));
  • Find a button
String buttonElement = "//button[@title='Button text here']";
WebElement buttonElement = driver.findElement(By.xpath(buttonElement ));
  • Find a content:
String contentId = "//span[@id='Content ID Here']";
WebElement contentElement = driver.findElement(By.xpath(contentId ));
  • Others (continues)

 

 

If this topic is helpful for you. Please share 🙂