code-rag-bench/online-tutorials huggingface dataset:
How to set Selenium Python WebDriver default timeout?

We can set default timeout with Selenium webdriver. The method set_page_load_timeout is used to have a timeout for the page loading. The wait time in seconds is passed as parameter to the method.
driver.set_page_load_timeout(5)
A TimeoutException is thrown if the page is still not loaded after the wait time is passed.
We can use the implicit wait concept in synchronization to define the default timeout time. This is a global wait time and applied to every element in the page. The method implicitly_wait is used to define implicit wait. The wait time in seconds is passed as parameter to the method.
driver.implicitly_wait(5);
A TimeoutException is thrown if the page is still not loaded after the implicit wait time is passed.
Code Implementation with set_page_load_timeout()
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# set_page_load_timeout to set the default page load time
driver.set_page_load_timeout(0.8)
driver.get("https://www.tutorialspoint.com/index.htm")
Code Implementation with implicit wait.
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
#implicit wait of 0.8 seconds applied
driver.implicitly_wait(0.8)
driver.get("https://www.tutorialspoint.com/index.htm")
Online Ruby Formatter

Editable Ruby Code
12345678910111213141516171819202122232425262728293031#!/usr/bin/ruby -w# define a classclass Box# constructor methoddef initialize(w,h)@width, @height = w, hend# accessor methodsdef getWidth@widthenddef getHeight@heightend# setter methodsdef setWidth=(value)@width = valueenddef setHeight=(value)@height = valueendend# create an objectbox = Box.new(10, 20)# use setter methodsX
Privacy Policy
Cookies Policy
Terms of Use
SWING - ActionEvent Class

This class is defined in java.awt.event package. The ActionEvent is generated when button is clicked or the item of a list is double-clicked.
Following is the declaration for java.awt.event.ActionEvent class −
public class ActionEvent
   extends AWTEvent

Following are the fields for java.awt.event.ActionEvent class −
static int ACTION_FIRST − The first number in the range of IDs used for action events.
static int ACTION_FIRST − The first number in the range of IDs used for action events.
static int ACTION_LAST − The last number in the range of IDs used for action events.
static int ACTION_LAST − The last number in the range of IDs used for action events.
static int ACTION_PERFORMED − This event ID indicates that a meaningful action has occured.
static int ACTION_PERFORMED − This event ID indicates that a meaningful action has occured.
static int ALT_MASK − The alt modifier.
static int ALT_MASK − The alt modifier.
static int CTRL_MASK − The control modifier.
static int CTRL_MASK − The control modifier.
static int META_MASK − The meta modifier.
static int META_MASK − The meta modifier.
static int SHIFT_MASK − The shift modifier.
static int SHIFT_MASK − The shift modifier.
ActionEvent(java.lang.Object source, int id, java.lang.String command)
Constructs an ActionEvent object.
ActionEvent(java.lang.Object source, int id, java.lang.String command, int modifiers)
Constructs an ActionEvent object with modifier keys.
ActionEvent(java.lang.Object source, int id, java.lang.String command, long when, int modifiers)
Constructs an ActionEvent object with the specified modifier keys and timestamp.
java.lang.String getActionCommand()
Returns the command string associated with this action.
int getModifiers()
Returns the modifier keys held down during this action event.
long getWhen()
Returns the timestamp of when this event occurred.
java.lang.String paramString()
Returns a parameter string identifying this action event.
This class inherits methods from the following classes −
java.awt.AWTEvent
java.util.EventObject
java.lang.Object

    30 Lectures 
     3.5 hours 

 Pranjal Srivastava

    13 Lectures 
     1 hours 

 Pranjal Srivastava

    25 Lectures 
     4.5 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    14 Lectures 
     1.5 hours 

 Travis Rose

    14 Lectures 
     1 hours 

 Travis Rose
 Print
 Add Notes
 Bookmark this page
How to identify server IP address in PHP ?

01 Aug, 2021
What is an IP Address ? IP Address or Internet Protocol Address is a numerical value assigned to every device on network which uses the Internet Protocol for Communication.An IP address serves two major functions:
Network/Host interface identification
Location addressing
Static IP addresses that do not change very often that are provided to servers. The ISP provides a unique IP address to a home machine that is dialing via modem, and the IP address is unique for that session and it may change the next time for the machine.
How to identify your server’s IP address: The $_SERVER is an array in PHP that contains the information regarding the headers, paths and script locations. The web server itself creates the entries of this array. Though it does not guarantee every web server will provide the contents of these arrays, servers may usually omit some of the $_SERVER array contents.In order to obtain the IP address of the server one can use [‘SERVER_ADDR’], it returns the IP address of the server under the current script is executing.
Another method is using the [‘REMOTE_ADDR’] in the $_SERVER array. [‘REMOTE_ADDR’] is only used for getting the IP address for the local servers although the output produced will be the same as using [‘SERVER_ADDR’] for the local server IP address.
Example 1: This example identify the servers IP address using [‘SERVER_ADDR’].
<?php  // PHP program to obtain IP address of// the server  // Creating a variable to store the// server address$ip_server = $_SERVER['SERVER_ADDR'];  // Printing the stored addressecho "Server IP Address is: $ip_server";  ?>
Output:
Server IP Address is: ::1
Example 2: This example identify the servers IP address using [‘REMOTE_ADDR’].
<?php  // PHP program to obtain IP address of// the server  // Create a variable to store the// server ip address$ip = $_SERVER['REMOTE_ADDR'];  // Printing the stored addressecho "IP Address is: $ip", "<br>";  ?>
Output:
Server IP Address is: ::1
Note: If you try to run the above code on any online IDE it would either return a runtime error or no output, as private domains don’t share their IP, try running on localhost or a server. For localhost, if ipv4 loopback address is used then it will give 127.0.0.1 and if ipv6 loopback address is used then it will give ::1.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
std::stof in C++

02 Aug, 2017
Parses string interpreting its content as a floating-point number, which is returned as a value of type float.
Syntax :
float stof (const string&  str, size_t* idx = 0);
float stof (const wstring& str, size_t* idx = 0);

Parameters :
str : String object with the representation of a floating-point number.
idx : Pointer to an object of type size_t, whose value is set by the function
to position of the next character in str after the numerical value.
This parameter can also be a null pointer, in which case it is not used.

Return Value :
On success, the function returns the converted floating-point number as a value of type float.

Below is the C++ implementation of std::stof :
// CPP code to convert floating // type number to string#include <bits/stdc++.h>  int main(){    // String to be parsed    std::string str = "100.80";      // val to store parsed floating type number    float val = std::stof(str);      // Printing parsed floating type number    std::cout << val;      return 0;}
Output:
100.8
// CPP code to convert integer // type number to string#include <bits/stdc++.h>  int main(){    // String to be parsed    std::string str = "1000";      // val to store parsed integer type number    float val = std::stof(str);      // Printing parsed integer type number    std::cout << val;      return 0;}
Output:
1000
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Unordered Sets in C++ Standard Template Library
Pair in C++ Standard Template Library (STL)
std::string class in C++
Friend class and function in C++
Queue in C++ Standard Template Library (STL)
List in C++ Standard Template Library (STL)
Inline Functions in C++
vector insert() function in C++ STL
SQL Correlated Subqueries

06 Feb, 2018
Correlated subqueries are used for row-by-row processing. Each subquery is executed once for every row of the outer query.A correlated subquery is evaluated once for each row processed by the parent statement. The parent statement can be a SELECT, UPDATE, or DELETE statement.
SELECT column1, column2, ....
FROM table1 outer
WHERE column1 operator
                    (SELECT column1, column2
                     FROM table2
                     WHERE expr1 = 
                               outer.expr2);
A correlated subquery is one way of reading every row in a table and comparing values in each row against related data. It is used whenever a subquery must return a different result or set of results for each candidate row considered by the main query. In other words, you can use a correlated subquery to answer a multipart question whose answer depends on the value in each row processed by the parent statement.
With a normal nested subquery, the inner SELECT query runs first and executes once, returning values to be used by the main query. A correlated subquery, however, executes once for each candidate row considered by the outer query. In other words, the inner query is driven by the outer query.NOTE : You can also use the ANY and ALL operator in a correlated subquery.EXAMPLE of Correlated Subqueries : Find all the employees who earn more than the average salary in their department.
SELECT last_name, salary, department_id
 FROM employees outer
 WHERE salary >
                (SELECT AVG(salary)
                 FROM employees
                 WHERE department_id =
                        outer.department_id);
Other use of correlation are in UPDATE and DELETE
UPDATE table1 alias1
 SET column = (SELECT expression 
               FROM table2 alias2
               WHERE alias1.column =
                     alias2.column);
Use a correlated subquery to update rows in one table based on rows from another table.
DELETE FROM table1 alias1
 WHERE column1 operator
               (SELECT expression
                FROM table2 alias2
                WHERE alias1.column = alias2.column);
Use a correlated subquery to delete rows in one table based on the rows from another table.
The EXISTS operator tests for existence of rows in the results set of the subquery. If a subquery row value is found the condition is flagged TRUE and the search does not continue in the inner query, and if it is not found then the condition is flagged FALSE and the search continues in the inner query.EXAMPLE of using EXIST operator :Find employees who have at least one person reporting to them.
SELECT employee_id, last_name, job_id, department_id
FROM employees outer
WHERE EXISTS ( SELECT ’X’
FROM employees
WHERE manager_id =
outer.employee_id);
OUTPUT :
EXAMPLE of using NOT EXIST operator :Find all departments that do not have any employees.
SELECT department_id, department_name
FROM departments d
WHERE NOT EXISTS (SELECT ’X’
FROM employees
WHERE department_id
= d.department_id);
OUTPUT :
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Pigeonhole Sort

This is an example of the non-comparison sorting technique. It is used where the number of items and the range of possible key values is approximately the same.
To perform this sort, we need to make some holes. The number of holes needed is decided by the range of numbers. In each hole, items are inserted. Finally deleted from the hole and stored into an array for sorted order.
Time Complexity: O(n+2^k)
Space Complexity: O(2^k)
Input:
The unsorted list: 802 630 20 745 52 300 612 932 78 187
Output:
Data before Sorting: 802 630 20 745 52 300 612 932 78 187
Data after Sorting: 20 52 78 187 300 612 630 745 802 932
pigeonHoleSort(array, size)
Input − An array of data, and the total number in the array
Output − The sorted Array
Begin
   find max and min from the array list
   holeRange := max – min +1
   define holeRange number of Lists

   for i := 0 to n-1 do
      hole[array[i]-min].append(array[i])
   done

   count := 0
   for j := 0 to holeRange-1 do
      while hole[j] is not empty do
         array[count] := get first node of hole[j] and delete it
         count := count +1
      done
   done
End
#include<iostream>
#include<list>
#include<cmath>
using namespace std;

void getMaxMin(int *arr, int n, int &maximum, int &minimum) {
   maximum = minimum = arr[0]; //initially max and min ar arr[0]

   for(int i = 1; i<n; i++) {
      if(arr[i] > maximum)
         maximum = arr[i]; //get maximum data
      if(arr[i] < minimum)
         minimum = arr[i]; //get minimum data
   }
}

void pegionHoleSort(int *arr, int n) {
   int max, min;
   getMaxMin(arr, n, max, min);
   int holeRange = max - min +1;
   list<int> hole[holeRange]; //create an array of holes

   for(int i = 0; i<n; i++) {
      hole[arr[i]-min].push_back(arr[i]);
   }

   int count = 0;
   for(int j = 0; j<holeRange; j++) {
      //delete from linked lists and store to array
      while(!hole[j].empty()) {
         arr[count] = *(hole[j].begin());
         hole[j].erase(hole[j].begin());
         count++;
      }
   }
}

void display(int *array, int size) {
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}

int main() {
   int n;
   cout << "Enter the number of elements: ";
   cin >> n;
   int arr[n]; //create an array with given number of elements
   cout << "Enter elements:" << endl;

   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }

   cout << "Data before Sorting: ";
   display(arr, n);
   pegionHoleSort(arr, n);
   cout << "Data after Sorting: ";
   display(arr, n);
}
Enter the number of elements: 10
Enter elements:
802 630 20 745 52 300 612 932 78 187
Data before Sorting: 802 630 20 745 52 300 612 932 78 187
Data after Sorting: 20 52 78 187 300 612 630 745 802 932
Binary search in sorted vector of pairs in C++

This is a C++ program to implement Binary search in a sorted vector of pairs.
Begin
   Declare a structure keycompare.
      Function operator()(const pair& v, const int& k)
      returns Booleans.
         Status = v.first < k.
         Return status.
      Function operator()(const pair& v, const int& k)
      returns Booleans.
         Status = k < v.first.
         Return status.
   Declare a vector v.
   Declare key and value pair within v of the integer datatype.
   Call push_back() function to insert values in v vector.
   Call sort() function to sort all elements of the vector v.
   Print “Sorted vector”.
   Print “Key” “Value”.
   for (pair& n : v)
      print the first and second value of n.
   if (binary_search(v.begin(), v.end(), 50,keycompare())) then
      print “50 exists in vector”.
   Else
      Print “50 does not exist”.
   if (binary_search(v.begin(), v.end(), 7,keycompare() )) then
      print “7 exists in vector”.
   Else
      Print “7 does not exist”.
End.
 Live Demo
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct keycompare {
   bool operator()(const pair<int, int>& v, const int& k) {
      return (v.first < k);
   }
   bool operator()(const int& k, const pair<int, int>& v) {
      return (k < v.first);
   }
};
int main() {
   vector<pair<int, int>> v;
   v.push_back(make_pair(7, 26));
   v.push_back(make_pair(6, 76));
   v.push_back(make_pair(4, 16));
   v.push_back(make_pair(5, 36));
   sort(v.begin(), v.end());
   cout<<"Sorted vector"<<endl;
   cout << "KEY" << '\t' << "VALUE" << endl;
   for (pair& n : v)
      cout << n.first << '\t' << n.second << endl;
   if (binary_search(v.begin(), v.end(), 50,keycompare()))
      cout << "50 exists in vector";
   else
      cout << "50 does not exist";
      cout << endl;
   if (binary_search(v.begin(), v.end(), 7,keycompare() ))
      cout << "7 exists in vector";
   else
      cout << "7 does not exist";
   return 0;
}
Sorted vector
KEY VALUE
4 16
5 36
6 76
7 26
50 does not exist
7 exists in vector
How to start dependent services in PowerShell?

To start dependent service in PowerShell, it is unlike the stopping the dependent services with –Force parameter because there is no –Force parameter is available.
You need to first get the dependent services and then start them.
Get-Service -Name Winmgmt -DependentServices | Start-Service -Verbose
How to set the tab size in Text widget in Tkinter? - GeeksforGeeks

08 Mar, 2021
Prerequisite: Tkinter
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
In this article, we will learn how to set the tab size in the text widget using Python in Tkinter. Here the tab size means that how many spaces will be printed after pressing the tab button. Let’s see the approach for doing the same.
Let’s Understand step by step implementation:
Create a Normal Tkinter window
Python3
# Import Modulefrom tkinter import *  # Create Objectroot = Tk()  # Set Geometryroot.geometry("400x400")  # Execute Tkinterroot.mainloop()
Output:
Add text widget
Syntax:
T = Text(root, bg, fg, bd, height, width, font, ..)
Python3
# Add Text Boxtext = Text(root)text.pack()
Set tab size
Here will use tkfont() method from the font package
Python3
# Set Fontfont = tkfont.Font(font=text['font'])  # Set Tab sizetab_size = font.measure('        ')text.config(tabs=tab_size)
Below is the Implementation:
Python3
# Import Modulefrom tkinter import *import tkinter.font as tkfont  # Create Objectroot = Tk()  # Set Geometryroot.geometry("400x400")  # Add Text Boxtext = Text(root)text.pack()  # Set Fontfont = tkfont.Font(font=text['font'])  # Set Tab sizetab_size = font.measure('           ')text.config(tabs=tab_size)  # Execute Tkinterroot.mainloop()
Output:
Picked
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
%n in scanf() in C with Example - GeeksforGeeks

19 Aug, 2020
In C, %n is a special format specifier. In the case of printf() function the %n assign the number of characters printed by printf(). When we use the %n specifier in scanf() it will assign the number of characters read by the scanf() function until it occurs. 
Key points:
It is an edit conversion code.
The edit conversion code %[^\n] can be used as an alternative of gets.
C supports this format specification with a scanf() function.
This edit conversion code can be used to read a line containing characters like variables and even white spaces.
In general scanf() function with format specification like %s and specification with the field width in the form of %ws can read-only strings till non-white space part.
It means they cannot be used for reading a text containing more than one word, especially with white space.
Syntax:
scanf("%[^\n]", variable_name);

Below is the program to demonstrate the working of %n in scanf(): 
C
// C++ to demonstrate %n in scanf()#include <stdio.h>  // Driver Codeint main(){    int check;    int a, b;      // Input two variables    scanf("%d%d%n", &a, &b, &check);      // Print value of a, b, and check    printf("%d\n%d\n%d", a, b, check);    return 0;}
C Programs
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Regular expressions in C
C++ Program for QuickSort
CSV file management using C++
cin in C++
delete keyword in C++
Shallow Copy and Deep Copy in C++
What is Realloc in C language?

The C library memory allocation function void *realloc(void *ptr, size_t size) attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.
Memory can be allocated in two ways as explained below −
Once memory is allocated at compile time, it cannot be changed during execution. There will be a problem of either insufficiency or else wastage of memory.
The solution is to create memory dynamically i.e. as per the requirement of the user during execution of program.
The standard library functions which are used for dynamic memory management are as follows −
malloc ( )
calloc ( )
realloc ( )
free ( )
It is used for reallocating already allocated memory.
It is used for reallocating already allocated memory.
It can either decrease or increase the allocated memory.
It can either decrease or increase the allocated memory.
It returns a void pointer that points to the base address of reallocated memory.
It returns a void pointer that points to the base address of reallocated memory.
The syntax for realloc() function is as follows −
Free void *realloc (pointer, newsize);
The following example shows the usage of realloc() function.
int *ptr;
ptr = (int * ) malloc (1000);// we can use calloc also
- - -
- - -
- - -
ptr = (int * ) realloc (ptr, 500);
- - -
- - -
ptr = (int * ) realloc (ptr, 1500);
Given below is the C program using realloc () function −
 Live Demo
#include<stdio.h>
#include<stdlib.h>
int main(){
   int *ptr, i, num;
   printf("array size is 5\n");
   ptr = (int*)calloc(5, sizeof(int));
   if(ptr==NULL){
      printf("Memory allocation failed");
      exit(1); // exit the program
   }
   for(i = 0; i < 5; i++){
      printf("enter number at %d: ", i);
      scanf("%d", ptr+i);
   }
   printf("\nLet's increase the array size to 7\n ");
   ptr = (int*)realloc(ptr, 7 * sizeof(int));
   if(ptr==NULL){
      printf("Memory allocation failed");
      exit(1); // exit the program
   }
   printf("\n enter 2 more integers\n\n");
   for(i = 5; i < 7; i++){
      printf("Enter element number at %d: ", i);
      scanf("%d", ptr+i);
   }
   printf("\n result array is: \n\n");
   for(i = 0; i < 7; i++){
      printf("%d ", *(ptr+i) );
   }
   return 0;
}
When the above program is executed, it produces the following result −
array size is 5
enter number at 0: 23
enter number at 1: 12
enter number at 2: 45
enter number at 3: 67
enter number at 4: 20
Let's increase the array size to 7
enter 2 more integers
Enter element number at 5: 90
Enter element number at 6: 60
result array is:
23 12 45 67 20 90 60
How to add name to data frame columns in R?

A data frame can be created by using data.frame function but in this case R generates the column names using the values we pass for the data. For example, if we pass a probability distribution as shown in the below examples then its name will be there. If we want to change those names then setNames function can be used along with the data frame name.
 Live Demo
df1<-data.frame(rnorm(20),rnorm(20))
df1
     rnorm.20.    rnorm.20..1
1  -0.24431409   1.48414429
2  -0.04429157  -1.07317747
3   1.03638861   1.23016674
4  -1.51950536   1.01723593
5  -1.29030669   1.59741022
6  -0.02540577   0.16847649
7   0.89598486   1.37993236
8  -1.61080153  -0.89799825
9  -0.54181883  -0.53642593
10 -0.21685719  -0.34991237
11 -0.48691372   0.03656945
12  0.61789184  -0.68130916
13  1.11895194  -1.03310011
14  0.46876609  -0.47855369
15  0.94841120  -0.25945237
16 -0.33669202   0.38229316
17 -0.84262751  -0.62787283
18  1.54774271  -1.97730922
19 -0.23887277   0.02692167
20 -0.33640096   0.35218858
Setting names of columns in df1 −
setNames(df1,c("x1","x2"))
      x1            x2
1  -0.24431409   1.48414429
2  -0.04429157  -1.07317747
3   1.03638861   1.23016674
4  -1.51950536   1.01723593
5  -1.29030669   1.59741022
6  -0.02540577   0.16847649
7   0.89598486   1.37993236
8  -1.61080153  -0.89799825
9  -0.54181883  -0.53642593
10 -0.21685719  -0.34991237
11 -0.48691372   0.03656945
12  0.61789184  -0.68130916
13  1.11895194  -1.03310011
14  0.46876609  -0.47855369
15  0.94841120  -0.25945237
16 -0.33669202   0.38229316
17 -0.84262751  -0.62787283
18  1.54774271  -1.97730922
19 -0.23887277   0.02692167
20 -0.33640096   0.35218858
 Live Demo
df2<-data.frame(rpois(20,8),rpois(20,5))
df2
rpois.20..8. rpois.20..5.
1    7         4
2   12         4
3    6         4
4    7         9
5   11         6
6    8         4
7    8         3
8    7         4
9    4         3
10  10         3
11   7         3
12  12         6
13   8         5
14  11         3
15   6         4
16   8         8
17   6         8
18  10         7
19  11         1
20   5        6
Setting names of columns in df2 −
setNames(df2,c("y1","y2"))
    y1  y2
1   7   4
2  12   4
3   6   4
4   7   9
5  11   6
6   8   4
7   8   3
8   7   4
9   4   3
10 10   3
11  7   3
12 12   6
13  8   5
14 11   3
15  6   4
16  8   8
17  6   8
18 10   7
19 11   1
20  5   6
Optional orElseGet() method in Java with examples - GeeksforGeeks

13 May, 2020
The orElseGet() method of java.util.Optional class in Java is used to get the value of this Optional instance if present. If there is no value present in this Optional instance, then this method returns the value generated from the specified supplier.
Syntax:
public T orElseGet(Supplier<T> supplier)

Parameters: This method accepts supplier as a parameter of type T to generate a value to return if there is no value present in this Optional instance.
Return supplier: This method returns the value of this Optional instance, if present. If there is no value present in this Optional instance, then this method returns the value generated from the specified supplier.
Exception: This method throws NullPointerException if there is no value present in this Optional instance.
Below programs illustrate orElseGet() method:Program 1:
// Java program to demonstrate// Optional.orElseGet() method  import java.util.*;import java.util.function.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.of(9455);          // print supplier        System.out.println("Optional: "                           + op);          // orElseGet supplier        System.out.println("Value by orElseGet"                           + "(Supplier) method: "                           + op.orElseGet(                                 () -> (int)(Math.random() * 10)));    }}
Optional: Optional[9455]
Value by orElseGet(Supplier) method: 9455

Program 2:
// Java program to demonstrate// Optional.orElseGet() method  import java.util.*;import java.util.function.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.empty();          // print supplier        System.out.println("Optional: "                           + op);          try {              // orElseGet supplier            System.out.println("Value by orElseGet"                               + "(Supplier) method: "                               + op.orElseGet(                                     () -> (int)(Math.random() * 10)));        }        catch (Exception e) {            System.out.println(e);        }    }}
Optional: Optional.empty
Value by orElseGet(Supplier) method: 1

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#orElseGet-java.util.function.Supplier-
umadevika
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
Groovy - Lists minus()

Creates a new List composed of the elements of the original without those specified in the collection.
List minus(Collection collection)

Collection – The collection of values to minus from the list.
New list of values.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      def lst = [11, 12, 13, 14]; 
      def newlst = [];
      
      newlst = lst.minus([12,13]); 
      println(newlst); 
   } 
}
When we run the above program, we will get the following result −
[11, 14]


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Difference between the AND and && operator in php

'AND' operator is a logical AND operator but has low precedence to = operator.
'&&' is also a logical AND operator but has high precedence to = operator.
Following the example, shows the difference of 'AND' vs '&&' operators.
 Live Demo
<!DOCTYPE html>
<html>
<head>
   <title>PHP Example</title>
</head>
<body>
   <?php
      $x = true;
      $y = false;
      $result = $x AND $y;
      print('$result = $x AND $y');
      print("<br/>");
      var_dump($result);
      print("<br/>");
      $result = $x && $y;
      print('$result = $x && $y');
      print("<br/>");
      var_dump($result);
   ?>
</body>
</html>
$result = $x AND $y
bool(true)
$result = $x && $y
bool(false)
Can we override private methods in Java


Ideally No. But, using the tricky code, a subclass can override a private method as well. See the example below −
Live Demo
class A {
   private void display() {
      System.out.println("A.display");
   }
    public void callDisplay() {
      System.out.println("A.callDisplay");
      display();
   }
}

class B extends A {
   private void display() {
      System.out.println("B.display");
   }
    public void callDisplay() {
      System.out.println("B.callDisplay");
      display();
   }  
}

public class Tester {
   public static void main(String[] args) {
      A a = new B();
      a.callDisplay();

      B b = new B();
      b.callDisplay();

      A a1 = new A();
      a1.callDisplay();
   }
}
B.callDisplay
B.display
B.callDisplay
B.display
A.callDisplay
A.display
In above example, an object is of B class, the a.callDisplay() makes a call to callDisplay() method of B which in turn calls B's display method.
As per the Java's documentation The Java Tutorials: Predefined Annotation Types.
While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.
Add @Override annotation over B.display() method. Java compiler will throw the error.
class B extends A {
   @Override
   private void display() {
      System.out.println("B.display");
   }

   public void callDisplay() {
      System.out.println("B.callDisplay");
      display();
   }  
}
The method display() of type B must override or implement a supertype method.
How to retrieve tasks in Task scheduler using PowerShell?

To retrieve the existing tasks in the task scheduler using PowerShell, we can use the PowerShell command Get-ScheduledTask. We can use the Task Scheduler GUI to retrieve the scheduled tasks.
 
To retrieve using PowerShell, use the Get-ScheduledTask command.
When we use the above command, it retrieves all the tasks from the different paths/folders as well including the root path. To retrieve tasks created at the root path we need to filter the task path,
Get-ScheduledTask | where{$_.TaskPath -eq "\"}
If we need to retrieve the specific task then we need to filter the task name,
TaskPath TaskName                          State
-------- --------                          -----
\        CreateExplorerShellUnelevatedTask Running
\        FirstTask                         Ready
\        TestScript                        Ready
 To retrieve the specific task,
Get-ScheduledTask | where{$_.TaskName -eq "TestScript"}
TaskPath TaskName   State
-------- --------   -----
\        TestScript Ready
To retrieve the tasks with the state, use the command below,
Get-ScheduledTask | where{$_.State -eq "Running"}
To retrieve the task of the remote computer, we can use the CimSession parameter.
$session = New-CimSession -ComputerName "Test1-Win2k12"
Get-ScheduledTask -CimSession $session | where{$_.TaskPath -eq "\"}
To retrieve the tasks located in a specific task folder,
Get-ScheduledTask -CimSession $sess -TaskPath '\DailyReport\'
TaskPath      TaskName       State PSComputerName
--------      --------       ----- --------------
\DailyReport\ DiskInforeport Ready Test1-Win2k12
\DailyReport\ TopProcesses   Ready Test1-Win2k12
 
In the above example, we have tasks stored in the DailyReport folder.
MongoDB $in Operator - GeeksforGeeks

22 Apr, 2020
MongoDB provides different types of comparison query operators and $in operator is one of them. This operator is used to select those documents where the value of the field is equal to any of the given value in the array. And if the field contains an array, then this operator selects only those documents whose field contains an array that holds at least one item that matches a value of the specified array. You can use this operator in methods like find(), update(), etc. according to your requirements.
Syntax:
{field: {$in: [value1, value2, value3, ...]}}
In the following examples, we are working with:
Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs.
In this example, we are retrieving only those employee’s documents whose name is either Amit or Suman.
db.contributor.find({name: {$in: ["Amit", "Suman"]}}).pretty()
In this example, we are retrieving only those employee’s documents who is working with either C#, Python, or both languages.
db.contributor.find({language: {$in: ["C#", "Python"]}}).pretty()
In this example, we are retrieving only those employee’s documents who got the given marks in their semester.
db.contributor.find({"personal.semesterMarks":{$in: [80, 89, 78]}}).pretty()
In this example, we are adding a new field-value pair(i.e, salary: 10000) in the documents of Amit and Suman by using update() method with $in and $set operators.
db.contributor.update({name: {$in: ["Amit", "Suman"]}}, {$set: {salary: 10000}})
Note: The update() method by default update only one document at a time. If you want to update multiple documents, then set the value of its multi parameter to true. So, in this example, the update() method updated the first document that matches the given condition as shown in the below image.
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
Principal Component Analysis with Python
OpenCV - Overview
Mounting a Volume Inside Docker Container
Fuzzy Logic | Introduction
Basics of API Testing Using Postman
How to create a REST API using Java Spring Boot
Classifying data using Support Vector Machines(SVMs) in Python
Getting Started with System Design
Q-Learning in Python
How to display an image in JavaFX?

The javafx.scene.image.Image class is used to load an image into a JavaFX application. This supports BMP, GIF, JPEG, and, PNG formats.
JavaFX provides a class named javafx.scene.image.ImageView is a node that is used to display, the loaded image.
To display an image in JavaFX −
Create a FileInputStream representing the image you want to load.
Create a FileInputStream representing the image you want to load.
Instantiate the Image class bypassing the input stream object created
above, as a parameter to its constructor.
Instantiate the Image class bypassing the input stream object created
above, as a parameter to its constructor.
Instantiate the ImageView class.
Instantiate the ImageView class.
Set the image to it by passing above the image object as a parameter to the setImage() method.
Set the image to it by passing above the image object as a parameter to the setImage() method.
Set the required properties of the image view using the respective setter
methods.
Set the required properties of the image view using the respective setter
methods.
Add the image view mode to the group object.
Add the image view mode to the group object.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
public class ImageViewExample extends Application {
   public void start(Stage stage) throws IOException {
      //creating the image object
      InputStream stream = new FileInputStream("D:\\images\\elephant.jpg");
      Image image = new Image(stream);
      //Creating the image view
      ImageView imageView = new ImageView();
      //Setting image to the image view
      imageView.setImage(image);
      //Setting the image view parameters
      imageView.setX(10);
      imageView.setY(10);
      imageView.setFitWidth(575);
      imageView.setPreserveRatio(true);
      //Setting the Scene object
      Group root = new Group(imageView);
      Scene scene = new Scene(root, 595, 370);
      stage.setTitle("Displaying Image");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]) {
      launch(args);
   }
}
Determine if file or directory exists in Java

The method java.io.File.exists() is used to check whether a file or a directory exists or not. This method returns true if the file or directory specified by the abstract path name exists and false if it does not exist.
A program that demonstrates this is given as follows −
import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("c:/JavaProgram/demo1.txt");
         file.createNewFile();
         System.out.println(file.exists());
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
The output of the above program is as follows −
true
Now let us understand the above program.
The method java.io.File.exists() is used to check whether the file or directory exists or not and the boolean value that is returned by the method is printed. A code snippet that demonstrates this is given as follows −
try {
   File file = new File("c:/JavaProgram/demo1.txt");
   file.createNewFile();
   System.out.println(file.exists());
} catch(Exception e) {
   e.printStackTrace();
}
How can the countplot be used to visualize data in Python Seaborn Library?

Seaborn is a library that helps in visualizing data. It comes with customized themes and a high-level interface.
In previous plots, we plotted the entire dataset on the graph. With the help of bar plots, we can understand the central tendency of the distribution of data.
The barplot function establishes the relationship between a categorical variable and a continuous variable. Data is represented in the form of rectangular bars where the length of the bar indicates the proportion of data in that specific category.
A special case of barplot is the countplot that shows the number of observations in every category with respect to the data instead of computing a statistical value of a second variable.
Let us understand the countplot with the help of ‘titanic’ dataset −
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
my_df = sb.load_dataset('titanic')
sb.countplot(x = "class", data = my_df, palette = "Blues");
plt.show()
The required packages are imported.
The input data is ‘titanic’ which is loaded from the seaborn library.
This data is stored in a dataframe.
The ‘load_dataset’ function is used to load the iris data.
This data is visualized using the ‘countplot’ function.
Here, the dataframe is supplied as parameter.
Also, the x and y values are specified.
This data is displayed on the console.
Creating a Basic hardcoded ChatBot using Python-NLTK

26 May, 2020
Creating a basic chatbot using Python in Jupyter Notebook. This chatbot interacts with the user using the hardcoded inputs and outputs which are fed into the Python code.
Requirements:You need to install the NLTK (Natural Language Toolkit), it provides libraries and programs for symbolic and statistical natural language processing for English written in the Python programming language. To install this module type the below command in the terminal.
pip install nltk
Below is the implementation
from nltk.chat.util import Chat, reflections  pairs =[    ['my name is (.*)', ['Hello ! % 1']],    ['(hi|hello|hey|holla|hola)', ['Hey there !', 'Hi there !', 'Hey !']],    ['(.*) your name ?', ['My name is Geeky']],    ['(.*) do you do ?', ['We provide a platform for tech enthusiasts, a wide range of options !']],    ['(.*) created you ?', ['Geeksforgeeks created me using python and NLTK']]]  chat = Chat(pairs, reflections)chat.converse()
Output:
Explanation of the above code:In the first line of code we have imported the Chat class and Reflections dictionary from the Natural Language Toolkit’s chatbot utilities. Chat class which will process the conversation between the user and your chatbot. Reflections is a dictionary that when a value in a regular expression group matches a key in the dictionary it will output the value in the response. So for the first item of list pairs if we input my name is geeky where geeky corresponds to the regex “(.*)” it will output “Hello ! Geeky”, that is it replaces the regex in response to “%1” that was referred to as “(.*)” with “Geeky”. Now we initialize the chatbot using pairs and reflections dictionary. Then after initialization we call the converse method of Chat class that automates the chatbot.
Python-nltk
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
HTTP headers | Access-Control-Request-Headers

27 Feb, 2020
Access-Control-Request-Headers is a request-type header used by browsers that contains information about the different HTTP headers that will be sent by the client in the ensuing request. Whenever a client initiates a request to a server, the browser checks if the request needs a CORS preflight or not. In case a CORS preflight request is required, the browser uses the HTTP Options method to send a request with a bunch of headers attached with it containing information about certain characteristics of the ensuing request. One of these characteristics is the different headers that the request might contain. This information is stored in the Access-Control-Request-Headers header of the preflight request.
Syntax:
Access-Control-Request-Headers: header-name-1, header-name-2, ...
Directives: The Access-Control-Request-Headers header accepts a single directive as mentioned above and described below:
header-name: A comma-separated list of header names that will be attached to the ensuing request.
Below example illustrate the Access-Control-Request-Headers in http headers.Example: Consider the following code to send a XHR request from the browser.
const xhr = new XMLHttpRequest();

xhr.open('POST', 'https://samplepostroute/');
xhr.setRequestHeader('X-PINGOTHER', 'pingpong');
xhr.setRequestHeader('Content-Type',
           'application/x-www-form-urlencoded');
xhr.onreadystatechange = handler;

xhr.send("id=100"); 

The request will contain Content-Type and X-PINGOTHER HTTP headers. Before sending the POST request, the browser will send a CORS preflight request. The CORS preflight request will contain the following header. In this manner, the server is informed about the different headers which might be present in the ensuing client request.
Access-Control-Request-Headers: X-PINGOTHER, Content-Type
Supported Browsers: The following browsers are compatible with the Access-Control-Request-Headers header functionality:
Google Chrome 4.0
Firefox Browser 3.5
Internet Explorer 10.0
Opera 12.0
Safari 4.0
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
turtle.onkey() function in Python

26 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to bind fun to the key-release event of the key. In order to be able to register key-events, TurtleScreen must have focus.
Syntax :
turtle.onkey(fun, key)

Parameters:
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle  # method for key calldef fxn():    turtle.forward(40)  # set turtle screen sizesc=turtle.Screen()sc.setup(600,300)  # motionturtle.forward(40)  # call method on Right keyturtle.onkey(fxn,'Right')  # to listen by the turtleturtle.listen()
Output :
Example 2 :
Python3
# import packageimport turtle  # methods with different work # at different keysdef fxn():    turtle.forward(20)      def fxn1():    turtle.right(90)  def fxn2():    turtle.left(90)    # set screen sizesc=turtle.Screen()sc.setup(500,300)  # call methodsturtle.onkey(fxn,'space')turtle.onkey(fxn1,'Right')turtle.onkey(fxn2,'Left')  # to listen by the turtleturtle.listen()
Output :
Python-turtle
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list