code-rag-bench/online-tutorials huggingface dataset:
Lex program to find the length of the longest word

30 Apr, 2019
Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
The commands for executing the lex program are:
lex abc.l (abc is the file name)
cc lex.yy.c -efl
./a.out 
Let’s see lex program to check valid email.
Examples:
Input:  geeks for geeks
Output:  5

Input:  facebook google yahoo
Output:  8 
Below is the implementation:
/*lex code to find the length of the longest word*/  % {  int counter = 0; %}  %% [a - zA - Z] + {  if (yyleng > counter) {    counter = yyleng;  }} %%  main() {  yylex();  printf("largest: %d", counter);  printf("\n");}
Output:
Lex program
C Programs
Compiler Design
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
Issues in the design of a code generator
Three address code in Compiler
Phases of a Compiler
Peephole Optimization in Compiler Design
Code Optimization in Compiler Design
exit command in Linux with Examples

15 May, 2019
exit command in linux is used to exit the shell where it is currently running. It takes one more parameter as [N] and exits the shell with a return of status N. If n is not provided, then it simply returns the status of last command that is executed.
Syntax:
exit [n]
Options for exit command –
exit: Exit Without ParameterAfter pressing enter, the terminal will simply close.
After pressing enter, the terminal will simply close.
exit [n] : Exit With ParameterAfter pressing enter, the terminal window will close and return a status of 110. Return status is important because sometimes they can be mapped to tell error, warnings and notifications. For example generally, return status –“0” means the program has executed successfully.“1” means the program has minnor errors.
After pressing enter, the terminal window will close and return a status of 110. Return status is important because sometimes they can be mapped to tell error, warnings and notifications. For example generally, return status –“0” means the program has executed successfully.“1” means the program has minnor errors.
exit n : Using “sudo su” we are going to the root directory and then exit the root directory with a return status of 5. After returning it will show how to display the return status code.echo $? command is used to see the last return status.
exit –help : It displays help information.
linux-command
Linux-Shell-Commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
'crontab' in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
Docker - COPY Instruction
UDP Server-Client implementation in C
scp command in Linux with Examples
diff command in Linux with examples
echo command in Linux with Examples
enchant.Dict() in Python

03 Jun, 2020
Enchant is a module in python which is used to check the spelling of a word, gives suggestions to correct words. Also, gives antonym and synonym of words. It checks whether a word exists in dictionary or not.
enchant.Dict() is an inbuilt method of enchant module. It is used to create a Dict object, which is the most important object in the enchantt module. The Dict object represents the dictionary of a particular language.
Syntax : enchant.Dict(tag)
Parameter :tag : the code of the language dictionary(optional)
Returns : a Dict object
Example 1 :
# import the enchant moduleimport enchant  # dictionary of en_USd = enchant.Dict("en_US")  # the dictionary tagtag = d.tagprint("The dictionary tag is " + tag)
The dictionary tag is en_US

Example 2 : When the enchant.Dict() method is executed without passing any parameter in it, it by default takes the the code of the language of the local machine.
# import the enchant moduleimport enchant  # instantiating the dictionary # without passing any parameterd = enchant.Dict()  # finding the dictionary tagtag = d.tagprint("The dictionary tag is " + tag)
The dictionary tag is en_IN

Example 3 : The enchant.Dict() method may fail if the appropriate dictionary is not available. In that case the following message is printed:
enchant.Dict()
Output :
Traceback (most recent call last):File “”, line 1, inenchant.Dict()File “C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\enchant\__init__.py”, line 541, in __init___EnchantObject.__init__(self)File “C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\enchant\__init__.py”, line 144, in __init__self._init_this()File “C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\enchant\__init__.py”, line 548, in _init_thisthis = self._broker._request_dict_data(self.tag)File “C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\enchant\__init__.py”, line 286, in _request_dict_dataself._raise_error(e_str % (tag, ), DictNotFoundError)File “C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\enchant\__init__.py”, line 233, in _raise_errorraise eclass(default)enchant.errors.DictNotFoundError: Dictionary for language ‘English_India’ could not be found
Python Enchant-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to display multiple images in one figure correctly in matplotlib?

To display multiple images in one figure, we can follow the steps given below −
Initialize the number of rows and cols. nrows*ncols subplot will be created in the current figure. nrows = 2 and ncols = 2, i.e., 2*2 = 4 subplots can be created.
Initialize the number of rows and cols. nrows*ncols subplot will be created in the current figure. nrows = 2 and ncols = 2, i.e., 2*2 = 4 subplots can be created.
Now add the figures at different indices from 1 to 4.
Now add the figures at different indices from 1 to 4.
Use plt.subplot(2, 2, 1) to add new images, i.e., pie at index 1.
Use plt.subplot(2, 2, 1) to add new images, i.e., pie at index 1.
To plot a pie chart, pass a list of numbers. Pie charts will be split into the size of list and %age section will depend upon the values in the list.
To plot a pie chart, pass a list of numbers. Pie charts will be split into the size of list and %age section will depend upon the values in the list.
Set the title of the subplot, i.e., “Figure 1”.
Set the title of the subplot, i.e., “Figure 1”.
Use plt.subplot(2, 2, 2) to add new images, i.e., pie at index 2.
Use plt.subplot(2, 2, 2) to add new images, i.e., pie at index 2.
Use plt.pie() to create a new pie chart.
Use plt.pie() to create a new pie chart.
Set the title of the subplot, i.e., “Figure 2”.
Set the title of the subplot, i.e., “Figure 2”.
Use plt.subplot(2, 2, 3) to add new images i.e., pie at index 3.
Use plt.subplot(2, 2, 3) to add new images i.e., pie at index 3.
Use plt.pie() to create a new pie chart.
Use plt.pie() to create a new pie chart.
Set the title of the subplot i.e., “Figure 3”.
Set the title of the subplot i.e., “Figure 3”.
Use plt.subplot(2, 2, 4) to add new images i.e., pie at index 4.
Use plt.subplot(2, 2, 4) to add new images i.e., pie at index 4.
Use plt.pie() to create a new pie chart.
Use plt.pie() to create a new pie chart.
Set the title of the subplot i.e., “Figure 4”.
Set the title of the subplot i.e., “Figure 4”.
Use plt.show(), to show the figure.
Use plt.show(), to show the figure.
import matplotlib.pyplot as plt

rows, cols = 2, 2
plt.subplot(rows, cols, 1)
plt.pie([1, 2, 3])
plt.title("Figure 1")
plt.subplot(rows, cols, 2)
plt.pie([3, 4, 5])
plt.title("Figure 2")
plt.subplot(rows, cols, 3)
plt.pie([6, 7, 8])
plt.title("Figure 3")
plt.subplot(rows, cols, 4)
plt.pie([8, 9, 10])
plt.title("Figure 4")

plt.show()
How to Concatenate image using Pillow in Python ?

07 Apr, 2021
Prerequisites: Python Pillow
Concatenate image means joining of two images. We can merge any image whether it has different pixels, different image formats namely, ‘jpeg’, ‘png’, ‘gif’, ‘tiff’, etc. In python, we can join two images using the Python image library also known as the pillow library. In this article, we will see how the concatenation of images is done.
Concatenation of images can be done in two ways :
Horizontal
Vertical
Approach:
Import module
Open the images
Resize the image using Resize() function. Both the resize images should be of the same width and height so that their aspect ratio is intact and can be pasted into the new background image.
To create a new image it has a new() function which has 3 parameters (“mode”,(size),color)
Paste the image to new image using paste()
Program:
Python3
# libraryfrom PIL import Imageimport matplotlib.pyplot as plt  # opening up of imagesimg = Image.open("logo.png")img1 = Image.open("logo2.png")img.sizeimg1.sizeimg_size = img.resize((250, 90))img1_size = img1.resize((250, 90))  # creating a new image and pasting # the imagesimg2 = Image.new("RGB", (500, 90), "white")  # pasting the first image (image_name,# (position))img2.paste(img_size, (0, 0))  # pasting the second image (image_name,# (position))img2.paste(img1_size, (250, 0))  plt.imshow(img2)
 Output :
The whole code is the same as horizontal but the only change is that in horizontal we double the width and the height is same but in vertical we make the size of width same, but we double the height. 
Approach:
Import the libraries for image processing.
Use Image.open() to open the library.
Use img.size to know the size of the image.
Use img.resize((width,height)) to resize the image.
Both the images should be of same size.
Create a new image using new() and pass the 3 parameters”mode”,size,”color”).
Size in new image should be (width, 2*height).
After the creation of new image, paste the first image by using paste() and pass the parameter(img_resize,(position)) #position(0,0)
After pasting the first image, paste the second image using paste and pass the parameter(img1_reszie, (position)). In position, width would be the same but the height would be the last position of the first image’s height. . #position=(0,180)
Use plt.imshow(img2) to show the concatenate of images.
Program:
Python3
# libraryfrom PIL import Imageimport matplotlib.pyplot as plt    # opening up of imagesimg = Image.open("logo.png")img1 = Image.open("logo2.png")img.sizeimg1.sizeimg_size = img.resize((250, 90))img1_size = img1.resize((250, 90))  # creating a new image and pasting the # imagesimg2 = Image.new("RGB", (250, 180), "white")  # pasting the first image (image_name,# (position))img2.paste(img_size, (0, 0))  # pasting the second image (image_name,# (position))img2.paste(img1_size, (0, 90)  plt.imshow(img2)
Output:
Picked
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to find all the values of particular key of MongoDB Database using Node.js ?

12 Feb, 2021
MongoDB module: This module of Node.js is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. The mongodb.connect() is the main method that is used for connecting to the MongoDB database which is running on a particular server on your machine (Refer to this article). We can also use promises, in this method to resolve the object contains all the methods and properties required for collection manipulation and reject the error that occurs during connection.
Project() method of MongoDB module is allowed only documents that specified as a parameter in this Method. This Method takes the document’s key name and with 0 and 1 value. 
0 means except this key show all other’s keys value of MongoDB Collection.
1 means show only given keys value. Of MongoDB Collection.
Installing module: You can install the mongodb module using the following command:
node install mongodb
Project Structure: The project structure will look like the following.
Running the server on Local IP: In the following command, data is the folder name.
mongod --dbpath=data --bind_ip 127.0.0.1
MongoDB Database: Our database name and collection is shown below with some dummy data.
Database:GFG
Collection:aayush
Filename: index.js
Javascript
// Requiring moduleconst MongoClient = require("mongodb"); // Connection URLconst url = 'mongodb://localhost:27017/'; // Database nameconst databasename = "GFG";  MongoClient.connect(url).then((client) => {     const connect = client.db(databasename);     // Connect to collection    const collection = connect.collection("aayush");     // Fetching the records of name key    collection.find({ }).project({name:1})        .toArray().then((values) => {         // Printing the values        console.log(ans);    });     }).catch((err) => {     // Printing the error message    console.log(err.Message);})
 Run the index.js file using the following command:
node index.js
Output:
mridulmanochagfg
Node.js-Misc
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Get topmost N records within each group of a Pandas DataFrame

28 Jul, 2020
Firstly, the pandas dataframe stores data in the form of a table. In some situations we need to retrieve data from dataframe according to some conditions. Such as if we want to get top N records of each group of the dataframe. Here we will use Groupby() function of pandas to group the columns. So we can do it as follows:
Firstly, we created a pandas dataframe:
Python3
#importing pandas as pdimport pandas as pd  #creating dataframedf=pd.DataFrame({ 'Variables': ['A','A','A','A','B','B',                                'B','C','C','C','C'],                 'Value': [2,5,0,3,1,0,9,0,7,5,4]})df
Output:
Now, we will get topmost N values of each group of the ‘Variables’ column. Here reset_index() is used to provide a new index according to the grouping of data. And head() is used to get topmost N values from the top.
Example 1: Suppose the value of N=2
Python3
# setting value of N as 2N = 2  # using groupby to group acc. to# column 'Variable'df.groupby('Variables').head(N).reset_index(drop=True)
Output:
Example 2: Now, suppose the value of N=4
Python3
# setting value of N as 2N = 4  # using groupby to group acc. # to column 'Variable'df.groupby('Variables').head(N).reset_index(drop=True)
Output:
Python pandas-groupby
Python-pandas
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
How can I get the list of files in a directory using C or C++?

Let us consider the following C++ sample code to get the list of files in a directory.
Begin
   Declare a poniter dr to the DIR type.
   Declare another pointer en of the dirent structure.
   Call opendir() function to open all file in present directory.
   Initialize dr pointer as dr = opendir(".").
   If(dr)
      while ((en = readdir(dr)) != NULL)
         print all the file name using en->d_name.
      call closedir() function to close the directory.
End.
#include <iostream>
#include <dirent.h>
#include <sys/types.h>
using namespace std;
int main(void) {
   DIR *dr;
   struct dirent *en;
   dr = opendir("."); //open all directory
   if (dr) {
      while ((en = readdir(dr)) != NULL) {
         cout<<" \n"<<en->d_name; //print all directory name
      }
      closedir(dr); //close all directory
   }
   return(0);
}
BINSEARC.C
BINTREE (1).C
BINTREE.C
BTREE.C
BUBBLE.C
c.txt
file3.txt
HEAP.C
HEAPSORT.C
HLINKLST.C
INSERTIO.C
LINKLIST.C
LINKLST.C
LLIST1.C
players.cpp
PolarRect.cpp
QUEUE.C
#include <stdio.h>
#include <dirent.h>
int main(void) {
   DIR *dr;
   struct dirent *en;
   dr = opendir("."); //open all or present directory
   if (dr) {
      while ((en = readdir(dr)) != NULL) {
         printf("%s\n", en->d_name); //print all directory name
      }
      closedir(dr); //close all directory
   }
   return(0);
}
BINSEARC.C
BINTREE (1).C
BINTREE.C
BTREE.C
BUBBLE.C
c.txt
file3.txt
HEAP.C
HEAPSORT.C
HLINKLST.C
INSERTIO.C
LINKLIST.C
LINKLST.C
LLIST1.C
PostgreSQL - LIMIT clause - GeeksforGeeks

28 Aug, 2020
The PostgreSQL LIMIT clause is used to get a subset of rows generated by a query. It is an optional clause of the SELECT statement.
Syntax: SELECT * FROM table_name LIMIT n;
Now let’s analyze the syntax above:
The above syntax returns “n” no. of query results.
If “n” is skipped or equal to NULL it returns all the query results.
For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link.
Now, let’s look into a few examples.
Example 1:In this example we will be using the LIMIT clause to get the first 10 films ordered by the “film_id” from the “film” table of our sample database.
SELECT
    film_id,
    title,
    rating
FROM
    film
ORDER BY
    film_id
LIMIT 10;
Output:
Example 2:In this example we will be using the LIMIT clause to get the top 10 expensive films ordered by the “rental_rate” from the “film” table of our sample database.
SELECT
    film_id,
    title,
    rental_rate
FROM
    film
ORDER BY
    rental_rate DESC
LIMIT 10;
Output:
postgreSQL-clauses
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - REPLACE Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - TIME Data Type
PostgreSQL - Copy Table
PostgreSQL - Rename Table
PostgreSQL - RENAME COLUMN
PostgreSQL - Cursor
Drop shadow for PNG image using CSS

22 Apr, 2019
There is a basic way to add shadow effect on images but that effect will behave like the image is square, so there is another way to do the shadow which is basically applied on PNG images. The normal shadow effect will always put a square image shadow for the image which can be squared or cannot be squared but the shadow will be always square. filter:drop-shadow(); and text-shadow(); property is more eye pleasant compare to box-shadow:() property.
Syntax:
filter: drop-shadow();
Example 1: This example uses filter: drop-shadow() property to add shadow effect on pngimage.
<!DOCTYPE html><html>  <head>          <!-- CSS style to add shadow -->    <style>        img {            filter: drop-shadow(5px 5px 5px #222);            width:200px;            height:220px;        }    </style></head>  <body style="text-align:center;">    <h3>Drop shadow effect on png</h3>    <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190405213436/left90.png" /></body>  </html>                                  
Output:
Example 2: This example differentiate between filter:drop-shadow();, text-shadow(); and box-shadow:(); property.
<!DOCTYPE html> <html>       <head>     <style>         img {            width:120px;        }        .Box-shadow {            float:left;            box-shadow:2px 2px 2px gray;        }                  .Text-shadow {            float:right;            text-shadow:2px 2px 2px gray;        }        .Drop-shadow {            float:right;        }        .Drop-shadow img {            filter:drop-shadow(2px 2px 2px gray);        }    </style> </head>   <body>       <div class = "images">         <div class="Box-shadow">            <p>Box-shadow                <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190405213436/left90.png" />            </p>        </div>                  <div class="Text-shadow">            <p>Text-shadow                <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190405213436/left90.png" />            </p>        </div>                  <div class="Drop-shadow">            <p>Drop-shadow                <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190405213436/left90.png" />            </p>         </div>    </div> </body>   </html>                                                    
Output:
CSS-Misc
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
EnvironmentError Exception in Python

21 Aug, 2020
EnvironmentError is the base class for errors that come from outside of Python (the operating system, file system, etc.). It is the parent class for IOError and OSError exceptions. 
exception IOError – It is raised when an I/O operation (when a method of a file object ) fails. e.g “File not found” or “Disk Full”.exception OSError – It is raised when a function returns a system-related error.
exception IOError – It is raised when an I/O operation (when a method of a file object ) fails. e.g “File not found” or “Disk Full”.
exception OSError – It is raised when a function returns a system-related error.
Any example of an IOError or OSError should also be an example of Environment Error.
Example 1 :
Python3
# importing the moduleimport sys  try:    # an invalid path    file = open("GeeksforGeeks.txt", 'r')except Exception as e:    print(e)    print(sys.exc_info()[0])
[Errno 2] No such file or directory: 'GeeksforGeeks.txt'
<class 'FileNotFoundError'>

Example 2 :
Python3
# importing the moduleimport osimport sys  try:    for i in range(7):        print(i)        print(os.ttyname(i))except Exception as e:    print(e)    print(sys.exc_info()[0])
0
[Errno 25] Inappropriate ioctl for device
<class 'OSError'>

Example 3 :
Python3
# importing the moduleimport sysimport os  try:    # an invalid path    os.rmdir('GEEKS')except Exception as e:    print(e)    print(sys.exc_info()[0])
[Errno 2] No such file or directory: 'GEEKS'
<class 'FileNotFoundError'>

Python-exceptions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Ways to increment Iterator from inside the For loop in Python

12 Feb, 2021
For loops, in general, are used for sequential traversal. It falls under the category of definite iteration. Definite iterations mean the number of repetitions is specified explicitly in advance. But have you ever wondered, what happens, if you try to increment the value of the iterator from inside the for loop. Let’s see with the help of the below example.Example: 
Python3
lis = [1, 2, 3, 4, 5] for i in range(len(lis)):         print(lis[i])    i += 2
Output: 
1
2
3
4
5
The above example shows this odd behavior of the for loop because the for loop in Python is not a convention C style for loop, i.e., for (i=0; i<n; i++) rather it is a for in loop which is similar to for each loop in other languages. However, there are few methods by which we can control the iteration in the for loop. Some of them are – 
Using While loop: We can’t directly increase/decrease the iteration value inside the body of the for loop, we can use while loop for this purpose.Example: 
Python
# Using while loop lis = [1, 2, 3, 4, 5]i = 0 while(i < len(lis)):    print(lis[i], end = " ")         # Changing the value of    # i inside the loop will    # change it's value at the    # time of checking condition    i += 2    
Output:  
1 3 5
 
Using another variable: We can use another variable for the same purpose because after every iteration the value of loop variable is re-initialized.Example:  
Python
# Using for loop lis = [1, 2, 3, 4, 5] i = 0 for j in range(len(lis)):     # Terminating condition for i    if(i >= len(lis)):        break         print(lis[i], end = " ")       i += 2
Output:  
1 3 5
 
Using Range Function: We can use the range function as the third parameter of this function specifies the step.Note: For more information, refer to Python range() Function.Example: 
Python3
# Using for loop lis = [1, 2, 3, 4, 5] for i in range(0, len(lis), 2):         print(lis[i], end = " ")   
Output: 
1 3 5
 
 
arorakashish0911
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
How to implement stack using priority queue or heap?

08 Feb, 2018
How to Implement stack using a priority queue(using min heap)?.
Asked In: Microsoft, Adobe.
Solution:
In priority queue, we assign priority to the elements that are being pushed. A stack requires elements to be processed in Last in First Out manner. The idea is to associate a count that determines when it was pushed. This count works as a key for the priority queue.
So the implementation of stack uses a priority queue of pairs, with the first element serving as the key.
pair <int, int> (key, value)
See Below Image to understand Better
Below is C++ implementation of the idea.
// C++ program to implement a stack using// Priority queue(min heap)#include<bits/stdc++.h>using namespace std;  typedef pair<int, int> pi;  // User defined stack classclass Stack{          // cnt is used to keep track of the number of    //elements in the stack and also serves as key    //for the priority queue.    int cnt;    priority_queue<pair<int, int> > pq;public:    Stack():cnt(0){}    void push(int n);    void pop();    int top();    bool isEmpty();};  // push function increases cnt by 1 and// inserts this cnt with the original value. void Stack::push(int n){    cnt++;    pq.push(pi(cnt, n));}  // pops element and reduces count.void Stack::pop(){    if(pq.empty()){ cout<<"Nothing to pop!!!";}    cnt--;    pq.pop();}  // returns the top element in the stack using// cnt as key to determine top(highest priority),// default comparator for pairs works fine in this case int Stack::top(){    pi temp=pq.top();    return temp.second;}  // return true if stack is emptybool Stack::isEmpty(){    return pq.empty();}  // Driver codeint main(){    Stack* s=new Stack();    s->push(1);    s->push(2);    s->push(3);    while(!s->isEmpty()){        cout<<s->top()<<endl;        s->pop();    }}
Output:
 3
 2
 1

Now, as we can see this implementation takes O(log n) time for both push and pop operations. This can be slightly optimized by using fibonacci heap implementation of priority queue which would give us O(1) time complexity for push operation, but pop still requires O(log n) time.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
priority-queue
Heap
Stack
Stack
Heap
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Find k numbers with most occurrences in the given array
Difference between Min Heap and Max Heap
Priority queue of pairs in C++ (Ordered by first)
K-th Largest Sum Contiguous Subarray
Stack Data Structure (Introduction and Program)
Stack in Python
Stack Class in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Introduction to Data Structures
How to select the Date Picker In Selenium WebDriver?

We can select the date picker in Selenium. It is slightly difficult to handle calendar controls as the day, month and year selection can be represented via different UI.
Sometimes they are represented by the dropdown or by forward and backward controls. Let us select the date picker as shown below.
From Date −
To Date −
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.Select;
public class DatePicker{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String frdate = "20";
      String todate = "26";
      driver.get("https://jqueryui.com/datepicker/#date−range");
      // wait of 4 seconds
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // maximize browser
      driver.manage().window().maximize();
      // identify frame and switch to it
      WebElement e = driver.findElement(By.xpath("//*[@id='content']/iframe"));
      driver.switchTo().frame(e);
      // choose from date
      driver.findElement(By.xpath("//input[@id='from']")).click();
      Thread.sleep(1000);
      // choose month from dropdown
      WebElement m = driver
      .findElement(By.xpath("//div/select[@class='ui− datepicker−month']"));
      Select s = new Select(m);
      s.selectByVisibleText("Jan");
      Thread.sleep(1000);
      // select day
      driver.findElement(By.xpath("//td[not(contains(@class,'ui−datepicker− month'))]/a[text()='"+frdate+"']")).click();
      Thread.sleep(1000);
      // choose to date
      driver.findElement(By.xpath("//input[@id='to']")).click();
      Thread.sleep(1000);
      // choose month from dropdown
      WebElement n = driver
      .findElement(By.xpath("//div/select[@class='ui− datepicker−month']"));
      Select sel = new Select(n);
      sel.selectByVisibleText("Feb");
      Thread.sleep(1000);
      // select day
      driver.findElement(By.xpath("//td[not(contains(@class,'ui−datepicker− month'))]/a[text()='"+todate+"']")).click();
      Thread.sleep(1000);
   }
}
Text Split Effect using CSS

18 Feb, 2022
In this article, we will see how we can create a text split effect using CSS.  HTML code is used to create the basic structure of the sections and CSS code is used to set the style.
Approach:
Create an HTML div element with the class “container”.
Inside the “container”,  create an HTML div with class “box”.
Create two p tags with text.
To split the text we are going to provide the text shape using clip-path and then use transform property on hover to translate it.
Example:
HTML
<!DOCTYPE html><html>  <head>    <style type="text/css">      /* Aligning container in center*/    .container {        position: absolute;        transform: translate(-50%, -50%);        top: 35%;        left: 35%;        color: green;    }      /* General styling to text and        transition of 2s*/        .text {        position: absolute;        text-transform: uppercase;        font-size: 3rem;        transition: 2s ease;    }      /* Giving shapes to text using clip-path*/        .text1 {        clip-path: polygon(0 0, 100% 0,             100% 100%, 50% 0, 0 100%);    }          .text2 {        clip-path: polygon(0 100%, 50% 0,            100% 100%, 100% 100%, 0 100%);    }      /* transforming box 1 position on hover */        .box:hover .text1 {        transform: translateY(-10px);    }      /* transforming box 2 position on hover */        .box:hover .text2 {        transform: translateY(10px);    }    </style></head>  <body>      <!-- Create container -->    <div class="container">          <!-- create div with class box -->        <div class="box">              <!-- write the text to be splitted                  into two p tags -->            <p class="text text1">geeksforgeeks</p>              <p class="text text2">geeksforgeeks</p>        </div>    </div></body>  </html>
Output:
Reference: https://www.geeksforgeeks.org/how-to-split-text-horizontally-on-mouse-move-over-using-css/
sagar0719kumar
CSS-Properties
CSS-Questions
HTML-Questions
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python: Iterating With Python Lambda

19 Dec, 2021
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python.
Syntax:
lambda variable : expression
Where,
variable is used in the expressionexpression can be an mathematical expression
variable is used in the expression
expression can be an mathematical expression
Example 1:
 In the below code, We make for loop to iterate over a list of numbers and find the square of each number and save it in the list. And then, print a list of square numbers.
Python3
# Iterating With Python Lambdas  # list of numbersl1 = [4, 2, 13, 21, 5]  l2 = []  # run for loop to iterate over listfor i in l1:          # lambda function to make square     # of number    temp=lambda i:i**2      # save in list2    l2.append(temp(i))  # print listprint(l2)
Output:
[16, 4, 169, 441, 25]
Example 2:
We first iterate over the list using lambda and then find the square of each number. Here map function is used to iterate over list 1. And it passes each number in a single iterate. We then save it to a list using the list function. 
Python3
# Iterating With Python Lambdas  # list of numbersl1 = [4, 2, 13, 21, 5]  # list of square of numbers# lambda function is used to iterate # over list l1l2 = list(map(lambda v: v ** 2, l1))  # print listprint(l2)
Output:
[16, 4, 169, 441, 25]
Example 3:
In the below code, we use map, filter, and lambda functions. We first find odd numbers from the list using filter and lambda functions. Then, we do to the square of it using map and lambda functions as we did in example 2.
Python3
# Iterating With Python Lambdas  # list of numbersl1 = [4, 2, 13, 21, 5]  # list of square of odd numbers# lambda function is used to iterate over list l1# filter is used to find odd numbersl2 = list(map(lambda v: v ** 2, filter(lambda u: u % 2, l1)))  # print listprint(l2)
Output:
[169, 441, 25]
Picked
python-lambda
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala Map transform() method with example

13 Aug, 2019
The transform() method is utilized to transform the elements of the map into a mutable map.
Method Definition: def transform(f: (K, V) => V): Map.this.type
Return Type: It transforms all the elements of the map and returns them into a mutable map.
Example #1:
// Scala program of transform()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs")                  // Applying transform method        val result = m1.transform((key,value) => value.toUpperCase)                  // Displays output        println(result)          }}
Map(3 -> GEEKS, 4 -> FOR, 2 -> CS)

Example #2:
// Scala program of transform()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map(3 -> "geeks", 4 -> "for", 4 -> "for")                  // Applying transform method        val result = m1.transform((key,value) => value.toUpperCase)                  // Displays output        println(result)          }}
Map(3 -> GEEKS, 4 -> FOR)

Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Type Casting in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Scala String substring() method with example
Lambda Expression in Scala
Scala Singleton and Companion Objects
How to implement HorizontalScrollView like Gallery in Android?

Before getting into an example, we should know what is Horizontal Scroll View. Horizontal Scrollview provides by android.widget.HorizontalScrollView class. It is used to scroll child views in a horizontal direction.
This example demonstrates how to use horizontal Scroll view.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:id="@+id/layout"
   android:layout_height="match_parent">
   <HorizontalScrollView
      android:layout_width="match_parent"
      android:layout_height="300dp">
      <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent">
         <ImageView
            android:layout_width="300dp"
            android:background="#c1c1c1"
            android:layout_height="match_parent"
            android:src="@drawable/a"/>
         <ImageView
            android:layout_width="300dp"
            android:background="#c1c1c1"
            android:layout_height="match_parent"
            android:layout_marginLeft="30dp"
            android:src="@drawable/b"/>
         <ImageView
            android:layout_width="300dp"
            android:background="#c1c1c1"
            android:layout_height="match_parent"
            android:layout_marginLeft="30dp"
            android:src="@drawable/c"/>
         <ImageView
            android:layout_width="300dp"
            android:background="#c1c1c1"
            android:layout_height="match_parent"
            android:layout_marginLeft="30dp"
            android:src="@drawable/d"/>
         <ImageView
            android:layout_width="300dp"
            android:background="#c1c1c1"
            android:layout_height="match_parent"
            android:layout_marginLeft="30dp"
            android:src="@drawable/e"/>
      </LinearLayout>
   </HorizontalScrollView>
</LinearLayout>
In this above code we have declare Linear layout as parent and added Horizontal Scroll view. Horizontal scroll view going to scroll its child view in horizontal direction so we have created Linear layout as a child for horizontal scroll view and added child for linear layout. We have given five child images views to scroll.
Step 3 − No need to change manifest.xml and activities.
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon  from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result is initial screen when you scroll horizontally it will scroll as shown below image-
In the above result, we are scrolling image views horizontally.
At finally it will reach to the last position of horizontal scroll view as show above.
Click here to download the project code
Python Program for n-th Fibonacci number

In this article, we will compute the nth Fibonacci number.
A Fibonacci number is defined by the recurrence relation given below −
Fn = Fn-1 + Fn-2
With F0= 0 and F1 = 1.
First, few Fibonacci numbers are
0,1,1,2,3,5,8,13,..................
We can compute the Fibonacci numbers using the method of recursion and dynamic programming.
Now let’s see the implementation in the form of Python script
 Live Demo
#recursive approach
def Fibonacci(n):
   if n<0:
      print("Fibbonacci can't be computed")
   # First Fibonacci number
   elif n==1:
      return 0
   # Second Fibonacci number
   elif n==2:
      return 1
   else:
      return Fibonacci(n-1)+Fibonacci(n-2)
# main
n=10
print(Fibonacci(n))
34
The scope of all the variables declared is shown below.
 Live Demo
#dynamic approach
Fib_Array = [0,1]
def fibonacci(n):
   if n<0:
      print("Fibbonacci can't be computed")
   elif n<=len(Fib_Array):
      return Fib_Array[n-1]
   else:
      temp = fibonacci(n-1)+fibonacci(n-2)
      Fib_Array.append(temp)
      return temp
# Driver Program
n=10
print(fibonacci(n))
34
The scope of all the variables declared is shown below
In this article, we learned about the computation of nth Fibonacci number using recursion and dynamic programming approach.
C++ String Library - push_back

It appends character c to the end of the string, increasing its length by one.
Following is the declaration for std::string::push_back.
void push_back (char c);
void push_back (char c);
void push_back (char c);
c − It is a character object.
none
if an exception is thrown, there are no changes in the string.
In below example for std::string::push_back.
#include <iostream>
#include <fstream>
#include <string>

int main () {
   std::string str;
   std::ifstream file ("sample.txt",std::ios::in);
   if (file) {
      while (!file.eof()) str.push_back(file.get());
   }
   std::cout << str << '\n';
   return 0;
}
 Print
 Add Notes
 Bookmark this page
Centering x-tick labels between tick marks in Matplotlib

To place labels between two ticks, we can take the following steps−
Load some sample data, r.
Create a copy of the array, cast to a specified type.
Create a figure and a set of subplots using subplots() method.
Plot date and r sample data.
Set the locator of the major/minor ticker using set_major_locator() and set_minor_locator() methods.
Set the locator of the major/minor formatter using set_major_locator() and set_minor_formatter() methods.
Now, place the ticklabel at the center.
To display the figure, use show() method.
import numpy as np
import matplotlib.cbook as cbook
import matplotlib.dates as dates
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
with cbook.get_sample_data('aapl.npz') as fh:
   r = np.load(fh)['price_data'].view(np.recarray)
r = r[-250:]
date = r.date.astype('O')
fig, ax = plt.subplots()
ax.plot(date, r.adj_close)
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=15))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))
for tick in ax.xaxis.get_minor_ticks():
   tick.tick1line.set_markersize(0)
   tick.tick2line.set_markersize(0)
   tick.label1.set_horizontalalignment('center')
imid = len(r) // 2
ax.set_xlabel(str(date[imid].year))
plt.show()
Image Resizing in Matlab - GeeksforGeeks

22 May, 2019
Prerequisite : RGB image representation
MATLAB stores most images as two-dimensional matrices, in which each element of the matrix corresponds to a single discrete pixel in the displayed image. Some images, such as truecolor images, represent images using a three-dimensional array. In truecolor images, the first plane in the third dimension represents the red pixel intensities, the second plane represents the green pixel intensities, and the third plane represents the blue pixel intensities.
Image resize changes the size of an image. There are two ways of using the imresize column. if the input image has more than two dimensions imresize only resizes the first two dimensions.
J = imresize(I, scale) : The method takes the input image I as input and a scaling factor and scales the input image with that factor. For eg. if we choose 0.5 as the scaling factor every two pixels in the original image is mapped to one pixel value in the output image for both the dimensions.
J = imresize(I, [numrows numcols]) : The methods takes the number of rows and columns and fits the original input image to an output image having the specified number of rows and columns.
Code #1: Read the image from file
% read image fileI = imread('image.jpg');  %display image sizesize(I)  %display the imagefigure, imshow(I);
Output :
ans = 371   660     3

 Code #2: Resize by scaling
% compress the image and save % in another variableI1 = imresize(I, 0.5);  %display image sizesize(I1)  %display the imagefigure, imshow(I1);
Output :
ans = 186   330     3

 Code #3: Resize with specified rows and columns
% resize by specifying rows % and columnsI2 = imresize(I, [100, 200]);  %display image sizesize(I2)  %display the imagefigure, imshow(I2);
Output :
ans = 100   200     3

Kaustav kumar Chanda
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
System Design Tutorial
Decision Tree Introduction with example
Python | Decision tree implementation
Copying Files to and from Docker Containers
ML | Underfitting and Overfitting
Clustering in Machine Learning
KDD Process in Data Mining
Docker - COPY Instruction
Getting started with Machine Learning
Python | Get first N key:value pairs in given dictionary - GeeksforGeeks

02 Aug, 2019
Given a dictionary, the task is to get N key:value pairs from given dictionary. This type of problem can be useful while some cases, like fetching first N values in web development.
Note that the given dictionary is unordered, the first N pairs will not be same here all the time. In case, you need to maintain order in your problem, you can use ordered dictionary.
Code #1: Using itertools.islice() method
# Python program to get N key:value pairs in given dictionary# using itertools.islice() method  import itertools     # Initialize dictionarytest_dict = {'Geeks' : 1, 'For':2,  'is' : 3, 'best' : 4, 'for' : 5, 'CS' : 6}     # printing original dictionary print("The original dictionary : " +  str(test_dict))     # Initialize limit N = 3    # Using islice() + items() # Get first N items in dictionary out = dict(itertools.islice(test_dict.items(), N))         # printing result  print("Dictionary limited by K is : " + str(out)) 
Output:
The original dictionary : {‘for’: 5, ‘best’: 4, ‘CS’: 6, ‘is’: 3, ‘Geeks’: 1, ‘For’: 2}Dictionary limited by K is : {‘for’: 5, ‘best’: 4, ‘CS’: 6}
 
Code #2: Using slicing on dictionary item list
# Python program to get N key:value pairs in given dictionary# using list slicing    # Initialize dictionarytest_dict = {'Geeks' : 1, 'For':2,  'is' : 3, 'best' : 4, 'for' : 5, 'CS' : 6}     # printing original dictionary print("The original dictionary : " +  str(test_dict))     # Initialize limit N = 3    # Using items() + list slicing # Get first K items in dictionary out = dict(list(test_dict.items())[0: N])         # printing result  print("Dictionary limited by K is : " + str(out)) 
Output:
The original dictionary : {‘best’: 3, ‘gfg’: 1, ‘is’: 2, ‘CS’: 5, ‘for’: 4}Dictionary limited by K is : {‘best’: 3, ‘gfg’: 1, ‘is’: 2}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?