code-rag-bench/online-tutorials huggingface dataset:
Measure execution time of small Python code snippets (timeit)

The Timer class and other convenience functions in timeit module of Python's standard library are designed to provide a mechanism to measure time taken by small bits of Python code to execute. The module has a command line interface and the functions can be called from within program as well.
Easiest way to measure time of execution is by using following convenience function
This function returns object of Timer class. It mainly requires two parameters.
stmt − a string containing valid Python statement whose execution time is to be measured.
stmt − a string containing valid Python statement whose execution time is to be measured.
setup − a string containing Python statement which will be executed once, primarily to initialize certain objects or variables.
setup − a string containing Python statement which will be executed once, primarily to initialize certain objects or variables.
Both strings may contains multiple statements separated by semi colon(;) or newlines, and both default to pass keyword. Another optional parameter number may be given which denotes number of executions of 'stmt'
In following example time required to perform thousand times the cumulative addition of numbers in a range 0-100 is measured.
import timeit
setupcode = "s = 0"
function = '''
for x in range(100):
s = s + x
'''
print (timeit.timeit(setup = setupcode, stmt = function, number = 1000))
Here a string contains a for loop within which numbers within range 0-100 are added. This string is the stmt parameter. For addition, the initialization of a variable is done by a setupcode string. The timeit() function calculates the time required in seconds.
Output
0.03055878530880241
The same result can be obtained by first creating a Timer object and then execute timeit() method on it.
The Timer class also has a repeat() method to call timeit() repeatedly. It returns a list of all calls.
An object oriented version of the above code is as follows −
import timeit
setupcode = "s = 0"
function = '''
for x in range(100):
s = s + x
'''
t = timeit.Timer(setup = setupcode, stmt = function)
print (t.timeit(number = 1000))
print ('calling repeat() :',t.repeat(3,1000))
Output
0.019971274194651528
calling repeat() : [0.023369810546474253, 0.020518432391765262, 0.02075439436427058]
As mentioned earlier, timeit module has a command line interface. The module itself is imported using –m option in the command line for execution of Python script. Following command line options define various parameter line setup and executable code, repeat frequency, etc.
Following is the command line equivalent of example code used earlier −
C:\Users\acer>python -m timeit -s "s = 0" "for x in range(100): s = s + x"
10000 loops, best of 3: 22.4 usec per loop
Python String isspace() Method - GeeksforGeeks

12 Aug, 2021
Python String isspace() is a built-in method used for string handling. The isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters such as:
‘ ‘ – Space
‘\t’ – Horizontal tab
‘\n’ – Newline
‘\v’ – Vertical tab
‘\f’ – Feed
‘\r’ – Carriage return
Syntax:
string.isspace()
Parameters:
isspace() does not take any parameters
Returns:
True – If all characters in the string are whitespace characters.False – If the string contains 1 or more non-whitespace characters.
True – If all characters in the string are whitespace characters.
False – If the string contains 1 or more non-whitespace characters.
Input : string = 'Geeksforgeeks'
Output : False

Input : string = '\n \n \n'
Output : True

Input : string = 'Geeks\nFor\nGeeks'
Output : False
Python3
# Python code for implementation of isspace()   # checking for whitespace charactersstring = 'Geeksforgeeks'  print(string.isspace())   # checking if \n is a whitespace characterstring = '\n \n \n'  print(string.isspace())  string = 'Geeks\nfor\ngeeks'print( string.isspace())
Output: 
False
True
False
Given a string in python, count the number of whitespace characters in the string. 
Input : string = 'My name is Ayush'
Output : 3

Input : string = 'My name is \n\n\n\n\nAyush'
Output : 8
Algorithm: 
Traverse the given string character by character up to its length, check if the character is a whitespace character. If it is a whitespace character, increment the counter by 1, else traverse to the next character. Print the value of the counter.
Traverse the given string character by character up to its length, check if the character is a whitespace character. 
If it is a whitespace character, increment the counter by 1, else traverse to the next character. 
Print the value of the counter.
Python3
# Python implementation to count whitespace characters in a string# Given string# Initialising the counter to 0string = 'My name is Ayush'count=0   # Iterating the string and checking for whitespace characters# Incrementing the counter if a whitespace character is found# Finally printing the countfor a in string:    if (a.isspace()) == True:        count+=1print(count)  string = 'My name is \n\n\n\n\nAyush'count = 0for a in string:    if (a.isspace()) == True:        count+=1print(count)
Output: 
3
8
AmiyaRanjanRout
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Execute INSERT if table is empty in MySQL?

You can execute insert if table is empty with the help of subquery. For that, work on not exists condition with subquery.
The below syntax will work only when your table is empty. If your table is not empty then it will not insert the record. The syntax is as follows:
INSERT INTO yourTableName(yourColumnName)
SELECT ‘anyValue’
WHERE NOT EXISTS (SELECT *FROM yourTableName);
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table ExecuteInsertDemo
   -> (
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.67 sec)
Let us insert record in the table using insert command. The query to insert record is as follows:
mysql> insert into ExecuteInsertDemo values('John');
Query OK, 1 row affected (0.19 sec)
Let’s say our table is not empty. It has only a single record. If you execute insert command then MySQL will not enter that record in the table.
The query to execute insert is as follows:
mysql> insert into ExecuteInsertDemo(Name)
   -> select 'Larry'
   -> where not exists (select *from ExecuteInsertDemo);
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
Display the record using select statement. The query is as follows:
mysql> select *from ExecuteInsertDemo;
The following is the output:
+------+
| Name |
+------+
| John |
+------+
1 row in set (0.00 sec)
Yo need to delete the record from the table to run the query we saw above. Use truncate command. The query is as follows:
mysql> truncate table ExecuteInsertDemo;
Query OK, 0 rows affected (1.10 sec)
Run the above query to execute insert command. The query is as follows:
mysql> insert into ExecuteInsertDemo(Name)
   -> select 'Larry'
   -> where not exists (select *from ExecuteInsertDemo);
Query OK, 1 row affected (0.33 sec)
Records: 1 Duplicates: 0 Warnings: 0
Display the record from the table using select. The query is as follows:
mysql> select *from ExecuteInsertDemo;
The following is the output:
+-------+
| Name  |
+-------+
| Larry |
+-------+
1 row in set (0.00 sec)
Look at the sample output, ’Larry’ has been inserted successfully when the table was empty.
Design finite automata from regular expressions - GeeksforGeeks

05 Jul, 2021
Prerequisite –  Finite automata, Regular expressions, grammar, and language.
In this article, we will see some popular regular expressions and how we can convert them to finite automata (NFA and DFA). Let’s discuss it one by one.
Overview :Let a and b are input symbols and r is the regular expression. Now we have to design NFA as well as DFA for each regular expression.
Design finite automata from the regular expression :Here, we will discuss the Design of finite automata from regular expression as follows.
Case-1 : When r = Φ, then FA will be as follows.
Case-2 : When r = ε, then FA will be as follows.
Case-3 : When r = a, then FA will be as follows.
Case-4 : When r = a+b , then FA will be as follows.
Case-5 : When r = r = a* , then FA will be as follows. 
Case-6 : When r = a* + b*, then FA will be as follows.
Case-7 : When r = (ab)*, then FA will be as follows.
Case-8 : When r = (ab)*b, then FA will be as follows.
Case-9 : When r = (ab)*a, then FA will be as follows.
Case-10 : When r = a*b*, then FA will be as follows.
Case-11 : When r = (a+b)*, then FA will be as follows.
Unary Design :Let a is the input symbol and r is the regular expression. For each regular expression, we will design finite automata.
Case-1 : r = a* 
Case-2 : r = (aa)*
Case-3 : r = (aa)*a
Case-4 : r = aaaa*
Case-5 : r= (aa + aaa)*
Case-6 : r=( aaa+aaaaa)*
Case-7 : r=(aa + aaaaaa)*It is a multiple of 1 term i.e. aa, so it can be reduced to r=(aa)*. 
L= {an | n = 7x+12, x €  Z, x >=0 }
General Methods :Here, we will discuss some general methods as follows.
Method-1 :
L = { aK1n+K2  ; n>=0 }
If K1>K2, No. of states = K1If K1<K2, No. of states = K2 +1If K1=K2, No. of states = K1 +1 = k2 +1
Method-2 :
L = { aKn  ; n>0 , K is a fixed integer }
   = { aKn  ; n>=1. K is an integer}         No. of states = K +1 
Method-3 :
L = { aKn  ; n>=0 , K is a fixed integer }
Here, residue i.e. K2=0,  K1>K2. Therefore, No. of states = K 
regular-expression
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Regular Expressions, Regular Grammar and Regular Languages
Difference between Clustered and Non-clustered index
Preemptive and Non-Preemptive Scheduling
Introduction of Process Synchronization
Third Normal Form (3NF)
Regular Expressions, Regular Grammar and Regular Languages
Difference between DFA and NFA
Introduction of Finite Automata
Pumping Lemma in Theory of Computation
Turing Machine in TOC
Print all possible words from phone digits in C++

In this problem, we are given a number and we have to print all words that can be formed by pressing those words in an old fashioned mobile keyboard.
We are quite familiar with the QWERTY keyboard style that we use today. But before the invention of QWERTY keypad phones were fitted with keypads with 12 buttons and each button contains words and numbers both. Like they word 6 on the keypad will contain words “MNO” which will be typed by clicking one, twice or thrice the keys.
The keypad looked like this −
In these keywords also all words are present and the user can type then. So, in
this problem, we will be print all possible words that can be generated using
the number sequence is given.
Let’s take an example to understand the problem better −
Input: 687
Output: MTP, MTQ, MTR, MTR, MUP, MUQ, MUR, MUS, MVP, MVQ,
MVR, MVR, NTP, NTQ, NTR, NTR, NUP, NUQ, NUR, NUS, NVP, NVQ,
NVR, NVR, OTP, OTQ, OTR, OTR, OUP, OUQ, OUR, OUS, OVP, OVQ,
OVR, OVR.
To solve this problem, let’s see the pattern that is made in the above example. Each button has its own associated characters and we will have to
use those while typing. So, for each number, there are at max 4 options(in
case of 7 and 9). For this, we can fix on digit and then use then digit and for
generated words. This can be done using recursion.
Lets we the program to implement the concept using recursion.
 Live Demo
#include <iostream>
#include <string.h>
using namespace std;
const char keypad[10][5] = {"", "", "abc", "def", "ghi", "jkl", "mno",
"pqrs", "tuv", "wxyz"};
void printWords(int number[], int curr_digit, char output[], int n){
   int i;
   if (curr_digit == n){
      cout<<output<<" ";
      return ;
   }
   for (i=0; i<strlen(keypad[number[curr_digit]]); i++){
      output[curr_digit] = keypad[number[curr_digit]][i];
      printWords(number, curr_digit+1, output, n);
      if (number[curr_digit] == 0 || number[curr_digit] == 1)
         return;
   }
}
int main(void){
   int number[] = {6,8,7};
   cout<<"The output character formed is : \n";
   int n = sizeof(number)/sizeof(number[0]);
   char result[n+1];
   result[n] ='\0';
   printWords(number, 0, result, n);
   return 0;
}
The output character formed is −
mtp mtq mtr mts mup muq mur mus mvp mvq mvr mvs ntp ntq ntr nts
nup nuq nur nus nvp nvq nvr nvs otp otq otr ots oup ouq our ous ovp
ovq ovr ovs
Recreating Gapminder Animation in 2 lines of Python with Plotly Express | by AbdulMajedRaja RS | Towards Data Science

Disclaimer: A new moduleplotly_express is used, Gapminder Animation not coded from scratch using 2 lines
It’s one of the iconic moments of Data Visualization when Hans Rosling presented the famous Gapminder Animation in his TED talk which is one of the most viewed TED talks ever. Since then, It’s been like a benchmark for anyone who does visualization to replicate it to show their Data Visualization prowess — much like replicating Edward Tufte’s or Nate Silver’s visualization pieces.
Very recently Plotly (who’s known for their Interactive Visualization DSL for R and Python) came up with a new tool/module/library called Plotly Express. As the name suggests, the primary objective of plotly express is to be a high-level API that’s insanely simple, fast and easy to use to build Interactive Visualizations.
Much more like this,
Plotly Express:Plotly.py :: Seaborn:Matplotlib
Inspired by ggplot2 of R and seaborn of Python, having simplicity at its core plotly express attempts to do things in one-liners . In this piece, We’ll see how to recreate (If not entirely, at least similar to) the iconic Gapminder animation using just plotly express .
pip3 install plotly_express
import plotly_express as px
px.scatter(px.data.gapminder(), x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",           size="pop", color="country", hover_name="country",            log_x = True,            size_max=45, range_x=[100,100000], range_y=[25,90])
That’s a pretty simplistic function (I’ve ever seen to do this Gapminder Animation). The function px.scatter() gets the data from px.data.gapminder() and then typically, defining x and y axis along with the animation_frame that gets incremented for every year. With a few more arguments for cosmetic improvements, the Animated Bubble Chart is ready!
Plotly Express Tutorial Video to build Gapminder Animation:
FIN
The objective of this post is to spread out the word about plotly_express which is nothing short of amazing to create beautiful interactive visualization (also similar to highcharter in R). If you want a course of Plotly in general, Check out Datacamp.
Complete Code used in this Post
A very comprehensive intro to Plotly Express
How to Recover Deleted Files Using Foremost in Linux? - GeeksforGeeks

17 Nov, 2020
Foremost is a digital forensic application that is used to recover lost or deleted files. Foremost can recover the files for hard disk, memory card, pen drive, and another mode of memory devices easily. It can also work on the image files that are being generated by any other Application. It is a free command-line tool that is pre-installed in Kali Linux. This tool comes pre-installed in Kali Linux. Foremost is a very useful software that is used to recover the deleted files, if some files are deleted accidentally or in any case files are deleted. You can recover the deleted files from foremost only if the data in the device is not overridden, which means after deleting the files no more data is added to the storage device because in that case data may be overridden and the chances of recovery also get reduced and data must get corrupted.
Installing the Foremost Tool:
Use the following command to install this tool in any Debian based Linux Operating System or in any other Operating System using the APT package manager.
sudo apt install foremost

Use the following command to install this tool using dnf package manager
sudo dnf install foremost

Use the following command to install this tool using Pacman package manager or in Arch Linux.
sudo pacman -S foremost

Syntax:
foremost [options]

Here you can check the options available and their functions. Let us now see how to recover deleted files using foremost: 
Recovering from USB/Hard Disk:
Connect the External memory storage with the system.
First, you need to know the path of your external memory device, for that use the command
fdisk -l

Now from here, you can copy the path of the disk.
After copying the device path, now we have to recover the files from that device.
Use the options available by the “foremost -h” command.
For example : 
foremost -t jpg,pdf,mp4,exe -v -q -i /dev/sdb2 -o /root/desktop/recover

Here I use this command to recover the data from the device.
-t: It is the type of files we want to recover. Here I want to recover jpg, pdf,mp4, and exe files.
-q: It is a quick scan for the device
-i: It means the input as in this case external memory.
-o: It is the output folder, where to save the recovered files.
Hereafter running this command, all the files will be saved in the folder name as mentioned. Here you can see the folder recover on desktop and all the files will be stored here.
Technical Scripter 2020
Linux-Unix
Technical Scripter
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Named Pipe or FIFO with example C program
Thread functions in C/C++
SED command in Linux | Set 2
Array Basics in Shell Scripting | Set 1
Introduction to Linux Shell and Shell Scripting
How to Find the Wi-Fi Password Using CMD in Windows?
Setting up the environment in Java
How to setup cron jobs in Ubuntu
How to Run a Python Script using Docker?
Running Python script on GPU.
How to compare string and number in Python?

Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address. When you order two strings or two numeric types the ordering is done in the expected way (lexicographic ordering for string, numeric ordering for integers).
When you order a numeric and a non-numeric type, the numeric type comes first.
If you have a number in a str object, you can simply convert it to a float or an int using their respective constructors. For example,
i = 100
j = "12"
int_j = int(j)
print(int_j < i)
This will give the output:
True
Explain the sorting techniques in C language

What are the different sorting techniques in C Language? Explain any one sorting technique with an example.
C language provides five sorting techniques, which are as follows −
Bubble sort (or) Exchange Sort.
Selection sort.
Insertion sort (or) Linear sort.
Quick sort (or) Partition exchange sort.
Merge Sort (or) External sort.
It is the simplest sorting technique which is also called as an exchange sort.
Compare the first element with the remaining elements in the list and exchange(swap) them if they are not in order.
Compare the first element with the remaining elements in the list and exchange(swap) them if they are not in order.
Repeat the same for other elements in the list until all the elements gets sorted.
Repeat the same for other elements in the list until all the elements gets sorted.
30 50 40 10 20
Consider the elements given below −
Compare first element with the remaining elements.
a[0] > a[1] ◻ ◻30 >50 (F) ◻ ◻no exchange
a[0] > a[2] ◻ ◻ 30 >40 (F) ◻ ◻ no exchange
a[0] > a[3] ◻ ◻ 30 >10 (T) ◻ ◻ exchange
a[0] > a[4] ◻ ◻ 10>20 (F) ◻ ◻ no exchange
10 50 40 30 20
Compare second element with the remaining elements.
a[1] > a[2] ◻ ◻ 50 >40 (T) ◻ ◻ exchange
a[1] > a[3] ◻ ◻ 40 >30 (T) ◻ ◻ exchange
a[1] > a[4] ◻ ◻ 30 >20 (T) ◻ ◻ exchange
10 20 50 40 30
Compare third element with the remaining elements.
a[2] > a[3] ◻ ◻ 50 >40 (T) ◻ ◻ exchange
a[2] > a[4] ◻ ◻ 40 >30 (T) ◻ ◻ exchange
10 20 30 50 40
Compare fourth element with the remaining elements.
a[3] > a[4] ◻ ◻ 50 >40 (T) ◻ ◻ exchange
10 20 30 40 50
Refer the procedure for bubble sort as given below −
for (i=0; i<n-1; i++){
   for (j=i+1; j<n; j++){
      if (a[i] > a[j]){
         t=a[i];
         a[i] = a[j];
         a[j] = t;
      }
   }
}
Following is the C program for bubble sorting technique −
 Live Demo
#include<stdio.h>
int main(){
   int a[50], i,j,n,t;
   printf("enter the No: of elements in the list:\n");
   scanf("%d", &n);
   printf("enter the elements:\n");
   for(i=0; i<n; i++){
      scanf ("%d", &a[i]);
   }
   printf("Before bubble sorting the elements are:\n");
   for(i=0; i<n; i++)
      printf("%d \t\n", a[i]);
   for (i=0; i<n-1; i++){
      for (j=i+1; j<n; j++){
         if (a[i] > a[j]){
            t = a[i];
            a[i] = a[j];
            a[j] = t;
         }
      }
   }
   printf ("after bubble sorting the elements are:\n");
   for (i=0; i<n; i++)
      printf("%d\t", a[i]);
   return 0;
}
When the above program is executed, it produces the following result −
enter the No: of elements in the list:
5
enter the elements:
12 11 45 26 67
Before bubble sorting the elements are:
12
11
45
26
67
after bubble sorting the elements are:
11 12 26 45 67
Set the speed of the hover effect with CSS

To set the speed of the hover, use the transition-duration property. To set the hover, use the :hover selector.
You can try to run the following code to speed the hover effect −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .btn {
            background-color: yellow;
            color: black;
            text-align: center;
            font-size: 15px;
            padding: 20px;
            border-radius: 15px;
            border: 3px dashed blue;
            transition-duration: 2s;
         }
         .btn:hover {
            background-color: orange;
            color: black;
            border: 3px solid blue;
         }
      </style>
   </head>
   <body>
      <h2>Result</h2>
      <p>Click below for result:</p>
      <button class = "btn">Result</button>
   </body>
</html>
C# Linq Sum() Method

Find the sum of elements using the Linq Sum() method.
Here’s our list with integer elements.
List<int> list = new List<int> { 99, 34, 77, 75, 87, 35, 88};
Now find the sum using the Sum() method.
list.AsQueryable().Sum();
The following is an example to find the sum of elements of a list with integer elements.
 Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      List<int> list = new List<int> { 99, 34, 77, 75, 87, 35, 88};
      int res = list.AsQueryable().Sum();
      Console.WriteLine("Sum = {0}", res);
   }
}
Sum = 495
Keyboard shortcuts with Tkinter in Python 3

Tkinter window contains many inbuilt functionalities and features which can be taken and used for various application development. There might be cases when we have to run a particular part of the application with the help of some key or function. It can be achieved by binding a particular key with the callback that contains the functions for the operation. The key can be anything from Mouse Buttons to Keyboard Keys. We can even bind the callback with Keyboard Key Combinations.
#Import the Tkinter Library
from tkinter import *

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry of window
win.geometry("700x350")

#Define a callback function for exit
def quit_program(e):
   win.destroy()

#Add a Label widget
label = Label(win, text= "Press Ctrl + x to Exit", font= ('Helvetica 15 bold'))
label.pack(pady= 40)

#Bind the Keyboard shortcut Key
win.bind('<Control-x>', quit_program)
win.mainloop()
In the above code, we have added a combination of Keys. Pressing the keys will close the window.
MySQL Error ERROR 1099 (HY000): Table was locked with a READ lock and can't be updated

To get rid of LOCK TABLES query, you need to use UNLOCK TABLES.
Let us create a table −
mysql> create table demo6
−> (
−> country_name varchar(100
−> )
−> );
Query OK, 0 rows affected (1.51 sec)
Insert some records into the table with the help of insert command −
mysql> insert into demo6 values('US');
Query OK, 1 row affected (0.11 sec)

mysql> insert into demo6 values('UK');
Query OK, 1 row affected (0.08 sec)

mysql> insert into demo6 values('AUS');
Query OK, 1 row affected (0.11 sec)
Display records from the table using select statement −
mysql> select *from demo6;
This will produce the following output −
+--------------+
| country_name |
+--------------+
| US           |
| UK           |
| AUS          |
+--------------+
3 rows in set (0.00 sec)
Here, I have a lock on the above table only for read operator. Following is the query −
mysql> lock tables demo6 read;
Query OK, 0 rows affected (0.00 sec)
Following is the error when you try to insert on the above table −
mysql> insert into demo6 values('IND');
ERROR 1099 (HY000): Table 'demo6' was locked with a READ lock and can't be updated
If you use UNLOCK TABLES, then you can insert records in the same table −
mysql> UNLOCK TABLES;
Query OK, 0 rows affected (0.00 sec)
Insert some records into the table with the help of insert command −
mysql> insert into demo6 values('IND');
Query OK, 1 row affected (0.09 sec)
Display records from the table using select statement −
mysql> select *from demo6;
This will produce the following output −
+--------------+
| country_name |
+--------------+
| US           |
| UK           |
| AUS          |
| IND          |
+--------------+
4 rows in set (0.00 sec)
Python PIL | Image.frombuffer() method

07 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
PIL.Image.frombuffer() Creates an image memory referencing pixel data in a byte buffer.
Note that this function decodes pixel data only, not entire images. If you have an entire image file in a string, wrap it in a BytesIO object, and use open() to load it.
Syntax: PIL.Image.frombuffer(mode, size, data, decoder_name=’raw’, *args)
Parameters:mode – The image mode. See: Modessize – The image size.data – A byte buffer containing raw data for the given mode.decoder_name – What decoder to use.args – Additional parameters for the given decoder. For the default encoder (“raw”), it’s recommended that you provide the full set of parameters:frombuffer(mode, size, data, "raw", mode, 0, 1)
Returns: An Image object.
Image Used:
     # importing image object from PILfrom PIL import Image  # creating an image objectim = Image.open(r"C:\Users\System-Pc\Desktop\rose.jpg")im1 = im.tobytes("xbm", "rgb")img = Image.frombuffer("L", (4, 4), im1, 'raw', "L", 0, 1)  # creating list img2 = list(img.getdata())print(img2)
Output:
[48, 120, 102, 102, 44, 48, 120, 102, 102, 44, 48, 120, 102, 102, 44, 48]
Another Example: Here we use another image.
Image Used:
     # importing image object from PILfrom PIL import Image   # creating an image objectim = Image.open(r"C:\Users\System-Pc\Desktop\ellipse1.png")im1 = im.tobytes("xbm", "rgb")img = Image.frombuffer("L", (10, 10), im1, 'raw', "L", 0, 1)  # creating list img2 = list(img.getdata())print(img2)
Output:
[48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 10, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56]
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
host command in Linux with examples

21 May, 2019
host command in Linux system is used for DNS (Domain Name System) lookup operations. In simple words, this command is used to find the IP address of a particular domain name or if you want to find out the domain name of a particular IP address the host command becomes handy. You can also find more specific details of a domain by specifying the corresponding option along with the domain name.
Syntax:
host [-aCdlriTWV] [-c class] [-N ndots] [-t type] [-W time]
     [-R number] [-m flag] hostname [server]

host command without any option: It will print the general syntax of the command along with the various options that can be used with the host command as well as gives a brief description about each option.
Example:
Different options with the host command:
host domain_name: This will print the IP address details of the specified domain.Example:host geeksforgeeks.org
Example:
host geeksforgeeks.org
host IP_Address: This will display the domain details of the specified IP Address.Example:host 52.25.109.230
Example:
host 52.25.109.230
-a or -v: It used to specify the query type or enables the verbose output.Example:host -a geeksforgeeks.org 
Example:
host -a geeksforgeeks.org 
-t : It is used to specify the type of query.Example 1:host -t ns geeksforgeeks.org  Example 2: To print SOA recordhost -t SOA geeksforgeeks.org  Example 3: To print txt recordhost -t txt geeksforgeeks.org  
Example 1:
host -t ns geeksforgeeks.org  
Example 2: To print SOA record
host -t SOA geeksforgeeks.org  
Example 3: To print txt record
host -t txt geeksforgeeks.org  
-C : In order to compare the SOA records on authoritative nameservers.Example:host -C geeksforgeeks.org 
Example:
host -C geeksforgeeks.org 
-R : In order to specify the number of retries you can do in case one try fails. If anyone try succeeds then the command stops.Example:host -R 3 geeksforgeeks.org 
Example:
host -R 3 geeksforgeeks.org 
-l :In order to list all hosts in a domain.For this command to work you need to be either an admin or a node server.Example:host -l geeksforgeeks.org 
Example:
host -l geeksforgeeks.org 
linux-command
Linux-networking-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
Tail command in Linux with examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
Reducing Execution time in Python using List Comprehensions

10 Jul, 2020
Prerequisites: Comprehensions in Python
Most of the competitive programmers who code in Python often face difficulty in executing the programs within the given time limit. List Comprehensions help us in reducing the execution time of a program where you are required to create a list based on any mathematical expression. We will consider an example to prove the above statement.
Example : To form a list of all even numbers upto 10**7, we can do it in the following ways
Method 1:
%%timeit -n 100  even =[ ]for i in range(10**7):    if i % 2 == 0:        even.append(i)
Output:
Method 2:
%%timeit -n 100  even =[i for i in range(10**7) if i % 2 == 0]
Output:
We can see the difference in the run-times of the above 2 programs, this difference increases as we increase the range, also when the math expression is a bit complex. This time difference matters a lot when these type of lists are part of a very large program.
Note:The %%timeit tool is used which is available in Jupyter Notebook, it repeats the execution of the same cell multiple times specified by us, and returns the average/mean time taken for the execution of the given program.
Below are the Python 3 code snippets to check the execution times for the above programs,
import time     # Using for loopstart = time.time()a =[ ]  for i in range(10**7):    if i % 2 == 0:        a.append(i)          print("Execution time = ", time.time()-start)  # Using list comprehensionstart = time.time()   a =[i for i in range(10**7) if i % 2 == 0]print("Execution time = ", time.time()-start)
Output:
Execution time =  1.558159589767456
Execution time =  0.9690220355987549
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Currency getInstance() Method in Java with Examples

09 Jul, 2021
The getInstance() Method of Currency class in Java is used to retrieve the instance of this currency for a given currency code.Syntax:  
CURRENCY.getInstance(String currency_code)
Parameters: This method accepts one parameter currency_code which is the currency of a particular currency.Return Value: This method returns the instance of the currency for a currency code.Exceptions: The method throws Runtime Error if an invalid code is called.Below program illustrates the working of getInstance() method:Program 1: 
Java
// Java Code to illustrate getInstance() method import java.util.*; public class Currency_Demo {    public static void main(String[] args)    {         // Creating a currency with the code        Currency curr_ency            = Currency.getInstance("INR");         // Getting the currency code        System.out.println("Currency Code of India is: "                           + curr_ency.toString());    }}
Currency Code of India is: INR
 
Program 2: 
Java
// Java Code to illustrate toString() method import java.util.*; public class Currency_Demo {    public static void main(String[] args)    {         // Creating a currency with the code        Currency curr_ency            = Currency.getInstance("USD");         // Getting the currency code        System.out.println("Currency Code of USA is: "                           + curr_ency.toString());    }}
Currency Code of USA is: USD
 
Program 3: For an invalid Currency Code. 
Java
// Java Code to illustrate getInstance() method import java.util.*; public class Currency_Demo {    public static void main(String[] args)    {        try {             // Creating a currency with the code            Currency curr_ency                = Currency.getInstance("USDA");             // Getting the currency code            String currency_code                = curr_ency.toString();            System.out.println("Invalid Currency Code: "                               + currency_code);        }        catch (Exception e) {            System.out.println(e);        }    }}
java.lang.IllegalArgumentException
 
singghakshay
Java - util package
Java-Currency
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Generating API Keys For Using Any Google APIs

15 Mar, 2022
Like most software giants, Google provides its enthusiastic developers community with its APIs, SDKs and Services. These APIs from Google are hosted on their cloud platform, popularly known as Google Cloud Platform (GCP). Software such as Google Maps, YouTube, Gmail, etc., use the same APIs and now are available for the public for implementation at a very minimal cost depending upon the usage. One can use these APIs in their projects and application to integrate similar features.
Through this article, we want to share with you how one can get access to those APIs. Most importantly, as these services are paid, every registered developer is provided with an API key to access the API features, which are indeed unique. So, one needs to have an API key before beginning to develop features. To your comfort, we have brought you the following steps to generate an API key.
Step 1: To generate an API key for using a specific Google API, you must have an account associated with the Google Cloud Platform (GCP) with billing enabled. You can refer to this article to set up one and create a project.
Step 2: Once the project is created, go to your project dashboard. You will see the APIs window below. Click on Go to APIs overview.
Step 3: Now you will see Traffic, Errors and Median Latency windows. On the left, you will have a drop-down menu. Click on Library.
Step 4: In the API Library page, we have access to a number of APIs and SDKs offered by Google and one can select an interested API.
Step 5: For demonstrating, we clicked on the Compute Engine API. We now get an overview, documentation, and support for that API. To use this API, just click Enable option and follow the steps if posed.
Step 6: Once the API is enabled, go to Credentials. You will find details about your API key.
Step 7: Use this key in your application to use the specific Google API.
Note (for Indian billing accounts): “On December 4, RBI had directed all banks including RRBs, NBFCs, and payment gateways that the processing of recurring transactions (domestic or cross-border) using cards or Prepaid Payment Instruments (PPIs) or Unified Payments Interface (UPI) under arrangements/practices not compliant with AFA would not be continued beyond March 31, 2021.” Source: The Hindu
Because of this, the process of setting up billing accounts or settlements by Google will fail from April 1, 2021, as payments made are automatic monthly. To avoid this, you must ensure to opt for automatic payments with your nationalized banks.
rkbhola5
Google Cloud Platform
TechTips
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What does the cascading portion of CSS means ?

08 Oct, 2021
CSS simplifies the task of maintaining a web document by separating its style information, which includes font size, font color, line width, and background color. This separation allows you to apply the same style rules to multiple web pages. CSS allows you to apply a style multiple times on a single web page. The style in a CSS file is defined according to the rules of CSS recommendation that suggests how a web page should be presented. A CSS file contains the style code for the structure, which includes a heading, listing, paragraph, and links.
Now talking about Cascading in CSS means the styling rules. This is the part where CSS can become unnecessarily complicated, even if the ability to use the cascading is occasionally useful.
So, let’s start this by asking a question, “What if you have two CSS classes that have conflicting properties?” Which one “wins” and is applied? Let’s look a the below example.
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <style>        h1 {            font-size: 40px;            text-align: center;            color: red;        }          h1 {            color: green;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>      <p>The second style gets applied because    it is applied after the first.</p>  </body>  </html>
 
Output:
We have two color properties with the same h1 tag. So which one gets applied? Here comes the role of C in CSS, Since they’re equal, the one that comes last wins. So in this case, the h1 would be green. So remember the rule: when everything is equal, the last one gets applied.
What does C in CSS stand for? CASCADING. So cascading means, if we list a style earlier in the document and we say it’s one way, and then later in the document, we can say it’s a different way, the thing that’s later in the document wins. Styles of higher precedence will override the rules of lower precedence.
CSS-Properties
CSS-Questions
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MySQL | ISNULL( ) Function

19 Nov, 2019
The MySQL ISNULL() function is used for checking whether an expression is NULL or not. This function returns 1 if the expression passed is NULL, else it returns 0.
The ISNULL() function accepts the expression as a parameter and returns an integer a value 0 or 1 depending on the parameter passed.
Syntax:
ISNULL(expression)
Parameters Used:
expression – It is used to specify the expression.
Return Value:The MySQL ISNULL() function returns 1 if the expression passed is a NULL expression, else it returns 0.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
MySQL 4.0
MySQL 3.23
Example-1: Implementing ISNULL() function.
SELECT ISNULL(NULL); 
Output:
1 
Example-2: Implementing ISNULL() function on a string.
SELECT ISNULL("gfg"); 
Output:
0 
Example-3: Implementing ISNULL() function on an integer value.
SELECT ISNULL(123); 
Output:
0 
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Oracle Database Connection in Python

Python can connect to oracle using a python package called cx_Oracle. Oracle is one of the famous and widely used database and python’s data processing features are leverages well using this connectivity. In this article we will see how we can connect to oracle database and query the DB.
We can use the below command to install the python package which can be used for establishing the connectivity.
pip install cx_Oracle
Now using this module we can connect to a oracle database which is accessible through the oracle service name. We create a cursor and execute the SQl query through the cursor for creating a table. All this is handled through a try and except structure to catch any exception or failure in database connectivity.
import cx_Oracle
# Connecting to DB
try:
   con = cx_Oracle.connect('username/password@servicename')
   cursor = con.cursor()
   
   #Creating a table
   cursor.execute("create table TableName(COL1 VARCHAR2(200),\COL2 NUMBER(8))")
      print("Table Created")
   
except cx_Oracle.DatabaseError as e:
   print("Problem connecting to Oracle", e)
   # Close the all database operation
   finally:
   if cursor:
      cursor.close()
   if con:
      con.close()
Running the above code gives us the following result −
Table Created
JavaScript Functions

A JavaScript function is a block of code designed to perform a 
particular task.
A JavaScript function is executed when 
"something" invokes it (calls it).
A JavaScript function is defined with the function keyword, 
followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs 
(same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
Function parameters are listed inside the parentheses () in 
the function definition.
Function arguments are the values 
received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
A Function is much the same as a Procedure or a Subroutine, in other programming languages.
The code inside the function will execute when "something" invokes (calls) the 
function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
You will learn a lot more about function invocation later in this 
tutorial.
When JavaScript reaches a return statement, 
the function will stop executing.
If the function was invoked from a statement, JavaScript will 
"return" to execute the code after the invoking statement.
Functions often compute a return value. The return value is 
"returned" back to 
the "caller":
Calculate the product of two numbers, and return the result:
The result in x will be:
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different 
results.
Convert Fahrenheit to Celsius:
Using the example above, toCelsius refers to the function object, and 
toCelsius() refers to the function result.
Accessing a function without () will return the function object instead of 
the function result.
Functions can be used the same way as you use variables, in all types of formulas, assignments, and 
calculations.
Instead of using a variable to store the return value of a function:
You can use the function directly, as a variable value:
You will learn a lot more about functions later in this tutorial.
Variables declared within a JavaScript function, become 
LOCAL to 
the function.
Local variables can only be accessed 
from within the function.
Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the function is completed.
Execute the function named myFunction.
function myFunction() {
  alert("Hello World!");
}
;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Count number of even and odd elements in an array in C++

In this tutorial, we will be discussing a program to find the number of even and odd elements in an array.
For this we will be provided with an array. Our task is to calculate the number of even and odd elements in the given array.
 Live Demo
#include<iostream>
using namespace std;
void CountingEvenOdd(int arr[], int arr_size){
   int even_count = 0;
   int odd_count = 0;
   //looping through the elements
   for(int i = 0 ; i < arr_size ; i++) {
      //checking if the number is odd
      if (arr[i]%2 != 0)
         odd_count ++ ;
      else
         even_count ++ ;
   }
   cout << "Number of even elements = " << even_count
      << "\nNumber of odd elements = " << odd_count ;
}
int main(){
   int arr[] = {2, 3, 4, 5, 6};
   int n = sizeof(arr) / sizeof(arr[0]);
   CountingEvenOdd(arr, n);
}
Number of even elements = 3
Number of odd elements = 2
Tryit Editor v3.7

Tryit: HTML euro symbol