code-rag-bench/online-tutorials huggingface dataset:
Program to make a histogram of an array in C++

In this tutorial, we will be discussing a program to make a histogram by the data given inside an array.
For this, we will be provided with integer values inside an array. Our task is to plot a histogram keeping the value of both coordinates x and y equal to the value provided in the array.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void make_histogram(int arr[], int n){
   int maxEle = *max_element(arr, arr + n);
   for (int i = maxEle; i >= 0; i--) {
      cout.width(2);
      cout << right << i << " | ";
      for (int j = 0; j < n; j++) {
         if (arr[j] >= i)
            cout << " x ";
         else
            cout << " ";
      }
      cout << "\n";
   }
   for (int i = 0; i < n + 3; i++)
   cout << "---";
   cout << "\n";
   cout << " ";
   for (int i = 0; i < n; i++) {
      cout.width(2);
      cout << right << arr[i] << " ";
   }
}
int main() {
   int arr[10] = { 10, 9, 12, 4, 5, 2,
   8, 5, 3, 1 };
   int n = sizeof(arr) / sizeof(arr[0]);
   make_histogram(arr, n);
   return 0;
}
12 | x
11 | x
10 | x x
9 | x x x
8 | x x x x
7 | x x x x
6 | x x x x
5 | x x x x x x
4 | x x x x x x x
3 | x x x x x x x x
2 | x x x x x x x x x
1 | x x x x x x x x x x
0 | x x x x x x x x x x
---------------------------------------
10 9 12 4 5 2 8 5 3 1
Change the color upon hovering over Button in Tkinter

Let us suppose that we are creating an application in which we want to change the color of the Button widget while we hover upon it. We can have the hovering property by defining the Event Callbacks.
To change the color of the Button while hovering on it, we have to bind the <Enter> and <Leave> events. For each event, we will configure the button property such as background color, foreground color, etc.
#Import required libraries
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Define the geometry of the window
win.geometry("750x250")
#Define functions
def on_enter(e):
   button.config(background='OrangeRed3', foreground= "white")

def on_leave(e):
   button.config(background= 'SystemButtonFace', foreground= 'black')
#Create a Button
button= Button(win, text= "Click Me", font= ('Helvetica 13 bold'))
button.pack(pady= 20)

#Bind the Enter and Leave Events to the Button
button.bind('<Enter>', on_enter)
button.bind('<Leave>', on_leave)
win.mainloop()
Running the above code will display a window that contains a button.
Now, hover over the button in the displayed window. It will change its basic color such as background color and foreground color.
C++ Program for Maximum and Minimum in a square matrix. - GeeksforGeeks

06 Jan, 2022
Given a square matrix of order n*n, find the maximum and minimum from the matrix given. 
Examples: 
Input : arr[][] = {5, 4, 9,
                   2, 0, 6,
                   3, 1, 8};
Output : Maximum = 9, Minimum = 0

Input : arr[][] = {-5, 3, 
                   2, 4};
Output : Maximum = 4, Minimum = -5
Naive Method : We find maximum and minimum of matrix separately using linear search. Number of comparison needed is n2 for finding minimum and n2 for finding the maximum element. The total comparison is equal to 2n2.
Pair Comparison (Efficient method): Select two elements from the matrix one from the start of a row of the matrix another from the end of the same row of the matrix, compare them and next compare smaller of them to the minimum of the matrix and larger of them to the maximum of the matrix. We can see that for two elements we need 3 compare so for traversing whole of the matrix we need total of 3/2 n2 comparisons.
Note : This is extended form of method 3 of Maximum Minimum of Array.
C++
// C++ program for finding maximum and minimum in// a matrix.#include<bits/stdc++.h>using namespace std;  #define MAX 100  // Finds maximum and minimum in arr[0..n-1][0..n-1]// using pair wise comparisonsvoid maxMin(int arr[][MAX], int n){    int min = INT_MAX;    int max = INT_MIN;      // Traverses rows one by one    for (int i = 0; i < n; i++)    {        for (int j = 0; j <= n/2; j++)        {            // Compare elements from beginning            // and end of current row            if (arr[i][j] > arr[i][n-j-1])            {                if (min > arr[i][n-j-1])                    min = arr[i][n-j-1];                if (max< arr[i][j])                    max = arr[i][j];            }            else            {                if (min > arr[i][j])                    min = arr[i][j];                if (max< arr[i][n-j-1])                    max = arr[i][n-j-1];            }        }    }    cout << "Maximum = " << max;         << ", Minimum = " << min;}  /* Driver program to test above function */int main(){    int arr[MAX][MAX] = {5, 9, 11,                        25, 0, 14,                        21, 6, 4};    maxMin(arr, 3);    return 0;}
Output: 
Maximum = 25, Minimum = 0
Please refer complete article on Maximum and Minimum in a square matrix. for more details!
C++
C++ Programs
Matrix
Matrix
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Program to print ASCII Value of a character
Sorting a Map by value in C++ STL
C++ Program to Find Largest Rectangular Area in a Histogram

This is a C++ Program to find largest Rectangular Area in a Histogram
Begin
   Create an empty stack.
   Initialize the largest_area.
   Do a while loop start from first bar for every bar hist[i], where i = 0 to
      less than n:
   If stack is empty or hist[i] is higher than the bar at top of stack, then
      push ‘i’ to stack.
   Else
      this bar is smaller than the top of stack, then keep removing the
      top of stack while top of the stack is greater. Calculate area of
      rectangle with smallest bar. Element before top in stack is left
      index and i is right index for the top.
   Pop the remaining bars from stack if stack is not empty and calculate
      area with every popped bar as the smallest bar.
End
#include<iostream>
#include<stack>
using namespace std;
int getArea(int hist[], int n)
{
   stack<int> st;
   int largest_area = 0;
   int top;
   int toparea;
   int i = 0;
   while (i < n)
   {
      if (st.empty() || hist[st.top()] <= hist[i])
      st.push(i++);
      else
      {
         top = st.top();
         st.pop();
         toparea = hist[top] * (st.empty() ? i :
         i - st.top() - 1);
         if (largest_area < toparea)
         largest_area = toparea;
      }
   }
   while (st.empty() == false)
   {
      top = st.top();
      st.pop();
      toparea = hist[top] * (st.empty() ? i :
      i - st.top() - 1);
      if (largest_area < toparea)
      largest_area = toparea;
   }
   return largest_area;
}
int main()
{
   int hist[] = {6,7,4,5,3,2};
   int n = sizeof(hist)/sizeof(hist[0]);
   cout << "Largest area is " << getArea(hist, n);
   return 0;
}
Largest area is 16
C++ Comma Operator

The purpose of comma operator is to string together several expressions. The value of a comma-separated list of expressions is the value of the right-most expression. Essentially, the comma's effect is to cause a sequence of operations to be performed.
The values of the other expressions will be discarded. This means that the expression on the right side will become the value of the entire comma-separated expression. For example −
var = (count = 19, incr = 10, count+1);

Here first assigns count the value 19, assigns incr the value 10, then adds 1 to count, and finally, assigns var the value of the rightmost expression, count+1, which is 20. The parentheses are necessary because the comma operator has a lower precedence than the assignment operator.
To see the effects of the comma operator, try running the following program −
#include <iostream>
using namespace std;

int main() {
   int i, j;
   
   j = 10;
   i = (j++, j+100, 999+j);

   cout << i;
   
   return 0;
}
When the above code is compiled and executed, it produces the following result −
1010

Here is the procedure how the value of i gets calculated: j starts with the value 10. j is then incremented to 11. Next, j is added to 100. Finally, j (still containing 11) is added to 999, which yields the result 1010.

    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Electron - Hello World

We have created a package.json file for our project. Now we will create our first desktop app using Electron.
Create a new file called main.js. Enter the following code in it −
const {app, BrowserWindow} = require('electron') 
const url = require('url') 
const path = require('path')  

let win  

function createWindow() { 
   win = new BrowserWindow({width: 800, height: 600}) 
   win.loadURL(url.format ({ 
      pathname: path.join(__dirname, 'index.html'), 
      protocol: 'file:', 
      slashes: true 
   })) 
}  

app.on('ready', createWindow) 
Create another file, this time an HTML file called index.html. Enter the following code in it.
<!DOCTYPE html>
<html>
   <head>
      <meta charset = "UTF-8">
      <title>Hello World!</title>
   </head>
   
   <body>
      <h1>Hello World!</h1>
      We are using node <script>document.write(process.versions.node)</script>,
      Chrome <script>document.write(process.versions.chrome)</script>,
      and Electron <script>document.write(process.versions.electron)</script>.
   </body>
</html>
Run this app using the following command −
$ electron ./main.js

A new window will open up. It will look like the following −
We created a main file and an HTML file. The main file uses two modules – app and BrowserWindow. The app module is used to control your application’s event lifecycle while the BrowserWindow module is used to create and control browser windows.
We defined a createWindow function, where we are creating a new BrowserWindow and attaching a URL to this BrowserWindow. This is the HTML file that is rendered and shown to us when we run the app.
We have used a native Electron object process in our html file. This object is extended from the Node.js process object and includes all of t=its functionalities while adding many more.

    251 Lectures 
     35.5 hours 

 Gowthami Swarna

    9 Lectures 
     41 mins

 Ashraf Said

    8 Lectures 
     32 mins

 Ashraf Said

    25 Lectures 
     1 hours 

 Ashraf Said

    17 Lectures 
     1 hours 

 Ashraf Said

    8 Lectures 
     25 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
Create a new column in Pandas DataFrame based on the existing columns - GeeksforGeeks

23 Jan, 2019
While working with data in Pandas, we perform a vast array of operations on the data to get the data in the desired form. One of these operations could be that we want to create new columns in the DataFrame based on the result of some operations on the existing columns in the DataFrame. Let’s discuss several ways in which we can do that.
Given a Dataframe containing data about an event, we would like to create a new column called ‘Discounted_Price’, which is calculated after applying a discount of 10% on the Ticket price.
Solution #1: We can use DataFrame.apply() function to achieve this task.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],                    'Cost':[10000, 5000, 15000, 2000]})  # Print the dataframeprint(df)
Output :
Now we will create a new column called ‘Discounted_Price’ after applying a 10% discount on the existing ‘Cost’ column.
# using apply function to create a new columndf['Discounted_Price'] = df.apply(lambda row: row.Cost -                                   (row.Cost * 0.1), axis = 1)  # Print the DataFrame after addition# of new columnprint(df)
Output :
 
Solution #2: We can achieve the same result by directly performing the required operation on the desired column element-wise.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],                    'Cost':[10000, 5000, 15000, 2000]})  # Create a new column 'Discounted_Price' after applying# 10% discount on the existing 'Cost' column.  # create a new columndf['Discounted_Price'] = df['Cost'] - (0.1 * df['Cost'])  # Print the DataFrame after # addition of new columnprint(df)
Output :
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
Print lists in Python (4 Different Ways)
Convert integer to string in Python
String in C - GeeksQuiz

01 Jun, 2021

char c[] = "GATE2011"; 
 
 // p now has the base address string "GATE2011" 
char *p = c;  
 
// p[3] is 'E' and p[1] is 'A'. 
// p[3] - p[1] = ASCII value of 'E' - ASCII value of 'A' = 4 
// So the expression  p + p[3] - p[1] becomes p + 4 which is 
// base address of string "2011" 
printf("%s", p + p[3] - p[1]);  // prints 2011
In below program, what would you put in place of “?” to print “Quiz”? 
C
arr 
(arr+5) 
(arr+4) 
Not possible 
Since %s is used, the printf statement will print everything starting from arr+5 until it finds ‘\0’ 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Axios in React: A Guide for Beginners
How to set background images in ReactJS ?
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
SQLAlchemy Core - Creating Table
How to Alter Multiple Columns at Once in SQL Server?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
How to create permutations as a list in R?

The permutation is the combination with orders. For example, if we want to create a key for lock with a sequence of numbers then it must be order in some direction, otherwise, it will be difficult to remember and easy to unlock. We can find the permutation of some numbers or characters by using permn function of combinat package.
Loading the combinat package −
library(combinat)
Examples that create list of permutations −
permn(LETTERS[1:4])
[[1]]
[1] "A" "B" "C" "D"
[[2]]
[1] "A" "B" "D" "C"
[[3]]
[1] "A" "D" "B" "C"
[[4]]
[1] "D" "A" "B" "C"
[[5]]
[1] "D" "A" "C" "B"
[[6]]
[1] "A" "D" "C" "B"
[[7]]
[1] "A" "C" "D" "B"
[[8]]
[1] "A" "C" "B" "D"
[[9]]
[1] "C" "A" "B" "D"
[[10]]
[1] "C" "A" "D" "B"
[[11]]
[1] "C" "D" "A" "B"
[[12]]
[1] "D" "C" "A" "B"
[[13]]
[1] "D" "C" "B" "A"
[[14]]
[1] "C" "D" "B" "A"
[[15]]
[1] "C" "B" "D" "A"
[[16]]
[1] "C" "B" "A" "D"
[[17]]
[1] "B" "C" "A" "D"
[[18]]
[1] "B" "C" "D" "A"
[[19]]
[1] "B" "D" "C" "A"
[[20]]
[1] "D" "B" "C" "A"
[[21]]
[1] "D" "B" "A" "C"
[[22]]
[1] "B" "D" "A" "C"
[[23]]
[1] "B" "A" "D" "C"
[[24]]
[1] "B" "A" "C" "D"
permn(c("Aluminium","Calcium","Carbon","Nitrogen"))
[[1]]
[1] "Aluminium" "Calcium" "Carbon" "Nitrogen"
[[2]]
[1] "Aluminium" "Calcium" "Nitrogen" "Carbon"
[[3]]
[1] "Aluminium" "Nitrogen" "Calcium" "Carbon"
[[4]]
[1] "Nitrogen" "Aluminium" "Calcium" "Carbon"
[[5]]
[1] "Nitrogen" "Aluminium" "Carbon" "Calcium"
[[6]]
[1] "Aluminium" "Nitrogen" "Carbon" "Calcium"
[[7]]
[1] "Aluminium" "Carbon" "Nitrogen" "Calcium"
[[8]]
[1] "Aluminium" "Carbon" "Calcium" "Nitrogen"
[[9]]
[1] "Carbon" "Aluminium" "Calcium" "Nitrogen"
[[10]]
[1] "Carbon" "Aluminium" "Nitrogen" "Calcium"
[[11]]
[1] "Carbon" "Nitrogen" "Aluminium" "Calcium"
[[12]]
[1] "Nitrogen" "Carbon" "Aluminium" "Calcium"
[[13]]
[1] "Nitrogen" "Carbon" "Calcium" "Aluminium"
[[14]]
[1] "Carbon" "Nitrogen" "Calcium" "Aluminium"
[[15]]
[1] "Carbon" "Calcium" "Nitrogen" "Aluminium"
[[16]]
[1] "Carbon" "Calcium" "Aluminium" "Nitrogen"
[[17]]
[1] "Calcium" "Carbon" "Aluminium" "Nitrogen"
[[18]]
[1] "Calcium" "Carbon" "Nitrogen" "Aluminium"
[[19]]
[1] "Calcium" "Nitrogen" "Carbon" "Aluminium"
[[20]]
[1] "Nitrogen" "Calcium" "Carbon" "Aluminium"
[[21]]
[1] "Nitrogen" "Calcium" "Aluminium" "Carbon"
[[22]]
[1] "Calcium" "Nitrogen" "Aluminium" "Carbon"
[[23]]
[1] "Calcium" "Aluminium" "Nitrogen" "Carbon"
[[24]]
[1] "Calcium" "Aluminium" "Carbon" "Nitrogen"
permn(c(1,2,3))
[[1]]
[1] 1 2 3
[[2]]
[1] 1 3 2
[[3]]
[1] 3 1 2
[[4]]
[1] 3 2 1
[[5]]
[1] 2 3 1
[[6]]
[1] 2 1 3
Java void Keyword

❮ Java Keywords

A method without any return values:
public class Main {
  static void myMethod() {
    System.out.println("I just got executed!");
  }

  public static void main(String[] args) {
    myMethod();
  }
}


Try it Yourself »

The void keyword specifies that a method should not have a return value.
Tip: If you 
want a method to return a value, you can use a primitive data type (such as int, 
char, etc.) instead of void, and use the return 
keyword inside the method:
public class Main {
  static int myMethod(int x) {
    return 5 + x;
  }

  public static void main(String[] args) {
    System.out.println(myMethod(3));
  }
}
// Outputs 8 (5 + 3)


Try it Yourself »

Read more about methods in our Java Methods Tutorial.

❮ Java Keywords

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to split a semicolon-separated string to a dictionary in Python?

If you have strings like:
"Name1=Value1;Name2=Value2;Name3=Value3"
and you want to convert it to a dictionary, it is fairly easy. You could simply split on ';' and then on '=' and pass this to dict constructor. 
>>> s = "Name1=Value1;Name2=Value2;Name3=Value3"
>>> dict(item.split("=") for item in s.split(";"))
{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1'}
Check if a large number is divisible by 3 or not in java

If the sum of the digits of a number is divisible by 3, then the number is divisible by 3.
Some examples of numbers divisible by 3 are as follows.
The number 85203 is divisible by 3 because the sum of its digits (8 + 5 + 2 + 0 + 3 = 18) is divisible by 3.
The number 79154 is not divisible by 3 because the sum of its digits (7 + 9 + 1 + 5 + 4 = 26) is not divisible by 3.
import java.util.Scanner;

public class DivisibleBy3 {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a number :");
      String num = sc.nextLine();
      int digitSum = 0;
     
      for(int i = 0; i<num.length(); i++) {
         digitSum = digitSum + num.charAt(i)-'0';
      }
      if(digitSum % 3 == 0) {
         System.out.println("Given number is divisible by 3");
      } else {
         System.out.println("Given number is not divisible by 3");
      }
   }
}
Enter a number :
85203
Given number is divisible by 3
AngularJS | angular.isUndefined() Function - GeeksforGeeks

12 Apr, 2019
The angular.isUndefined() function in AngularJS is used to determine the value inside isUndefined function is undefined or not. It returns true if the reference is undefined otherwise returns false.
Syntax:
angular.isUndefined( value )
Return Value: It returns true if the value passed is undefined else returns false.
Example: This example uses angular.isUndefined() function to determine the value inside isUndefined function is undefined or not.
<!DOCTYPE html><html>    <head>        <title>angular.isUndefined() function</title>                  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">        </script>    </head>       <body ng-app="app" style="text-align:center">        <h1 style="color:green">GeeksforGeeks</h1>        <h2>angular.isUndefined()</h2>                  <div ng-controller="isDefinedController">            <b>Date:</b> {{date}}<br><br>                    {{isUndefined}}            <br><br><br>            <b>Date1:</b> {{date1}}<br><br>                            {{isUndefined1}}           </div>                  <!-- Script to uses angular.isUndefined() function -->        <script>            var app = angular.module("app", []);            app.controller('isDefinedController',                        ['$scope', function ($scope) {                $scope.date = new Date;                $scope.date1;                                  $scope.isUndefined = angular.isUndefined($scope.date)                        == true ? "$scope.date is Undefined."                         : "$scope.date is not Undefined.";                                  $scope.isUndefined1 = angular.isUndefined($scope.date1)                        == true ? "$scope.date1 is Undefined."                         : "$scope.date1 is not Undefined.";            }]);        </script>    </body></html>
Output:
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
Angular File Upload
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
IntStream parallel() in Java - GeeksforGeeks

06 Dec, 2018
IntStream parallel() is a method in java.util.stream.IntStream. This method returns a parallel IntStream, i.e, it may return itself, either because the stream was already present, or because the underlying stream state was modified to be parallel.
IntStream parallel() is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.
Syntax :
IntStream parallel()

Where, IntStream is a sequence of 
primitive int-valued elements and the function 
returns a parallel IntStream.

Below given are some examples to understand the function in a better way.Example 1 :
// Java program to demonstrate working of// IntStream parallel() on a given rangeimport java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating a stream of integers        IntStream stream = IntStream.range(5, 12);          System.out.println("The corresponding " +                          "parallel IntStream is :");        stream.parallel().forEach(System.out::println);    }}
Output :
The corresponding parallel IntStream is :
9
8
11
10
6
5
7

Example 2 :
// Printing sequential stream for the // same input as above example 1.import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        IntStream stream = IntStream.range(5, 12);          System.out.println("The corresponding " +                       "sequential IntStream is :");        stream.sequential().forEach(System.out::println);    }}
Output :
The corresponding sequential IntStream is :
5
6
7
8
9
10
11

Example 3 :
// Java program to show sorted output// of parallel stream.import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating a stream of integers        IntStream stream = IntStream.of(3, 4, 1, 5, 2, 3, 9);          System.out.println("The sorted parallel" +                               " IntStream is :");        stream.parallel().sorted().forEach(System.out::println);    }}
Output :
The sorted parallel IntStream is :
4
2
3
1
3
5
9

Note that it still shows as unsorted. That’s because forEach() is being used. To get the items processed in sorted order, use forEachOrdered(). But note that this negates the advantage of using parallel.
ampyjoe
Java - util package
Java-Functions
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
StringBuilder Class in Java with Examples
HashMap get() Method in Java
Functional Interfaces in Java
Strings in Java
How to Merge multiple CSV Files into a single Pandas dataframe ?

09 May, 2021
While working with CSV files during data analysis, we often have to deal with large datasets. Sometimes, it might be possible that a single CSV file doesn’t consist of all the data that you need. In such cases, there’s a need to merge these files into a single data frame. Luckily, the Pandas library provides us with various methods such as merge, concat, and join to make this possible. Through the examples given below, we will learn how to combine CSV files using Pandas.
File Used:
First CSV – 
Second CSV – 
Third CSV – 
Let us first understand each method used in the program given above:
pd.concat(): This method stitches the provided datasets either along the row or column axis. It takes the dataframe objects as parameters. Along with that, it can also take other parameters such as axis, ignore_index, etc.
map(function, iterable): It executes a specified function for each item in iterables. In the example above, the pd.read_csv() function is applied to all the CSV files in the list given.
Approach:
At first, we import Pandas.
Using pd.read_csv() (the function), the map function reads all the CSV files (the iterables)  that we have passed. Now, pd.concat() takes these mapped CSV files as an argument and stitches them together along the row axis (default).  We can pass axis=1 if we wish to merge them horizontally along the column. Further,  ignore_index = True sets continuous index values for the merged dataframe.
The images are given below show mydata.csv, mydata1.csv, and the merged dataframe.
Example:
Python3
# importing pandasimport pandas as pd  # merging two csv filesdf = pd.concat(    map(pd.read_csv, ['mydata.csv', 'mydata1.csv']), ignore_index=True)print(df)
Output:
Approach:
os.path.join() takes the file path as the first parameter and the path components to be joined as the second parameter. “mydata*.csv helps to return every file in the home directory that starts with “mydata” and ends with .CSV (Use of wildcard *).
glob.glob() takes these joined file names and returns a list of all these files. In this example, mydata.csv, mydata1.csv, and mydata2.csv are returned.
Now, just like the previous example, this list of files is mapped and then concatenated.
We can simply write these three lines of code as:
df = pd.concat(map(pd.read_csv, glob.glob(os.path.join(“/home”, “mydata*.csv”))), ignore_index= True)
Example:
Python3
# importing librariesimport pandas as pdimport globimport os  # merging the filesjoined_files = os.path.join("/home", "mydata*.csv")  # A list of all joined files is returnedjoined_list = glob.glob(joined_files)  # Finally, the files are joineddf = pd.concat(map(pd.read_csv, joined_list), ignore_index=True)print(df)
Output:
Picked
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Scala List apply() method with example

26 Jul, 2019
The apply() method is utilized to select an element in the list by its index.
Method Definition: def apply(n: Int): A
Return Type: It returns an element from the given list by its index which is present in the apply method as argument.
Example #1:
// Scala program of apply()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(1, 3, 5, 2)                  // Applying apply method        val res = m1.apply(3)                  // Displays output        println(res)          }}
2

Example #2:
// Scala program of apply()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(1, 3, 5, 2)                  // Applying apply method        val res = m1.apply(0)                  // Displays output        println(res)          }}
1

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in Scala
How to Install Scala with VSCode?
Scala | Option
Hello World in Scala
Scala | Traits
Scala ListBuffer
Scala Sequence
Introduction to Scala
Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Implicit Parameters In Scala
GRE Geometry | Triangles

06 Sep, 2021
Triangle is one of the basic 2-D shapes in geometry. It consists of three angles, three side and three vertices, e.g., 
On the basis of measurement of sides and angles there different types of triangle listed below: 
1. Equilateral triangle: All edges are equal, all angles are also equal to 60°, e.g.,  
2. Isosceles triangle: Two edges are equal, hence two angles are also equal or sides opposite to equal sides are equal, e.g., 
3. Scalene triangle: All edges are different, hence all angles are also different, e.g., 
4. Right angle triangle: One angle is 90° and side opposite to 90° is the hypotenuse, e.g., 
5. Obtuse triangle: One angle is obtuse, e.g., 
6. Acute triangle: All angles are acute, e.g., 
Important properties of the triangle: 
Sum of angles of a triangle is 180°
Third side of triangle is greater than the difference of other two sides and less than sum of other two sides.
Area of triangle = (1 / 2) * base * height.
In right angle triangle, hypotenuse2 = base2 + perpendicular2. [Pythagoras theorem]
Area of equilateral triangle = (√3 / 4)side2
Congruency and similarity in triangles: 
1. Congruent triangle: Two triangles are congruent if shape and size of two triangles is same or two triangles have same angles and same sides, e.g., 
Triangle ABC and XYZ are congruent. or △ABC ≅△XYZ 
Rules of congruency: 
(i) SSS (side – side – side) rule: If all sides of a triangle is equal to all sides of another triangle. Then these two triangles are congruent to each other by SSS rule, e.g.,
(ii) SAS (side – angle – side) rule: If two sides of a triangle are equal to two sides in another triangle and angle between them is equal to angle between equal side in another triangle then these two triangles are congruent to each other by SAS rule, e.g.,  
(iii) AAA (angle – angle – angle) rule:If all angles of a triangle are equal to all angles of another triangle then these two triangles are congruent to each other by AAA rule, e.g.,  
(iv) ASA (angle – side – angle) rule: If two angles of a triangle are equal to two angles in another triangle and side between them is equal to side between equal angles in another triangle then these two triangles are congruent to each other by ASA rule, e.g.,  
(v) AAS (angle – angle – side) rule: If two angles and one side of a triangle is equal to two angles and one side in another triangle then these triangles are congruent to each other by AAS rule, e.g.,  
2. Similar triangles: Two triangles are similar if their shape is same but it is not necessary that their size is also same. To prove two triangles are similar scale factor of similarity is used, this factor check the equivalence of ratio of corresponding sides and corresponding angles, e.g.,  
△ABC is similar to △XYZ. 
Since, △ABC is similar to △XYZ we can write scale factor of similarity as: 
XY / AB = XZ / AC = YZ / BC. 
To obtain AB/AC just cross multiply, 
XY / AB = XZ / AC.
AB / AC = XY / XZ.
surindertarika1234
varshagumber28
sumitgumber28
rajeev0719singh
Aptitude
placement preparation
GRE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dart Programming – If Else Statement (if , if..else, Nested if, if-else-if)

30 Jun, 2020
Decision-making statements are those statements which allow the programmers to decide which statement should run in different conditions. There are four ways to achieve this: 
This type of statements simply checks the condition and if it is true the statements within it is executed but if it in is not then the statements are simply ignored in the code.
Syntax: 
if ( condition ){
  // body of if
}

 
Example:  
Dart
void main(){    int gfg = 10;      // Condition is true    if (gfg > 3) {       // This will be printed        print("Condition is true");     }}
Output: 
Condition is true

This type of statement simply checks the condition and if it is true, the statements within is executed but if not then else statements are executed. 
Syntax: 
if ( condition ){
  // body of if
}
else {
  // body of else
}

 
Example:  
Dart
void main(){    int gfg = 10;      // Condition is false    if (gfg > 30) {       // This will not be printed        print("Condition is true");     }    else {      // This will be printed        print("Condition id false");     }}
Output: 
Condition is false

This type of statement simply checks the condition and if it is true the statements within it is executed but if it in is not then other if conditions are checked, if they are true then they are executed and if not then the other if conditions are checked. This process is continued until the ladder is completed.
Syntax: 
if ( condition1 ){
  // body of if
}
else if ( condition2 ){
  // body of if
}
.
.
.
else {
  // statement
}

Example:  
Dart
void main(){    int gfg = 10;    if (gfg < 9) {        print("Condition 1 is true");        gfg++;    }    else if (gfg < 10) {        print("Condition 2 is true");    }    else if (gfg >= 10) {        print("Condition 3 is true");    }    else if (++gfg > 11) {        print("Condition 4 is true");    }    else {        print("All the conditions are false");    }}
Output: 
Condition 3 is true

This type of statements checks the condition and if it is true then the if statement inside it checks its condition and if it is true then the statements are executed otherwise else statement is executed.
Syntax: 
if ( condition1 ){
  if ( condition2 ){
     // Body of if
  }
  else {
    // Body of else
  }
}

 
Example:  
Dart
void main(){    int gfg = 10;    if (gfg > 9) {        gfg++;        if (gfg < 10) {            print("Condition 2 is true");        }        else {            print("All the conditions are false");        }    }}
Output: 
All the conditions are false

 
Dart decision-making
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
ListView Class in Flutter
Flutter - Stack Widget
Dart Tutorial
Flutter - Search Bar
Container class in Flutter
Operators in Dart
Flutter - FutureBuilder Widget
Flutter - Flexible Widget
How to convert JSON file to CSV file using PowerShell?

To convert the JSON file to the CSV file using PowerShell, we need to use the ConvertTo-CSV command as a pipeline.
For example, we have a JSON file called PatchingServer.JSON stored at C:\temp and its content is as below.
PS C:\> Get-Content C:\Temp\PatchingServer.json
{
   "Port": "9000",
   "ApplicationName": "TestApp",
   "MaintenanceWindow": "Every Saturday",
   "BusinessUnit": "IT",
   "AppOwner": "Josh",
   "AppID": "1jj2221-223443s",
   "Location": "EastUS"
}
We need to convert the above file to the CSV file so we will use the ConvertTo-CSV command but before that, we need the JSON file need to be converted from JSON format to table format using ConvertFrom-JSON so the ConvertTo-CSV command can make it into a readable format.
PS C:\> Get-Content C:\Temp\PatchingServer.json |ConvertFrom-Json
Port              : 9000
ApplicationName   : TestApp
MaintenanceWindow : Every Saturday
BusinessUnit      : IT
AppOwner          : Josh
AppID             : 1jj2221-223443s
Location          : EastUS
So the final command should be,
Get-Content C:\Temp\PatchingServer.json | ConvertFrom-Json | ConvertTo-Csv
"Port","ApplicationName","MaintenanceWindow","BusinessUnit","AppOwner","AppID","Location"
"9000","TestApp","Every Saturday","IT","Josh","1jj2221-223443s","EastUS"
With the last command, the table is converted to the headers and values. We can save this CSV file as well.
Get-Content C:\Temp\PatchingServer.json | ConvertFrom-Json | ConvertTo-Csv | Out-File C:\Temp\Patching.csv
variables – Django Templates

02 Dec, 2021
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variables, for loops, etc. This article revolves about how to use a variable in Template. A variable outputs a value from the context, which is a dict-like object mapping keys to values.  
Syntax:
{{ variable_name }}
Example:Variables are surrounded by {{ and }} like this:  
My first name is {{ first_name }}. My last name is {{ last_name }}. 
With a context of {‘first_name’: ‘Naveen’, ‘last_name’: ‘Arora’}, this template renders to:  
My first name is Naveen. My last name is Arora.
Illustration of How to use variables in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks. 
Refer to the following articles to check how to create a project and an app in Django.  
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Now create a view through which we will pass the context dictionary, In geeks/views.py, 
Python3
# import render from djangofrom django.shortcuts import render # create a functiondef geeks_view(request):    # create a dictionary    context = {        "first_name" : "Naveen",        "last_name"  : "Arora",    }    # return response    return render(request, "geeks.html", context)
Create a url path to map to this view. In geeks/urls.py, 
Python3
from django.urls import path # importing views from views..pyfrom .views import geeks_view urlpatterns = [    path('', geeks_view),]
Create a template in templates/geeks.html, 
html
My First Name is {{ first_name }}.<br/>My Last Name is  {{ last_name }}.
Let’s check is variables are displayed in the template. 
surindertarika1234
Django-templates
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Python Dictionary
Python OOPs Concepts
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Python Classes and Objects
Introduction To PYTHON
Stack in Python
Python set to check if string is panagram

20 Jun, 2022
Given a string, check if the given string is pangram or not.Examples:  
Input : The quick brown fox jumps over the lazy dog
Output : The string is a pangram

Input : geeks for geeks
Output : The string is not pangram
 
A normal way would have been to use frequency table and check if all elements were present or not. But using import ascii_lowercase as asc_lower we import all the lower characters in set and all characters of string in another set. In the function, two sets are formed- one for all lower case letters and one for the letters in the string. The two sets are subtracted and if it is an empty set, the string is a pangram.Below is Python implementation of the above approach:  
Python
# import from string all ascii_lowercase and asc_lowerfrom string import ascii_lowercase as asc_lower # function to check if all elements are present or notdef check(s):    return set(asc_lower) - set(s.lower()) == set([])     # driver codestring ="The quick brown fox jumps over the lazy dog"if(check(string)== True):    print("The string is a pangram")else:    print("The string isn't a pangram")
Output:  
The string is a pangram
Time Complexity: O(n)
Auxiliary Space: O(1) 
sweetyty
riya55
python-set
Python
Strings
python-set
Strings
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
Read a file line by line in Python
How to Install PIP on Windows ?
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
Can we use LIKE and OR together in MySql?

You can use LIKE with OR operator which works same as IN operator.
Let us see the syntax for both the cases −
select *from yourTableName where yourColumnName Like ‘Value1’
or yourColumnName Like ‘Value2’
or yourColumnName Like ‘Value3’
.
.
.
N
select *from yourTableName where IN(value1,value2,value3,.....N);
To understand both the syntaxes, let us create a table. The query to create a table is as follows −
mysql> create table LikeDemo
−> (
−> Id varchar(20)
−> );
Query OK, 0 rows affected (0.58 sec)
Now you can insert records in the table with the help of insert statement. The query is as follows −
mysql> insert into LikeDemo values('John123');
Query OK, 1 row affected (0.22 sec)

mysql> insert into LikeDemo values('Smith205');
Query OK, 1 row affected (0.18 sec)

mysql> insert into LikeDemo values('Bob999');
Query OK, 1 row affected (0.18 sec)

mysql> insert into LikeDemo values('Carol9091');
Query OK, 1 row affected (0.17 sec)

mysql> insert into LikeDemo values('Johnson2222');
Query OK, 1 row affected (0.15 sec)

mysql> insert into LikeDemo values('David2345');
Query OK, 1 row affected (0.21 sec)
Display all records from the table with the help of select statement. The query is as follows −
mysql> select *from LikeDemo;
The following is the output −
+-------------+
| Id          |
+-------------+
| John123     |
| Smith205    |
| Bob999      |
| Carol9091   |
| Johnson2222 |
| David2345   |
+-------------+
6 rows in set (0.00 sec)
The following is the query to use single Like with OR operator −
mysql> select *from LikeDemo where Id Like 'John123%' or Id Like 'Carol9091%' or Id Like 'David2345%';
The following is the output −
+-----------+
| Id        |
+-----------+
| John123   |
| Carol9091 |
| David2345 |
+-----------+
3 rows in set (0.00 sec)
The query is as follows −
mysql> select *from LikeDemo where Id in('John123','Carol9091', 'David2345');
The following is the output −
+-----------+
| Id        |
+-----------+
| John123   |
| Carol9091 |
| David2345 |
+-----------+
3 rows in set (0.04 sec)
How to change the automatic sorting of X-axis of a bar plot using ggplot2 in R?

If there is a category for which the frequency is significantly different from others then the X-axis labels of the bar plot using ggplot2 are automatically sorted to present the values alternatively. We might want to keep the original sequence of categories that is available in the categorical variable. Therefore, we can store the categorical variable as a factor and then create the bar plot.
Consider the below data frame −
> Group<-c("India","USA","UK","Germany")
> Frequency<-c(12,18,35,20)
> df<-data.frame(Group,Frequency)
> df
Group Frequency
1 India   12
2 USA     18
3 UK      35
4 Germany 20
> library(ggplot2)
> ggplot(df,aes(Group,Frequency))+geom_bar(stat="identity")
Here, we can see that Germany is the last category in Group variable but we might want to create the plot with the same sequence as we have in our variable. This can be done as shown below −
> df$Group<-factor(df$Group, levels = df$Group)
> ggplot(df,aes(Group,Frequency))+geom_bar(stat="identity")
SAP UI5 - Notepad Controls

A Control is used to define the appearance and screen area. It contains properties likewidth and text. These properties are used to modify the appearance or change the data displayed by the control. You can create aggregate controls or associated controls.
Associated control of a control is defined as loosely related controls, which are not child controls or a part of the main control. Controls are used to trigger well-defined events.
Controls in SAPUI5 can be created directly using a tool or JavaScript file. Controls that are created using the extend() method are also known as Notepad controls.
The following code is used to define a Control using the Extend method −
Sap.ui.core.control.extend (sname, oDefinition);

The parameters that are passed to this control −
Name of the control
Definition of the control
The definition of a control contains information about control API, aggregations, events, etc. and implementation methods.
You can also create custom controls. Definition of custom control can contain public and private methods, metadata, and rendering method, etc.
metadata:{
   properties: {},
   events: {},
   aggregations: {}
},

publicMethod: function() {},
_privateMethod: function() {},
init: function() {}
onclick: function(e) {},
renderer: function(rm, oControl) {}
Creating a new control inherits from Button −
Sap.ui.commons.Button.extend (sname, oDefinition);

The metadata in control definition consists of objects for control properties, events, and aggregations.
Type: data type of control property
String: string for a string property
Int or float for number properties
Int[] for an integers array
String[] for an string array
Events are defined by the name event only. You normally pass an empty object to an event. Application use enablePreventDefault flag to interrupt the event.
Events: {
   Logout:{},
   Close: {
      enablePreventDefault : true
   }
}


    25 Lectures 
     6 hours 

 Sanjo Thomas

    26 Lectures 
     2 hours 

 Neha Gupta

    30 Lectures 
     2.5 hours 

 Sumit Agarwal

    30 Lectures 
     4 hours 

 Sumit Agarwal

    14 Lectures 
     1.5 hours 

 Neha Malik

    13 Lectures 
     1.5 hours 

 Neha Malik
 Print
 Add Notes
 Bookmark this page
How to selectively retrieve value from json output JavaScript

We have the following data inside a json file data.json −
data.json
{
   "names": [{
      "name": "Ramesh",
      "readable": true
   }, {
      "name": "Suresh",
      "readable": false
   }, {
      "name": "Mahesh",
      "readable": true
   }, {
      "name": "Gourav",
      "readable": true
   }, {
      "name": "Mike",
      "readable": false
   } ]
}
Our job is to create a function parseData that takes in the path to this file as one and only
argument, reads this json file, and returns an sub array of names array where the property
readable is true.
Now, let’s write the code for this, we will use the require module to fetch the json data and then
return a filtered array like this −
const path = "./data.json";
const parseData = (path) => {
   const data = require(path);
   //no need to parse the data as it is already parsed
   return data.names.filter(el => el.readable);
}
const results = parseData(path);
console.log(results);
The console output will be −
[
   { name: 'Ramesh', readable: true },
   { name: 'Mahesh', readable: true },
   { name: 'Gourav', readable: true }
]