code-rag-bench/online-tutorials huggingface dataset:
numpy.not_equal() in Python - GeeksforGeeks

28 Mar, 2022
The numpy.not_equal() checks whether two element or unequal or not. Syntax : 
numpy.not_equal(x1, x2[, out])
Parameters : 
x1, x2 : [array_like]Input Array whose elements we want to check
out    : [ndarray, optional]Output array that returns True/False.
    A placeholder the same shape as x1 to store the result.
Return : 
Boolean array 
Code 1 : 
Python
# Python Program illustrating# numpy.not_equal() method  import numpy as geek a  = geek.not_equal([1., 2.], [1., 3.])print("Not equal : \n", a, "\n") b = geek.not_equal([1, 2], [[1, 3],[1, 4]])print("Not equal : \n", b, "\n")
Output : 
Not equal : 
 [False  True] 

Not equal : 
 [[False  True]
 [False  True]] 
Code 2 : 
Python
# Python Program illustrating# numpy.not_equal() method   import numpy as geek # Here we will compare Complex values with inta = geek.array([0 + 1j, 2])b = geek.array([1,2]) d  = geek.not_equal(a, b)print("Comparing complex with int using .not_equal() : ", d)
Output : 
Comparing complex with int using .not_equal() :  [ True False]
Code 3 : 
Python
# Python Program illustrating# numpy.not_equal() method   import numpy as geek # Here we will compare Float with int valuesa = geek.array([1.1, 1])b = geek.array([1, 2])  d  = geek.not_equal(a, b)print("\nComparing float with int using .not_equal() : ", d)
Output : 
 Comparing float with int using .not_equal() :  [ True  True]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.not_equal.html Note :These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
nidhi_biet
vinayedula
Python numpy-Logic Functions
Python-numpy
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()
Lexical analysis - GeeksforGeeks

21 Jan, 2014
printf
(
"i = %d, &i = %x"
, 
i
,
&
i
)
;
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
How to calculate MOVING AVERAGE in a Pandas DataFrame?
Find size of largest subset with bitwise AND greater than their bitwise XOR
What is Transmission Control Protocol (TCP)?
Python OpenCV - Canny() Function
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
Class getDeclaredMethods() method in Java with Examples - GeeksforGeeks

25 Jan, 2022
The getDeclaredMethods() method of java.lang.Class class is used to get the methods of this class, which are the methods that are private, public, protected or default and its members or the members of its member classes and interfaces, but not the inherited methods. The method returns the methods of this class in the form of an array of Method objects. Syntax:  
public Method[] getDeclaredMethods()
               throws SecurityException
Parameter: This method does not accept any parameter.Return Value: This method returns the methods of this class in the form of an array of Method objects. Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getDeclaredMethods() method.Example 1: 
Java
// Java program to demonstrate getDeclaredMethods() method import java.util.*; public class Test {    public static void main(String[] args)        throws ClassNotFoundException    {         // returns the Class object for this class        Class myClass = Class.forName("Test");         System.out.println("Class represented by myClass: "                           + myClass.toString());         // Get the methods of myClass        // using getDeclaredMethods() method        System.out.println(            "DeclaredMethods of myClass: "            + Arrays.toString(                  myClass.getDeclaredMethods()));    }}
Class represented by myClass: class Test DeclaredMethods of myClass: [public static void Test.main(java.lang.String[]) throws java.lang.ClassNotFoundException] 
 
Example 2: 
Java
// Java program to demonstrate getDeclaredMethods() method import java.util.*; class Main {     public Object obj;     private void function() {}     Main()    {         class Arr {        };         obj = new Arr();    }     public static void main(String[] args)        throws ClassNotFoundException    {        // returns the Class object for this class        Class myClass = Class.forName("Main");         System.out.println("Class represented by myClass: "                           + myClass.toString());         // Get the methods of myClass        // using getDeclaredMethods() method        System.out.println(            "DeclaredMethods of myClass: "            + Arrays.toString(                  myClass.getDeclaredMethods()));    }}
Class represented by myClass: class Main DeclaredMethods of myClass: [public static void Main.main(java.lang.String[]) throws java.lang.ClassNotFoundException, private void Main.function()] 
 
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredMethods– 
adnanirshad158
Java-Functions
Java-lang package
Java.lang.Class
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
Internal Working of HashMap in Java
Strings in Java
ArrayList size() method in Java with Examples - GeeksforGeeks

26 Nov, 2018
The size() method of java.util.ArrayList class is used to get the number of elements in this list.
Syntax:
public int size()
Returns Value: This method returns the number of elements in this list.
Below are the examples to illustrate the size() method.
Example 1:
// Java program to demonstrate// size() method// for Integer value  import java.util.*;  public class GFG1 {    public static void main(String[] argv)        throws Exception    {        try {              // Creating object of ArrayList<Integer>            ArrayList<Integer>                arrlist = new ArrayList<Integer>();              // Populating arrlist1            arrlist.add(1);            arrlist.add(2);            arrlist.add(3);            arrlist.add(4);            arrlist.add(5);              // print arrlist            System.out.println("Before operation: "                               + arrlist);              // getting total size of arrlist            // using size() method            int size = arrlist.size();              // print the size of arrlist            System.out.println("Size of list = "                               + size);        }          catch (IndexOutOfBoundsException e) {              System.out.println("Exception thrown: "                               + e);        }    }}
Before operation: [1, 2, 3, 4, 5]
Size of list = 5

Example 2:
// Java program to demonstrate// size() method// for String value  import java.util.*;  public class GFG1 {    public static void main(String[] argv)        throws Exception    {        try {              // Creating object of ArrayList<Integer>            ArrayList<String>                arrlist = new ArrayList<String>();              // Populating arrlist1            arrlist.add("A");            arrlist.add("B");            arrlist.add("C");              // print arrlist            System.out.println("Before operation: "                               + arrlist);              // getting total size of arrlist            // using size() method            int size = arrlist.size();              // print the size of arrlist            System.out.println("Size of list = "                               + size);        }          catch (IndexOutOfBoundsException e) {              System.out.println("Exception thrown: "                               + e);        }    }}
Before operation: [A, B, C]
Size of list = 3

Java - util package
Java-ArrayList
Java-Collections
Java-Functions
Java
Java
Java-Collections
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
Stream In Java
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
reflect.Interface() Function in Golang with Examples - GeeksforGeeks

03 May, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Interface() Function in Golang is used to get the v’s current value as an interface{}. To access this function, one needs to imports the reflect package in the program.
Syntax:
func (v Value) Interface() (i interface{})

Parameters: This function accept only one parameter.
i : This parameter is the interface{} type
Return Value: This function returns v’s current value as an interface{}.
Below examples illustrate the use of the above method in Golang:
Example 1:
// Golang program to illustrate// reflect.Interface() Function    package main   import (    "fmt"    "reflect")   // Main function func main() {    t := reflect.TypeOf(5)           //use of Interface method    arr := reflect.ArrayOf(4, t)    inst := reflect.New(arr).Interface().(*[4]int)       for i := 1; i <= 4; i++ {        inst[i-1] = i*i    }       fmt.Println(inst)}
Output:
&[1 4 9 16]

Example 2:
// Golang program to illustrate// reflect.Interface() Function   package main   import (    "fmt"    "reflect")   // Main functionfunc main() {       var str []string    var v reflect.Value = reflect.ValueOf(&str)       v = v.Elem()          v = reflect.Append(v, reflect.ValueOf("a"))    v = reflect.Append(v, reflect.ValueOf("b"))    v = reflect.Append(v, reflect.ValueOf("c"), reflect.ValueOf("j, k, l"))       fmt.Println("Our value is a type of :", v.Kind())       vSlice := v.Slice(0, v.Len())    vSliceElems := vSlice.Interface()       fmt.Println("With the elements of : ", vSliceElems)   }
Output:
Our value is a type of : slice
With the elements of :  [a b c j, k, l]

Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
How to Split a String in Golang?
Slices in Golang
Golang Maps
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
How to Trim a String in Golang?
How to compare times in Golang?
How To Calculate Variance in Excel? - GeeksforGeeks

09 May, 2021
In this article, we will learn about the calculation of the variance(var) in Excel.
First, let’s learn about Variance. In real-life scenarios, we have populations like marks of students in a particular subject, salaries of multiple employees in a company. Let us consider, in a company named ABC, we have 5 employees.
Now, it will tell us the expectation of standard deviation. In other words, the factor of difference in salaries.
The formula for std is –
\sigma^{2}  =   \sum_1^n (x_{i} -  \mu  )^{2}  / N
It will be shown as
Where x represents the value, and μ is the mean of the sample.
Mean = 30
N = 5
Var = 200
Now, Let’s learn how to use it in Excel –
In Excel we have formulas for everything and as you might have guessed for var also.
We can have this list of formulas using ‘=’ symbol shown below
Let’s talk about them briefly,
1. VAR.P – It calculates the var assuming that the entire population is its argument. It returns an approximate value and is used with a large population. Uses the same formula shown above.
2. VAR.S – It calculates the var assuming that the sample of the population is its argument. It returns an approximate value and is used with a large population. Uses the same formula shown below
\sigma^{2}  =   \sum_1^n (x_{i} -  \mu  )^{2}  / (N -1)
3. VARA – It includes text and logical symbols whereas the above 2 functions don’t include text and logical symbols. It is used for a sample of the population. Uses “n-1” formula.
4. VARPA – It includes text and logical symbols. It is used for the whole population. Uses “n” formula.
Let’s see the difference here,
Here, the discrepancy occurs because VARPA and VARA read TRUE as 1 and VAR.P and VAR.S ignore it.
The formula goes like this –
1. =STDEV.P(A38:A43)        [Formula used in A37 cell]
2. =STDEV.S(B38:B43)        [Formula used in B37 cell]
3. =STDEVPA(C38:B43)        [Formula used in C37 cell]
4. =STDEVA(D38:B43)         [Formula used in D37 cell]
Note – VAR and VARP are for Excel 2007 or earlier. DVAR and DVARP are used for fetching data from Database.
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Get Length of Array in Excel VBA?
Using CHOOSE Function along with VLOOKUP in Excel
Macros in Excel
How to Extract the Last Word From a Cell in Excel?
Introduction to Excel Spreadsheet
How to Show Percentages in Stacked Column Chart in Excel?
How to Remove Duplicates From Array Using VBA in Excel?
How to Sum Values Based on Criteria in Another Column in Excel?
GATE | GATE-CS-2003 | Question 81 - GeeksforGeeks

28 Jul, 2021
Suppose we want to synchronize two concurrent processes P and Q using binary semaphores S and T. The code for the processes P and Q is shown below.
Process P:
while (1) {
W:
   print '0';
   print '0';
X:
}
	
Process Q:
while (1) {
Y:
   print '1';
   print '1';
Z:
}
Synchronization statements can be inserted only at points W, X, Y and Z
Which of the following will ensure that the output string never contains a substring of the form 01^n0 or 10^n1 where n is odd?(A) P(S) at W, V(S) at X, P(T) at Y, V(T) at Z, S and T initially 1(B) P(S) at W, V(T) at X, P(T) at Y, V(S) at Z, S and T initially 1(C) P(S) at W, V(S) at X, P(S) at Y, V(S) at Z, S initially 1(D) V(S) at W, V(T) at X, P(S) at Y, P(T) at Z, S and T initially 1Answer: (C)Explanation: P(S) means wait on semaphore ’S’ and V(S) means signal on semaphore ‘S’. The definition of these functions are :
 
Wait(S)  {
   while (i <= 0) ;
   S-- ; 
}


Signal(S)  {
   S++ ; 
}
 
Initially S = 1 and T = 0 to support mutual exclusion in process ‘P’ and ‘Q’.Since, S = 1 , process ‘P’ will be executed and function Wait(S) will decrement the value of ‘S’. So, S = 0 now.Simultaneously, in process ‘Q’ , T = 0 . Therefore, in process ‘Q’ control will be stuck in while loop till the time process ‘P’ prints ‘00’ and increments the value of ‘T’ by calling function V(T).While the control is in process ‘Q’, S = 0 and process ‘P’ will be stuck in while loop. Process ‘P’ will not execute till the time process ‘Q’ prints ‘11’ and makes S = 1 by calling function V(S).
 
Thus, process ‘P’ and ‘Q’ will keep on repeating to give the output ‘00110011 ...... ‘ .
Watch GeeksforGeeks Video Explanation :
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE Previous Year Questions based on Semaphore with Viomesh Singh | GeeksforGeeks GATE GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:50 / 1:00:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=MRza1t01xgE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 Please comment below if you find anything wrong in the above post.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 IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Java Program for Recursive Bubble Sort - GeeksforGeeks

28 Jun, 2021
Background :Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.Following is iterative Bubble sort algorithm :
// Iterative Bubble Sort
bubbleSort(arr[], n)
{
  for (i = 0; i < n-1; i++)      

     // Last i elements are already in place   
     for (j = 0; j  arr[j+1])
         swap(arr[j], arr[j+1]);
} 
Recursion Idea.
Base Case: If array size is 1, return.Do One Pass of normal Bubble Sort. This pass fixes last element of current subarray.Recur for all elements except last of current subarray.
Base Case: If array size is 1, return.
Do One Pass of normal Bubble Sort. This pass fixes last element of current subarray.
Recur for all elements except last of current subarray.
// Java program for recursive implementation// of Bubble sort import java.util.Arrays; public class GFG{    // A function to implement bubble sort    static void bubbleSort(int arr[], int n)    {        // Base case        if (n == 1)            return;              // One pass of bubble sort. After        // this pass, the largest element        // is moved (or bubbled) to end.        for (int i=0; i<n-1; i++)            if (arr[i] > arr[i+1])            {                // swap arr[i], arr[i+1]                int temp = arr[i];                arr[i] = arr[i+1];                arr[i+1] = temp;            }              // Largest element is fixed,        // recur for remaining array        bubbleSort(arr, n-1);    }         // Driver Method    public static void main(String[] args)    {        int arr[] = {64, 34, 25, 12, 22, 11, 90};              bubbleSort(arr, arr.length);                 System.out.println("Sorted array : ");        System.out.println(Arrays.toString(arr));    }}
Please refer complete article on Recursive Bubble Sort for more details!
BubbleSort
Java Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Iterate HashMap in Java?
Iterate through List in Java
Program to print ASCII Value of a character
Factory method design pattern in Java
Java program to count the occurrence of each character in a string using Hashmap
Bubble Sort
Selection Sort
std::sort() in C++ STL
Time Complexities of all Sorting Algorithms
Python Set | pop() - GeeksforGeeks

08 Aug, 2021
This in-built function of Python helps to pop out elements from a set just like the principle used in the concept while implementing Stack. This method removes a top element from the set but not the random element and returns the removed element. 
We can verify this by printing the set before using the pop() method.
Syntax: 
# Pops a First element from S
# and returns it.
S.pop()
This is one of the basic functions of the set and accepts no arguments. The return value is the popped element from the set. Once the element is popped out of the set, the set loses the element and it is updated to a set without the element. 
Examples: 
Input : 
sets = {1, 2, 3, 4, 5}
Output : 
1
Updated set is {2, 3, 4, 5}

Input : 
sets = {"ram", "rahim", "ajay", "rishav", "aakash"}
Output :
rahim
Updated set is {'ram', 'rishav', 'ajay', 'aakash'}
 
Python3
# Python code to illustrate pop() method S = {"ram", "rahim", "ajay", "rishav", "aakash"} # Print the set before using pop() method# First element after printing the set will be popped outprint(S) # Popping three elements and printing themprint(S.pop())print(S.pop())print(S.pop()) # The updated setprint("Updated set is", S)
Output: 
rishav
ram
rahim
Updated set is {'aakash', 'ajay'}
On the other hand, if the set is empty, then a TypeError is returned as shown by the following program.  
Python3
# Python code to illustrate pop() method# on an empty setS = {} # Popping three elements and printing themprint(S.pop()) # The updated setprint("Updated set is", S)
Error: 
Traceback (most recent call last):
  File "/home/7c5b1d5728eb9aa0e63b1d70ee5c410e.py", line 6, in 
    print(S.pop())
TypeError: pop expected at least 1 arguments, got 0
hrishabhjain67
python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python - Index Value Summation List - GeeksforGeeks

27 Feb, 2020
To access the elements of lists, there are various methods. But sometimes we may require to access the element along with the index on which it is found and compute its summation, and for that we may need to employ different strategies. This article discusses some of those strategies.
Method 1 : Naive methodThis is the most generic method that can be possibly employed to perform this task of accessing the index along with the value of the list elements. This is done using a loop. The task of performing sum is performed using external variable to add.
# Python 3 code to demonstrate # Index Value Summation List# using naive method  # initializing listtest_list = [1, 4, 5, 6, 7]  # Printing list print ("The original list is : " + str(test_list))  # using naive method to# Index Value Summation Listres = []for i in range(len(test_list)):    res.append(i + test_list[i])  print ("The list index-value summation is : " + str(res))
The original list is : [1, 4, 5, 6, 7]
The list index-value summation is : [1, 5, 7, 9, 11]

 
Method 2 : Using list comprehension + sum()This method works in similar way as the above method but uses the list comprehension technique for the same, this reduces the possible lines of code to be written and hence saves time. The task of performing summation is done by sum().
# Python 3 code to demonstrate # Index Value Summation List# using list comprehension  # initializing listtest_list = [1, 4, 5, 6, 7]  # Printing list print ("The original list is : " + str(test_list))  # using list comprehension to# Index Value Summation Listres = [sum(list((i, test_list[i]))) for i in range(len(test_list))]  print ("The list index-value summation is : " + str(res))
The original list is : [1, 4, 5, 6, 7]
The list index-value summation is : [1, 5, 7, 9, 11]

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.locator_params() in Python - GeeksforGeeks

21 Apr, 2020
Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays.Pyplot is a collection of command style functions that make matplotlib work like MATLAB.
Note: For more information, refer to Python Matplotlib – An Overview
locator_params() is used for controlling the behaviors of tick locators. The attribute axis is for specifying on which axis is the function being applied.
# for Y axis
matplotlib.pyplot.locator_params(axis='y', nbins=3) 

# for X axis
matplotlib.pyplot.locator_params(axis='x', nbins=3) 

# for both, x-axis and y-axis: Default
matplotlib.pyplot.locator_params(nbins=3) 

Reducing the maximum number of ticks and use tight bounds:
plt.locator_params(tight=True, nbins=4)

Example 1:
# importing librariesimport matplotlib.pyplot as plt  # Y-axis Valuesy =[-1, 4, 9, 16, 25]  # X-axis Valuesx =[1, 2, 3, 4, 5]  plt.locator_params(axis ='x', nbins = 5)  # adding grid to the plotaxes = plt.axes()axes.grid()  # defining the plotplt.plot(x, y, 'mx', color ='green')  # range of y-axis in the plotplt.ylim(ymin =-1.2, ymax = 30)  # Set the marginsplt.margins(0.2)  # printing the plotplt.show()
Output:
Example 2:
# importing librariesimport matplotlib.pyplot as plt  # defining the functiondef for_lines(xlab, ylab, plot_title,              size_x, size_y, content =[]):         width = len(content[0][1:])  s = [x for x in range(1, width + 1)]     # specifying the size of figure  plt.figure(figsize =(size_x, size_y))    for line in content:         plt.plot(s,  line[1:], 'ro--',                  color ='green',                 label = line[0])            # to add title to the plot  plt.title(plot_title)        # for adding labels to the plot  plt.xlabel(xlab)  plt.ylabel(ylab)     t = len(s)   plt.locator_params(nbins = t)  for_lines("x-axis", "y-axis",          "GeeksForGeeks", 7, 7,          [[1, 2, 4, 3, 5]])
Output:
Example 3:
# importing librariesimport matplotlib.pyplot as plt  plt.locator_params(nbins = 10)  # defining the plotplt.plot([1, 2, 3, 5, 7],         [2, 3, 9, 15, 16],         'ro-', color ='red')  # printing the plotplt.show()
Output:
Python-matplotlib
Python
Write From Home
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
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
Factory method design pattern in Java
Python | Playing audio file in Pygame - GeeksforGeeks

27 Feb, 2020
Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so.
Note: For more information, refer to Introduction to pygame
In order to play music/audio files in pygame, pygame.mixer is used (pygame module for loading and playing sounds). This module contains classes for loading Sound objects and controlling playback. There are basically four steps in order to do so:
Starting the mixermixer.init()
mixer.init()
Loading the song.mixer.music.load("song.mp3")
mixer.music.load("song.mp3")
Setting the volume.mixer.music.set_volume(0.7)
mixer.music.set_volume(0.7)
Start playing the song.mixer.music.play()
mixer.music.play()
Below is the implementation.
from pygame import mixer  # Starting the mixermixer.init()  # Loading the songmixer.music.load("song.mp3")  # Setting the volumemixer.music.set_volume(0.7)  # Start playing the songmixer.music.play()  # infinite loopwhile True:          print("Press 'p' to pause, 'r' to resume")    print("Press 'e' to exit the program")    query = input("  ")          if query == 'p':          # Pausing the music        mixer.music.pause()         elif query == 'r':          # Resuming the music        mixer.music.unpause()    elif query == 'e':          # Stop the mixer        mixer.music.stop()        break
Output:
This code will also play the “song.mp3” file.
Python-PyGame
Python
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
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to merge a transparent PNG image with another image using PIL? - GeeksforGeeks

03 Mar, 2021
This article discusses how to put a transparent PNG image with another image. This is a very common operation on images. It has a lot of different applications. For example, adding a watermark or logo on an image. To do this, we are using the PIL module in Python. In which we use some inbuilt methods and combine the images in such a way that it looks to be pasted.
Open Function – It is used to open an image.
Convert Function – It returns a converted copy of a given image. It converts the image to its true color with a transparency mask.
Paste Function – It is used to paste an image on another image. 
Syntax: PIL.Image.Image.paste(image_1, image_2, box=None, mask=None)OR image_object.paste(image_2, box=None, mask=None)
Parameters:
image_1/image_object : It is the image on which other image is to be pasted.
image_2: Source image or pixel value (integer or tuple).
box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it’s treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner.
mask: a mask that will be used to paste the image. If you pass an image with transparency, then the alpha channel is used as the mask.
Approach:
Open the front and background image using Image.open() function.
Convert both the image to RGBA.
Calculate the position where you want to paste the image.
Use the paste function to merge the two images.
Save the image.
Input Data:
To input the data, we are using two images:
Front Image: A transparent image like a logo
Background image: For background like any wallpaper image
Implementation:
Python3
# import PIL modulefrom PIL import Image  # Front Imagefilename = 'front.png'  # Back Imagefilename1 = 'back.jpg'  # Open Front ImagefrontImage = Image.open(filename)  # Open Background Imagebackground = Image.open(filename1)  # Convert image to RGBAfrontImage = frontImage.convert("RGBA")  # Convert image to RGBAbackground = background.convert("RGBA")  # Calculate width to be at the centerwidth = (background.width - frontImage.width) // 2  # Calculate height to be at the centerheight = (background.height - frontImage.height) // 2  # Paste the frontImage at (width, height)background.paste(frontImage, (width, height), frontImage)  # Save this imagebackground.save("new.png", format="png")
Output:
Picked
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python - Integers String to Integer List - GeeksforGeeks

05 Sep, 2020
Given a Integers String, composed of negative and positive numbers, convert to integer list.
Input : test_str = ‘4 5 -3 2 -100 -2’Output : [4, 5, -3, 2, -100, -2]Explanation : Negative and positive string numbers converted to integers list.
Input : test_str = ‘-4 -5 -3 2 -100 -2’Output : [-4, -5, -3, 2, -100, -2]Explanation : Negative and positive string numbers converted to integers list.
Method #1 : Using list comprehension + int() + split()
In this, we split integers using split() and int() is used to integral conversion. Elements inserted in List using list comprehension
Python3
# Python3 code to demonstrate working of # Integers String to Integer List# Using list comprehension + int() + split()import string  # initializing stringtest_str = '4 5 -3 2 -100 -2 -4 9'  # printing original stringprint("The original string is : " + str(test_str))  # int() converts to required integersres = [int(ele) for ele in test_str.split()]      # printing result print("Converted Integers : " + str(res)) 
The original string is : 4 5 -3 2 -100 -2 -4 9
Converted Integers : [4, 5, -3, 2, -100, -2, -4, 9]

Method #2 : Using map() + int()
In this, the task of extension of logic of integer conversion is done using map().
Python3
# Python3 code to demonstrate working of # Integers String to Integer List# Using map() + int()import string  # initializing stringtest_str = '4 5 -3 2 -100 -2 -4 9'  # printing original stringprint("The original string is : " + str(test_str))  # int() converts to required integers# map() extends logic of int to each splitres = list(map(int, test_str.split()))      # printing result print("Converted Integers : " + str(res)) 
The original string is : 4 5 -3 2 -100 -2 -4 9
Converted Integers : [4, 5, -3, 2, -100, -2, -4, 9]

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
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 - Extract Row with any Boolean True - GeeksforGeeks

11 Oct, 2020
Given a Boolean Matrix, extract row which contains at least one boolean True value.
Input : test_list = [[False, False], [True, True, True], [False, True], [False]] Output : [[True, True, True], [False, True]] Explanation : All rows with atleast 1 True extracted.
Input : test_list = [[False, False], [False]] Output : [] Explanation : No rows with even one True.  
Method #1 : Using list comprehension + any()
In this, we check for any element to be boolean true using any() and list comprehension is used for task of iteration of rows in matrix.
Python3
# Python3 code to demonstrate working of # Extract Row with any Boolean True# Using list comprehension + any()  # initializing listtest_list = [[False, False], [True, True, True], [False, True], [False]]  # printing original listprint("The original list is : " + str(test_list))  # using any() to check for any True value res = [sub for sub in test_list if any(ele for ele in sub)]  # printing result print("Extracted Rows : " + str(res))
Output:
The original list is : [[False, False], [True, True, True], [False, True], [False]] Extracted Rows : [[True, True, True], [False, True]]
Method #2 : Using any() + filter() + lambda
In this, we perform task of checking for any True value using any() and filter() and lambda is used to filter out matching rows.
Python3
# Python3 code to demonstrate working of # Extract Row with any Boolean True# Using any() + filter() + lambda  # initializing listtest_list = [[False, False], [True, True, True], [False, True], [False]]  # printing original listprint("The original list is : " + str(test_list))  # using any() to check for any True value # filter() to perform filteringres = list(filter(lambda sub : any(ele for ele in sub), test_list))  # printing result print("Extracted Rows : " + str(res))
Output:
The original list is : [[False, False], [True, True, True], [False, True], [False]] Extracted Rows : [[True, True, True], [False, True]]
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
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?
What is SGML ? - GeeksforGeeks

20 Aug, 2021
In this article, we are going to learn about SGML.SGML stands for Standard generalized markup language is a Standard generalized markup language that makes use of a superset of extensively used markup languages like HTML and XML. It is used for marking up files and has the gain of now no longer be depending on a particular application.
It is basically derived from GML (Generalized Markup Language), which allowed users to work on standardized formatting styles for electronic documents. It was developed and standardized by the International Organization for Standards (ISO) in 1986. SGML  specifies the rules for tagging elements. These tags can then be interpreted to layout factors in specific ways.
It is used extensively to manipulate massive files which are a concern with common revisions and want to be published in one-of-a-kind formats due to the fact it’s far a massive and complicated system, it isn’t always but extensively used on private computers.
Components of SGML:
SGML provides a way of describing the relationships between these entities, elements, and attributes, and tells the computer how it can recognize the component parts of a document and it is based on the concept of a document being composed of a series of entities (object).
It provides rules that allow the computer to recognize where the various elements of a text entity start and end.
Document Type Definition (DTD) in SGML is used to describe each element of the document in a form that the computer can understand.
SGML is the simplest medium to produce files that can be read by people and exchanged between machines and applications in a straightforward manner. It is easy to understand by the human as well as the machine.
Structure of SGML:
<mainObject> 
    <subObject>  
    </subObject>
</mainObject> 
The extension of SGML files is: 
File_Name.sgml
Syntax:
<NAME TYPE="user">
   Geeks for Geeks
</NAME> 
Example 1: 
SGML
<EMAIL>    <SENDER>        <PERSON>            <FIRSTNAME>GEEKS FOR GEEKS</FIRSTNAME>             </PERSON>    </SENDER>    <BODY>                <p>A Computer Science Portal For Geeks</p>    </BODY></EMAIL>
Output:
simple Paragraph
Example 2:
SGML
<EMAIL>    <RECEIVER>        <PERSON>            <FIRSTNAME>Krishna</FIRSTNAME>             </PERSON>    </RECEIVER>    <BODY>                <p>It is a name of the person.</p>      </BODY></EMAIL>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Questions
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
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
JavaScript String prototype Property - GeeksforGeeks

30 Jun, 2020
The prototype property allows to add new properties and methods to the existing JavaScript object types. There are two examples to describe the JavaScript String prototype property.
Syntax:
object.prototype.name = value
Return Value: It returns a reference to the String.prototype object.
Example 1: This example adds a property salary to the all objects.
<!DOCTYPE HTML><html>  <head>    <title>        JavaScript String prototype Property    </title></head>  <body style="text-align:center;">      <h1>GeeksForGeeks</h1>          <p id="GFG_UP"></p>      <button onclick="GFG_Fun();">        Click Here    </button>          <p id="GFG_DOWN"></p>          <script>        var up = document.getElementById('GFG_UP');        var down = document.getElementById('GFG_DOWN');                  function person(name, age) {            this.name = name;            this.age = age;        }        var p1 = new person("p1", 24);        up.innerHTML = "Click on the button to add "                + "a new property to all objects of"                + " a given type.< br > "                 + JSON.stringify(p1);          function GFG_Fun() {            person.prototype.salary = 1000;            down.innerHTML = p1.salary;        }    </script></body>  </html> 
Output:
Example 2: This example adds a method info to the all objects.
<!DOCTYPE HTML><html>  <head>    <title>        JavaScript String prototype Property    </title></head>  <body style="text-align:center;">      <h1>GeeksForGeeks</h1>      <p id="GFG_UP"></p>      <button onclick="GFG_Fun();">        Click Here    </button>          <p id="GFG_DOWN"></p>          <script>        var up = document.getElementById('GFG_UP');        var down = document.getElementById('GFG_DOWN');        function person(name, age) {            this.name = name;            this.age = age;        }        var p1 = new person("p1", 22);        up.innerHTML = "Click on the button to add"                + " a new property to all objects "                + "of a given type.< br > "                 + JSON.stringify(p1);          function getData(name, age) {            return "Information of person <br>Name - '"                         + name + "'<br>Age - " + age;        }          function GFG_Fun() {            person.prototype.info                     = getData(p1.name, p1.age);                                  down.innerHTML = p1.info;        }    </script></body>  </html> 
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
How to Reverse keys and values in Scala Map

13 Aug, 2019
In Scala, Map is same as dictionary which holds key:value pairs. In this article, we will learn how to reverse the keys and values in given Map in Scala. After reversing the pairs, keys will become values and values will become keys. We can reverse the keys and values of a map with a Scala for-comprehension. Keys should be unique for reverse these values otherwise we can lose some content.Syntax:
val reverseMap = for ((k,v) <- map) yield (v, k)
Below is the example to reverse keys and values in Scala Map.
Example #1:
// Scala program to reverse keys and values  // Creating object object GfG {       // Main method     def main(args:Array[String])     {               // Creating a map         val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs")                   // reversing key:value pairs         val reverse = for ((k, v) <- m1) yield (v, k)          // Displays output         println(reverse)           } } 
Output:
Map(geeks -> 3, for -> 4, cs -> 2)

Example #2:
// Scala program to reverse keys and values  // Creating object object GfG {       // Main method     def main(args:Array[String])     {               // Creating a map         val mapIm = Map("Ajay" -> 30,                         "Bhavesh" -> 20,                         "Charlie" -> 50)                   // Applying keySet method         val reverse = for ((k, v) <- mapIm) yield (v, k)          // Displays output         println(reverse)           } } 
Output:
Map(30 -> Ajay, 20 -> Bhavesh, 50 -> Charlie)

Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Weak Entity Set in ER diagrams

05 Jul, 2021
An entity type should have a key attribute which uniquely identifies each entity in the entity set, but there exists some entity type for which key attribute can’t be defined. These are called Weak Entity type. 
The entity sets which do not have sufficient attributes to form a primary key are known as weak entity sets and the entity sets which have a primary key are known as strong entity sets. 
As the weak entities do not have any primary key, they cannot be identified on their own, so they depend on some other entity (known as owner entity). The weak entities have total participation constraint (existence dependency) in its identifying relationship with owner identity. Weak entity types have partial keys. Partial Keys are set of attributes with the help of which the tuples of the weak entities can be distinguished and identified. 
Note – Weak entity always has total participation but Strong entity may not have total participation. 
Weak entity is depend on strong entity to ensure the existence of weak entity. Like strong entity, weak entity does not have any primary key, It has partial discriminator key. Weak entity is represented by double rectangle. The relation between one strong and one weak entity is represented by double diamond. 
 
Weak entities are represented with double rectangular box in the ER Diagram and the identifying relationships are represented with double diamond. Partial Key attributes are represented with dotted lines. 
 
Example-1: In the below ER Diagram, ‘Payment’ is the weak entity. ‘Loan Payment’ is the identifying relationship and ‘Payment Number’ is the partial key. Primary Key of the Loan along with the partial key would be used to identify the records. 
 
Example-2: The existence of rooms is entirely dependent on the existence of a hotel. So room can be seen as the weak entity of the hotel. 
Example-3: The bank account of a particular bank has no existence if the bank doesn’t exist anymore. 
Example-4: A company may store the information of dependents (Parents, Children, Spouse) of an Employee. But the dependents don’t have existence without the employee. So Dependent will be weak entity type and Employee will be Identifying Entity type for Dependent. 
Other examples:  
Strong entity | Weak entity
Order | Order Item
Employee | Dependent
Class | Section
Host | Logins 
Note – Strong-Weak entity set always has parent-child relationship. 
singghakshay
DBMS-ER model
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.