code-rag-bench/online-tutorials huggingface dataset:
Multiple Density Plots with Pandas in Python - GeeksforGeeks

03 Jan, 2021
Multiple density plots are a great way of comparing the distribution of multiple groups in your data.  We can make multiple density plots using pandas plot.density() function. However, we need to convert data in a wide format if we are using the density function. Wide data represents different groups in different columns. We convert data in a wide format using Pandas pivot() function.
Let’s create the simple data-frame and then reshape it into a wide-format:
Example 1:
Here we are using this data set.
Step 1: Creating dataframe from data set.
Python3
import pandas as pd  # creating a dataframedf = pd.read_csv(r"gapminder1.csv")df.head()
Output: 
dataset
Step 2: Let’s group data according to countries in different columns so that we can apply the density() function to plot multiple density plots.
Python3
# converting data into wide-formatdata_wide = df.pivot(columns='continent',                     values='lifeExp')data_wide.head()
Output: 
Step 3: Now let’s plot multiple density plot using plot.density()
Python3
import matplotlib.pyplot as plt  # calling density() to make# multiple density plot data_wide.plot.density(figsize = (7, 7),                       linewidth = 4)  plt.xlabel("life_Exp")
Output :
Multiple density plots
Example 2: We can also call plot.kde() function on dataframe to make multiple density plots with Pandas.
Here we are using the tips dataset for this example, You can find it here.
Step 1: Creating dataframe from data set.
Python3
import pandas as pd  # creating a dataframedf = pd.read_csv(r"tips.csv")df.head()
Output:
tips_df
Step 2: Now apply pivot() function to have dataframe in the wide-format then apply kde() to have multiple density plot. 
Python3
# Converting to wide dataframedata_wide = df.pivot(columns = 'day',                     values = 'total_bill')  # plotting multiple density plotdata_wide.plot.kde(figsize = (8, 6),                   linewidth = 4)
Output:
tips multiple D.P
Picked
Python pandas-plotting
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 ?
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()
PHP | base64_decode() Function - GeeksforGeeks

08 Jul, 2021
The base64_decode() is an inbuilt function in PHP which is used to Decodes data which is encoded in MIME base64.Syntax:  
string base64_decode( $data, $strict )
Parameters: This function accepts two parameter as mentioned above and described below:  
$data: It is mandatory parameter which contains the encoded string.
$strict: It is an optional parameter. If this parameter is set to TRUE then the base64_decode() function will return FALSE if the input contains character from outside the base64 alphabet. Invalid characters will be silently discarded.
Return value: This function returns the decoded string on success or returns False in case of failure.Below programs illustrate the base64_decode() function in PHP:Program 1:  
php
<?php // Program to illustrate base64_decode()// function$str = 'R2Vla3Nmb3JHZWVrcw=='; echo base64_decode($str);?>
GeeksforGeeks
 
Program 2:  
php
<?php // Program to illustrate base64_decode()// function$str = 'R0ZHLCBBIGNvbXB1dGVyIFNjaWVuY2UgUG9ydGFsIEZvciBHZWVrcw';echo base64_decode($str). "\n"; $str = 'MQ==';echo base64_decode($str). "\n";?>
GFG, A computer Science Portal For Geeks
1
 
Reference: http://php.net/manual/en/function.base64-decode.php 
adnanirshad158
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to receive JSON POST with 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 ?
How to insert spaces/tabs in text using HTML/CSS?
Python - Get the indices of Uppercase characters in given string - GeeksforGeeks

02 Sep, 2020
Given a String extract indices of uppercase characters.
Input : test_str = ‘GeeKsFoRGeeks’Output : [0, 3, 5, 7, 8]Explanation : Returns indices of uppercase characters.
Input : test_str = ‘GFG’Output : [0, 1, 2]Explanation : All are uppercase.
Method #1 : Using list comprehension  + range() + isupper()
In this we iterate through the indices till string length, and check for uppercase character using isupper(), if found, index is recorded.
Python3
# Python3 code to demonstrate working of # Uppercase Indices# Using list comprehension + range() + isupper()  # initializing stringtest_str = 'GeeKsFoRGEEks'  # printing original stringprint("The original string is : " + str(test_str))  # Uppercase check using isupper()res = [idx for idx in range(len(test_str)) if test_str[idx].isupper()]  # printing result print("Uppercase elements indices : " + str(res)) 
The original string is : GeeKsFoRGEEks
Uppercase elements indices : [0, 3, 5, 7, 8, 9, 10]

Method #2 : Using enumerate() + isupper()
In this, the indices are captured using enumerate(), and isupper() does task of uppercase check as in above method.
Python3
# Python3 code to demonstrate working of # Uppercase Indices# Using enumerate() + isupper()  # initializing stringtest_str = 'GeeKsFoRGEEks'  # printing original stringprint("The original string is : " + str(test_str))  # Uppercase check using isupper()# enumerate() gets indicesres = [idx for idx, chr in enumerate(test_str) if chr.isupper()]  # printing result print("Uppercase elements indices : " + str(res)) 
The original string is : GeeKsFoRGEEks
Uppercase elements indices : [0, 3, 5, 7, 8, 9, 10]

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 ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
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?
Optional Class | isPresent() function - GeeksforGeeks

22 Feb, 2018
The isPresent() function in Optional Class is used to evaluate whether the value if assigned to variable is present or not.
Syntax
value.isPresent()
Returns:
It returns true if value is assigned otherwise false 

Examples:
Input : Optional value1 = Optional.ofNullable(10);
        value1.isPresent()
Output : True

Input : Optional value2 = Optional.ofNullable(null);
        value2.isPresent()
Output : False

// Write Java code hereimport java.util.Optional;public class present {public static void main(String args[]) {      // Optional.ofNullable - allows passed    // parameter to be not null.    Optional<Integer> value1 = Optional.ofNullable(10);      // Optional.ofNullable - allows passed    // parameter to be null.    Optional<Integer> value2 = Optional.ofNullable(null);    System.out.println("First parameter is present:" +                        value1.isPresent());    System.out.println("Second parameter is present:" +                        value2.isPresent());}}
Output : true
Output : false

Java - util package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
POSITION() function in MySQL - GeeksforGeeks

04 Dec, 2020
POSITION() : 
This function in MySQL is used for finding the location of a substring in a string. It will return the location of the first occurrence of the substring in the string. If the substring is not present in the string then it will return 0. When searching for the location of a substring in a string then the function does not perform a case-sensitive search.
Syntax :
POSITION(substring IN string)
Parameters :
This method accepts two parameters 
substring – The string whose position is to be retrieved.
string – The string within which the position of the substring is to be retrieved.
Returns :
The location of the first occurrence of the substring in the string.
Example-1 : 
Searching the String ‘g’ in the string ‘geeksforgeeks’ with the help of the POSITION Function as follows.
SELECT POSITION('g' IN 'geeksforgeeks') AS location;
Output :
Example-2 : 
Searching the String ‘this’ in the string ‘That is a tree’ with the help of the POSITION Function as follows.
SELECT POSITION('this' IN 'That is a tree') AS location;
Output :
Example-3 :
POSITION Function can also be used on column data as follows.  
Creating a Student table :
CREATE TABLE Student
(
Student_id INT AUTO_INCREMENT,  
Student_name VARCHAR(100) NOT NULL,
Roll INT NOT NULL,
Department VARCHAR(10) NOT NULL,
PRIMARY KEY(Student_id )
);
Inserting data into the Table :
INSERT INTO Student
(Student_name ,Roll, Department )
VALUES
('Anik Biswas ',10100,'CSE'),
('Bina Mallick', 11000,'ECE' ),
('Niket Sharma', 12000,'IT' ),
('Sayani Samanta',13000, 'ME'  ),
('Riyanka Shah ', 14000,'EE' ), 
('Bipin Kohli', 15000,'CE' );
To verify used the following command as follows.
SELECT  * from Student ;
Output :
Now we are going to find the first occurrence of the string ‘a’ for every student’s name.
SELECT *,POSITION('a' IN Student_name ) AS First_Occ_A  
FROM STUDENT;
Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
How to Filter DataFrame Rows Based on the Date in Pandas? - GeeksforGeeks

24 Jan, 2021
Filtering a DataFrame rows by date selects all rows which satisfy specified date constraints, based on a column containing date data. For instance, selecting all rows between March 13, 2020, and December 31, 2020, would return all rows with date values in that range.
Use DataFrame.loc() with the indexing syntax [condition] to select only the rows from DataFrame which satisfy condition.Define condition to check if the date column in DataFrame is within the constraints.It will create a boolean array for all the rows. Only rows having true value will be printed.
Refer below examples. Download the Dataframe from here.
 Approach:
Convert the data column into date format supported by python
Filter the rows on the basis of date
Access rows using .loc() function and store them in dataframe.
Example 1:
Python3
# import pandas libraryimport pandas as pd  # load csv filedf = pd.read_csv(    "C:\\Users\\Rohan\\OneDrive\\Desktop\\GFG\\netflix_titles.csv")  # convert date column into date formatdf['date_added'] = pd.to_datetime(df['date_added'])  # filter rows on the basis of datenewdf = (df['date_added'] > '01-03-2020') & (df['date_added'] <= '31-12-2020')  # locate rows and access them using .loc() functionnewdf = df.loc[newdf]  # print dataframeprint(newdf)
Output:
All the movies between date 13-Mar-2020 and 31-Dec-2020 will be printed.
Example 2:
Python3
# import pandas libraryimport pandas as pd  # load csv filedf = pd.read_csv(    "C:\\Users\\Rohan\\OneDrive\\Desktop\\GFG\\netflix_titles.csv")  # convert date column into date formatdf['date_added'] = pd.to_datetime(df['date_added'])  # filter rows on the basis of datenewdf = (df['date_added'] > '01-01-2019') & (df['date_added'] <= '31-12-2019')  # locate rows and access them using .loc() functionnewdf = df.loc[newdf]  # print dataframeprint(newdf)
Output:
The above output prints all the movies added on Netflix in the year 2019.
Picked
Python pandas-dataFrame
Python pandas-datetime
Python Pandas-exercise
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 ?
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 | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Python – Unique value keys in a dictionary with lists as values

08 May, 2020
Sometimes, while working with Python dictionaries, we can have problem in which we need to extract keys with values that are unique (there should be at least one item not present in other lists), i.e doesn’t occur in any other key’s value lists. This can have applications in data preprocessing. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + count()The combination of above functionalities can be used to solve this problem. In this, we perform the task of counting occurrence using count and extraction and testing is done using loop using conditional statement.
# Python3 code to demonstrate working of # Unique Keys Values# Using loop + count()  # initializing dictionarytest_dict = {'Gfg' : [6, 5], 'is' : [6, 10, 5], 'best' : [12, 6, 5]}   # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Unique Keys Values# Using loop + count()temp = [sub for ele in test_dict.values() for sub in ele]res = []for key, vals in test_dict.items():    for val in vals:        if temp.count(val) == 1:            res.append(key)            break  # printing result print("The unique values keys are : " + str(res)) 
The original dictionary is : {'Gfg': [6, 5], 'best': [12, 6, 5], 'is': [6, 10, 5]}
The unique values keys are : ['best', 'is']

 
Method #2 : Using list comprehension + any() + count()The combination of above functions can be used to perform this task. In this, we check for the unique elements using any() and count(). This is one liner way in which this task can be performed.
# Python3 code to demonstrate working of # Unique Keys Values# Using list comprehension + any() + count()  # initializing dictionarytest_dict = {'Gfg' : [6, 5], 'is' : [6, 10, 5], 'best' : [12, 6, 5]}   # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Unique Keys Values# Using list comprehension + any() + count()res = [key for key, vals in test_dict.items() if any([ele for sub in test_dict.values()       for ele in set(sub)].count(idx) == 1 for idx in vals)]  # printing result print("The unique values keys are : " + str(res)) 
The original dictionary is : {'Gfg': [6, 5], 'best': [12, 6, 5], 'is': [6, 10, 5]}
The unique values keys are : ['best', 'is']

Python dictionary-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Parallel matrix-vector multiplication in NumPy

23 Sep, 2021
In this article, we will discuss how to do matrix-vector multiplication in NumPy.
For a matrix-vector multiplication, there are certain important points:
The end product of a matrix-vector multiplication is a vector.
Each element of this vector is obtained by performing a dot product between each row of the matrix and the vector being multiplied.
The number of columns in the matrix is equal to the number of elements in the vector.
# a and b are matrices
prod = numpy.matmul(a,b)
For matrix-vector multiplication, we will use np.matmul() function of NumPy, we will define a 4 x 4 matrix and a vector of length 4.
Python3
import numpy as np  a = np.array([[1, 2, 3, 13],              [4, 5, 6, 14],              [7, 8, 9, 15],              [10, 11, 12, 16]])  b = np.array([10, 20, 30, 40])  print("Matrix a =", a)print("Matrix b =", b)print("Product of a and b =",      np.matmul(a, b))
Output:
We use the dot product to do matrix-matrix multiplication. We will use the same function for this also.
prod = numpy.matmul(a,b)  # a and b are matrices
For a matrix-matrix multiplication, there are certain important points:
The number of columns in the first matrix should be equal to the number of rows in the second matrix.
If we are multiplying a matrix of dimensions m x n with another matrix of dimensions n x p, then the resultant product will be a matrix of dimensions m x p
We will define two 3 x 3 matrix:
Python3
import numpy as np  a = np.array([[1, 2, 3],              [4, 5, 6],              [7, 8, 9]])  b = np.array([[11, 22, 33],              [44, 55, 66],              [77, 88, 99]])  print("Matrix a =", a)print("Matrix b =", b)print("Product of a and b =", np.matmul(a, b))
Output:
Picked
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
YAML Comments

14 Dec, 2020
YAML_Comments
Comments are used to prevent the execution of statements. Comments are ignored while the compiler executes the code. Comments are user-friendly as user can get explanations of code using comments.
Since you are alright with the sentence structure and fundamentals of YAML, let us continue further into its details. In this part, we will perceive how to utilize comment in YAML. Comment are utilized to depict meaningful message about life of code.  
There are two kinds of Comments.  
Inline or single line commentBlock level comment
Inline or single line comment
Block level comment
YAML has the language structure uphold for inline remarks, yet not for block level Comment  
Inline comment: Inline comments are remarks proclaimed at the line of code, Hashtag image is utilized toward the beginning of the line to tell processor that it is comment.
Example:
# remarks Punctuation model in YAML document  
or
#### #### comment model
These just determines as single line Comments. Each line of comment begins with hashtag image and clear space followed by portrayal. Each line ends with new line break.  
Block level Comment: Square Comments are to remark the various lines. YAML has no help for block Comment naturally, you can utilize numerous inline Comment  
# block level Comment model  
# Comment line 1  
# Comment line 2  
# Comment  line 3
Significant notes of Comment in YAML: Comments are disregarded by yaml processor. It is helpful to report about the line of code, empowers designers life is straightforward, help easy route orders by various IDE
YAML underpins single line comment. Its structure is clarified beneath with the assistance of a model −
# This is single line comment.
Highlights of comments: The highlights of comments in YAML are given underneath –
A commented block is skipped during the execution of code.
Comments help to add portrayal for determined code block.
Comments must not show up inside scalars.
YAML does exclude any approach to get away from the hash image (#) so inside multi-line string it is highly unlikely to isolate the comment from the crude string esteem.
Example:
#comment 1
- Value line 1

#comment 2
- value line 2

#comment 3
- value line 3
The alternate way key mix for commenting YAML blocks is Ctrl+Q.
Note: The similar advances are suitable on the off chance. It is constantly prescribed to utilize Superb Word processor for making YAML documents as it upheld by most working frameworks and incorporates engineer neighborly easy route keys.
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Display images with PyGame

08 Jan, 2019
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit.
Command to install pygame :
pip install pygame

There are four basic steps to displaying images on the pygame window :
Create a display surface object using display.set_mode() method of pygame.
Create a Image surface object i.e.surface object in which image is drawn on it, using image.load() method of pygame.
Copy the image surface object to the display surface object using blit() method of pygame display surface object.
Show the display surface object on the pygame window using display.update() method of pygame.
Now, let’s see the code displaying image using pygame :
# import pygame module in this programimport pygame  # activate the pygame library .# initiate pygame and give permission# to use pygame's functionality.pygame.init()  # define the RGB value# for white colourwhite = (255, 255, 255)  # assigning values to X and Y variableX = 400Y = 400  # create the display surface object# of specific dimension..e(X, Y).display_surface = pygame.display.set_mode((X, Y ))  # set the pygame window namepygame.display.set_caption('Image')  # create a surface object, image is drawn on it.image = pygame.image.load(r'C:\Users\user\Pictures\geek.jpg')  # infinite loopwhile True :      # completely fill the surface object    # with white colour    display_surface.fill(white)      # copying the image surface object    # to the display surface object at    # (0, 0) coordinate.    display_surface.blit(image, (0, 0))      # iterate over the list of Event objects    # that was returned by pygame.event.get() method.    for event in pygame.event.get() :          # if event object type is QUIT        # then quitting the pygame        # and program both.        if event.type == pygame.QUIT :              # deactivates the pygame library            pygame.quit()              # quit the program.            quit()          # Draws the surface object to the screen.          pygame.display.update()              
Output :
Python-PyGame
python-utility
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python - WordNet Interface

WordNet is a dictionary of English, similar to a traditional thesaurus NLTK includes the English WordNet. We can use it as a reference for getting the meaning of words, usage example and definition. A collection of similar words is called lemmas. The words in WordNet are organized and nodes and edges where the nodes represent the word text and the edges represent the relations between the words. below we will see how we can use the WordNet module.
 
from nltk.corpus import wordnet as wn
res=wn.synset('locomotive.n.01').lemma_names()
print res
When we run the above program, we get the following output −
[u'locomotive', u'engine', u'locomotive_engine', u'railway_locomotive']

The dictionary definition of a word can be obtained by using the definition function. It describes the meaning of the word as we can find in a normal dictionary.
from nltk.corpus import wordnet as wn
resdef = wn.synset('ocean.n.01').definition()
print resdef
When we run the above program, we get the following output −
a large body of water constituting a principal part of the hydrosphere

We can get the example sentences showing some usage examples of the words using the exmaples() function.
from nltk.corpus import wordnet as wn
res_exm = wn.synset('good.n.01').examples()
print res_exm
When we run the above program we get the following output −
['for your own good', "what's the good of worrying?"]

Get All the opposite words by using the antonym function. 
from nltk.corpus import wordnet as wn
# get all the antonyms
res_a = wn.lemma('horizontal.a.01.horizontal').antonyms()
print res_a
When we run the above program we get the following output −
[Lemma('inclined.a.02.inclined'), Lemma('vertical.a.01.vertical')]


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
C# | Identifiers - GeeksforGeeks

07 Jul, 2021
In programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name or label. Example:  
public class GFG {
    static public void Main () 
    {
          int x;
    }
}
Here the total number of identifiers present in the above example is 3 and the names of these identifiers are:  
GFG: Name of the class
Main: Method name
x: Variable name
Rules for defining identifiers in C#:There are certain valid rules for defining a valid C# identifier. These rules should be followed, otherwise, we will get a compile-time error.  
The only allowed characters for identifiers are all alphanumeric characters([A-Z], [a-z], [0-9]), ‘_‘ (underscore). For example “geek@” is not a valid C# identifier as it contain ‘@’ – special character.
Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid in C# identifier.
Identifiers should not contain white spaces. 
Identifiers are not allowed to use as keyword unless they include @ as a prefix. For example, @as is a valid identifier, but “as” is not because it is a keyword.
C# identifiers allow Unicode Characters.
C# identifiers are case-sensitive.
C# identifiers cannot contain more than 512 characters.
Identifiers does not contain two consecutive underscores in its name because such types of identifiers are used for the implementation.
Example: 
CSharp
// Simple C# program to illustrate identifiersusing System; class GFG {     // Main Method    static public void Main()    {         // variable        int a = 10;        int b = 39;        int c;         // simple addition        c = a + b;        Console.WriteLine("The sum of two number is: {0}", c);    }}
Output:  
The sum of two number is: 49
Below table shows the identifiers and keywords present in the above example: 
 
onidavid97
shubham_singh
kapoorsagar226
abhishek0719kadiyan
CSharp-Basics
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# | IsNullOrEmpty() Method
C# | How to check whether a List contains a specified element
String.Split() Method in C# with Examples
C# | Arrays of Strings
Difference between Ref and Out keywords in C#
C# | Delegates
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
C# | Abstract Classes
Erlang - Lists

The List is a structure used to store a collection of data items. In Erlang, Lists are created by enclosing the values in square brackets.
Following is a simple example of creating a list of numbers in Erlang.
-module(helloworld). 
-export([start/0]). 

start() -> 
   Lst1 = [1,2,3], 
   io:fwrite("~w~n",[Lst1]).
The output of the above example will be −
[1 2 3]

Let us now discuss the various methods available for Lists. Note that the lists library needs to be imported for these methods to work.
all
Returns true if Pred(Elem) returns true for all elements Elem in List, otherwise false.
any
Returns true if Pred(Elem) returns true for at least one element Elem in List.
append
Returns a new list List3 which is made from the elements of List1 followed by the elements of List2.
delete
Deletes an element from the list and returns a new list.
droplast
Drops the last element of a List.
duplicate
Returns a list which contains N copies of the term Elem
last
Returns the last element of the list
max
Returns the element of the list which has the maximum value.
member
Checks if an element is present in the list or not.
min
Returns the element of the list which has the minimum value.
merge
Returns the sorted list formed by merging all the sub-lists of ListOfLists.
nth
Returns the Nth element of List.
nthtail
Returns the Nth tail of the List.
reverse
Reverses a list of elements.
sort
Sorts a list of elements.
sublist
Returns a sublist of elements.
sum
Returns the sum of elements in the list.
 Print
 Add Notes
 Bookmark this page
How to convert a String to an enum in Java?

The valueOf() method of the Enum class in java accepts a String value and returns an enum constant of the specified type.
Let us create an enum with name Vehicles with 5 constants representing models of 5 different scoters with their prices as values, as shown below −
enum Vehicles {
   //Constants with values
   ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000); //Instance variable
   private int price;
   //Constructor to initialize the instance variable
   Vehicles(int price) {
      this.price = price;
   }
   //Static method to display the price
   public int getPrice(){
      return this.price;
   }
}
The following Java program, accepts a String value from the user, converts it into an enum constant of the type Vehicles using the valueOf() method and, displays the value (price) of the selected constant.
public class EnumerationExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Available scoters: [activa125, activa5g, access125, vespa, tvsjupiter]");
      System.out.println("Enter the name of required scoter: ");
      String name = sc.next();
      Vehicles v = Vehicles.valueOf(name.toUpperCase());
      System.out.println("Price: "+v.getPrice());
   }
}
Available scoters: [activa125, activa5g, access125, vespa, tvsjupiter]
Enter the name of required scoter:
activa125
Price: 80000
How to blur an image using Node Jimp blur() function?

NodeJS – Blur() is an inbuilt function that is used to blur images. The effect produced by JIMP blur() will be similar to that of the Gaussian blur. It blurs based on the pixels input.
blur(r, cb)
r – It takes the input for blur and blurs based upon the pixels. If r is 2, it will blur 2 pixels at a time.
r – It takes the input for blur and blurs based upon the pixels. If r is 2, it will blur 2 pixels at a time.
cb – This is an optional parameter that can be invoked after the compilation is complete.
cb – This is an optional parameter that can be invoked after the compilation is complete.
Before proceeding to use blur() functions, please check that the following statements arealready executed for setting up the environment.
npm init -y // Initialising the Node environment
npm init -y // Initialising the Node environment
npm install jimp --save // Installing the jimp dependency
npm install jimp --save // Installing the jimp dependency
Create a blur.js file and copy-paste the following code snippet in it.
Create a blur.js file and copy-paste the following code snippet in it.
Use node blur.js to run the code.
Use node blur.js to run the code.
Note – Note that the method name should match with the JS file name. Only then it will be able to call the desired method.
const Jimp = require('jimp') ;

async function blur() { // Function name is same as of file name
   // Reading Image
   const image = await Jimp.read
   ('/home/jimp/tutorials_point_img.jpg');
   image.blur(3)
   .write('/home/jimp/blur.jpg');
}

blur(); // Calling the function here using async
console.log("Image is processed successfully");
const Jimp = require('jimp') ;

async function blur() {
   // Reading Image
   const image = await Jimp.read
   ('/home/jimp/tutorials_point_img.jpg');
   image.blur(7, function(err){
      if (err) throw err;
   })
   .write('/home/jimp/blur.jpg');
}

blur();
console.log("Image is processed successfully");
Python - Edit objects inside tuple - GeeksforGeeks

03 Jun, 2020
Sometimes, while working with tuples, being immutable, can offer a lot of confusion regarding its working. One of the questions that can pop from mind is, that Are objects inside tuples mutable?. The answer to this is Yes. Let’s discuss certain ways in which this can be achieved.
Method #1 : Using Access methodsThis is one of the way in which edit inside objects of tuples can be performed. This occurs similar to any other container and inplace using list access method.
# Python3 code to demonstrate working of # Edit objects inside tuple# Using Access Methods  # initializing tupletest_tuple = (1, [5, 6, 4], 9, 10)  # printing original tupleprint("The original tuple : " + str(test_tuple))  # Edit objects inside tuple# Using Access Methodstest_tuple[1][2] = 14         # printing result print("The modified tuple : " + str(test_tuple)) 
The original tuple : (1, [5, 6, 4], 9, 10)
The modified tuple : (1, [5, 6, 14], 9, 10)

 
Method #2 : Using pop() + index()The combination of above functionalities can also be used to solve this problem. In this, we perform task of removak using pop() and add element at particular index using index().
# Python3 code to demonstrate working of # Edit objects inside tuple# Using pop() + index()  # initializing tupletest_tuple = (1, [5, 6, 4], 9, 10)  # printing original tupleprint("The original tuple : " + str(test_tuple))  # Edit objects inside tuple# Using pop() + index()test_tuple[1].pop(2)test_tuple[1].insert(2, 14)        # printing result print("The modified tuple : " + str(test_tuple)) 
The original tuple : (1, [5, 6, 4], 9, 10)
The modified tuple : (1, [5, 6, 14], 9, 10)

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
C++ Program to Check Whether a Number is Prime or Not

A prime number is a whole number that is greater than one and the only factors of a prime number should be one and itself. Some of the first prime numbers are −
2, 3, 5, 7, 11, 13 ,17
The program to check if a number is prime or not is as follows.
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int n=17, i, flag = 0;
   for(i=2; i<=n/2; ++i) {
      if(n%i==0) {
         flag=1;
         break;
      }
   }
   if (flag==0)
   cout<<n<<" is a prime number";
   else
   cout<<n<<" is not a prime number";
   return 0;
}
17 is a prime number
In the above program, there is a loop that runs from 2 to half of n, where n is the number to be determined. Each of the values of the loop divide n. If the remainder of this division is 0, that means n is divisible by a number, not one or itself. So, it is not a prime number and the flag is set to 1. Then break statement is used to exit the loop.
for(i=2; i<=n/2; ++i) {
   if(n%i==0) {
      flag=1;
      break;
   }
}
If the value of flag remained zero, then the number is a prime number and that is displayed. If the value of flag was changed to one, then the number is not a prime number and that is displayed.
if (flag==0)
cout<<n<<" is a prime number";
else
cout<<n<<" is not a prime number";
Matplotlib.pyplot.autoscale() in Python - GeeksforGeeks

23 Jun, 2020
Matplotlib is a widely used library in Python for plotting various graphs, as it provides very efficient ways and easy to understand methods for complex plots also. matplotlib.pyplot is a plotting library used for 2D graphics in Python programming language. Pyplot is a collection of command style functions that make matplotlib work like MATLAB.
matplotlib.pyplot.autoscale() is a method for simple axis view autoscaling. It turns autoscaling on or off, and then, if autoscaling for either axis is on, it performs the autoscaling on the specified axis or axes.
Syntax: matplotlib.pyplot.autoscale(enable=True, axis=’both’, tight=None)
Parameters:enable is a Boolean valued parameter, if it is set to True the autoscaling is on else auto-scaling is off. It is an optional parameter. When not specified, it takes the default value as ‘true’.axis is another optional parameter which states that axis to operate on. Usually it can be ‘both’, ‘x’, or ‘y’. When not specified, it takes default value as ‘both’.tight takes the boolean argument, If True, first set the margins to zero. Then, this argument is forwarded to autoscale_view (regardless of its value). This is also an optional parameter of the autoscale method.
Example 1:
# importing the required module import matplotlib.pyplot as plt   # x axis values x = [1,2,3]   # corresponding y axis values y = [2,4,1]   # plotting the points plt.plot(x, y)   # naming the x axis plt.xlabel('x - axis')   # naming the y axis plt.ylabel('y - axis')   plt.autoscale() plt.show() 
Output:
Example 2:
import numpy as npimport matplotlib.pyplot as plt    x, y = np.arange(0, 101, 1), 300 - 0.1 * np.arange(0, 101, 1)mask = (x >= 50) & (x <= 100)  fig, ax = plt.subplots()ax.scatter(x[mask], y[mask])  plt.autoscale()plt.show()
Output:
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Python - Poisson Distribution

A Poisson distribution is a distribution which shows the likely number of times that an event will occur within a pre-determined period of time. It is used for independent events which occur at a constant rate within a given interval of time. The Poisson distribution is a discrete function, meaning that the event can only be measured as occurring or not as occurring, meaning the variable can only be measured in whole numbers.
We use the seaborn python library which has in-built functions to create such probability distribution graphs. Also the scipy package helps is creating the binomial distribution.
from scipy.stats import poisson
import seaborn as sb

data_binom = poisson.rvs(mu=4, size=10000)
ax = sb.distplot(data_binom,
                  kde=True,
                  color='green',
                  hist_kws={"linewidth": 25,'alpha':1})
ax.set(xlabel='Poisson', ylabel='Frequency')
Its output is as follows −

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Python Dictionary popitem() method

04 Oct, 2021
Python dictionary popitem() method removes the last inserted key-value pair from the dictionary and returns it as a tuple.
Syntax : dict.popitem() 
Parameters : None 
Returns : A tuple containing the arbitrary key-value pair from dictionary. That pair is removed from dictionary. 
Generating a random number has many applications in daily life. In a list, various functions are supported for the same. A whole library is dedicated to Python to handle random numbers. But sometimes, we need to perform a similar task with a dictionary.
Note: popitem() method return keyError if dictionary is empty.
Here we are going to use python dict to popitem at last element.
Python3
# Python 3 code to demonstrate# working of popitem() # initializing dictionarytest_dict = {"Nikhil": 7, "Akshat": 1, "Akash": 2} # Printing initial dictprint("The dictionary before deletion : " + str(test_dict)) # using popitem() to return + remove arbitrary# pairres = test_dict.popitem() # Printing the pair returnedprint('The arbitrary pair returned is : ' + str(res)) # Printing dict after deletionprint("The dictionary after removal : " + str(test_dict))
Output : 
The dictionary before deletion : {'Nikhil': 7, 'Akshat': 1, 'Akash': 2}
The arbitrary pair returned is : ('Akash', 2)
The dictionary after removal : {'Nikhil': 7, 'Akshat': 1}
Practical Application: This particular function can be used to formulate the random name for playing a game or deciding the random ranklist without using any random function.
Python3
# Python 3 code to demonstrate# application of popitem() # initializing dictionarytest_dict = {"Nikhil": 7, "Akshat": 1, "Akash": 2} # Printing initial dictprint("The dictionary before deletion : " + str(test_dict)) n = len(test_dict) # using popitem to assign ranksfor i in range(0, n):    print("Rank " + str(i + 1) + " " + str(test_dict.popitem())) # Printing end dictprint("The dictionary after deletion : " + str(test_dict))
Output : 
The dictionary before deletion : {'Nikhil': 7, 'Akshat': 1, 'Akash': 2}
Rank 1 ('Akash', 2)
Rank 2 ('Akshat', 1)
Rank 3 ('Nikhil', 7)
The dictionary after deletion : {}
Python3
# Python3 code to demonstrate working of# Get random dictionary pair in dictionary# Using popitem() # Initialize dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Get random dictionary pair in dictionary# Using popitem()res = test_dict.popitem() # printing resultprint("The random pair is : " + str(res))
Output:
The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2}
The random pair is : ('is', 2)
mkumarchaudhary06
kumar_satyam
python-dict
Python-dict-functions
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Time Complexity of a Loop when Loop variable “Expands or Shrinks” exponentially

08 May, 2019
For such cases, time complexity of the loop is O(log(log(n))).The following cases analyse different aspects of the problem.
Case 1 :
for (int i = 2; i <=n; i = pow(i, k)) {     // some O(1) expressions or statements}
In this case, i takes values 2, 2k, (2k)k = 2k2, (2k2)k = 2k3, ..., 2klogk(log(n)). The last term must be less than or equal to n, and we have 2klogk(log(n)) = 2log(n) = n, which completely agrees with the value of our last term. So there are in total logk(log(n)) many iterations, and each iteration takes a constant amount of time to run, therefore the total time complexity is O(log(log(n))).
Case 2 :
// func() is any constant root functionfor (int i = n; i > 1; i = func(i)) {    // some O(1) expressions or statements}
In this case, i takes values n, n1/k, (n1/k)1/k = n1/k2, n1/k3, ..., n1/klogk(log(n)), so there are in total logk(log(n)) iterations and each iteration takes time O(1), so the total time complexity is O(log(log(n))).
Refer below article for analysis of different types of loops.https://www.geeksforgeeks.org/analysis-of-algorithms-set-4-analysis-of-loops/
This article is contributed by Rishav Raj. 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.
Analysis
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Difference between Deterministic and Non-deterministic Algorithms
What is algorithm and why analysis of it is important?
Time-Space Trade-Off in Algorithms
Complexity analysis of various operations of Binary Min Heap
Applications of Hashing
Time Complexity Analysis | Tower Of Hanoi (Recursion)
How to learn Pattern printing easily?
Time Complexity of Euclidean Algorithm
Examples of Big-O analysis
How to match parentheses in Python regular expression?

The following code matches parentheses in the string s  and then removes the parentheses in string s1 using Python regular expression.
import re
s = 'I love book()'
result = re.search(r'\(\)',s)
print result.group()
s1 = 'I love book(s)'
result2 = re.sub(r'[\(\)]','',s1)
print result2
This gives the output
()
I love books
GATE | GATE-CS-2003 | Question 61

28 Jun, 2021
In a permutation a1.....an of n distinct integers, an inversion is a pair (ai, aj) such that i aj. If all permutations are equally likely, what is the expected number of inversions in a randomly chosen permutation of 1.....n ?(A) n(n – 1)/2
(B) n(n – 1)/4(C) n(n + 1)/4(D) 2n[log2 n]Answer: (B)Explanation:
There are n(n-1)/2 pairs such that i < j.

For a pair (ai, aj), probability of being inversion is 1/2.

Therefore expected value of inversions = 1/2 * (n(n-1)/2)
                                       = n(n-1)/4
Quiz of this Question
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
Branch Testing

Branch coverage is a testing method, which aims to ensure that each one of the possible branch from each decision point is executed at least once and thereby ensuring that all reachable code is executed.
That is, every branch taken each way, true and false. It helps in validating all the branches in the code making sure that no branch leads to abnormal behavior of the application. 
Branch Testing = (Number of decisions outcomes tested / Total Number of decision Outcomes) x 100 %
Read A
Read B 
IF A+B > 10 THEN 
  Print "A+B is Large" 
ENDIF 
If A > 5 THEN 
  Print "A Large"
ENDIF
The above logic can be represented by a flowchart as:
To calculate Branch  Coverage, one has to find out the minimum number of paths which will ensure that all the edges are covered. In this case there is no single path which will ensure coverage of  all the edges at once. The aim is to cover all possible true/false decisions.
(1) 1A-2C-3D-E-4G-5H
(2) 1A-2B-E-4F
Hence Branch Coverage is 2.