code-rag-bench/online-tutorials huggingface dataset:
How to write the comparator as a lambda expression in Java?

A lambda expression is an anonymous method and doesn't execute on its own in java. Instead, it is used to implement a method defined by the functional interface. A lambda expression used with any functional interface and Comparator is a functional interface. The Comparator interface has used when sorting a collection of objects compared with each other.
In the below example, we can sort the employee list by name using the Comparator interface.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Employee {
   int id;
   String name;
   double salary;
   public Employee(int id, String name, double salary) {
      super();
      this.id = id;
      this.name = name;
      this.salary = salary;
   }
}
public class LambdaComparatorTest {
   public static void main(String[] args) {
      List<Employee> list = new ArrayList<Employee>();

      // Adding employees
      list.add(new Employee(115, "Adithya", 25000.00));
      list.add(new Employee(125, "Jai", 30000.00));
      list.add(new Employee(135, "Chaitanya", 40000.00));
      System.out.println("Sorting the employee list based on the name");

      // implementing lambda expression
      Collections.sort(list, (p1, p2) -> {
         return p1.name.compareTo(p2.name); 
      }); 
      for(Employee e : list) {
         System.out.println(e.id + " " + e.name + " " + e.salary);
      }
   }
}
Sorting the employee list based on the name
115 Adithya 25000.0
135 Chaitanya 40000.0
125 Jai 30000.0
QlikView - Bar Chart

Bar charts are very widely used charting method to study the relation between two dimensions in form of bars. The height of the bar in the graph represents the value of one dimension. The number of bars represent the sequence of values or grouped values of another dimension.
Let us consider the following input data, which represents the sales figure of different product lines and product categories.
Product_Line,Product_category,Value
Sporting Goods,Outdoor Recreation,5642
Food, Beverages & Tobacco,2514
Apparel & Accessories,Clothing,2365
Apparel & Accessories,Costumes & Accessories,4487
Sporting Goods,Athletics,812
Health & Beauty,Personal Care,6912
Arts & Entertainment,Hobbies & Creative Arts,5201
Arts & Entertainment,Paintings,8451
Arts & Entertainment,Musical Instruments,1245
Hardware,Tool Accessories,456
Home & Garden,Bathroom Accessories,241
Food,Drinks,1247
Home & Garden,Lawn & Garden,5462
Office Supplies,Presentation Supplies,577
Hardware,Blocks,548
Baby & Toddler,Diapering,1247
Baby & Toddler,Toys,257
Home & Garden,Pipes,1241
Office Supplies,Display Board,2177

The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option form the "Data from Files" tab and browse for the file containing the above data. Edit the load script to add the following code. Click "OK" and press "Control+R" to load the data into
the QlikView's memory.
LOAD Product_Line, 
     Product_category, 
     Value
FROM
[C:\Qlikview\data\product_sales.csv]
(txt, codepage is 1252, embedded labels, delimiter is ',', msq);
For the above data, let us create a Table Box, which will show the data in a tabular form. Go to the menu Layout → New Sheet Object → Table Box and choose the column as shown below.
Click Apply and then OK to finish creating the Table box. The below given screen appears.
To start creating a bar chart, we will use the quick chart wizard. On clicking it, the following
screen appears which prompts for selecting the chart type. Choose bar Chart and click
Next.
Choose Product Line as the First Dimension.
The chart expression is used to apply the functions like Sum, Average, or Count on the fields with numeric values. We will apply the Sum function on the filed named Value. Click Next.
The Chart format defines the style and orientation of the chart. We choose the first option
in each category. Click Next.
The Bar chart appears as shown below. It shows the height of the field value for different product lines.

    70 Lectures 
     5 hours 

 Arthur Fong
 Print
 Add Notes
 Bookmark this page
Drawing multiple figures in parallel in Python with Matplotlib

To draw multiple figures in parallel in Python with matplolib, we can take the following steps−
Create random data using numpy.
Add a subplot to the current figure, nrows=1, ncols=4 and at index=1.
Display data as an image, i.e., on a 2D regular raster, using imshow() method with cmap="Blues_r".
Add a subplot to the current figure, nrows=1, ncols=4 and at index=2.
Display data as an image, i.e., on a 2D regular raster, using imshow() method with cmap="Accent_r".
Add a subplot to the current figure, nrows=1, ncols=4 and at index=3.
Display data as an image, i.e., on a 2D regular raster, using imshow() method with cmap="terrain_r"
Add a subplot to the current figure, nrows=1, ncols=4 and at index=4.
Display data as an image, i.e., on a 2D regular raster, using imshow() method with cmap="twilight_shifted_r".
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.rand(5, 5)
plt.subplot(1, 4, 1)
plt.imshow(data, cmap="Blues_r")
plt.subplot(1, 4, 2)
plt.imshow(data, cmap="Accent_r")
plt.subplot(1, 4, 3)
plt.imshow(data, cmap="terrain_r")
plt.subplot(1, 4, 4)
plt.imshow(data, cmap="twilight_shifted_r")
plt.show()
Sum of square of first n odd numbers

The series of squares of first n odd numbers takes squares of of first n odd numbers in series.
The series is: 1,9,25,49,81,121...
The series can also be written as − 12, 32, 52, 72, 92, 112....
The sum of this series has a mathematical formula −
n(2n+1)(2n-1)/ 3= n(4n2 - 1)/3
Lets take an example,
Input: N = 4
Output: sum =
12 + 32 + 52 + 72 = 1 +9+ 25 + 49 = 84
Using formula, sum = 4(4(4)2- 1)/3 = 4(64-1)/3 = 4(63)/3 = 4*21 = 84 both these methods are good but the one using mathematical formula is better because it does not use looks which reduces its time complexity.
#include <stdio.h>
int main() {
   int n = 8;
   int sum = 0;
   for (int i = 1; i <= n; i++)
      sum += (2*i - 1) * (2*i - 1);
   printf("The sum of square of first %d odd numbers is %d",n, sum);
   return 0;
}
The sum of square of first 8 odd numbers is 680
#include <stdio.h>
int main() {
   int n = 18;
   int sum = ((n*((4*n*n)-1))/3);
   printf("The sum of square of first %d odd numbers is %d",n, sum);
   return 0;
}
The sum of square of first 18 odd numbers is 7770
Write a program to form a cumulative sum list in Python

The cumulative sum till ith element refers to the total sum from 0th to ith element.
The program statement is to form a new list from a given list. The ith element in the new list will be the cumulative sum from 0 to ith element in the given list.
For example,
[10,20,30,40,50]
[10,30,60,100,150]
[1,2,3,4,5]
[1,3,6,10,15]
Following is a program to form a cumulative sum list using the input list −
The input list is passed to the function cumSum() which returns the cumulative sum list.
The input list is passed to the function cumSum() which returns the cumulative sum list.
We declare an empty list cum_list to which we will append elements to form the cumulative sum list.
We declare an empty list cum_list to which we will append elements to form the cumulative sum list.
Initialize a sum variable sm=0.
Initialize a sum variable sm=0.
Start iterating over the input list, with each iteration we increment the sum value to previous value+ the current element.
Start iterating over the input list, with each iteration we increment the sum value to previous value+ the current element.
On each iteration, the sum value is appended to the cum_list.
On each iteration, the sum value is appended to the cum_list.
Thus, on ith iteration, the sum variable will contain sum till the ith element(included), which is then appended to the cum_list.
Thus, on ith iteration, the sum variable will contain sum till the ith element(included), which is then appended to the cum_list.
After iterating through the whole list, the cum_list is returned.
After iterating through the whole list, the cum_list is returned.
 Live Demo
def cumSum(s):
   sm=0
   cum_list=[]
   for i in s:
      sm=sm+i
      cum_list.append(sm)
   return cum_list

a=[10,20,30,40,50]
print(cumSum(a))
[10, 30, 60, 100, 150]
Convert String to Tuple in Python

When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used.
The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.
The 'int' method converts the given data type to an integer type, if that operation is permitted.
The split method splits the given data into different sections based on a delimiter or a default delimiter. The 'tuple' method converts the given data type into a tuple type.
Below is a demonstration of the same −
Live Demo
my_str_1 = "7, 8, 0, 3, 45, 3, 2, 22, 4"

print ("The string is : " )
print(my_str_1)

my_result = tuple(map(int, my_str_1.split(', ')))

print("The tuple after converting from a string is : ")
print(my_result)
The string is :
7, 8, 0, 3, 45, 3, 2, 22, 4
The tuple after converting from a string is :
(7, 8, 0, 3, 45, 3, 2, 22, 4)
A string is defined and is displayed on the console.
The string is split, and every element is converted to an integer, and this operation is applied to every element using the 'map' method.
This is again converted to a tuple type.
This result is assigned to a value.
It is displayed as output on the console.
Lucky Numbers

Lucky numbers are some special integer numbers. From basic numbers, some special numbers are eliminated by their position. Instead of their value, for their position, the numbers are eliminated. The numbers which are not deleted, they are the lucky numbers.
The number deletion follows some rule. At first, every second number are deleted, after that, all 3rd numbers are deleted and so on.
Here is some example −
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 (1 – 25 all)
1 3 5 7 9 11 13 15 17 19 21 23 25 (deleting all 2nd numbers)
1 3 7 9 13 15 19 21 25 (All 3rd numbers are deleted, starting from 5)
1 3 7 9 13 15 21 25 (All 7th numbers are deleted starting from 19)
Input: Put a number to check whether it is lucky or not. Let the number is 13 Output: 13 is a lucky number.
isLuckyNumber(number)
Input − A number.
Output − Check the number is lucky or not.
Begin
   counter := 2 (It is static data, not be initialized again in recursion call)
   if counter > n, then
      return 1
   if n mod counter = 0, then
      return 0
   n := n – (n / counter)
   counter := counter + 1
   isLuckyNumber(n)
End
#include <iostream>
using namespace std;

int counter = 2;    //used during recursion

bool isLuckyNumber(int n) {
   if(counter > n)
      return 1;
   if(n%counter == 0)
      return 0;
   
   n -= n/counter;    //n will be next position for recursion
   counter++;
   return isLuckyNumber(n);
}

int main() {
   int x = 13;

   if(isLuckyNumber(x))
      cout << x<<" is a lucky number.";
   else
      cout << x<<" is not a lucky number.";
}
13 is a lucky number.
Create a MySQL stored procedure that generates five random numbers?

With the help of the following query we can create a stored procedure to generate five random numbers −
mysql> DELIMITER //
mysql> DROP PROCEDURE IF EXISTS RandomNumbers;
    -> CREATE PROCEDURE RandomNumbers()
    -> BEGIN
    -> SET @i = 0;
    -> REPEAT
    -> SELECT RAND() AS 'Random Number';
    -> SET @i = @i + 1;
    -> UNTIL @i >=5 END REPEAT;
    -> END
    -> //
Query OK, 0 rows affected (0.16 sec)

Query OK, 0 rows affected (0.16 sec)
Now, invoke the procedure to get the result −
mysql> DELIMITER ;
mysql> CALL RandomNumbers();
+---------------------+
| Random Number       |
+---------------------+
| 0.25968261739209536 |
+---------------------+
1 row in set (0.00 sec)

+--------------------+
| Random Number |
+--------------------+
| 0.1659662734400167 |
+--------------------+
1 row in set (0.01 sec)

+---------------------+
| Random Number       |
+---------------------+
| 0.05078354575744229 |
+---------------------+
1 row in set (0.01 sec)

+--------------------+
| Random Number      |
+--------------------+
| 0.7560189392008064 |
+--------------------+
1 row in set (0.04 sec)

+------------------+
| Random Number    |
+------------------+
| 0.62774408946535 |
+------------------+
1 row in set (0.04 sec)

Query OK, 0 rows affected (0.05 sec)
C program to interchange the diagonal elements in given matrix

We need to write a code to interchange the main diagonal elements with the secondary diagonal elements. The size of the matrix is given at runtime.
If the size of matrix m and n values are not equal, then it prints that the given matrix is not a square.
Only a square matrix can interchange the main diagonal elements and can interchange with the secondary diagonal elements.
The solution to write a C program to interchange the diagonal elements in given matrix is as follows −
The logic to interchange the diagonal elements is explained below −
for (i=0;i<m;++i){
   a = ma[i][i];
   ma[i][i] = ma[i][m-i-1];
   ma[i][m-i-1] = a;
}
Following is the C program to interchange the diagonal elements in given matrix −
 Live Demo
#include<stdio.h>
main (){
   int i,j,m,n,a;
   static int ma[10][10];
   printf ("Enter the order of the matrix m and n\n");
   scanf ("%dx%d",&m,&n);
   if (m==n){
      printf ("Enter the co-efficients of the matrix\n");
      for (i=0;i<m;++i){
         for (j=0;j<n;++j){
            scanf ("%d",&ma[i][j]);
         }
      }
      printf ("The given matrix is \n");
      for (i=0;i<m;++i){
         for (j=0;j<n;++j){
            printf (" %d",ma[i][j]);
         }
         printf ("\n");
      }
      for (i=0;i<m;++i){
         a = ma[i][i];
         ma[i][i] = ma[i][m-i-1];
         ma[i][m-i-1] = a;
      }
      printf ("Matrix after changing the \n");
      printf ("Main & secondary diagonal\n");
      for (i=0;i<m;++i){
         for (j=0;j<n;++j){
            printf (" %d",ma[i][j]);
         }
         printf ("\n");
      }
   }
   else
      printf ("The given order is not square matrix\n");
}
When the above program is executed, it produces the following result −
Run 1:
Enter the order of the matrix m and n
3x3
Enter the co-efficient of the matrix
1
2
3
4
5
6
7
8
9
The given matrix is
1 2 3
4 5 6
7 8 9
Matrix after changing the
Main & secondary diagonal
3 2 1
4 5 6
9 8 7

Run 2:
Enter the order of the matrix m and n
4x3
The given order is not square matrix
Python - Filtering data with Pandas .query() method

Pandas is a very widely used python library for data cleansing, data analysis etc. In this article we will see how we can use the query method to fetch specific data from a given data set. We can have both single and multiple conditions inside a query.
Let’s first read the data into a pandas data frame using the pandas library. The below program just does that.
import pandas as pd

# Reading data frame from csv file
data = pd.read_csv("D:\\heart.csv")

print(data)
Running the above code gives us the following result −
Next we see how we can use the query method with single condition. As you can see only 119 rows from the original 303 rows are returned as a result.
import pandas as pd

# Data frame from csv file
data = pd.read_csv("D:\\heart.csv")

data.query('chol < 230', inplace=True)

# Result
print(data)
Running the above code gives us the following result −
In a similar approach as above we can apply multiple conditions to the query method. This will restrict the result data set further. Only 79 rows are returned now when we also restrict the age to greater than 60.
import pandas as pd

# Data frame from csv file
data = pd.read_csv("D:\\heart.csv")

data.query('chol < 230' and 'age > 60', inplace=True)

# Result
print(data)
Running the above code gives us the following result −
C# | Check if an element is in the Collection<T>

01 Feb, 2019
Collection<T>.Contains(T) method is used to determine whether an element is in the Collection<T>.
Syntax:
public bool Contains (T item);

Here, item is the object to locate in the Collection<T>. The value can be null for reference types.
Return Value: This method return True if item is found in the Collection<T>, otherwise, False.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to check if an// element is in the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel;  class GFG {      // Driver code    public static void Main()    {        // Creating a collection of strings        Collection<string> myColl = new Collection<string>();          myColl.Add("A");        myColl.Add("B");        myColl.Add("C");        myColl.Add("D");        myColl.Add("E");          // Checking if an element is in the Collection        // The function returns "True" if the        // item is present in Collection        // else returns "False"        Console.WriteLine(myColl.Contains("A"));    }}
Output:
True

Example 2:
// C# code to check if an// element is in the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel;  class GFG {      // Driver code    public static void Main()    {        // Creating a collection of ints        Collection<int> myColl = new Collection<int>();          myColl.Add(2);        myColl.Add(3);        myColl.Add(4);        myColl.Add(5);          // Checking if an element is in the Collection        // The function returns "True" if the        // item is present in Collection        // else returns "False"        Console.WriteLine(myColl.Contains(6));    }}
Output:
False

Note: This method performs a linear search. Therefore, this method is an O(n) operation, where n is Count.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.contains?view=netframework-4.7.2
CSharp-Collection-Class
CSharp-Collections.ObjectModel-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C#
\substack - Tex Command

\substack - Used to create multi-line subscripts or superscripts.
{ \substack}
\substack command draws multi-line subscripts or superscripts.

\sum_{
\substack{
1\lt i\lt 3 \\
1\le j\lt 5
}}
a_{ij}


∑1<i<31≤j<5aij


^{\substack{\text{a very} \\
\text{contrived} \\
\text{example}
}}
{\frac ab}_{\substack{
\text{isn't} \\
\text{it?}
}}


a verycontrivedexampleabisn'tit?



\sum_{
\substack{
1\lt i\lt 3 \\
1\le j\lt 5
}}
a_{ij}


∑1<i<31≤j<5aij


\sum_{
\substack{
1\lt i\lt 3 \\
1\le j\lt 5
}}
a_{ij}

^{\substack{\text{a very} \\
\text{contrived} \\
\text{example}
}}
{\frac ab}_{\substack{
\text{isn't} \\
\text{it?}
}}


a verycontrivedexampleabisn'tit?


^{\substack{\text{a very} \\
Read a zipped file as a Pandas DataFrame

28 Sep, 2021
In this article, we will try to find out how can we read data from a zip file using a panda data frame. 
People use related groups of files together and to make files compact, so they are easier and faster to share via the web. Zip files are ideal for archiving since they save storage space. And, they are also useful for securing data using the encryption method.
Requirement: 
zipfile36 module: This module is used to perform various operations on a zip file using a simple python program. It can be installed using the below command:
pip install zipfile36
Method #1: Using compression=zip in pandas.read_csv() method. 
By assigning the compression argument in read_csv() method as zip, then pandas will first decompress the zip and then will create the dataframe from CSV file present in the zipped file. 
Python3
# import required modulesimport zipfileimport pandas as pd # read the dataset using the compression zipdf = pd.read_csv('test.zip',compression='zip') # display datasetprint(df.head())
Output:
Method #2: Opening the zip file to get the CSV file.
Here, initially, the zipped file is opened and the CSV file is extracted, and then a dataframe is created from the extracted CSV file. 
Python3
# import required modulesimport zipfileimport pandas as pd # open zipped datasetwith zipfile.ZipFile("test.zip") as z:   # open the csv file in the dataset   with z.open("test.csv") as f:             # read the dataset      train = pd.read_csv(f)             # display dataset      print(train.head())
Output:
surindertarika1234
Python pandas-io
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
What does .modal(‘dispose’) do in Bootstrap 4 ?

13 Mar, 2020
In Bootstrap 4, .modal(‘dispose’) is a function defined to destroy the modal. The modal remains a part of the DOM even after using .modal(‘dispose’), this function only destroys the current instance of the modal component.
Syntax:
$("#modalID").modal("dispose");
Example: This example illustrates the use of .modal(‘dispose’) method. When the dispose button is clicked, the jQuery instance of the modal component gets deleted. Hence, none of the other modal functions work after the button has been clicked.
<!DOCTYPE html><html lang="en">  <head>    <title>Dispose Modal</title>    <meta charset="UTF-8">    <link rel="stylesheet"           href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">  </script>    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js">  </script>    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js">  </script></head>  <body>    <button id="clickBtn"             class="btn btn-primary">      Click Me!  </button>      <div id="myModal" class="modal fade">        <div class="modal-dialog">            <div class="modal-content">                <div class="modal-header">                    <h5 class="modal-title">Example Modal</h5>                    <button id="dismissBtn"                            type="button"                            class="close">                        <span aria-hidden="true">×</span>                    </button>                </div>                <div class="modal-body">                    Body of the Modal                </div>                <div class="modal-footer">                    <button id="closeBtn"                            class="btn btn-secondary">                      Close                  </button>                    <button id="disposeBtn"                            class="btn btn-secondary">                      Dispose                  </button>                </div>            </div>        </div>    </div></body>  <script>    $(document).ready(function() {        $("#clickBtn").click(function() {            $("#myModal").modal('show');        });        $("#dismissBtn").click(function() {            $("#myModal").modal('hide');        });        $("#closeBtn").click(function() {            $("#myModal").modal('hide');        });        $("#disposeBtn").click(function() {            $("#myModal").modal('dispose');        });    });</script>  </html>
Output:
Note: To close the modal after using the dispose function, we can modify the above code to hide the modal and remove the fade class along with destroying it.
$("#disposeBtn").click(function(){
     $("#myModal").removeClass('fade').modal('hide');
     $("#myModal").modal("dispose");
});

Bootstrap-Misc
Picked
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Converting Color video to grayscale using OpenCV in Python

20 Oct, 2021
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will see how to convert a colored video to a gray-scale format.
Approach:
Import the cv2 module.Read the video file to be converted using the cv2.VideoCapture() method.Run an infinite loop.Inside the loop extract the frames of the video using the read() method.Pass the frame to the cv2.cvtColor() method with cv2.COLOR_BGR2GRAY as a parameter to convert it into gray-scale.Display the frame using the cv2.imshow() method.
Import the cv2 module.
Read the video file to be converted using the cv2.VideoCapture() method.
Run an infinite loop.
Inside the loop extract the frames of the video using the read() method.
Pass the frame to the cv2.cvtColor() method with cv2.COLOR_BGR2GRAY as a parameter to convert it into gray-scale.
Display the frame using the cv2.imshow() method.
Example: Suppose we have the video file CountdownTimer.mov as the input.
Python3
# importing the moduleimport cv2 # reading the videosource = cv2.VideoCapture('Countdown Timer.mov') # running the loopwhile True:     # extracting the frames    ret, img = source.read()         # converting to gray-scale    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)     # displaying the video    cv2.imshow("Live", gray)     # exiting the loop    key = cv2.waitKey(1)    if key == ord("q"):        break     # closing the windowcv2.destroyAllWindows()source.release()
 
 
Output:
 
 
simmytarika5
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Matplotlib.axes.Axes.streamplot() in Python

16 Jun, 2022
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.streamplot() function in axes module of matplotlib library is also used to draw streamlines of a vector flow..
Syntax: Axes.streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle=’-|>’, minlength=0.1, transform=None, zorder=None, start_points=None, maxlength=4.0, integration_direction=’both’, *, data=None) Parameters: This method accept the following parameters that are described below:
X, Y : These parameter are the x and y coordinates of the evenly spaced grid.
U, V: This parameter is the number of rows and columns must match the length of y and x.
density : This parameter is used to controls the closeness of streamlines.
linewidth : This parameter is the width of the stream lines.
color : This parameter is the streamline color.
cmap : This parameter is used to plot streamlines and arrows.
norm : This parameter is used to normalize object used to scale luminance data to 0, 1.
arrowsize : This parameter is the scaling factor for the arrow size.
minlength : This parameter is the minimum length of streamline in axes coordinates..
maxlength : This parameter is the maximum length of streamline in axes coordinates.
zorder : This parameter is the zorder of the stream lines and arrows.
Returns:This method returns the following:
stream_container :This returns the StreamplotSet Container object with attributes
Below examples illustrate the matplotlib.axes.Axes.streamplot() function in matplotlib.axes: Example 1: 
Python3
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np      X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2),                   np.arange(0, 2 * np.pi, .2))U = np.cos(X**2)V = np.sin(Y**2) fig, ax = plt.subplots()ax.streamplot(X, Y, U, V, density =[0.5, 1]) ax.set_title('matplotlib.axes.Axes.streamplot()\ Example\n', fontsize = 14, fontweight ='bold')plt.show()
Output:  Example 2: 
Python3
# Implementation of matplotlib function  import matplotlib.pyplot as pltimport numpy as np      X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2),                   np.arange(0, 2 * np.pi, .2))U = np.cos(X**2)V = np.sin(Y**2) fig, (ax, ax1)= plt.subplots(nrows = 2, ncols = 1)ax.streamplot(X, Y, U, V, density =[0.5, 1],             color = V * U, linewidth = 2,             cmap ='autumn')val = np.array([[2, 1, 0, 1, 2, 1],                [2, 1,  0, 1, 2, 2]]) ax1.streamplot(X, Y, U, V, color = V * U, linewidth = 2,               cmap ='autumn',               start_points = val.T) ax.set_title('matplotlib.axes.Axes.streamplot() \Example\n', fontsize = 14, fontweight ='bold')plt.show()
Output: 
surinderdawra388
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Print Right Triangle Star Pattern

09 Mar, 2021
In this article, we will learn about printing Right Triangle Star Pattern.
Examples:
Input : n = 5
Output: 
* 
* * 
* * * 
* * * * 
* * * * *  
Right Triangle Star Pattern:
Java
import java.io.*;  // Java code to demonstrate right star trianglepublic class GeeksForGeeks {    // Function to demonstrate printing pattern    public static void StarRightTriangle(int n)    {        int a, b;          // outer loop to handle number of rows        // k in this case        for (a = 0; a < n; a++) {              // inner loop to handle number of columns            // values changing acc. to outer loop            for (b = 0; b <= a; b++) {                // printing stars                System.out.print("* ");            }              // end-line            System.out.println();        }    }      // Driver Function    public static void main(String args[])    {        int k = 5;        StarRightTriangle(k);    }}
* 
* * 
* * * 
* * * * 
* * * * * 
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between data type and data structure

27 Dec, 2019
Data Type
A data type is the most basic and the most common classification of data. It is this through which the compiler gets to know the form or the type of information that will be used throughout the code. So basically data type is a type of information transmitted between the programmer and the compiler where the programmer informs the compiler about what type of data is to be stored and also tells how much space it requires in the memory. Some basic examples are int, string etc. It is the type of any variable used in the code.
#include <iostream.h>using namespace std;  void main(){    int a;    a = 5;      float b;    b = 5.0;      char c;    c = 'A';      char d[10];    d = "example";}
As seen from the theory explained above we come to know that in the above code, the variable ‘a’ is of data type integer which is denoted by int a. So the variable ‘a’ will be used as an integer type variable throughout the process of the code. And, in the same way, the variables ‘b’, ‘c’ and ‘d’ are of type float, character and string respectively. And all these are kinds of data types.
Data Structure
A data structure is a collection of different forms and different types of data that has a set of specific operations that can be performed. It is a collection of data types. It is a way of organizing the items in terms of memory, and also the way of accessing each item through some defined logic. Some examples of data structures are stacks, queues, linked lists, binary tree and many more.
Data structures perform some special operations only like insertion, deletion and traversal. For example, you have to store data for many employees where each employee has his name, employee id and a mobile number. So this kind of data requires complex data management, which means it requires data structure comprised of multiple primitive data types. So data structures are one of the most important aspects when implementing coding concepts in real-world applications.
Difference between data type and data structure:
HarshitHiremath
Picked
Data Structures
Difference Between
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Advantages and Disadvantages of Linked List
Data Structures | Array | Question 2
Data Structures | Binary Search Trees | Question 8
Data Structures | Queue | Question 2
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Python program to split and join a string?

Python program provides built in function for string joining and split of a string.
split
Str.split()
join
Str1.join(str2)

Step 1: Input a string.
Step 2: here we use split method for splitting and for joining use join function.
Step 3: display output.

#split of string
str1=input("Enter first String with space :: ")
print(str1.split())    #splits at space

str2=input("Enter second String with (,) :: ")
print(str2.split(','))    #splits at ','

str3=input("Enter third String with (:) :: ")
print(str3.split(':'))    #splits at ':'

str4=input("Enter fourth String with (;) :: ")
print(str4.split(';'))    #splits at ';'

str5=input("Enter fifth String without space :: ")
print([str5[i:i+2]for i in range(0,len(str5),2)])    #splits at position 2
Enter first String with space :: python program
['python', 'program']
Enter second String with (,) :: python, program
['python', 'program']
Enter third String with (:) :: python: program
['python', 'program']
Enter fourth String with (;) :: python; program
['python', 'program']
Enter fifth String without space :: python program
['py', 'th', 'on', 'pr', 'og', 'ra', 'm']

#string joining
str1=input("Enter first String   :: ")
str2=input("Enter second String  :: ")
str=str2.join(str1)     #each character of str1 is concatenated to the #front of str2
print(“AFTER JOINING OF TWO STRING ::>”,str)
Enter first String   :: AAA
Enter second String  :: BBB
AFTER JOINING OF TWO STRING ::>ABBBABBBA
How to autoplay audio on chrome ?

05 Jun, 2020
Here we will learn how to auto-play audio on selected devices in web pages. To load the audio in the web page, we use the <audio> tag.
There are some attribute of this “audio” tag:
controls: This feature is used for audio be visible the controls on the web pages. After using this feature, we can pause or play music, high or low music.
autoplay: This feature is used for audio to start audio clip when page load. If you run a web page, the audio file will load and just the audio will play automatically.
Example:
<!DOCTYPE html> <html>   <head>     <title>         HTML audio autoplay Attribute     </title> </head>   <body style="text-align: center">       <h1 style="color: green">         GeeksforGeeks     </h1>           <h2>HTML audio autoplay Attribute</h2>       <audio controls autoplay>         <source src="GFG.ogg" type="audio/ogg">         <source src="GFG.mp3" type="audio/mpeg">     </audio> </body>   </html>
Output:
HTML-Misc
HTML5
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js os.platform() Method

13 Oct, 2021
The os.platform() method is an inbuilt application programming interface of the os module which is used to get the Operating system platform. 
Syntax:  
os.platform()
Parameters: This method does not accept any parameters.Return Value: This method returns a string that represents operating system platform. The returned values can be one of these ‘aix’, ‘android’, ‘darwin’, ‘freebsd’, ‘linux’, ‘openbsd’, ‘sunos’, and ‘win32’. This values is set at compile time.Below examples illustrate the use of os.platform() method in Node.js:Example 1: 
javascript
// Node.js program to demonstrate the    // os.platform() method      // Require os moduleconst os = require('os');  // Printing os.platform() valueconsole.log(os.platform());
Output:  
linux
Example 2: This example is the alternative of first example. 
javascript
// Node.js program to demonstrate the    // os.platform() methodconsole.log(process.platform);
Output:  
linux
Example 3: 
javascript
// Node.js program to demonstrate the    // os.platform() method      // Require os moduleconst os = require('os');  // Printing os.platform() valuevar platform = os.platform();  switch(platform) {    case 'aix': console.log("IBM AIX platform");        break;    case 'android': console.log("Android platform");        break;    case 'darwin': console.log("Darwin platform(MacOS, IOS etc)");        break;    case 'freebsd': console.log("FreeBSD Platform");        break;    case 'linux': console.log("Linux Platform");        break;    case 'openbsd': console.log("OpenBSD platform");        break;    case 'sunos': console.log("SunOS platform");        break;    case 'win32': console.log("windows platform");        break;        default: console.log("unknown platform");}
Output:  
Linux Platform
Note: The above program will compile and run by using the node index.js command.Reference: https://nodejs.org/api/os.html#os_os_platform
simmytarika5
Node.js-Methods
Node.js-os-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to plot Andrews curves using Pandas in Python? - GeeksforGeeks

01 Aug, 2020
Andrews curves are used for visualizing high-dimensional data by mapping each observation onto a function. It preserves means, distance, and variances. It is given by formula:
T(n) = x_1/sqrt(2) + x_2 sin(n) + x_3 cos(n) + x_4 sin(2n) + x_5 cos(2n) + ...
Plotting Andrews curves on a graph can be done using the andrews_curves() method of the plotting module. This function generates a matplotlib plot of Andrews curves, for visualising clusters of multivariate data.
Syntax: andrews_curves(frame, class_column, ax=None, samples=200, color=None, colormap=None, **kwargs)
Parameters:
frame: It is the data to be plotted.
class_column: This is the name of the column containing class names.
ax: This parameter is a matplotlib axes object. Its default value is None.
samples: This parameter is the number of points to plot in each curve.
color: This parameter is an optional parameter and it is the list or tuple of colors to use for the different classes.
colormap: This parameter is the string/matplotlib colormap object. Its default value is None.
Returns: This function returns an object of class matplotlip.axis.Axes
Example 1: In the following example, A data frame is made from the CSV file and the data frame is used to plot andrews_curves. The used CSV file is here.
Python3
# importing various packageimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt  # making data frame from csv filedf = pd.read_csv(    'C:\\Users\\digital india\\Desktop\\pand.csv')  # Creating Andrews curvesx = pd.plotting.andrews_curves(df, 'animal')  # ploting the Curvex.plot()  # Displayplt.show()
Output:
Example 2: 
Python3
# importing various packageimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt  # making data frame from csv filedf = pd.read_csv(    'https://raw.github.com/pandas-dev/'    'pandas/master/pandas/tests/io/data/csv/iris.csv')  # Creating Andrews curvesx = pd.plotting.andrews_curves(df, 'Name')  # ploting the Curvex.plot()  # Displayplt.show()
Output:
Python pandas-plotting
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Does MySQL converts bool to tinyint(1) internally?


Yes, MySQL internally convert bool to tinyint(1) because tinyint is the smallest integer data type.
You can also say the bool is synonym for tinyint(1). Let us first create a sample table:
mysql> create table boolToTinyIntDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20),
   -> isAgeGreaterThan18 bool
   -> );
Query OK, 0 rows affected (1.02 sec)
Let us now check the description of table:
mysql> desc boolToTinyIntDemo;
This will produce the following output
+--------------------+-------------+------+-----+---------+----------------+
| Field              | Type        | Null | Key | Default | Extra          |
+--------------------+-------------+------+-----+---------+----------------+
| Id                 | int(11)     | NO   | PRI | NULL    | auto_increment |
| Name               | varchar(20) | YES  |     | NULL    |                |
| isAgeGreaterThan18 | tinyint(1)  | YES  |     | NULL    |                |
+--------------------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
Look at the above sample output, the column isAgeGreaterThan18 data type is converted from bool to tinyint(1) internally.
Following is the query to insert some records in the table using insert command:
mysql> insert into boolToTinyIntDemo(Name,isAgeGreaterThan18) values('Larry',true);
Query OK, 1 row affected (0.18 sec)

mysql> insert into boolToTinyIntDemo(Name,isAgeGreaterThan18) values('Sam',false);
Query OK, 1 row affected (0.14 sec)
Following is the query to display records from the table using select command:
mysql> select *from boolToTinyIntDemo;
This will produce the following output
+----+-------+--------------------+
| Id | Name  | isAgeGreaterThan18 |
+----+-------+--------------------+
| 1  | Larry |                  1 |
| 2  | Sam   |                  0 |
+----+-------+--------------------+
2 rows in set (0.00 sec)
Creating Reports with R Markdown. An explanation of writing a report... | by Jaemin Lee | Towards Data Science

It’s easy to turn python scripts into reports using Jupyter notebook or Google Colab. Did you know that you could also do the same for R scripts?
In this tutorial, I’m going to demonstrate how to turn your R script into a report.
We need to have two software installed.
RR Studio — Free version
R
R Studio — Free version
Make sure to download the package which lets you convert your R Markdown files into reports.
You can run the command (shown below) in the console to download the package.
install.packages("knitr")
Under the “File” tab, click “New File” and “R Markdown”.
Name your file and choose the default output format. You can always change the output format later.
Once you hit “Ok”, you can now code and write a report on R Markdown.
The highlighted section (or the cell) is where you can write your code.
```{r cars}YOU CAN WRITE YOUR CODE HERE```
And the non-highlighted section is where you can write your report.
You can run the code in the entire cell by clicking the green run button on the upper right corner in the cell.
Alternatively, you can hit Ctrl + Enter to only run the selected code.
For you to knit R Markdown files, you may need to install a few packages. R studio will automatically detect that you are missing the necessary packages and it will ask you to download them.
There are three ways of outputting your report.
HTMLPDFMS Word
HTML
PDF
MS Word
HTML Output
PDF Output
MS Word Output
I hope you find this post useful. Thank you for reading it!
MongoDB $push in nested array?

Here, $push can be used to add new documents in nested array. To understand the above $push concept, let us create a collection with nested array document. The query to create a collection with document is as follows:
>db.nestedArrayDemo.insertOne({"EmployeeName":"Larry","EmployeeSalary":9000,"EmployeeDetails":
   [{"EmployeeDOB":new Date('1990-01-21'),"EmployeeDepartment":"ComputerScience","EmployeeProject":
   [{"Technology":"C","Duration":6},{"Technology":"Java","Duration":7}]}]});
The following is the output:
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6d73090c3d5054b766a76e")
}
Now you can display documents from a collection with the help of find() method. The query is as follows:
> db.nestedArrayDemo.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6d73090c3d5054b766a76e"),
   "EmployeeName" : "Larry",
   "EmployeeSalary" : 9000,
   "EmployeeDetails" : [
      {
         "EmployeeDOB" : ISODate("1990-01-21T00:00:00Z"),
         "EmployeeDepartment" : "ComputerScience",
         "EmployeeProject" : [
            {
               "Technology" : "C",
               "Duration" : 6
            },
            {
               "Technology" : "Java",
               "Duration" : 7
            }
         ]
      }
   ]
}
Here is the demo of $push in nested array to add new documents. The query is as follows:
>db.nestedArrayDemo.update({"_id":ObjectId("5c6d73090c3d5054b766a76e"),
   "EmployeeDetails.EmployeeDepartment":"ComputerScience"}, {"$push":
   {"EmployeeDetails.$.EmployeeProject": {"Technology":"Python", "Duration":4 }}});
   WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
In the above query, I have added a document {"Technology":"Python", "Duration":4 } in nested array. Now display the documents from the collection once again. The query is as follows:
> db.nestedArrayDemo.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6d73090c3d5054b766a76e"),
   "EmployeeName" : "Larry",
   "EmployeeSalary" : 9000,
   "EmployeeDetails" : [
      {
         "EmployeeDOB" : ISODate("1990-01-21T00:00:00Z"),
         "EmployeeDepartment" : "ComputerScience",
         "EmployeeProject" : [
            {
               "Technology" : "C",
               "Duration" : 6
            },
            {
               "Technology" : "Java",
               "Duration" : 7
            },
            {
               "Technology" : "Python",
               "Duration" : 4
            }
         ]
      }
   ]
}
Tryit Editor v3.7

Tryit: change innerHTML