code-rag-bench/online-tutorials huggingface dataset:
Ranking Rows of Pandas DataFrame

14 Jan, 2019
To rank the rows of Pandas DataFrame we can use the DataFrame.rank() method which returns a rank of every respective index of a series passed. The rank is returned on the basis of position after sorting.
Example #1 :
Here we will create a DataFrame of movies and rank them based on their ratings.
# import the required packages import pandas as pd   # Define the dictionary for converting to dataframe movies = {'Name': ['The Godfather', 'Bird Box', 'Fight Club'],         'Year': ['1972', '2018', '1999'],         'Rating': ['9.2', '6.8', '8.8']}  df = pd.DataFrame(movies)print(df)
Output:
# Create a column Rating_Rank which contains# the rank of each movie based on ratingdf['Rating_Rank'] = df['Rating'].rank(ascending = 1)  # Set the index to newly created column, Rating_Rankdf = df.set_index('Rating_Rank')print(df)
Output:
# Sort the dataFrame based on the indexdf = df.sort_index()print(df)
Output: Example #2Let’s take an example of marks scored by 4 students. We will rank the students based on the highest mark they have scored.
# Create a dictionary with student detailsstudent_details = {'Name':['Raj', 'Raj', 'Raj', 'Aravind', 'Aravind', 'Aravind',                             'John', 'John', 'John', 'Arjun', 'Arjun', 'Arjun'],                   'Subject':['Maths', 'Physics', 'Chemistry', 'Maths', 'Physics',                             'Chemistry', 'Maths', 'Physics', 'Chemistry', 'Maths',                                                           'Physics', 'Chemistry'],                   'Marks':[80, 90, 75, 60, 40, 60, 80, 55, 100, 90, 75, 70]               }  # Convert dictionary to a DataFramedf = pd.DataFrame(student_details)print(df)
Output:
# Create a new column with Marks # ranked in descending orderdf['Mark_Rank'] = df['Marks'].rank(ascending = 0)  # Set index to newly created column df = df.set_index('Mark_Rank')print(df)
Output:
# Sort the DataFrame based on the index df = df.sort_index()  print(df)
Output:
Explanation:Notice here that we have Raj and Arjun getting 90 marks each and hence they get ranked 2.5 (average of 2nd and 3rd rank i.e the two ranks they share). This can be seen for other marks in the table as well.
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
Capitalize first letter of a column in Pandas dataframe

A pandas dataframe is similar to a table with rows and columns. Sometimes we may have a need of capitalizing the first letters of one column in the dataframe which can be achieved by the following methods.
In the below example we first create a dataframe with column names as Day and Subject.
import pandas as pd
# A dataframe
df = pd.DataFrame({'Day': ['mon', 'tue', 'wed', 'thu', 'fri'], 'Subject': ['Math', 'english', 'science', 'music', 'games']})
print(df)
Running the above code gives us the following result −
      Day    Subject
0     mon       Math
1     tue    english
2     wed science
3     thu music
4     fri games
We apply the str.capitalize() function to the above dataframe for the column named Day. As you can notice, the name of all the days are capitalized at the first letter.
import pandas as pd
# A dataframe
df = pd.DataFrame({'Day': ['mon', 'tue', 'wed', 'thu', 'fri'], 'Subject': ['Math', 'english', 'science', 'music', 'games']})
#print(df)
df['Day'] = df['Day'].str.capitalize()
print(df)
Running the above code gives us the following result −
      Day       Subject
0     Mon          Math
1     Tue       english
2     Wed       science
3     Thu         music
4     Fri         games
Logger setUseParentHandlers() method in Java with Examples - GeeksforGeeks

26 Mar, 2019
setUseParentHandlers() method of a Logger class used to set the configuration which defines whether or not this logger should send its output to its parent Logger. if we want to send the output to its parent Logger then we have to set the parameter to this method equal to true. This means that any log records will also be written to the parent’s Handlers, and potentially to its parent, recursively up the namespace.
Syntax:
public void setUseParentHandlers(boolean useParentHandlers)

Parameters: This method accepts one parameter useParentHandlers which represents true if output is to be sent to the logger’s parent.
Return value: This method returns nothing.
Exception: This method throws SecurityException if a security manager exists, this logger is not anonymous, and the caller does not have LoggingPermission(“control”).
Below programs illustrate the setUseParentHandlers() method:
Program 1:
// Java program to demonstrate// Logger.setUseParentHandlers() method  import java.util.logging.Logger;  public class GFG {      private static Logger logger        = Logger.getLogger(            GFG.class                .getPackage()                .getName());      public static void main(String args[])    {          // Set that this logger will        // sent logs to its parent logger.        logger.setUseParentHandlers(true);          // Log the flag value        logger.info("output sent to the"                    + " logger's parent - "                    + logger.getUseParentHandlers());    }}
Output:The output printed on console of Eclipse is shown below-
Program 2:
// Java program to demonstrate// Logger.setUseParentHandlers() method  import java.util.logging.Logger;  public class GFG {      private static Logger logger        = Logger.getLogger(            GFG.class                .getPackage()                .getName());      public static void main(String args[])    {          // Set that this logger will not        // send logs to its parent logger.        logger.setUseParentHandlers(false);          // Print the flag value        System.out.println("output sent to the"                           + " logger's parent - "                           + logger.getUseParentHandlers());    }}
Output:The output printed on console output is shown below-
Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#setUseParentHandlers(boolean)
Java - util package
Java-Functions
Java-Logger
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
How to remove an element from ArrayList in Java?
Apache Drill - Querying Parquet Files

Parquet is a columnar storage format. Apache Drill uses Parquet format for easy, fast and efficient access.
Before moving to create a table in parquet, you must change the Drill storage format using the following command.
0: jdbc:drill:zk = local> alter session set `store.format`= 'parquet';
+-------+------------------------+
|  ok   |        summary         |
+-------+------------------------+
| true  | store.format updated.  |
+———----+------------------------+

You can create a table using the following syntax.
0: jdbc:drill:zk = local> create table dfs.tmp.`/Users/../workspace` as select * from
   dfs.`/Users/../workspace/Drill-samples/student_list.json`;
+----------+---------------------------+
| Fragment | Number of records written |
+----------+---------------------------+
|   0_0    |            10             |
+----------+---------------------------+

To see the table contents, type-in the following query −
0: jdbc:drill:zk = local> select * from dfs.tmp.`/Users/../workspace`;
+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+
| ID  | name  | age | gender | standard | mark1 | mark2 | mark3 |      addr         | pincode |
+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+
| 001 | Adam  | 12  |  male  |   six    |  70   |  50   |  60   | 23 new street     | 111222  |
| 002 | Amit  | 12  |  male  |   six    |  40   |  50   |  40   | 12 old street     | 111222  |
| 003 | Bob   | 12  |  male  |   six    |  60   |  80   |  70   | 10 cross street   | 111222  |
| 004 | David | 12  |  male  |   six    |  50   |  70   |  70   | 15 express avenue | 111222  |
| 005 | Esha  | 12  | female |   six    |  70   |  60   |  65   | 20 garden street  | 111222  |
| 006 | Ganga | 12  | female |   six    |  100  |  95   |  98   | 25 north street   | 111222  |
| 007 | Jack  | 13  |  male  |   six    |  55   |  45   |  45   | 2 park street     | 111222  |
| 008 | Leena | 12  | female |   six    |  90   |  85   |  95   | 24 south street   | 111222  |
| 009 | Mary  | 13  | female |   six    |  75   |  85   |  90   | 5 west street     | 111222  |
| 010 | Peter | 13  | female |   six    |  80   |  85   |  88   | 16 park avenue    | 111222  |
+-----+-------+-----+--------+----------+-------+-------+-------+-------------------+---------+


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Python | Add substring at specific index - GeeksforGeeks

07 Jun, 2019
In Python, String is immutable datatype, what this means is, that there are lot many restrictions when one handles its manipulation. The problem of adding something at a position at string is not possible, without the list reconstruction. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list slicing
This task can be performed using the list slicing. In this, we just slice the list into two parts, breaking at the target position and then rejoining it after inserting target substring at middle.
# Python3 code to demonstrate# Add substring at specific index# using list slicing  # initializing stringtest_string = 'geeksgeeks'  # initializing add_stringadd_string = "for"  # printing original string  print("The original string : " + test_string)  # printing add string  print("The add string : " + add_string)  # initializing N N = 5  # using list slicing# Add substring at specific index res = test_string[ : N] + add_string + test_string[N : ]      # print resultprint("The string after performing addition : " + str(res))
The original string : geeksgeeks
The add string : for
The string after performing addition : geeksforgeeks

 
Method #2 : Using join() + list() + insert()
Another possible hack that can be performed in for the following problem is that converting the string to list and then adding the string at particular position and then performing the join.
# Python3 code to demonstrate# Add substring at specific index# using join() + list() + insert()  # initializing stringtest_string = 'geeksgeeks'  # initializing add_stringadd_string = "for"  # printing original string  print("The original string : " + test_string)  # printing add string  print("The add string : " + add_string)  # initializing N N = 5  # using join() + list() + insert()# Add substring at specific index res = list(test_string)res.insert(N, add_string)res = ''.join(res)      # print resultprint("The string after performing addition : " + str(res))
The original string : geeksgeeks
The add string : for
The string after performing addition : geeksforgeeks

Python string-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 ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python | Concatenate dictionary value lists - GeeksforGeeks

27 Aug, 2019
Sometimes, while working with dictionaries, we might have a problem in which we have lists as it’s value and wish to have it cumulatively in single list by concatenation. This problem can occur in web development domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using sum() + values()This is the most recommended method and one liner to perform this task. In this, we access all list values using values() and concatenation utility is performed using sum().
# Python3 code to demonstrate working of# Concatenating dictionary value lists# Using sum() + values()  # initializing dictionarytest_dict = {"Gfg" : [4, 5], "is" : [6, 8], "best" : [10]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Concatenating dictionary value lists# Using sum() + values()res = sum(test_dict.values(), [])  # printing result print("The Concatenated list values are : " + str(res))
The original dictionary is : {'Gfg': [4, 5], 'best': [10], 'is': [6, 8]}
The Concatenated list values are : [4, 5, 10, 6, 8]

 
Method #2 : Using chain() + * operatorThis task can also be performed using the combination of these methods. In these, we just use inbuilt function of chain for concatenation to list and * operator is used to access all the list values into one.
# Python3 code to demonstrate working of# Concatenating dictionary value lists# Using chain() + * operatorfrom itertools import chain  # initializing dictionarytest_dict = {"Gfg" : [4, 5], "is" : [6, 8], "best" : [10]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Concatenating dictionary value lists# Using chain() + * operatorres = list(chain(*test_dict.values()))  # printing result print("The Concatenated list values are : " + str(res))
The original dictionary is : {'Gfg': [4, 5], 'best': [10], 'is': [6, 8]}
The Concatenated list values are : [4, 5, 10, 6, 8]

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 | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python - Keys associated with Values in Dictionary - GeeksforGeeks

28 Apr, 2020
Sometimes, while working with Python dictionaries, we can have problem in which we need to reform the dictionary, in the form in which all the values point to the keys that they belong to. This kind of problem can occur in many domains including web development and data domains. Lets discuss certain way in which this task can be performed.
Input : test_dict = {‘abc’ : [10, 30], ‘bcd’ : [30, 40, 10]}Output : {10: [‘abc’, ‘bcd’], 30: [‘abc’, ‘bcd’], 40: [‘bcd’]}
Input : test_dict = {‘gfg’ : [1, 2, 3], ‘is’ : [1, 4], ‘best’ : [4, 2]}Output : {1: [‘is’, ‘gfg’], 2: [‘gfg’, ‘best’], 3: [‘gfg’], 4: [‘is’, ‘best’]}
Method : Using defaultdict() + loopThe combination of above functionalities can solve this problem. In this, we create defaultdict of list and insert the element by checking the association inside the look using brute force approach.
# Python3 code to demonstrate working of # Values Associated Keys# Using defaultdict() + loopfrom collections import defaultdict  # initializing dictionarytest_dict = {'gfg' : [1, 2, 3], 'is' : [1, 4], 'best' : [4, 2]}   # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Values Associated Keys# Using defaultdict() + loopres = defaultdict(list)for key, val in test_dict.items():    for ele in val:        res[ele].append(key)  # printing result print("The values associated dictionary : " + str(dict(res))) 
The original dictionary is : {'is': [1, 4], 'gfg': [1, 2, 3], 'best': [4, 2]}
The values associated dictionary : {1: ['is', 'gfg'], 2: ['gfg', 'best'], 3: ['gfg'], 4: ['is', 'best']}

 
Python dictionary-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Display div element on hovering over <a> tag using CSS - GeeksforGeeks

05 Nov, 2021
In this article, we will know how to render the div element by hovering over the <a> tag using CSS, & will understand its implementation through the example. We can apply an adjacent sibling CSS selector property to the <a> tag that will display the hidden div element’s content while hovering over it. The Adjacent sibling selector is a CSS Combinators, used to select the element that is adjacent or the element that is next to the specified selector tag. CSS combinators explain the relationship between two selectors. CSS selector is used to apply the various styling properties to the selected elements based on the patterns & it can be a simple selector or a complex selector that consists of more than one selector connected using combinators. 
Here, this combinator will select only 1 tag that is just next to the specified tag. To display div element using CSS on hover a tag:
First, set the div element invisible i.e display:none;.
By using the adjacent sibling selector and hover on a tag to display the div element.
Example: This example illustrates how to display the div element on hovering a tag.
HTML
<!DOCTYPE html><html>  <head>    <style>    h1 {        color: green;    }          div {        display: none;    }          a:hover + div {        display: block;        color: green;        font-size: 25px;    }    </style></head>  <body style="text:align:center;">    <h1>GeeksforGeeks</h1> <b>      Hovering below element to see       the <div> element.    </b>    <br>    <br> <a>GeeksforGeeks</a>    <div> A computer science portal for Geeks. </div></body>  </html>
Output: 
Supported Browsers: The browser that the adjacent sibling CSS selector property, are listed below:
Google Chrome 1.0
Microsoft Edge 12.0
Firefox 1.0
Internet Explorer 7.0
Opera 3.5
Safari 1.0
CSS is the foundation of web pages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
bhaskargeeksforgeeks
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
How to set space between the flexbox ?
How to Upload Image into Database and Display it using PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
C++ Program to Find the Longest Prefix Matching of a Given Sequence

Here we shall discuss a C++ program to find the Longest Subsequence Common to All Sequences in a Set of Sequences.
Begin
Take the array of strings as input.
function matchedPrefixtill(): find the matched prefix between string s1 and s2 :
   n1 = store length of string s1.
   n2 = store length of string s2.
   for i = 0, j = 0 to i <= n1 – 1 && j <= n2 - 1
      if s1[i] != s2[j]
         break
      result.push_back(s1[i])
   return result
End
Begin
function matchedPrefix(): returns the longest matched prefix from the array of strings:
   for int i = 1 to n - 1
      pre = matchedPrefixtill(pre, a[i])
   return pre.
End
#include<bits/stdc++.h>
using namespace std;
string matchedPrefixtill(string s1, string s2) {
   string res;
   int n1 = s1.length(); //store length of string s1.
   int n2 = s2.length(); //store length of string s2.
   for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) {    
      if (s1[i] != s2[j])
         break;
      res.push_back(s1[i]);
   }
   return (res);
}
string matchedPrefix (string a[], int n) {
   string pre = a[0];
   for (int i = 1; i <= n - 1; i++)
   pre = matchedPrefixtill(pre, a[i]);
   return (pre);
}
int main() {
   string a[] = {"Tutorialspoint", "Tutor", "Tutorials"}; //taking inputs
   int n = sizeof(a) / sizeof(a[0]);
   string res = matchedPrefix(a, n);
   if (res.length())
      cout<<"Longest common subsequence is matched - "<<res.c_str();
   else
      cout<<"No matched prefix";
   return (0);
}
Longest common subsequence is matched - Tutor
Python - Longest Substring Length of K - GeeksforGeeks

02 Sep, 2020
Given a String and a character K, find longest substring length of K.
Input : test_str = ‘abcaaaacbbaa’, K = bOutput : 2Explanation : b occurs twice, 2 > 1.
Input : test_str = ‘abcaacccbbaa’, K = cOutput : 3Explanation : Maximum times c occurs is 3.
Method #1 : Using loop
This is brute way to solve this problem, in this, when K is encountered, counter is maintained till other character occurs, and count is noted, the maximum of these counts is kept and is returned as result.
Python3
# Python3 code to demonstrate working of # Longest Substring of K# Using loop  # initializing stringtest_str = 'abcaaaacbbaa'  # printing original Stringprint("The original string is : " + str(test_str))  # initializing K K = 'a'  cnt = 0res = 0for idx in range(len(test_str)):          # increment counter on checking    if test_str[idx] == K:        cnt += 1    else:        cnt = 0              # retaining max    res = max(res, cnt)  # printing result print("The Longest Substring Length : " + str(res)) 
The original string is : abcaaaacbbaa
The Longest Substring Length : 4

Method #2 : Using findall() + max()
In this, we get all the possible substrings of K using findall() and max() is used over it to get maximum length with len as key.
Python3
# Python3 code to demonstrate working of # Longest Substring of K# Using findall() + max()import re  # initializing stringtest_str = 'abcaaaacbbaa'  # printing original Stringprint("The original string is : " + str(test_str))  # initializing K K = 'a'  # getting all substringsres = re.findall(r'' + K + '+', test_str)  # getting maximum of substrings Lengthres = len(max(res, key = len))  # printing result print("The Longest Substring Length : " + str(res)) 
The original string is : abcaaaacbbaa
The Longest Substring Length : 4

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Merge list of tuple into list by joining the strings - GeeksforGeeks

02 Aug, 2019
Sometimes, we are required to convert list of tuples into a list by joining two element of tuple by a special character. This is usually with the cases with character to string conversion. This type of task is usually required in the development domain to merge the names into one element. Let’s discuss certain ways in which this can be performed.
Let’s try to understand it better with code examples.
Method 1: Using list comprehension and join()
# Python code to convert list of tuple into list# by joining elements of tuple  # Input list initialisationInput = [('Hello', 'There'), ('Namastey', 'India'), ('Incredible', 'India')]  # using join and list comprehensionOutput = ['_'.join(temp) for temp in Input]  # printing outputprint(Output)
['Hello_There', 'Namastey_India', 'Incredible_India']

 Method 2: Using map and join()
# Python code to convert list of tuple into list# by joining elements of tuple  # Input list initialisationInput = [('Hello', 'There'), ('Namastey', 'India'), ('Incredible', 'India')]  # using map and joinOutput = list(map('_'.join, Input))  # printing outputprint(Output)
['Hello_There', 'Namastey_India', 'Incredible_India']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
matplotlib.pyplot.pcolormesh() in Python - GeeksforGeeks

22 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The pcolormesh() function in pyplot module of matplotlib library is used to create a pseudocolor plot with a non-regular rectangular grid.
Syntax:
matplotlib.pyplot.pcolormesh(\*args, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, shading='flat', antialiased=False, data=None, \*\*kwargs)

Parameters: This method accept the following parameters that are described below:
C : This parameter contains the values in 2D array which are to be color-mapped.
X, Y: These parameter are the coordinates of the quadrilateral corners.
cmap : This parameter is a colormap instance or registered colormap name.
norm : This parameter is the Normalize instance scales the data values to the canonical colormap range [0, 1] for mapping to colors
vmin, vmax : These parameter are optional in nature and they are colorbar range.
alpha : This parameter is a intensity of the color.
snap : This parameter is used to snap the mesh to pixel boundaries.
edgecolors : This parameter is the color of the edges. {‘none’, None, ‘face’, color, color sequence}
shading : This parameter is the fill style. It cabe flat or gouraud.
Returns: This returns the following:
mesh : This returns the matplotlib.collections.QuadMesh
Below examples illustrate the matplotlib.pyplot.pcolormesh() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm     Z = np.random.rand(25, 25)     plt.pcolormesh(Z)  plt.title('matplotlib.pyplot.pcolormesh() function Example', fontweight ="bold")plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm     dx, dy = 0.015, 0.05y, x = np.mgrid[slice(-4, 4 + dy, dy),                slice(-4, 4 + dx, dx)]z = (1 - x / 3. + x ** 6 + y ** 3) * np.exp(-x ** 2 - y ** 2)z = z[:-1, :-1]z_min, z_max = -np.abs(z).max(), np.abs(z).max()     c = plt.pcolormesh(x, y, z, cmap ='Greens', vmin = z_min, vmax = z_max)plt.colorbar(c)  plt.title('matplotlib.pyplot.pcolormesh() function Example', fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How to Create Subplots in Seaborn? - GeeksforGeeks

19 Dec, 2021
Prerequisites: Matplotlib, Seaborn
In this article, we will explore how to create a subplot or multi-dimensional plot in seaborn, It is a useful approach to draw subplot instances of the same plot on different subsets of your dataset. It allows a viewer to quickly extract a large amount of data about complex information. 
Example 1: Here, we are Initializing the grid without arguments returns a Figure and a single Axes.
Python3
import seaborn as snsimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt  figure, axes = plt.subplots()figure.suptitle('Geeksforgeeks - one axes with no data')
Output:
Example 2: In this example we create a plot with 1 row and 2 columns, still no data passed i.e. nrows and ncols. If given in this order, we don’t need to type the arg names, just its values. 
figsize set the total dimension of our figure.
sharex and sharey are used to share one or both axes between the charts.
Python3
figure, axes = plt.subplots(1, 2, sharex=True,                            figsize=(10, 5))figure.suptitle('Geeksforgeeks')axes[0].set_title('first chart with no data')axes[1].set_title('second chart with no data')
Output:
Example 3: Creating subpolt with many levels 
Python3
figure, axes = plt.subplots(3, 4, sharex=True,                            figsize=(16, 8))figure.suptitle('Geeksforgeeks - 3 x 4 axes with no data')
Output:
Example 4: A gridspec() is for a grid of rows and columns with some specified width and height space. The plt.GridSpec object does not create a plot by itself but it is simply a convenient interface that is recognized by the subplot() command.
Python3
import matplotlib.pyplot as plt  Grid_plot = plt.GridSpec(2, 3, wspace = 0.8,                        hspace = 0.6)  plt.subplot(Grid_plot[0, 0])plt.subplot(Grid_plot[0, 1:])plt.subplot(Grid_plot[1, :2])plt.subplot(Grid_plot[1, 2])
Output:
Example 4: Here we’ll create a 3×4 grid of subplot using subplots(), where all axes in the same row share their y-axis scale, and all axes in the same column share their x-axis scale
Python3
import matplotlib.pyplot as plt  figure, axes = plt.subplots(3, 4,                            figsize=(15, 10))  figure.suptitle('Geeksforgeeks - 2 x 3 axes\grid plot using subplots')
Output:
Picked
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python | Bitwise OR among List elements - GeeksforGeeks

27 Aug, 2019
Sometimes, while programming, we have a problem in which we might need to perform certain bitwise operations among list elements. This is an essential utility as we come across bitwise operations many times. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using reduce() + lambda + "|" operatorThe above functions can be combined to perform this task. We can employ reduce() to accumulate the result of OR logic specified by the lambda function. Works only with Python2.
# Python code to demonstrate working of# Bitwise OR among List elements# Using reduce() + lambda + "|" operator  # initializing listtest_list = [7, 8, 9, 1, 10, 7]  # printing original listprint("The original list is : " + str(test_list))  # Bitwise OR among List elements# Using reduce() + lambda + "|" operatorres = reduce(lambda x, y: x | y, test_list)  # printing result print("The Bitwise OR of list elements are : " + str(res))
The original list is : [7, 8, 9, 1, 10, 7]
The Bitwise OR of list elements are : 15

 
Method #2 : Using reduce() + operator.iorThis task can also be performed using this method. In this the task performed by lambda function in above method is performed using ior function for cumulative OR operation. Works with Python2 only.
# Python code to demonstrate working of# Bitwise OR among List elements# Using reduce() + operator.iorfrom operator import ior  # initializing listtest_list = [7, 8, 9, 1, 10, 7]  # printing original listprint("The original list is : " + str(test_list))  # Bitwise OR among List elements# Using reduce() + operator.iorres = reduce(ior, test_list)  # printing result print("The Bitwise OR of list elements are : " + str(res))
The original list is : [7, 8, 9, 1, 10, 7]
The Bitwise OR of list elements are : 15

Python list-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
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
NPDA for accepting the language L = {an bn cm | m,n>=1} - GeeksforGeeks

28 Aug, 2019
Prerequisite – Pushdown automata, Pushdown automata acceptance by final state
Problem – Design a non deterministic PDA for accepting the language L = {   | m, n>=1}, i.e.,
L = { abc, abcc, abccc,  aabbc, aaabbbcc, aaaabbbbccccc, ...... }

In each of the string, the number of a’s is equal to number of b’s. And the number of c’s is independent of the number of a’s and b’s. This problem is quite similar to the NPDA for accepting the language L = {   | n>=1 }. The only difference is that here we add .
Explanation –Here, we need to maintain the order of a’s, b’s and c’s.That is, all the a’s are coming first and then all the b’s and then c’s are coming. Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack. We will take 2 stack alphabets:
 = { a, z }

Where,  = set of all the stack alphabetz = stack start symbol
Approach used in the construction of PDA –As we want to design a NPDA, thus every time ‘a’ comes before ‘b’. When ‘a’ comes then push it in stack and if again ‘a’ comes then also push it. After that, when ‘b’ comes then pop one ‘a’ from the stack each time . Then for ‘c’, we will do nothing.So, at the end if the stack becomes empty then we can say that the string is accepted by the PDA.
Stack transition functions –
(q0, a, z)  (q0, az)
(q0, a, a)  (q0, aa)
(q0, b, a)  (q1,  )
(q1, b, a)  (q1,  )
(q1, c, z)  (qf, z )
(qf, c, z)  (qf, z )
        
Where, q0 = Initial stateqf = Final state = indicates pop operation
So, this is our required non deterministic PDA for accepting the language L = {   | m, n>=1 }
nidhi_biet
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
Difference between DFA and NFA
Regular expression to ∈-NFA
NPDA for accepting the language L = {wwR | w ∈ (a,b)*}
Design 101 sequence detector (Mealy machine)
Closure properties of Regular languages
JavaScript SyntaxError: Unterminated string literal - GeeksforGeeks

23 Jul, 2020
This JavaScript error unterminated string literal occurs if there is string which is not terminated properly. String literals must be enclosed by single (‘) or double (“) quotes.
Message:
SyntaxError: Unterminated string constant (Edge)
SyntaxError: unterminated string literal (Firefox)

Error Type:
SyntaxError
What happened?
There is  a string in the code which is not terminated. String literals needs to be enclosed by single (‘) or double (“) quotes. JavaScript sees no difference between single-quoted strings and double-quoted strings.
Example 1: In this example, the single quotes are used and the string is not terminated, So the error has occurred.
<!DOCTYPE html><html><head><title>Syntax Error</title></head><body>    <script>    var GFG_str = 'This                     is                      GeeksForGeeks';    document.write(GFG_str);    </script></body></html>
Output(In console):
SyntaxError: Unterminated string constant

Example 2: In this example, the double quotes are used and the string is not terminated, So the error has occurred.
<!DOCTYPE html><html><head><title>Syntax Error</title></head><body>    <script>    var GFG_str = "This                     is                      GeeksForGeeks";    document.write(GFG_str);    </script></body></html>
Output(In console):
SyntaxError: Unterminated string constant

JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Data Structures | Linked List | Question 8 - GeeksforGeeks

28 Jun, 2021
The following C function takes a single-linked list of integers as a parameter and rearranges the elements of the list. The function is called with the list containing the integers 1, 2, 3, 4, 5, 6, 7 in the given order. What will be the contents of the list after the function completes execution?
struct node {  int value;  struct node *next;};void rearrange(struct node *list){  struct node *p, * q;  int temp;  if ((!list) || !list->next)       return;  p = list;  q = list->next;  while(q)   {     temp = p->value;     p->value = q->value;     q->value = temp;     p = q->next;     q = p?p->next:0;  }}
(A) 1,2,3,4,5,6,7(B) 2,1,4,3,6,5,7(C) 1,3,2,5,4,7,6(D) 2,3,4,5,6,7,1Answer: (B)Explanation: The function rearrange() exchanges data of every node with its next node. It starts exchanging data from the first node itself.Quiz of this Question
Data Structures
Data Structures-Linked List
Linked Lists
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Tree Traversals | Question 4
Data Structures | Graph | Question 9
FIFO vs LIFO approach in Programming
Introduction to Data Structures
Binary Search Tree | Set 3 (Iterative Delete)
Advantages of vector over array in C++
Program to create Custom Vector Class in C++
Bit manipulation | Swap Endianness of a number
Data Structures | Heap | Question 12
Data Structures | Queue | Question 2
Isoformat to datetime - Python - GeeksforGeeks

14 Sep, 2021
In this article, we are going to see how to convert Isoformat to datetime in Python.
In this method, we are going to use fromisoformat() which converts the string into DateTime object.
Syntax: 
datetime.fromisoformatc(date)
Example: Converting isoformat to datetime
Python3
# importing datetime modulefrom datetime import datetime  # Getting today's datetodays_Date = datetime.now()  # Get date into the isoformatisoformat_date = todays_Date.isoformat()  # print the type of dateprint(type(isoformat_date))  # convert string date into datetime formatresult = datetime.fromisoformat(isoformat_date)print(type(result))
Output:
<class 'str'>
<class 'datetime.datetime'>
In this method, we will use this inbuilt Python library python-dateutil, The parse() method can be used to detect date and time in a string. 
Syntax: dateutil.parser.parse((isoformat_string)
Parameters: Isoformat_string: Str.
Return: Datetime object
Example: converting isoformat to datetime
Python3
# importing datetime modulefrom datetime import datetimeimport dateutil  # Getting today's datetodays_Date = datetime.now()isoformat_date = todays_Date.isoformat()  # display isoformat typeprint(type(isoformat_date))  # convert it into datetime and displayresult = dateutil.parser.parse(isoformat_date)print(type(result))
Output:
<class 'str'>
<class 'datetime.datetime'>
Picked
Python datetime-program
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
What are file operations in C#?

C# has the following file operations −
Create, open, read and write a file.
Append,
Delete, etc.
The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream.
You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows −
FileStream = new FileStream( <file_name>, <FileMode Enumerator>,
<FileAccess Enumerator>, <FileShare Enumerator>);
Here, the file operations are also included as shown below −
The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are −
Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist.
Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist.
Create − It creates a new file.
Create − It creates a new file.
CreateNew − It specifies to the operating system, that it should create a new file.
CreateNew − It specifies to the operating system, that it should create a new file.
Open − It opens an existing file.
Open − It opens an existing file.
OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file.
OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file.
Truncate − It opens an existing file and truncates its size to zero bytes.
Truncate − It opens an existing file and truncates its size to zero bytes.
FileAccess - The FileAccess enumerators have members −
Read,
ReadWrite and
Write.
FileShare - The FileShare enumerators have the following members −
Inheritable − It allows a file handle to pass inheritance to the child processes
Inheritable − It allows a file handle to pass inheritance to the child processes
None − It declines sharing of the current file
None − It declines sharing of the current file
Read − It allows opening the file for readin.
Read − It allows opening the file for readin.
ReadWrite − It allows opening the file for reading and writing
ReadWrite − It allows opening the file for reading and writing
Write − It allows opening the file for writing
Write − It allows opening the file for writing
Let us see an example to create, open and read the contents of a file −
 Live Demo
using System;
using System.IO;

namespace FileIOApplication {
   class Program {
      static void Main(string[] args) {
         FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate,
         FileAccess.ReadWrite);
         for (int i = 1; i <= 20; i++) {
            F.WriteByte((byte)i);
         }
         F.Position = 0;
         for (int i = 0; i <= 20; i++) {
            Console.Write(F.ReadByte() + " ");
         }
         F.Close();
         Console.ReadKey();
      }
   }
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1
How to find the index of an element in a vector in R?

There are three ways to find the index of an element in a vector.
> x <- sample(1:10)
> x
[1] 8 10 9 6 2 1 4 7 5 3
Using which
> which(x == 6)[[1]]
[1] 4
Here we found the index of 6 in vector x.
Using match
> match(c(4,8),x)
[1] 7 1
Here we found the index of 4 and 8 in vector x.
Using which with %in%
> which(x %in% c(2,4))
[1] 5 7
Here we found the index of 2 and 4 in vector x.
How to convert NFA with epsilon to DFA in TOC?

In this method, we first convert Non-deterministic finite automata (NFA) with ε to NFA without ε.
Then, NFA without ε- can be converted to its equivalent Deterministic Finite Automata (DFA).
The method for converting the NFA with ε to DFA is explained below −
Step 1 − Consider M={Q, Σ, δ,q0,F) is NFA with ε. We have to convert this NFA with ε to equivalent DFA denoted by
M0=(Q0,Σ, δ0,q0,F0)
Then obtain,
ε-closure(q0) ={p1,p2,p3,......pn}
then [p1,p2,p2,....pn] becomes a start state of DFA
now[p1,p2,p3,....pn] ∈ Q0
Step 2 − We will obtain δ transition on [p1,p2,p3,...pn] for each input.
δ 0([p1,p2,p3,..pn],a) = ε-closure(δ(p1,a) U δ(p2,a2)U.................. δ(pn,a))
= U (i=1 to n) ε-closure d(pi,a)
Where a is input ∈Σ
Step 3 − The state obtained [p1,p2,p3,...pn] ∈ Q0 .
The states containing final state in pi is a final state in DFA
Convert the following NFA with epsilon to equivalent DFA
Consider the following NFA for conversion of NFA with epsilon to DFA −
To convert this NFA with epsilon, we will first find the ε-closures, as given below −
ε-closure(q0)={q0,q1,q2}
ε-closure(q1)={q1,q2}
ε-closure(q2)={q2}
Let us start from ε-closure of start state, as mentioned below −
When, ε-closure(q0)={q0,q1,q2}, we will call this state as A.
Now, let us find transition on A with every input symbol, as shown below −
δ'(A, a) = ε-closure(δ(A,a))
   = ε-closure(δ(q0,q1,q2), a))
   = ε-closure(δ(q0, a) ∪ δ(q1,a) U δ(q2,a) )
   = ε-closure(ΦUq1 ∪q2)
   = ε-closure(q1)
   = {q1, q2} let us call it as state B
δ'(A, b) = ε-closure(δ(A,b))
   = ε-closure(δ(q0,q1,q2), b))
   = ε-closure(δ(q0, b) ∪ δ(q1,b) U δ(q2,b) )
   = ε-closure(q0 U Φ∪q0)
   = ε-closure(q0)
   = {q0,q1, q2} its nothing but state A
δ'(B, a) = ε-closure(δ(B,a))
   = ε-closure(δ(q1,q2), a))
   = ε-closure(δ(q1,a) U δ(q2,a) )
   = ε-closure(q1 ∪q2)
   = ε-closure(q1)
   = {q1, q2} its nothing but state B
δ'(B, b) = ε-closure(δ(B,b))
   = ε-closure(δ(q1,q2), b))
   = ε-closure(δ(q1,b) U δ(q2,b) )
   = ε-closure(Φ∪q0)
   = ε-closure(q0)
   = {q0,q1, q2} its nothing but state A
Hence, the transition table for the generated DFA is as follows −
The DFA diagram is as follows −
As, A={q0,q1,q2} in which the final state q2 lies. Hence, A is the final state.
In B ={q1,q2} the state q2 lies. Hence, B is also the final state.
Concurrent Program with Precedence Graph - GeeksforGeeks

26 Oct, 2020
In this article, we are going to cover the Concurrent Program in the Operating System and will make a Precedence Graph for the program, and will cover the program execution for the same.
In concurrent programming, the Real concurrent program is possible on the multiprocessor system. Any two statements Si and Sj can be executed concurrently or parallel if they are following the below condition.
Read set(Si) ∩ Write set(Sj) = φ
Write set(Si) ∩ Read set(Sj) = φ
Write set(Si) ∩ Write set(Sj) = φ
In concurrent programming “Concurrent” word has a different meaning.
They can execute concurrently or parallel.
They do not have any dependency.
Anyone can start first.
Example –Let us consider the following expression –
S1: p = q+r;
S2: s = t×u;
S3: v = w/x;
S4: y = z×a;
Read Set and Write set for the above expression as follows –
Read Set = {q, r, t, u, w, x, z, a}
Write Set ={p, s, v, y}
Precedence Graph for the read and write set as follows –
In concurrent programming, it will be done or return by using the following statement given below –
par begin - par end
or 
Co begin - Co end 
Concurrent program for Precedence Graph :
Let us consider the following Precedence Graph given below –
Concurrent program for the given precedence graph as follows –
begin 
    S1:
    par begin 
        begin
            S2;
            S6;
        end
        begin
            S3;
            S7;
        end
            S4;
            S5;
    par end
            S8;
end
Process Synchronization
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Memory Management in Operating System
File Allocation Methods
Logical and Physical Address in Operating System
File Access Methods in Operating System
Difference between Internal and External fragmentation
Memory Hierarchy Design and its Characteristics
Process Table and Process Control Block (PCB)
File Systems in Operating System
States of a Process in Operating Systems
Introduction of Process Management