code-rag-bench/online-tutorials huggingface dataset:
Python – Pandas dataframe.append()

08 Jul, 2022
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object. Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value.
Syntax: DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None)
Parameters :other : DataFrame or Series/dict-like object, or list of theseignore_index : If True, do not use the index labels.verify_integrity : If True, raise ValueError on creating index with duplicates.sort : Sort columns if the columns of self and other are not aligned. The default sorting is deprecated and will change to not-sorting in a future version of pandas. Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
Returns: appended : DataFrame
Example #1: Create two data frames and append the second to the first one.
# Importing pandas as pdimport pandas as pd  # Creating the first Dataframe using dictionarydf1 = df = pd.DataFrame({"a":[1, 2, 3, 4],                         "b":[5, 6, 7, 8]})  # Creating the Second Dataframe using dictionarydf2 = pd.DataFrame({"a":[1, 2, 3],                    "b":[5, 6, 7]})  # Print df1print(df1, "\n")  # Print df2df2
Now append df2 at the end of df1.
# to append df2 at the end of df1 dataframedf1.append(df2)
Output :Notice the index value of second data frame is maintained in the appended data frame. If we do not want it to happen then we can set ignore_index=True.
# A continuous index value will be maintained# across the rows in the new appended data frame.df1.append(df2, ignore_index = True)
Output : Example #2: Append dataframe of different shape.
For unequal no. of columns in the data frame, non-existent value in one of the dataframe will be filled with NaN values.
# Importing pandas as pdimport pandas as pd  # Creating the first Dataframe using dictionarydf1 = pd.DataFrame({"a":[1, 2, 3, 4],                    "b":[5, 6, 7, 8]})  # Creating the Second Dataframe using dictionarydf2 = pd.DataFrame({"a":[1, 2, 3],                    "b":[5, 6, 7],                     "c":[1, 5, 4]})  # for appending df2 at the end of df1df1.append(df2, ignore_index = True)
Output :
Notice, the new cells are populated with NaN values.
Kaustav kumar Chanda
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
Create a Pandas DataFrame from Lists
PostgreSQL – SELECT DISTINCT clause

07 Oct, 2021
This article will be focusing on the use of SELECT statement with the DISTINCT clause to remove duplicates rows from a result set of query data. 
Removing duplicate rows from a query result set in PostgreSQL can be done using the SELECT statement with the DISTINCT clause. It keeps one row for each group of duplicates. The DISTINCT clause can be used for a single column or for a list of columns. 
 
Syntax:SELECT DISTINCT column_1 FROM table_name;
 
If you desire to operate on a list of columns the syntax will somewhat be like below: 
 
Syntax:SELECT DISTINCT column_1, column_2, column_3 FROM table_name;
 
Now, let’s look into a few examples for better understanding. For the sake of example, we will create a sample database as explained below: 
Create a database(say, Favourite_colours) using the commands shown below:  
CREATE DATABASE Favourite_colours;
Now add a table(say, my_table) with columns(say, id, colour_1 and colour_2) to the database using the command below: 
 
CREATE TABLE my_table(
    id serial NOT NULL PRIMARY KEY,
    colour_1 VARCHAR,
    colour_2 VARCHAR
);
Now insert some data in the table that we just added to our database using the command below:  
INSERT INTO my_table(colour_1, colour_2)
VALUES
    ('red', 'red'),
    ('red', 'red'),
    ('red', NULL),
    (NULL, 'red'),
    ('red', 'green'),
    ('red', 'blue'),
    ('green', 'red'),
    ('green', 'blue'),
    ('green', 'green'),
    ('blue', 'red'),
    ('blue', 'green'),
    ('blue', 'blue');
Now check if everything is as intended by making a query as below:  
SELECT
    id,
    colour_1,
    colour_2
FROM
    my_table;
If everything is as intended, the output will be like as shown below:  
Since, our database is good to go, we move onto the implementation of the SELECT DISTINCT clause. 
Example 1: PostgreSQL DISTINCT on one column  
SELECT
    DISTINCT colour_1
FROM
    my_table
ORDER BY
    colour_1;
Output: 
 
Example 2: PostgreSQL DISTINCT on multiple columns  
SELECT
    DISTINCT colour_1,
    colour_2
FROM
    my_table
ORDER BY
    colour_1,
    colour_2;
Output:  
 
akshaysingh98088
postgreSQL-clauses
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
errors.New() Function in Golang with Examples

03 May, 2020
Errors package in Golang is used to implement the functions to manipulate the errors. errors.New()function returns an error that formats like given text. Each call to New returns distinct error value indeed in the event that the content is indistinguishable.
Syntax:
func New(text string) error
It returns an error.
Example 1:
// Golang program to illustrate// the errors.new() function package main  import (    "errors"    "fmt")// Main functionfunc main() {    err := errors.New("Sample Error")    if err != nil {        fmt.Print(err)    }}
Output:
Sample Error
Example 2:
// Golang program to illustrate// the errors.new() functionpackage main  import (    "errors"    "fmt")  // Main functionfunc main() {    err := errors.New("It Says Error!")    if err != nil {        fmt.Print(err)    }}
Output:
It Says Error!
Golang-errors
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.axes.Axes.invert_xaxis() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.invert_xaxis() function in axes module of matplotlib library is used to invert the x-axis.
Syntax: Axes.invert_xaxis(self)
Parameters: This method does not accepts any parameters.
Returns:This method does not returns any value.
Below examples illustrate the matplotlib.axes.Axes.invert_xaxis() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np       X = np.arange(-20, 20, 0.5)Y = np.arange(-20, 20, 0.5)U, V = np.meshgrid(X, Y)   fig, ax = plt.subplots()ax.quiver(X, Y, U, V)w = ax.invert_xaxis()ax.set_title('matplotlib.axes.Axes.invert_xaxis() \Example', fontsize = 14, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np       x = np.linspace(0, 200, 10)yy = np.transpose([2 * np.sin(x + phi) for phi in x])   fig, ax = plt.subplots()ax.plot(yy)w = ax.invert_xaxis()ax.set_title('matplotlib.axes.Axes.invert_xaxis() \Example', fontsize = 14, fontweight ='bold')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Remove the given substring from end of string

07 Jun, 2019
Sometimes we need to manipulate our string to remove extra information from string for better understanding and faster processing. Given a task in which substring needs to be removed from the end of the string. Given below are a few methods to solve the given task. 
Method #1: Using Naive Method
# Python3 code to demonstrate# to remove a substring from end of the string  # Initialising stringini_string = 'xbzefdgstb'  # initializing stringsstring = 'stb'  # printing initial string and substringprint ("initial_strings : ", ini_string, "\nsubstring : ", sstring)  # removing substring from end# of string using Naive Methodif ini_string.endswith(sstring):    res = ini_string[:-(len(sstring))]  # printing resultprint ("resultant string", res)
initial_strings :  xbzefdgstb 
substring :  stb
resultant string xbzefdg

 Method #2: Using sub() method
# Python3 code to demonstrate# to remove a substring from end of string  import re  # Initialising stringini_string = 'xbzefdgstb'  # initializing stringsstring = 'stb'  # printing initial string and substringprint ("initial_strings : ", ini_string, "\nsubstring : ", sstring)  # removing substring from end# of string using sub Methodif ini_string.endswith(sstring):    res = re.sub(sstring, '', ini_string)  # printing resultprint ("resultant string", res)
initial_strings :  xbzefdgstb 
substring :  stb
resultant string xbzefdg

 Method #3: Using replace() method
# Python3 code to demonstrate# to remove a substring from end of string  # Initialising stringini_string = 'xbzefdgstb'  # initializing stringsstring = 'stb'  # printing initial string and substringprint ("initial_strings : ", ini_string, "\nsubstring : ", sstring)  # removing substring from end# of string using replace Methodif ini_string.endswith(sstring):    res = ini_string.replace(sstring, '')  # printing resultprint ("resultant string", res)
initial_strings :  xbzefdgstb 
substring :  stb
resultant string xbzefdg

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change view of Tensor in Pytorch - GeeksforGeeks

30 Jun, 2021
In this article, we are going to change the view of the given tensor in PyTorch. For this, we will use view() function to be used to change the tensor in two-dimensional format IE rows and columns. We have to specify the number of rows and the number of columns to be viewed.
Syntax: tensor.view(no_of_rows,no_of_columns)
Example 1: Python program to create a tensor with 10 elements and view with 5 rows and 2 columns and vice versa
Python3
# importing torch moduleimport torch  # create one dimensional tensor # 10 elementsa = torch.FloatTensor([10, 20, 30, 40, 50, 1, 2, 3, 4, 5])    # view tensor in 5 rows and 2# columnsprint(a.view(5, 2))   # view tensor in 2 rows and 5 # columnsprint(a.view(2, 5))
Output:
Example 2: Change the view of a tensor into 4 rows and 3 columns and vice versa
Python3
# importing torch moduleimport torch  # create one dimensional tensor 12 elementsa = torch.FloatTensor([34, 56, 10, 20, 30, 40, 50, 1, 2, 3, 4, 5])  # view tensor in 4 rows and 3 columnsprint(a.view(4, 3))  # view tensor in 3 rows and 4 columnsprint(a.view(3, 4))
Output:
Picked
Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Matplotlib.axes.Axes.stem() in Python - GeeksforGeeks

13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.stem() function in axes module of matplotlib library is used to create a stem plot.
Syntax: Axes.stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0, label=None, use_line_collection=False, data=None)
Parameters: This method accept the following parameters that are described below:
x: This parameter is the sequence of x coordinates of the stems.
y: This parameter is the sequence of y coordinates of the stem heads.
linefmt: This parameter is the string defining the properties of the vertical lines.
markerfmt: This parameter is the string defining the properties of the markers at the stem heads.
basefmt: This parameter is the string defining the properties of the baseline.
bottom: This parameter is the y-position of the baseline.
label: This parameter is the label to use for the stems in legends.
Returns: This returns the following:
StemContainer: This returns the container which may be treated like a tuple (markerline, stemlines, baseline).
Below examples illustrate the matplotlib.axes.Axes.broken_barh() function in matplotlib.axes:
Example-1:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt  fig, ax = plt.subplots()  ax.stem([0.3, 1.5, 2.7],         [1, 3.6, 2.7],         label ="stem test")  ax.legend()ax.set_title('matplotlib.axes.Axes.stem Example')plt.show()
Output:Example-2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  x = np.linspace(0.1, 2 * np.pi, 41)y = np.exp(np.sin(x))  fig, ax = plt.subplots()  ax.stem(x, y, linefmt ='grey',         markerfmt ='D',         bottom = 1.1,         use_line_collection = True)  ax.set_title('matplotlib.axes.Axes.stem Example')plt.show()
Python-matplotlib
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()
PyQt5 – Set status bar message in window - GeeksforGeeks

26 Mar, 2020
In this article, we will see how to set message to status bar of window. A status bar is a graphical control element which poses an information area typically found at the window’s bottom. It can be divided into sections to group information. Its job is primarily to display information about the current state of its window.
In order to do this we will use showMessage() method.
Syntax : self.statusBar().showMessage(message)
Argument : It takes string as argument.
Action performed : It sets the message to status bar.
Code :
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Python")          # setting  the geometry of window        self.setGeometry(60, 60, 600, 400)          # setting status bar message        self.statusBar().showMessage("this is status bar")          # creating a label widget        self.label_1 = QLabel("Status Bar", self)          # moving position        self.label_1.move(100, 100)          # setting up the border        self.label_1.setStyleSheet("border :5px solid blue;")          # resizing label        self.label_1.resize(80, 100)          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
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
HashSet toArray() method in Java with Example - GeeksforGeeks

24 Dec, 2018
The toArray() method of Java HashSet is used to form an array of the same elements as that of the HashSet. Basically, it copies all the element from a HashSet to a new array.
Syntax:
Object[] arr = HashSet.toArray()
Parameters: The method does not take any parameters.
Return Value: The method returns an array containing the elements similar to the HashSet.
Below programs illustrate the HashSet.toArray() method:
Program 1:
// Java code to illustrate toArray()  import java.util.*;  public class HashSetDemo {    public static void main(String args[])    {        // Creating an empty HashSet        HashSet<String>            abs_col = new HashSet<String>();          // Use add() method to add        // elements into the HashSet        abs_col.add("Welcome");        abs_col.add("To");        abs_col.add("Geeks");        abs_col.add("For");        abs_col.add("Geeks");          // Displaying the HashSet        System.out.println("The HashSet: "                           + abs_col);          // Creating the array and using toArray()        Object[] arr = abs_col.toArray();          System.out.println("The array is:");        for (int j = 0; j < arr.length; j++)            System.out.println(arr[j]);    }}
The HashSet: [Geeks, For, Welcome, To]
The array is:
Geeks
For
Welcome
To

Program 2:
// Java code to illustrate toArray()  import java.util.*;  public class HashSetDemo {    public static void main(String args[])    {        // Creating an empty HashSet        HashSet<Integer>            abs_col = new HashSet<Integer>();          // Use add() method to add        // elements into the HashSet        abs_col.add(10);        abs_col.add(15);        abs_col.add(30);        abs_col.add(20);        abs_col.add(5);        abs_col.add(25);          // Displaying the HashSet        System.out.println("The HashSet: "                           + abs_col);          // Creating the array and using toArray()        Object[] arr = abs_col.toArray();          System.out.println("The array is:");        for (int j = 0; j < arr.length; j++)            System.out.println(arr[j]);    }}
The HashSet: [20, 5, 25, 10, 30, 15]
The array is:
20
5
25
10
30
15

Java - util package
Java-Collections
Java-Functions
java-hashset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
Java Program for Activity Selection Problem | Greedy Algo-1 - GeeksforGeeks

22 Aug, 2019
You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.Example:
Example 1 : Consider the following 3 activities sorted
by finish time.
     start[]  =  {10, 12, 20};
     finish[] =  {20, 25, 30};
A person can perform at most two activities. The 
maximum set of activities that can be executed 
is {0, 2} [ These are indexes in start[] and 
finish[] ]

Example 2 : Consider the following 6 activities 
sorted by by finish time.
     start[]  =  {1, 3, 0, 5, 8, 5};
     finish[] =  {2, 4, 6, 7, 9, 9};
A person can perform at most four activities. The 
maximum set of activities that can be executed 
is {0, 1, 3, 4} [ These are indexes in start[] and 
finish[] ]

Java
// The following implementation assumes that the activities// are already sorted according to their finish timeimport java.util.*;import java.lang.*;import java.io.*;  class ActivitySelection {    // Prints a maximum set of activities that can be done by a single    // person, one at a time.    // n   -->  Total number of activities    // s[] -->  An array that contains start time of all activities    // f[] -->  An array that contains finish time of all activities    public static void printMaxActivities(int s[], int f[], int n)    {        int i, j;          System.out.print("Following activities are selected : n");          // The first activity always gets selected        i = 0;        System.out.print(i + " ");          // Consider rest of the activities        for (j = 1; j < n; j++) {            // If this activity has start time greater than or            // equal to the finish time of previously selected            // activity, then select it            if (s[j] >= f[i]) {                System.out.print(j + " ");                i = j;            }        }    }      // driver program to test above function    public static void main(String[] args)    {        int s[] = { 1, 3, 0, 5, 8, 5 };        int f[] = { 2, 4, 6, 7, 9, 9 };        int n = s.length;          printMaxActivities(s, f, n);    }}
Following activities are selected : n0 1 3 4

Please refer complete article on Activity Selection Problem | Greedy Algo-1 for more details!
nidhi_biet
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Java Program to Read a File to String
How to Write Data into Excel Sheet using Java?
How to Replace a Element in Java ArrayList?
Java Program to Find Sum of Array Elements
Tic-Tac-Toe Game in Java
Removing last element from ArrayList in Java
Comparing two ArrayList In Java
Python - math.asin() function - GeeksforGeeks

28 May, 2020
Math module contains a number of functions which is used for mathematical operations. The math.asin() function returns the arc sine value of a number. The value passed in this function should be between -1 to 1.
Syntax: math.asin(x)
Parameter:This method accepts only single parameters.
x :This parameter is the value to be passed to asin()
Returns:This function returns the arc sine value of a number.
Below examples illustrate the use of above function:
Example 1:
# Python code to implement# the acos()function        # importing "math"# for mathematical operations  import math         a = math.pi / 6        # returning the value of arc sine of pi / 6  print ("The value of arc sine of pi / 6 is : ", end ="")  print (math.asin(a))
Output:
The value of arc sine of pi / 6 is : 0.5510695830994463

Example 2:
# Python code to implement# the aasin()functionimport math import matplotlib.pyplot as plt      in_array = [-0.14159265, -0.57039399, -0.28559933,             0.28559933, 0.57039399,  0.94159265]     out_array = []     for i in range(len(in_array)):     out_array.append(math.asin(in_array[i]))     i += 1       print("Input_Array : \n", in_array)  print("\nOutput_Array : \n", out_array)      plt.plot(in_array, out_array, "go:")  plt.title("math.asin()")  plt.xlabel("X")  plt.ylabel("Y")  plt.show()  
Output:
Input_Array : 
 [-0.14159265, -0.57039399, -0.28559933, 0.28559933, 0.57039399, 0.94159265]

Output_Array : 
 [-0.14207008957392517, -0.6069854488522558, -0.2896317474780172, 0.2896317474780172, 0.6069854488522558, 1.227328875116741]

Python math-library
Python math-library-functions
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
Python | Sort the list alphabetically in a dictionary - GeeksforGeeks

28 Jan, 2019
In Python Dictionary is quite a useful data structure, which is usually used to hash a particular key with value, so that they can be retrieved efficiently.
Let’s see how to sort the list alphabetically in a dictionary.
Example #1:
# Python program to sort the list # alphabetically in a dictionarydict ={    "L1":[87, 34, 56, 12],    "L2":[23, 00, 30, 10],    "L3":[1, 6, 2, 9],    "L4":[40, 34, 21, 67]}  print("\nBefore Sorting: ")for x in dict.items():    print(x)  print("\nAfter Sorting: ")  for i, j in dict.items():    sorted_dict ={i:sorted(j)}    print(sorted_dict)
Before Sorting: 
('L2', [23, 0, 30, 10])
('L3', [1, 6, 2, 9])
('L4', [40, 34, 21, 67])
('L1', [87, 34, 56, 12])

After Sorting: 
{'L2': [0, 10, 23, 30]}
{'L3': [1, 2, 6, 9]}
{'L4': [21, 34, 40, 67]}
{'L1': [12, 34, 56, 87]}

 Example #2:
# Python program to sort the list # alphabetically in a dictionary  dict ={    "L1":["Geeks", "for", "Geeks"],    "L2":["A", "computer", "science"],    "L3":["portal", "for", "geeks"],}  print("\nBefore Sorting: ")for x in dict.items():    print(x)  print("\nAfter Sorting: ")for i, j in dict.items():    sorted_dict ={i:sorted(j)}    print(sorted_dict)
Before Sorting: 
('L3', ['portal', 'for', 'geeks'])
('L1', ['Geeks', 'for', 'Geeks'])
('L2', ['A', 'computer', 'science'])

After Sorting: 
{'L3': ['for', 'geeks', 'portal']}
{'L1': ['Geeks', 'Geeks', 'for']}
{'L2': ['A', 'computer', 'science']}

 Example #3:
# Python program to sort the list # alphabetically in a dictionarydict={    "L1":[87,34,56,12],    "L2":[23,00,30,10],    "L3":[1,6,2,9],    "L4":[40,34,21,67]}  print("\nBefore Sorting: ")for x in dict.items():    print(x)  sorted_dict = {i: sorted(j) for i, j in dict.items()}print("\nAfter Sorting: ", sorted_dict)
Before Sorting: 
('L1', [87, 34, 56, 12])
('L2', [23, 0, 30, 10])
('L3', [1, 6, 2, 9])
('L4', [40, 34, 21, 67])

After Sorting:  {'L1': [12, 34, 56, 87], 
                 'L2': [0, 10, 23, 30],
                 'L3': [1, 2, 6, 9], 
                 'L4': [21, 34, 40, 67]}

Picked
Python dictionary-programs
python-dict
Python
python-dict
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
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks

28 Jun, 2021
Let # be a binary operator defined as X # Y = X′ + Y′ where X and Y are Boolean variables. Consider the following two statements.
S1: (P # Q) # R = P # (Q # R)
S2: Q # R = R # Q 
Which of the following is/are true for the Boolean variables P, Q and R?
(A) Only S1 is True(B) Only S2 is True(C) Both S1 and S2 are True(D) Neither S1 nor S2 are TrueAnswer: (B)Explanation:
S2 is true, as X' + Y' = Y' + X'
S1 is false.
Let P = 1, Q = 1, R = 0, we get different results
(P # Q) # R = (P' + Q')' + R' = (0 + 0)' + 1 = 1 + 1 = 1
P # (Q # R) = P' + (Q' + R')' = 0 + (0 + 1)' = 0 + 0 = 0
Quiz of this Question

    
        My Personal Notes
        arrow_drop_up
    
    
        
        
            
            Save
        
    
                        
S1 is false.
Let P = 1, Q = 1, R = 0, we get different results
(P # Q) # R = (P' + Q')' + R' = (0 + 0)' + 1 = 1 + 1 = 1
P # (Q # R) = P' + (Q' + R')' = 0 + (0 + 1)' = 0 + 0 = 0

Quiz of this Question


GATE-CS-2015 (Set 3)


GATE-GATE-CS-2015 (Set 3)


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
Difference between service-oriented (SOA) and Micro service Architecture (MSA) - GeeksforGeeks

28 Jul, 2020
1. Service-oriented architecture (SOA) :It is a huge collection of services in which services communicate with each other. This framework is used for designing a software system using a software architecture that views all components as services. The communication is provided by SOA generally used for data passing it could communicate two or more services and complete some activity.
It provides various microservices as function which has following –
1. Loosely coupled
2. Reusable
3. Composable
4. Autonomic
5. Standardized 
2. Microservice Architecture (MSA) :It takes large number of services and breaks down into small services or shareable components. It also called a monolith in which all functionality is placed into a single process. This approach is used for developing application and communication with different approaches which may write in different programming language and data storage.
Here are some characteristic functions of MSA –
1. Business capabilities
2. Products
3. Smart End Point
4. Automation
5. Evolutionary 
Difference between SOA and MSA :
Difference Between
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Stack vs Heap Memory Allocation
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Types of Software Testing
Software Engineering | COCOMO Model
Software Engineering | Spiral Model
Software Engineering | Classical Waterfall Model
Functional vs Non Functional Requirements
How to print number of paragraphs in textview in android?

This example demonstrate about How to print number of paragraphs in textview in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center_horizontal"
   android:layout_marginTop="100dp"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/text"
      android:gravity="center"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">
   </TextView>
</LinearLayout>
In the above code, we have taken textview to show paragraph and toast will show the information about number of paragraphs.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
   TextView text;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      text = findViewById(R.id.text);
      text.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                    Lorem Ipsum has been the industry's standard dummy text ever since the
                    1500s, when an unknown printer took a galley of type and scrambled it to
                    make a type specimen book. It has survived not only five centuries, but
                    also the leap into electronic typesetting, remaining essentially unchanged.
                    It was popularised in the 1960s with the release of Letraset sheets
                    containing Lorem Ipsum passages, and more recently with desktop publishing
                    software like Aldus PageMaker including versions of Lorem Ipsum.");
      String[] para = text.getText().toString().split("\r\n\r\n");
      Toast.makeText(MainActivity.this, "" + para.length, Toast.LENGTH_LONG).show();
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
C++ Iterator Library - advance

It advances the iterator it by n element positions.
Following is the declaration for std::advance.
template <class InputIterator, class Distance>
  void advance (InputIterator& it, Distance n);

it − Iterator used in advance.
it − Iterator used in advance.
n − It is the number of position to be advanced in iterator.
n − It is the number of position to be advanced in iterator.
none
If any of the arithmetical operations performed on the iterator throws.
constant for random-access iterators.
The following example shows the usage of std::advance.
#include <iostream>     
#include <iterator>     
#include <list>         

int main () {
   std::list<int> mylist;
   for (int i = 0; i < 10; i++) mylist.push_back (i*10);

   std::list<int>::iterator it = mylist.begin();

   std::advance (it,9);

   std::cout << "The 9th element in mylist is: " << *it << '\n';

   return 0;
}
Let us compile and run the above program, this will produce the following result −
The 9th element in mylist is: 90

 Print
 Add Notes
 Bookmark this page
How to access the table values in R?

Sometimes we want to extract table values, especially in cases when we have a big table. This helps us to understand the frequency for a particular item in the table. To access the table values, we can use single square brackets. For example, if we have a table called TABLE then the first element of the table can accessed by using TABLE[1].
 Live Demo
x1<−rpois(200,5)
x1
[1] 10 7 6 4 3 8 4 5 4 4 2 8 7 5 3 5 3 5 3 9 7 5 8 4 2
[26] 7 6 6 5 3 11 3 5 8 7 6 3 5 6 1 3 7 8 4 6 6 3 6 7 6
[51] 14 3 3 3 8 9 4 3 9 2 8 5 2 2 3 8 4 3 3 6 5 6 6 5 5
[76] 5 4 3 1 6 11 9 10 7 6 4 4 5 8 4 4 2 6 6 7 5 3 5 3 4
[101] 5 2 6 6 5 6 2 5 5 6 3 4 5 4 16 5 2 0 2 5 5 5 2 4 3
[126] 6 3 3 2 3 5 5 6 3 7 4 5 7 4 7 5 6 5 5 6 11 3 2 7 4
[151] 4 5 7 4 9 6 4 1 4 8 4 3 3 10 7 4 8 5 4 9 5 6 3 2 4
[176] 8 4 5 7 4 6 5 5 1 7 4 7 6 5 4 7 9 3 11 5 6 4 4 3 4
Table1<−table(x1)
Table1
x1
0 1 2 3 4 5 6 7 8 9 10 11 14 16
1 4 14 31 35 39 29 19 12 7 3 4 1 1
Table1[1]
0
1
Table1[2]
1
4
Table1[5]
4
35
Table1[10]
9
7
 Live Demo
x2<−rpois(200,10)
x2
[1] 8 8 10 12 12 9 7 8 13 8 9 3 10 8 9 11 11 15 10 12 9 5 14 8 9
[26] 14 7 4 7 8 9 12 8 10 16 7 7 6 10 9 14 17 11 6 10 7 13 13 8 11
[51] 11 6 8 9 11 9 16 8 10 11 6 12 10 13 10 10 11 6 12 6 9 7 6 7 17
[76] 16 13 9 9 13 13 9 10 10 10 13 9 11 10 10 13 13 11 15 10 12 7 11 15 2
[101] 10 7 14 7 15 9 9 13 19 16 12 3 13 20 10 16 7 16 16 17 13 11 7 11 8
[126] 8 9 2 10 16 12 13 6 10 12 16 10 15 8 5 9 11 8 3 5 7 10 10 5 11
[151] 5 8 6 11 2 7 8 9 17 9 10 10 15 7 8 8 14 8 10 15 6 12 12 11 8
[176] 8 14 8 8 17 8 11 14 11 8 12 13 9 13 9 9 7 5 12 9 6 12 9 11 12
Table2<−table(x2)
Table2
x2
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 19 20
3 3 1 6 11 17 26 25 26 20 16 16 7 7 9 5 1 1
Table2[2]
3
3
Table2[10]
11
20
Table2[15]
16
9
 Live Demo
x3<−sample(501:510,200,replace=TRUE)
x3
[1] 501 505 508 503 506 510 505 507 502 501 503 502 502 509 506 509 507 504
[19] 501 510 501 509 506 504 501 501 503 506 509 504 505 505 509 502 509 509
[37] 508 504 505 506 503 504 505 503 507 506 503 510 506 506 506 505 502 506
[55] 502 503 510 501 505 510 501 508 506 506 501 507 508 508 507 505 508 509
[73] 507 506 508 504 510 506 510 505 509 504 505 505 510 507 504 505 503 506
[91] 507 509 504 504 506 508 503 502 505 508 510 508 506 501 501 507 506 501
[109] 504 507 501 510 508 504 510 507 506 505 502 507 510 506 501 510 509 508
[127] 503 508 504 508 504 505 503 503 508 506 501 503 502 509 502 508 509 506
[145] 510 502 508 507 509 507 506 510 501 508 502 505 502 503 510 508 503 506
[163] 505 505 509 502 504 501 501 508 508 507 509 501 505 509 502 508 508 505
[181] 508 502 509 501 508 502 510 507 504 509 503 503 509 501 504 503 508 501
[199] 506 502
Table3<−table(x3)
Table3
x3
501 502 503 504 505 506 507 508 509 510
22 18 18 17 21 25 16 26 20 17
Table3[1]
501
22
Table3[5]
505
21
Table3[1:5]
x3
501 502 503 504 505
22 18 18 17 21
Table3[6:10]
x3
506 507 508 509 510
25 16 26 20 17
MySQL query to convert timediff() to seconds?

For this, you can use TIME_TO_SEC() function. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> SourceTime time,
   -> DestinationTime time
   -> );
Query OK, 0 rows affected (1.33 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('10:20:00','4:50:54');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values('12:05:10','7:45:12');
Query OK, 1 row affected (0.30 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+-----------------+
| SourceTime | DestinationTime |
+------------+-----------------+
| 10:20:00   | 04:50:54        |
| 12:05:10   | 07:45:12        |
+------------+-----------------+
2 rows in set (0.00 sec)
Following is query to convert the time difference to seconds −
mysql> SELECT ABS(TIME_TO_SEC(timediff(DestinationTime, SourceTime))) from DemoTable;
This will produce the following output −
+---------------------------------------------------------+
| ABS(TIME_TO_SEC(timediff(DestinationTime, SourceTime))) |
+---------------------------------------------------------+
| 19746                                                   |
| 15598                                                   |
+---------------------------------------------------------+
2 rows in set (0.00 sec)
math Package in Golang

08 Jun, 2020
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package.
Example 1:
// Golang program to illustrate how to // find the IEEE 754 binary representation package main    import (     "fmt"    "math")    // Main function func main() {        // Finding IEEE 754 binary     // representation of the     // given numbers     // Using Float64bits() function     res_1 := math.Float64bits(2)     res_2 := math.Float64bits(1)     res_3 := math.Float64bits(0)     res_4 := math.Float64bits(2.3)        // Displaying the result     fmt.Println("Result 1: ", res_1)     fmt.Println("Result 2: ", res_2)     fmt.Println("Result 3: ", res_3)     fmt.Println("Result 4: ", res_4)    } 
Output:
Result 1: 4611686018427387904
Result 2: 4607182418800017408
Result 3: 0
Result 4: 4612361558371493478

Example 2:
// Golang program to illustrate // the use of math.Yn() function    package main    import (     "fmt"    "math")    // Main function func main() {        // Finding the order-n Bessel     // function of the second kind     // Using Yn() function     res_1 := math.Yn(-3, -2)     res_2 := math.Yn(6, 3)     res_3 := math.Yn(1, 1.1)     res_4 := math.Yn(1, math.NaN())     res_5 := math.Yn(-1, 0)        // Displaying the result     fmt.Println("Result 1: ", res_1)     fmt.Println("Result 2: ", res_2)     fmt.Println("Result 3: ", res_3)     fmt.Println("Result 4: ", res_4)     fmt.Println("Result 5: ", res_5)    } 
Output:
Result 1:  NaN
Result 2:  -5.436470340703773
Result 3:  -0.698119560067667
Result 4:  NaN
Result 5:  +Inf

Golang-Math
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Arrays in Go
Golang Maps
Interfaces in Golang
Slices in Golang
How to Parse JSON in Golang?
How to convert a string in lower case in Golang?
How to Trim a String in Golang?
Different Ways to Find the Type of Variable in Golang
PostgreSQL – JSON Data Type

22 Feb, 2021
JSON stands for JavaScript Object Notation. It is used to store data in the form of key-value pairs and is generally used for communicating between the server and the client. Contrary to other formats, JSON is human-readable text.PostgreSQL has support for native JSON data type since version 9.2. It offers numerous functions and operators for handling JSON data.
Syntax: variable_name json;
Now let’s look into a few examples for demonstration.
Example 1:First, create a table (say, orders) using the below command:
CREATE TABLE orders (
    ID serial NOT NULL PRIMARY KEY,
    info json NOT NULL
);
Now insert some data into the orders table as follows:
INSERT INTO orders (info)
VALUES
    (
        '{ "customer": "Raju Kumar", "items": {"product": "coffee", "qty": 6}}'
    );
Now we will query for the orders information using the below command:
SELECT
    info
FROM
    orders;
Output:
Example 2:In the above example we created an orders table and added single JSON data into it. In this example we will be looking onto inserting multiple JSON data in the same table using the command below:
INSERT INTO orders (info)
VALUES
    (
        '{ "customer": "Nikhil Aggarwal", "items": {"product": "Diaper", "qty": 24}}'
    ),
    (
        '{ "customer": "Anshul Aggarwal", "items": {"product": "Tampons", "qty": 1}}'
    ),
    (
        '{ "customer": "Naveen Arora", "items": {"product": "Toy Train", "qty": 2}}'
    );
Now we will query for the orders information using the below command:
SELECT
    info
FROM
    orders;
Output:
postgreSQL
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks

28 Jun, 2021
In the following pairs of OSI protocol layer/sub-layer and its functionality, the INCORRECT pair is(A) Network layer and Routing(B) Data Link Layer and Bit synchronization(C) Transport layer and End-to-end process communication(D) Medium Access Control sub-layer and Channel sharingAnswer: (B)Explanation:
1) Yes, Network layer does Rotuing
2) No, Bit synchronization is provided by Physical Layer
3) Yes, Transport layer provides End-to-end process 
   communication
4) Yes, Medium Access Control sub-layer of Data Link Layer provides
   Channel sharing. 
Quiz of this Question
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
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-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Lodash _.isEmpty() Method - GeeksforGeeks

29 Jul, 2020
The Lodash _.isEmpty() Method Checks if the value is an empty object, collection, map, or set. Objects are considered empty if they have no own enumerable string keyed properties. Collections are considered empty if they have a 0 length. Similarly, maps and sets are considered empty if they have a 0 size.
Syntax:
_.isEmpty( value )

Parameters: This method accepts a single parameter as mentioned above and described below:
value: This parameter holds the value that needs to be Checked for Empty value.
Return Value: This method returns a Boolean value(Returns true if the given value is an Empty value, else false).
Example 1: This method returns true when the value is null.
// Defining Lodash variableconst _ = require('lodash');      // Checking for Empty Valueconsole.log("The Value is Empty : "        +_.isEmpty(null));
Output:
The Value is Empty : true
Example 2: This method returns true when an Array is empty.
// Defining Lodash variableconst _ = require('lodash');      var val = []  // Checking for Empty Valueconsole.log("The Value is Empty : "        +_.isEmpty(val));
Output:
The Value is Empty : true
Example 3: This method returns true for Boolean value.
// Defining Lodash variableconst _ = require('lodash');      var val = false;  // Checking for Empty Valueconsole.log("The Value is Empty : "         +_.isEmpty(val));
Output:
The Value is Empty : true
Example 4: In this example, the method will return false.
// Defining Lodash variableconst _ = require('lodash');      var val = { "a": 1 };  // Checking for Empty Valueconsole.log("The Value is Empty : "         +_.isEmpty(val)); 
Output:
The Value is Empty : false
Note: This will not work in normal JavaScript because it requires the lodash library to be installed. 
Lodash library can be installed using npm install lodash.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
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?
C# | Check if Output is Redirected on the Console or not - GeeksforGeeks

28 Jan, 2019
Given the normal Console in C#, the task is to check if the Output is Redirected on the Console.
Approach: This can be done using the IsOutputRedirected property in the Console class of the System package in C#. This property returns a boolean value stating whether the Output is Redirected or not.
Program:
// C# program to demonstrate the// Console.IsOutputRedirected Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;  namespace GFG {  class Program {      // Main Method    static void Main(string[] args)    {          // Check if Output is Redirected        Console.WriteLine("Is Output Redirected: {0}",                          Console.IsOutputRedirected);    }}}
Output:
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Linked List Implementation in C#
Histograms Equalization using Python OpenCv Module

This is a method in image processing to do contrast adjustment using the image's histogram.
Actually this method usually increases the global contrast of many images, especially when the usable data of the image is represented by close contrast values and through this adjustment, the intensities can be better distributed on the histogram and it allows for areas of lower local contrast to gain a higher contrast.
OpenCV has a function to do this, cv2.equalizeHist() and its input is just grayscale image and output is our histogram equalized image.
This technique is good when histogram of the image is confined to a particular region and it won't work good in places where there are large intensity variations and where histogram covers a large region, i.e. both bright and dark pixels are present.
import cv2
# import Numpy
import numpy as np
# reading an image using imreadmethod
my_img = cv2.imread('C:/Users/TP/Pictures/west bengal/bishnupur/pp.jpg', 0)
equ = cv2.equalizeHist(my_img)
# stacking both the images side-by-side orientation
res = np.hstack((my_img, equ))
# showing image input vs output
cv2.imshow('image', res)
cv2.waitKey(0)
cv2.destroyAllWindows()