Create Temporary Table in MySQL

In this article we are going to discuss about how to create temporary table in MySQL.

MySQL has a property to create a temporary table where we can keep keep temporary data.MySQL can also delete this table automatically whenever current session is ended or the user stop the program. WE can also remove it manualy using Drop method.

In MySQL we can create temporary table using ‘Temporary’ keyword.

Create temporary table and insert data

Here we are going to create a temporary table and insert some data in it.

Syntax:

CREATE TEMPORARY TABLE temporary_table_name SELECT * FROM existing_table_name LIMIT 0;

So suppose we have an existing table ‘registration_details’,

MySQL create table_existing
Now we are going to create a new table with the help of our existing table ‘registration_details’ below is our query for this,

CREATE TEMPORARY TABLE registered_employee
SELECT first_name, desig_post FROM registration_details WHERE desig_post ="Developer"  AND last_name="Mishra" ;

Now by using below select query we will see our output,
select * from registered_employee;

MySQL create table_2
So you can see that we have got our output registered_employee having only those employee who have last_name =’mishra’ and desig_post=’developer’ as we have given condition.

Now we are going to add some data using insert query,let’s see how it will work

INSERT INTO registered_employee(first_name,desig_post)
SELECT first_name,desig_post
FROM registration_details
WHERE
desig_post="tester"
;

Here is our output:

MySQL insert table_3
In above query you can see that we have given condition desig_post=”tester” so it added those name having tester designation.

Create temporary table in a select statement without a separate create table

Now we are going to create a table using ‘AS’ keyword,below is the query for it.

CREATE TEMPORARY TABLE IF NOT EXISTS registered_employee AS 
 (SELECT first_name,desig_post  FROM registration_details 
 WHERE desig_post ="developer" & "tester");

Here is output:

MySQL insert table_3

Create a temporary table in MySQL with an index

Now we are going to create a temporary table with an index,

Syntax:

CREATE TEMPORARY TABLE temporary_table_name (index_column_name INTEGER NOT NULL AUTO_INCREMENT, PRIMARY
KEY(index_column_name), INDEX(index_column_name))
SELECT * FROM existing_table_name
WHERE  ;

Now let’s take an example to understand this,

CREATE TEMPORARY TABLE registered_employee_with_index (registration_number INTEGER NOT NULL AUTO_INCREMENT, PRIMARY    
KEY(registration_number), INDEX(registration_number))
SELECT * FROM registration_details
WHERE desig_post ="developer" ;

Here is our output:

MySQL create table_4
So you can see that above we have given condition that ‘WHERE desig_post =”developer”‘ and we got our new table “registered_employee_with_index” with index number.

Add a column to temporary table in MySQL

Here we are going to add a new column using Alter command in our temporary table,

Syntax:

ALTER TABLE temporary_table_name ADD new_column_name  
DEFAULT default_value;

Let’s take an example,

We will be use above table registered_employee_with_index and adding a new column state_name to it.

ALTER TABLE registered_employee_with_index ADD state_name varchar(255) 
DEFAULT 'Andhra Pradesh';

MySQL create table_5
You can see in the above output, a new column state_name got added to the table registered_employee_with_index.

Conclusion:

In this article we have discussed  about how to create temporary table in MySQL using different method.Thank you!

C++: Check if given path is a file or directory using Boost & C++17 FileSystem Library

C++ - Check if given path is a file or directory using Boost &; C++17 FileSystem Library

In this tutorial, we are going to discuss different ways to check if the given path is a file or directory using Boost & C++17 FileSystem Library.

There are certain functions that we are using here for both Boost Filesystem library & C++17 Experimental filesystem library,

bool exists(const path& p);

bool exists(const path& p);
bool exists(const path& p, error_code& ec);

In Boost Library’s ‘boost::filesystem namespace’ and in C++17 ‘std::experimental::filesystem namespace’, both return true if the given path points to a file or directory that exists in the filesystem. Also, the first one throws filesystem_error, whereas overload with error_code & throws nothing.

bool is_regular_file(const path& p);

bool is_regular_file( const path& p );
bool is_regular_file( const path& p, error_code& ec );

bool is_directory(const path& p);

bool is_regular_file( const path& p );
bool is_regular_file( const path& p, error_code& ec );

In all both returns true if the given path points to a file or directory that exists in the filesystem. Furthermore, the first one throws filesystem_error, whereas overload with error_code& throws nothing.

Do Read: 

Check if given path is a file that exists using Boost & C++17 FileSystem Library

For this, we will write an algorithm-

  • First, we will convert the given string path to boost::filesystem::path object
  • After that, we will check if the given path exists or not using boost::filesystem::exists() API.
  • Also, check if given path is a regular file using boost::filesystem::is_directory() API.

For C++17 library we use this-

#include <experimental/filesystem>

namespace filesys = std::experimental::filesystem;

For Boost Library we use this,

#include <boost/filesystem.hpp>
namespace filesys = boost::filesystem;

so here is the complete code:

#include <iostream>
#include <cassert>
#include <experimental/filesystem>
namespace filesys = std::experimental::filesystem;
/*
    Check if given string path is of a file
*/
bool checkIfFIle(std::string filePath)
{
    try {
        // Create a Path object from given path string
        filesys::path pathObj(filePath);
        // Check if path exists and is of a regular file
        if (filesys::exists(pathObj) && filesys::is_regular_file(pathObj))
            return true;
    }
    catch (filesys::filesystem_error & e)
    {
        std::cerr << e.what() << std::endl;
    }
    return false;
}

Check if given path is a Directory that exists using Boost & C++17 FileSystem Library

For this, we will also write an algorithm-

First, we will convert the given string path to boost::filesystem::path object later we will check if given path exists or not using boost::filesystem::exists() API. And finally, we will also check if given path is a directory using boost::filesystem::is_directory() API.

For C++17 librery we use this-

#include <experimental/filesystem>

namespace filesys = std::experimental::filesystem;

For Boost Library we use this,

#include <boost/filesystem.hpp>

namespace filesys = boost::filesystem;

Complete function is as follows,

#include <iostream>
#include <cassert>

#include <boost/filesystem.hpp>
namespace filesys = boost::filesystem;
/*
Check if given string path is of a Directory
*/
bool checkIfDirectory(std::string filePath)
{
    try {
        // Create a Path object from given path string
        filesys::path pathObj(filePath);
        // Check if path exists and is of a directory file
        if (filesys::exists(pathObj) && filesys::is_directory(pathObj))
            return true;
    }
    catch (filesys::filesystem_error & e)
    {
        std::cerr << e.what() << std::endl;
    }
    return false;
}
}

If you are going to use Boost library then compile with the following command in Linux,

g++ -std=c++11 example.cpp -lboost_filesystem -lboost_system

If you are going to use the C++17 library then compile with the following command in Linux,

g++ -std=c++11 example.cpp -lboost_filesystem -lboost_system

Conclusion:

In this article, we have discussed different ways to check if given path is a file or directory using Boost & C++17 FileSystem Library.

Python3 delete file – Python: How to remove files by matching pattern | wildcards | certain extensions only?

Python- How to remove files by matching pattern, wildcards, certain extensions only

Python find files matching pattern: In this ultimate tutorial, we are going to discuss how to remove files from a directory based on a matching pattern or wildcard, or specific extensions. You will get the information regarding these also, Python Os.Remove Wildcard, Python Delete File Wildcard, Python Remove Files With Wildcard, Python Delete Files With Wildcard, Python Remove Files Wildcard, Python Remove Files Matching Pattern, Delete File Python, Remove File Python, Python Os Delete File, Delete A File Python, Python Remove File Wildcard, Python Delete Files Matching Pattern, Python Remove Directory.

How to delete text files using different techniques?

Python remove all files in directory: Let’s discuss how to delete text files using different techniques, Suppose we have a directory that contains some log files and some text files and we want to delete all .txt files from that directory.

Then, continue your read so that you can successfully learn to remove files by matching patterns or wildcards by the following methods and techniques.

Remove files by pattern using glob.glob() & os.remove()

Python3 delete file: First, we will get a list of all file paths that match the specified patterns using glob.glob() and then delete all text files.

import os
import glob
# Get a list of all the file paths that ends with .txt from in specified directory
fileList = glob.glob('C://Users/HP/Desktop/A plus topper/*.txt')
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file : ", filePath)

So you can see that it will remove all ‘.txt’ files in the directory ‘C:\\Users\HP\Desktop\A plus topper\*.txt’. It will remove all text files because we mention” *.txt “.

Get the list of files using glob.glob()

Python os remove file: glob.glob() accepts path name and finds the path of all the files that match the specified pattern. By default recursive parameter is False, which means that it will find files in the main directory, not in a subdirectory.

glob.glob(pathname, *, recursive=False)

As we have seen by this approach we can not recursively delete files from subdirectories. For that, we will find another solution,

Read More:

Recursively Remove files by matching pattern or wildcard

Python delete all files in directory: It will search all the ‘txt’ files including files in subdirectories because we will use 'C://Users/HP/Desktop/A plus topper/**/*.txt'‘ **  ‘ in it.

Then we can iterate over the list and delete each file one by one using os.remove().

import os
import glob
# get a recursive list of file paths that matches pattern including sub directories
fileList = glob.glob('C://Users/HP/Desktop/A plus topper/**/*.txt', recursive=True)
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
    try:
        os.remove(filePath)
    except OSError:
        print("Error while deleting file")

It will delete all the text files from the directory and its sub-directories.

Recursively Remove files by matching pattern or wildcard using os.walk()

Python rm file: In this, we are going to use os.walk(). It generates filename in the given directory by walking over the tree structure in a top-down or bottom-up approach.

os.walk(top, topdown=True, onerror=None, followlinks=False)

It will return a tuple consisting of the main directory, a list of all subdirectories, and a list of all file names in the main directory.

Let’s use this os.walk() to get a list of all files in a given directory that matches a pattern. Then delete those files,

import os
import fnmatch
# Get a list of all files in directory
for rootDir, subdirs, filenames in os.walk('C://HP/Users/Desktop/A plus topper'):
    # Find the files that matches the given patterm
    for filename in fnmatch.filter(filenames, '*.txt'):
        try:
            os.remove(os.path.join(rootDir, filename))
        except OSError:
            print("Error while deleting file")

It will delete all the text files from the directory and also from its subdirectories.

Now we are going to create a Generic function to delete all the files from a given directory based on a matching pattern and it will also return the names of the files that were not deleted due to some error.

import os
import fnmatch
'''
Generic function to delete all the files from a given directory based on matching pattern
'''
def removeFilesByMatchingPattern(dirPath, pattern):
    listOfFilesWithError = []
    for parentDir, dirnames, filenames in os.walk(dirPath):
        for filename in fnmatch.filter(filenames, pattern):
            try:
                os.remove(os.path.join(parentDir, filename))
            except:
                print("Error while deleting file : ", os.path.join(parentDir, filename))
                listOfFilesWithError.append(os.path.join(parentDir, filename))
    return listOfFilesWithError
listOfErrors = removeFilesByMatchingPattern('/home/varung/Documents/python/logs/', '*.txt')
print('Files that can not be deleted : ')
for filePath in listOfErrors:
    print(filePath)

So in the above code, you can see that it will also return file names that can not be deleted.

Read also: How to delete a directory recursively using shutil.rmtree()

Analyze these: 

  • How To Delete File In Python
  • Python Remove File Wildcard
  • Delete Files Python
  • Python Rm File

Conclusion:

In this article, we have seen how to remove files from a directory based on matching patterns or wildcards, or certain extensions.

print entire dataframe panda – Python Pandas: How to display full Dataframe i.e. print all rows & columns without truncation

Python Pandas- How to display full Dataframe i.e. print all rows & columns without truncation

Print entire dataframe pandas: In this tutorial, we will discuss the different methods to display or print full Data frame i.e. print all rows & columns without truncation. So, get into this page and learn completely about Pandas display full data frame in python i.e. how to print all rows & columns without truncation. Also, you can get a clear idea of how to display full data frame from here. Pandas will be displayed column in the full data frame. And also include pandas print without truncation, python print data frame without truncation, pandas print data frame without truncation, display full data frame pandas, pandas print column without truncating, pandas dataframe print without truncation etc…

Display Full Contents of a Dataframe

Pandas show all rows: Pandas implement an operating system to customize the behavior & display similar stuff. By applying this benefits module we can configure the display to show the complete dataframe rather than a truncated one. A function set_option()is provided in pandas to set this kind of option,

pandas.set_option(pat, value)

It sets the value of the defined option. Let’s use this to display the full contents of a dataframe.

Setting to display All rows of Dataframe

Print all columns pandas: In pandas when we print a dataframe, it displays at max_rows number of rows. If we have more rows, then it truncates the rows.

pandas.options.display.max_rows

This option outlines the maximum number of rows that pandas will present while printing a dataframe. The default value of max_rows is 10.

In case, it is set to ‘None‘ then it implies unlimited i.e. pandas will display all the rows in the dataframe. Let’s set it to None while printing the contents of above-created dataframe empDfObj,

# Default value of display.max_rows is 10 i.e. at max 10 rows will be printed.
# Set it None to display all rows in the dataframe
pd.set_option('display.max_rows', None)

Let’s examine the contents of the dataframe again,

print(empDfObj)

Output: 

    A B ... Z AA
0 jack 34 ... 122 111
1 Riti 31 ... 222 211
2 Aadi 16 ... 322 311
3 Sunil 41 ... 422 411
4 Veena 33 ... 522 511
5 Shaunak 35 ... 622 611
6 Shaun 35 ... 722 711
7 jack 34 ... 122 111
8 Riti 31 ... 222 211
9 Aadi 16 ... 322 311
10 Sunil 41 ... 422 411
11 Veena 33 ... 522 511
12 Shaunak 35 ... 622 611
13 Shaun 35 ... 722 711
14 jack 34 ... 122 111
15 Riti 31 ... 222 211
16 Aadi 16 ... 322 311
17 Sunil 41 ... 422 411
18 Veena 33 ... 522 511
19 Shaunak 35 ... 622 611
20 Shaun 35 ... 722 711
21 jack 34 ... 122 111
22 Riti 31 ... 222 211
23 Aadi 16 ... 322 311
24 Sunil 41 ... 422 411
25 Veena 33 ... 522 511
26 Shaunak 35 ... 622 611
27 Shaun 35 ... 722 711
28 jack 34 ... 122 111
29 Riti 31 ... 222 211
30 Aadi 16 ... 322 311
31 Sunil 41 ... 422 411
32 Veena 33 ... 522 511
33 Shaunak 35 ... 622 611
34 Shaun 35 ... 722 711
35 jack 34 ... 122 111
36 Riti 31 ... 222 211
37 Aadi 16 ... 322 311
38 Sunil 41 ... 422 411
39 Veena 33 ... 522 511
40 Shaunak 35 ... 622 611
41 Shaun 35 ... 722 711
42 jack 34 ... 122 111
43 Riti 31 ... 222 211
44 Aadi 16 ... 322 311
45 Sunil 41 ... 422 411
46 Veena 33 ... 522 511
47 Shaunak 35 ... 622 611
48 Shaun 35 ... 722 711
49 jack 34 ... 122 111
50 Riti 31 ... 222 211
51 Aadi 16 ... 322 311
52 Sunil 41 ... 422 411
53 Veena 33 ... 522 511
54 Shaunak 35 ... 622 611
55 Shaun 35 ... 722 711
56 jack 34 ... 122 111
57 Riti 31 ... 222 211
58 Aadi 16 ... 322 311
59 Sunil 41 ... 422 411
60 Veena 33 ... 522 511
61 Shaunak 35 ... 622 611
62 Shaun 35 ... 722 711

[63 rows x 27 columns]

Also Check:

How to print an entire Pandas DataFrame in Python?

Pandas print dataframe: When we use a print large number of a dataset then it truncates. In this article, we are going to see how to print the entire pandas Dataframe or Series without Truncation or print pandas dataframe without truncation or print df without truncating.

The complete data frame is not printed when the length exceeds.

import numpy as np
from sklearn.datasets import load_iris
import pandas as pd
  
# Loading irirs dataset
data = load_iris()
df = pd.DataFrame(data.data,columns = data.feature_names)
print(df)

Output:

How-to-print-an-entire-Pandas-DataFrame-in-Python.png

By default our complete contents of out dataframe are not printed, output got truncated. It printed only 10 rows all the remaining data is truncated. Now, what if we want to print the full dataframe without any truncation.

Four Methods to Print the entire pandas Dataframe

  1. Use to_string() Method
  2. Use pd.option_context() Method
  3. Use pd.set_options() Method
  4. Use pd.to_markdown() Method

1. Using to_string()

Pandas print all columns: This is a very simple method. That is why it is not used for large files because it converts the entire data frame into a string object. But this works very well for data frames for size in the order of thousands.

import numpy as np
from sklearn.datasets import load_iris
import pandas as pd
  
data = load_iris()
df = pd.DataFrame(data.data,
                  columns = data.feature_names)
  
# Convert the whole dataframe as a string and display
print(df.to_string())

Output:

How-to-display-full-Dataframe-i.e.-print-all-rows-columns-without-truncation_output.pn

So in the above example, you have seen it printed all columns without any truncation.

2. Using pd.option_context()

Pandas print row: option_context() and set_option() both methods are identical but there is only one difference that is one changes the settings and the other do it only within the context manager scope.

import numpy as np
from sklearn.datasets import load_iris
import pandas as pd
  
data = load_iris()
df = pd.DataFrame(data.data, 
                  columns = data.feature_names)
  
with pd.option_context('display.max_rows', None,'display.max_columns', None,
    'display.precision', 3,
                       ):
print(df)

Output:

How-to-display-full-Dataframe-i.e.-print-all-rows-columns-without-truncation_output.pn

In the above example, we are used ‘display.max_rows‘ but by default its value is 10 & if the dataframe has more rows it will truncate. So it will not be truncated we used None so all the rows are displayed.

3. Using pd.set_option()

Python show all columns: This method is similar to pd.option_context() method and takes the same parameters. pd.reset_option(‘all’) used to reset all the changes.

import numpy as np
from sklearn.datasets import load_iris
import pandas as pd
  
data = load_iris()
df = pd.DataFrame(data.data,
                  columns = data.feature_names)
  
# Permanently changes the pandas settings
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', -1)
  
# All dataframes hereafter reflect these changes.
print(df)
  
print('**RESET_OPTIONS**')
  
# Resets the options
pd.reset_option('all')
print(df)

Output:

How-to-display-full-Dataframe-i.e.-print-all-rows-columns-without-truncation_output.pn

**RESET_OPTIONS**

: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.

How-to-print-an-entire-Pandas-DataFrame-in-Python.png

4. Using to_markdown()

Print dataframe: This method is similar to the to_string() method as it also converts the data frame to a string object and also adds styling & formatting to it.

import numpy as np
from sklearn.datasets import load_iris
import pandas as pd
  
data = load_iris()
df = pd.DataFrame(data.data,
                  columns=data.feature_names)
  
# Converts the dataframe into str object with fromatting
print(df.to_markdown())

Output:
How-to-display-full-Dataframe-i.e.-print-all-rows-columns-without-truncation_output.pn

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Answer these:

  1. How to print entire dataframe in python
  2. How to print pandas dataframe without truncation
  3. How to display full dataframe in pandas
  4. How to view full dataframe in python
  5. How to see the whole dataframe in python

Also Refer: How to get & check data types of Dataframe columns in Python Pandas

Read more Articles on Python Data Analysis Using Pandas

How to execute python program – How to Run a Python Script

How to execute python program: Python is not just one of the leading programming languages, but also a top choice for dealing with big data and data science projects. The fact that it is among the easiest languages to learn makes the high-level, interpreted, general-purpose programming language even more lucrative.

For using Python on a system, the user first needs to install the Python environment. It will also install the Python interpreter, which is responsible for carrying out Python code execution. It is possible to run Python code directly from the terminal using the Python interpreter.

Python is a well known high-level programming language. The Python script is basically a file containing code written in Python. The file containing python script has the extension ‘.py’ or can also have the extension ‘.pyw’ if it is being run on a windows machine. To run a python script, we need a python interpreter that needs to be downloaded and installed.

Scripts vs Modules:

A Python script is a collection of commands in a file designed to be executed like a program. The file can of course contain functions and import various modules, but the idea is that it will be run or executed from the command line or from within a Python interactive shell to perform a specific task. Often a script first contains a set of function definitions and then has the main program that might call the functions.

Scripts are always processed by some kind of interpreter, which is responsible for executing each command sequentially.

A plain text file containing Python code that is intended to be directly executed by the user is usually called script, which is an informal term that means top-level program file.

On the other hand, a plain text file, which contains Python code that is designed to be imported and used from another Python file, is called module.

So, the main difference between a module and a script is that modules are meant to be imported, while scripts are made to be directly executed.

Different ways to run Python Script:

  1. Interactive Mode
  2. Command Line
  3. Text Editor
  4. IDE (PyCharm)

 

1.Interactive Mode:

Interactive mode, also known as the REPL provides us with a quick way of running blocks or a single line of Python code. The code executes via the Python shell, which comes with Python installation. Interactive mode is handy when you just want to execute basic Python commands or you are new to Python programming and just want to get your hands dirty with this beautiful language.

To access the Python shell, open the terminal of your operating system and then type “python”. Press the enter key and the Python shell will appear. This is the same Python executable you use to execute scripts, which comes installed by default on Mac and Unix-based operating systems.

How to Run a Python Script_interactive mode
The >>> indicates that the Python shell is ready to execute and send your commands to the Python interpreter. The result is immediately displayed on the Python shell as soon as the Python interpreter interprets the command.

To run your Python statements, just type them and hit the enter key. You will get the results immediately, unlike in script mode. For example, to print the text “Hello World”, we can type the following:

Interactive Mode output

2.Command Line:

To run a Python script store in a ‘.py’ file in command line, we have to write ‘python’ keyword before the file name in the command prompt.

python hello.py

You can write your own file name in place of ‘hello.py’.

Using command line
3.Text Editor :

Python’s standard distribution includes IDLE as the default IDE, and you can use it to write, debug, modify, and run your modules and scripts.

Other IDEs such as Eclipse-PyDev, PyCharm, Eric, and NetBeans also allow you to run Python scripts from inside the environment.

Advanced text editors like Sublime Text andVisual Studio Code also allow you to run your scripts.

4.IDE (PyCharm):

To run Python script on a IDE like PyCharm you will have to do the following:

  • Create a new project.
  • Give a name to that project as ‘NewProject’ and click on Create.
  • Select the root directory with the project name we specified in the last step. Right click on it, go in New and click on ‘Python file’ option. Then give the name of the file as ‘hello’ (you can specify any name as per your project requirement). This will create a ‘hello.py’ file in the project root directory.
    Note: You don’t have to specify the extension as it will take it automatically.

Using IDE (PyCharm)
Now write the below Python script to print the message:

print('Hello World !')

Using IDE (PyCharm) output

Conclusion:

With the reading of this tutorial, you have acquired the knowledge and skills you need to be able to run Python scripts and code in several ways and in a variety of situations and development environments.

How to get first key in Dictionary – Python | Get the First Key in Python Dictionary

How to get first key in Dictionary – Python

How to get First Key in a Dictionary Python: In this tutorial, we will discuss different ways to get the first key in a dictionary. Later, we will see & learn how to choose the first N Keys of a dictionary in Python.

Get the first key from a dictionary using keys() method

Python print first item in dictionary: Dictionary stores elements in key-value pairs.Dictionary act as a container in python. Dictionary provided keys() function which we will use to fetch all keys in it and after that we select the first key from a sequence.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first key in a dictionary
first_key = list(word_freq.keys())[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

Get first element of dictionary python: In the above example, you can see that first we have fetched all dictionary elements and by using indexing we find out the first key value.

Do Refer:

Here is another way to do the same,

Another Way for How to get First Key in Dictionary Python

Print keys of dictionary python: By using this method, it will convert all keys of the dictionary to a list and then we can select the first element from the list.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first ket in a dictionary
first_key = list(word_freq)[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

In the above example, we didn’t call the keys() function. We created a list of keys from the dictionary and selected the first item from it.

Get first key in a dictionary using iter() & next()

What we have done above that was not a perfect solution because first, we created a list and then fetch the first key in a dictionary. It is very difficult to apply that method in a large number of dictionaries. First, we iterate the object of keys using the iter() function then we apply the next() function on it for getting the first element.

Get first key in a dictionary using iter() & next()

This is an efficient solution because didn’t iterate over all the keys in a dictionary, we just selected the first one.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first key in a dictionary
first_key = next(iter(word_freq))
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

Get the First Key in Dictionary Using list() Function

Also, there is a possible way to convert the dict type into a list using thelist() function at first and later get the first key at the 0th index of the dictionary.

my_dict = { 'Russia': 2, 'New York': 1, 'Lahore': 6, 'Tokyo': 11}

print(list(my_dict.keys())[0])

Result:

Russia

Get the First Key in Dictionary Using for Loop

One more easiest way to get the initial key in a dictionary is using theforloop. After getting the first key of the dictionary break the loop.

Let’s see an example on it:

my_dict = { 'London': 2, 'New York': 1, 'Lahore': 6, 'Tokyo': 11}

for key, value in my_dict.items():
  print(key)
  break

Output:

London

Get first N keys from a Dictionary in Python

To select the first N keys from a dictionary, convert the keys of a dictionary to a list and then select the first N entries from that. For example, let’s see how to select the first 3 keys from a dictionary,

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first ket in a dictionary
first_key = list(word_freq)[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

Conclusion on Get First value in a dictionary of string and int

In this article, we have seen discuss different ways to find out the first key of a dictionary in python. All these dictionary keys methods in python help to find easily the key value in a dictionary of string and int word_freq. Get first key of the dictionary in python information completely from this article.

Compiling C++ with Debug Symbols – gdb debugger Tutorial & Examples

g++ gdb: In this article we are going to discuss how to debugging using gdb debugger in C++.

gdb debugger is an application for execute C or C++ program to check the code working and it’s crashes.There are so many task which can be done using gdb debugger,like check prgram,run code,test new conditions and find out errors.

Compile Code with Debug Symbols

We should debug C or C++ program in debug mode.We should use -g option in it.

Below is our first step to debug program using gdb,

g++ -g filename.cpp -o Sample

Now there is two way to debug using gdb debugger;

1.Debugging with executable name,

gdb filename

It will read symbols from ‘filename’ after this type below command;

(gdb) run

2.Start gdb alone without debugging-

gdb

Now give the file name for execution,

(gdb) file filename

After that your application start debugging in debug mode.

Passing Command Line Arguments while debugging

We can also pass command argument at the time of debugging.For this we use below command;

Reading symbols from filename...done.
(gdb) run 1 2 3

There are so many different command in gdb debugger to know them you can run help command,

(gdb) help

It will show you all command list and their working,like below;

Command Description
help Provides information about a topic or commands you can use
file Indicates which file to debug
run Executes the program under GDB
break Adds breakpoints to stop the program execution temporary
delete Deletes breakpoints
clear Deletes breakpoints for a specific function
continue Resets the program after a breakpoint triggers
step Runs the current source line and stops before executing the next one
ext Runs the current source line. However, if the line is a function call, the debugger will fully execute the function before the execution stops again
until Runs the current source line. If you are at the beginning of a loop, the debugger runs until the loop ends
list Prints a certain list from the source code
print Prints values of certain expressions

How do I exit the debugging

For exiting you have to write quit command and you will be out from debug mode,

(gdb) quit

And if you again want to come in debug mode then you will just press “Ctrl-C”.

Conclusion:

In this article we have discussed how to debugging using gdb debugger in C++.Thank you!

Python timestamp to string – Python: How to convert a timestamp string to a datetime object using datetime.strptime()

Python- How to convert a timestamp string to a datetime object using datetime.strptime()

Python timestamp to string: In this tutorial, we will learn how to convert a timestamp string to a datetime object using datetime.strptime(). Also, you can understand how to to create a datetime object from a string in Python with examples below.

String to a DateTime object using datetime.strptime()

Python convert timestamp to string: Thestrptime()method generates a datetime object from the given string.

Datetime module provides a datetime class that has a method to convert string to a datetime object.

Syntax:

datetime.strptime(date_string, format)

So in the above syntax, you can see that it accepts a string containing a timestamp. It parses the string according to format codes and returns a datetime object created from it.

First import datetime class from datetime module to use this,

from datetime import datetime

Also Read:

Complete Format Code List

Format Codes Description Example
%d Day of the month as a zero-padded decimal number 01, 02, 03, 04 …, 31
%a Weekday as the abbreviated name Sun, Mon, …, Sat
%A Weekday as full name Sunday, Monday, …, Saturday
%m Month as a zero-padded decimal number 01, 02, 03, 04 …, 12
%b Month as an abbreviated name Jan, Feb, …, Dec
%B Month as full name January, February, …, December
%y A Year without century as a zero-padded decimal number 00, 01, …, 99
%Y A Year with a century as a decimal number 0001, …, 2018, …, 9999
%H Hour (24-hour clock) as a zero-padded decimal number 01, 02, 03, 04 …, 23
%M Minute as a zero-padded decimal number 01, 02, 03, 04 …, 59
%S Second as a zero-padded decimal number 01, 02, 03, 04 …, 59
%f Microsecond as a decimal number, zero-padded on the left 000000, 000001, …, 999999
%I Hour (12-hour clock) as a zero-padded decimal number 01, 02, 03, 04 …, 12
%p Locale’s equivalent of either AM or PM AM, PM
%j Day of the year as a zero-padded decimal number 01, 02, 03, 04 …, 366

How strptime() works?

In thestrptime()class method, it takes two arguments:

  • string (that be converted to datetime)
  • format code

In the accordance with the string and format code used, the method returns its equivalent datetime object.

Let’s see the following example, to understand how it works:

python strptime method example

where,

%d – Represents the day of the month. Example: 01, 02, …, 31
%B – Month’s name in full. Example: January, February etc.
%Y – Year in four digits. Example: 2018, 2019 etc.

Examples of converting a Time String in the format codes using strptime() method

Timestamp to string python: Just have a look at the few examples on how to convert timestamp string to a datetime object using datetime.strptime() in Python and gain enough knowledge on it.

Example 1:

Let’s take an example,

from datetime import datetime
datetimeObj = datetime.strptime('2021-05-17T15::11::45.456777', '%Y-%m-%dT%H::%M::%S.%f')
print(datetimeObj)
print(type(datetimeObj))

Output:

2021-05-17 15:11:45.456777
<class 'datetime.datetime'>

So in the above example, you can see that we have converted a time string in the format “YYYY-MM-DDTHH::MM::SS.MICROS” to a DateTime object.

Let’s take another example,

Example 2:

from datetime import datetime
datetimeObj = datetime.strptime('17/May/2021 14:12:22', '%d/%b/%Y %H:%M:%S')
print(datetimeObj)
print(type(datetimeObj))

Output:

2021-05-17 14:12:22
<class 'datetime.datetime'>

So this is the other way to show timestamp here we have converted a time string in the format “DD/MM/YYYY HH::MM::SS” to a datetime object.

Example 3:

If we want to show the only date in this format “DD MMM YYYY”. We do like this,

from datetime import datetime
datetimeObj = datetime.strptime('17 May 2021', '%d %b %Y')
# Get the date object from datetime object
dateObj = datetimeObj.date()
print(dateObj)
print(type(dateObj))

Output:

2021-05-17
<class 'datetime.date'>

Example 4:

So if we want to show only time “‘HH:MM:SS AP‘” in this format. We will do like that,

from datetime import datetime
datetimeObj = datetime.strptime('08:12:22 PM', '%I:%M:%S %p') 
# Get the time object from datetime object 
timeObj = datetimeObj.time()
print(timeObj) 
print(type(timeObj))

Output:

20:12:22
<class 'datetime.time'>

Example 5:

If we want to show our timestamp in text format. We will execute like that,

from datetime import datetime
textStr = "On January the 17th of 2021 meet me at 8 PM"
datetimeObj = datetime.strptime(textStr, "On %B the %dth of %Y meet me at %I %p")
print(datetimeObj)

Output:

2021-01-17 20:00:00

Conclusion:

So in the above tutorial, you can see that we have shown different methods of how to convert a timestamp string to a datetime object using datetime.strptime(). Thank you!

Pad string with spaces python – Python: How to pad strings with zero, space or some other character?

Python-How to pad strings with zero, space or some other character

Pad string with spaces python: In this tutorial, we are going to discuss how to do padding of strings using zero, space, or some other character. Also, you can get complete knowledge of the methods used for padding strings in Python. So, let’s get started on learning How to pad strings with Zero, Space, or some other character.

Types of Padding in Python

There are two types of padding:

  1. Left padding
  2. Right padding

1. Left padding of string in Python

Python pad string with spaces: Left padding means adding a given character on the left side of a string.

For Example – If we pad three zeros in string 6 i.e, ‘0006’, or if we pad three space in string i.e,’6′

numStr = "6"
print('Original String :', numStr)
# Left pad the string with 0 to make it's length 4
numStr = numStr.zfill(4)
print('Updated String :' , numStr)

Output:

Original String : 6
Updated String : 0006

So in the above example, we have used'string.zfill(s, width)'to pad a given string on the left with zeros (0).

Also Check:

Left pad a string with space using string.rjust()

Python zero pad: In this, we are going to use string.rjust() to add space in a given string.

numStr = "6"
print('Original String :', numStr)
# Make string right justified of length 4 by padding 3 spaces to left
numStr = numStr.rjust(4, ' ')
print('Updated String :', numStr)

Output:

Original String : 6
Updated String :    6

Left pad a string with some character using string.rjust()

Python pad string: For adding any character to our string we will use string.rjust() and pass that character in it.

numStr = "6"
print('Original String :', numStr)
# Make string right justified of length 4 by padding 3 '-' to left
numStr = numStr.rjust(4, '-')
print('Updated String :', numStr)

Output:

Original String : 6
Updated String : ---6

2. Right padding of string in Python

Python pad string: Right padding means adding a given character on the right side of the string.

Example- If we have a number string i.e. “ram”. Now we want to convert this string of length 3 to a string of length 6 by,

  • Right padding three zeros to the string i.e. “ram000”
  • Right padding three-space to the string i.e. “ram “
  • Right padding three characters to the string i.e. “ram—“

Right pad a string with zeros using string.ljust()

string.ljust() is used for padding a given character to the right of string to make its a length equal to the given width.

numStr = "67"
print('Original String :', numStr)
# Make string left justified of length 5 by padding 3 0s to the right of it
numStr = numStr.ljust(5, '0')
print('Updated String :', numStr)

Output:

Original String : 67
Updated String : 67000

Right pad a string with space using string.ljust()

In this, we will use string.ljust() to pad given character,

userName = "Shikha"
print('Original String :', userName)
# Make string left justified of length 7 by padding 3 spaces to the right of it
userName = userName.ljust(7, ' ')
print('Updated String :' , userName, 'is')

Here 3 spaces are padded to the right of the given string to make its length 9.

Output:

Original String : Shikha
Updated String : Shikha   is

Right pad a string with some character using string.ljust()

We can pass a character in string.ljust(s, width[, fillchar]) to right pad the given string by that passed character.

userName = "shikha"
print('Original String :', userName)
# Make string left justified of length 7 by padding 3 '-' to the right of it
userName = userName.ljust(7, '-')
print('Updated String :' , userName)

Output:

Here, three ‘-‘ are padded to the right of the given string to make its length 9.

Original String : shikha
Updated String : shikha---

Conclusion:

In this article, you have seen that how to do padding of strings using zero, space, or some other character.

Thank you!

CPP 11 Multithreading – Part 2: Joining and Detaching Threads | std::thread::join() & std::thread::detach() Methods with Examples

CPP 11 Multithreading – Part 2- Joining and Detaching Threads

Thread join c++: In the previous article, we have discussed about How to trim strings in C++ using Boost String Algorithm Library. Let us learn how to find Multithreading – Part 2 in C++ Program.

Let’s discover this tutorial for getting more knowledge about C++11 Multithreading Part-2.  Here we are going to learn what is joining and detaching threads of std::thread. Apart from that, you may also see the explanation of std::thread::join() & std::thread::detach() Methods with Examples. So, stay tuned to this tutorial easily via available quick links.

Joining Threads with std::thread::join()

Std thread join: When the first thread is started then the other thread that is going to start yet should wait for the first thread to finish. For this, another we need to call the join() function on the std::thread object.

Syntax:

std::thread th(funcPtr);

// Some Code

th.join();

Suppose Main Thread has to start 10 Worker Threads and after starting all these threads, the main function will wait for them to finish. After joining all the threads the main function will continue.

So, let’s take an example. There is one main thread and some worker threads after joining all the threads the main function will continue. The main function will wait for them to finish.

#include <iostream>
#include <thread>
#include <algorithm>
#include <vector>
#include <functional>
class WorkerThread
{
public:
    void operator()()     
    {
        std::cout<<"Worker Thread "<<std::this_thread::get_id()<<" is Executing"<<std::endl;
    }
};
int main()  
{
    std::vector<std::thread> threadList;
    for(int i = 0; i < 10; i++)
    {
        threadList.push_back( std::thread( WorkerThread() ) );
    }
    // Now wait for all the worker thread to finish i.e.
    // Call join() function on each of the std::thread object
    std::cout<<"wait for all the worker thread to finish"<<std::endl;
    std::for_each(threadList.begin(),threadList.end(), std::mem_fn(&std::thread::join));
    std::cout<<"Exiting from Main Thread"<<std::endl;
    return 0;
}

Detaching Threads using std::thread::detach()

Detached threads are background threads sometimes also called daemon threads. To detach a thread we need to call std::detach() function on std::thread object. ie.,

std::thread th(funcPtr);
th.detach();

Once you call the detach(), then the std::thread object is no longer connected with the actual thread of execution.

Also Check:

Be cautious with calling detach() and join() on Thread Handles

We have to be careful on calling detach() and join() on thread handles. We are going to discuss some cases below for this:

Case 1: Never call join() or detach() on std::thread object with no associated executing thread

std::thread threadObj( (WorkerThread()) );
   threadObj.join();
   threadObj.join(); // It will cause Program to Terminate

When a join() function called on a thread object, join returns 0 then that ‘td::thread’ object has no associated thread with it. If the join() function again called on such an object then it will cause the program to Terminate. Similarly, detach() function will work.

Syntax:

std::thread threadObj( (WorkerThread()) );
   threadObj.detach();
   threadObj.detach(); // It will cause Program to Terminate

Before calling join() or detach() we should check if the thread is join-able every time or not,

std::thread threadObj( (WorkerThread()) );
   if(threadObj.joinable())
   {
       std::cout<<"Detaching Thread "<<std::endl;
       threadObj.detach();
   }
   if(threadObj.joinable())    
   {
       std::cout<<"Detaching Thread "<<std::endl;
       threadObj.detach();
   }
   
   std::thread threadObj2( (WorkerThread()) );
   if(threadObj2.joinable())
   {
       std::cout<<"Joining Thread "<<std::endl;
       threadObj2.join();
   }
   if(threadObj2.joinable())    
   {
       std::cout<<"Joining Thread "<<std::endl;
       threadObj2.join();
   }

Case 2: Never forget to call either join or detach on a std::thread object with associated executing thread

In this case, if neither join nor detach is called with a ‘std::thread’ object that has associated executing thread then during that object’s destruct-or it will terminate the program.

#include <iostream>
#include <thread>
#include <algorithm>
class WorkerThread
{
public:
    void operator()()     
    {
        std::cout<<"Worker Thread "<<std::endl;
    }
};
int main()  
{
    std::thread threadObj( (WorkerThread()) );
    // Program will terminate as we have't called either join or detach with the std::thread object.
    // Hence std::thread's object destructor will terminate the program
    return 0;
}

Similarly, we should not forget to call either join() or detach() in case of exceptions.

To prevent this with we should use Resource Acquisition Is Initialization (RAII) which is show below,

#include <iostream>
#include <thread>
class ThreadRAII
{
    std::thread & m_thread;
    public:
        ThreadRAII(std::thread  & threadObj) : m_thread(threadObj)
        {
            
        }
        ~ThreadRAII()
        {
            // Check if thread is joinable then detach the thread
            if(m_thread.joinable())
            {
                m_thread.detach();
            }
        }
};
void thread_function()
{
    for(int i = 0; i < 10000; i++);
        std::cout<<"thread_function Executing"<<std::endl;
}
 
int main()  
{
    std::thread threadObj(thread_function);
    
    // If we comment this Line, then program will crash
    ThreadRAII wrapperObj(threadObj);
    return 0;
}

Conclusion:

In this article, we have discussed completely regarding C++11 Multithreading joining and detaching threads of std::thread and some risk cases. Thank you!