code-rag-bench/online-tutorials huggingface dataset:
StringJoiner toString() method in Java

12 Dec, 2021
The toString() of StringJoiner is used to convert StringJoiner to String. It returns the current value, consisting of the prefix, the values added so far separated by the delimiter, and the suffix, unless no elements have been added in which case, the prefix + suffix or the emptyValue characters are returnedSyntax: 
public String toString()
Returns: This method returns the string representation of this StringJoinerBelow programs illustrate the toString() method:Example 1: To demonstrate toString() with delimiter ” ” 
Java
// Java program to demonstrate// toString() method of StringJoiner import java.util.StringJoiner; public class GFG {    public static void main(String[] args)    {         // Creating StringJoiner with delimiter " "        StringJoiner str = new StringJoiner(" ");         // Adding elements in the StringJoiner        str.add("Geeks");        str.add("for");        str.add("Geeks");         // Print the StringJoiner        // using toString() method        System.out.println("StringJoiner: "                           + str.toString());    }}
StringJoiner: Geeks for Geeks
 
Example 2: To demonstrate toString() with delimiter “, “
Java
// Java program to demonstrate// toString() method of StringJoiner import java.util.StringJoiner; public class GFG {    public static void main(String[] args)    {         // Creating StringJoiner with delimiter ""        StringJoiner str = new StringJoiner(", ");         // Adding elements in the StringJoiner        str.add("Geeks");        str.add("for");        str.add("Geeks");        str.add("A");        str.add("Computer");        str.add("Portal");         // Print the StringJoiner        // using toString() method        System.out.println("StringJoiner: "                           + str.toString());    }}
StringJoiner: Geeks, for, Geeks, A, Computer, Portal
 
akshaysingh98088
Java - util package
Java-Functions
Java-StringJoiner
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
MATLAB - Inverse of a Matrix

The inverse of a matrix A is denoted by A−1 such that the following relationship holds −
AA−1 = A−1A = 1
The inverse of a matrix does not always exist. If the determinant of the matrix is zero, then the inverse does not exist and the matrix is singular.
Inverse of a matrix in MATLAB is calculated using the inv function. Inverse of a matrix A is given by inv(A).
Create a script file and type the following code −
a = [ 1 2 3; 2 3 4; 1 2 5]
inv(a)
When you run the file, it displays the following result −
a =
   1     2     3
   2     3     4
   1     2     5
ans =
   -3.5000    2.0000    0.5000
   3.0000   -1.0000    -1.0000
   -0.5000      0       0.5000
JavaScript String substring() Method

07 Oct, 2021
The string.substring() is an inbuilt function in JavaScript which is used to return the part of the given string from start index to end index. Indexing start from zero (0). Syntax:  
string.substring(Startindex, Endindex)
Parameters: Here the Startindex and Endindex describes the part of the string to be taken as substring. Here the Endindex is optional. Return value: It returns a new string which is part of the given string. JavaScript code to show the working of string.substring() function: Code #1:  
javascript
<script>     // Taking a string as variable    var string = "geeksforgeeks";    a = string.substring(0, 4)    b = string.substring(1, 6)    c = string.substring(5)    d = string.substring(0)     // Printing new string which are    // the part of the given string    document.write(a + "<br>");    document.write(b + "<br>");    document.write(c + "<br>");    document.write(d + "<br>"); </script>                   
Output:  
geek
eeksf
forgeeks
geeksforgeeks
Code #2: Index always start with 0. If still we take index as negative, it will be considered as zero and index can’t be in fraction if it found so, it will be converted into its just lesser whole number.  
javascript
<script>     // Taking a string as variable    var string = "geeksforgeeks";    a = string.substring(-1)    b = string.substring(2.5)    c = string.substring(2.9)     // Printing new string which are    // the part of the given string    document.write(a + "<br>");    document.write(b + "<br>");    document.write(c + "<br>"); </script>                   
Output:  
geeksforgeeks
eksforgeeks
eksforgeeks
 
Supported Browser:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 3 and above
Opera 3 and above
Safari 1 and above
arorakashish0911
ysachin2314
javascript-string
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
How to get character array from string in JavaScript?
Node.js | fs.writeFileSync() Method
JavaScript | Promises
How to filter object array based on attributes?
How to Use the JavaScript Fetch API to Get Data?
Node.js Query String

07 Feb, 2022
The Query String module used to provides utilities for parsing and formatting URL query strings.It can be used to convert query string into JSON object and vice-versa. 
The Query String is the part of the URL that starts after the question mark(?).
Requiring Module: You can include the module using the following code: 
const querystring = require('querystring');
Note: It’s not a global object, so need to install it explicitly. Install Module:  
npm install querystring
 
Example 1: Using parse():
 
Javascript
// Importing the modelsimport url from 'url'import querystring from 'querystring' // A URL is takenlet exampleUrl ='http://www.company.com:81/a/b/c.html?user=GEEKSFORGEEKS&year=2021#p2'; //Parse the whole URLlet parsed_Url = url.parse(exampleUrl); // Parse only querystring.let parsed_queryString = querystring.parse(parsed_Url.query); // Print the result.console.log("This is parsed URL :",parsed_Url); console.log("This is parsed Query String :",parsed_queryString);
Output: 
This is parsed URL : Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'www.company.com:81',
  port: '81',
  hostname: 'www.company.com',
  hash: '#p2',
  search: '?user=GEEKSFORGEEKS&year=2021',
  query: 'user=GEEKSFORGEEKS&year=2021',
  pathname: '/a/b/c.html',
  path: '/a/b/c.html?user=GEEKSFORGEEKS&year=2021',
  href: 
'http://www.company.com:81/a/b/c.html?user=GEEKSFORGEEKS&year=2021#p2'
}
This is parsed Query String : [Object: null prototype] 
               { user: 'GEEKSFORGEEKS', year: '2021' }
 
Example 2: Using stringify(): 
 
Javascript
// Importing the modelimport querystring from 'querystring' // Specify the  object// to be serializedconst q2=querystring.stringify({                            name:'Testing',                            company:'GeeksforGeeks',                            content:'Article',                            date:'9thMarch2021'                           });  // Print the result.console.log(q2);
Output:  
name=Testing&company=GeeksforGeeks&
content=Article&date=9thMarch2021
Reference: https://nodejs.org/api/querystring.html 
varshagumber28
Node.js- querystring-Module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to wait for iFrames to load completely in Selenium webdriver?

We can wait for the iframe to load completely with Selenium webdriver.First of all we need to identify the iframe with the help iframe id, name, number or webelement. Then we shall use the explicit wait concept in synchronization to wait for the iframe to load.
We need to import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait to incorporate expected conditions and WebDriverWait class. We will wait for the iframe to be loaded with the condition frameToBeAvailableAndSwitchToIt.
Let us see an html document of a frame.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class FrameLoadWait{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
      driver.get("https://the-internet.herokuapp.com/nested_frames");
      // frame load explicit condition
      WebDriverWait w = new WebDriverWait(driver, 5);    
      w.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("frame-bottom"));
      // identify element inside frame
      WebElement p=driver.findElement(By.cssSelector("body"));
      System.out.println("Text inside frame is: " + p.getText());
      driver.close();
   }
}
Write a C Program to count the frequency of each character

Follow the algorithm to write a C program which enables to count the frequency of each character.
Step 1: Define MAX size.
Step 2: Declare char and integer variables.
Step 3: Read the string from console.
Step 4: Find length of the string.
Step 5: Initialize frequency of each character to 0.
Step 6: Find total number of occurrences of each character.
for(i=0; i<length; i++)
   i. if(string[i]>='a' && string[i]<='z')
   frequency[string[i] - 97]++;
   ii. else if(string[i]>='A' && string[i]<='Z')
      frequency[string[i] - 65]++;
Step 7: Print the frequency of all characters in the string.
if(frequency[i] != 0)
   printf("'%c' = %d\n", (i + 97), frequency[i]);
Given below is the C program to count frequency of each character in a string −
 Live Demo
#include <stdio.h>
#include <string.h>
#define MAX 100 // Maximum string size
int main(){
   char string[MAX];
   int i, length;
   int frequency[20];
   /* Input string from user */
   printf("enter the string:\n ");
   gets(string);
   length = strlen(string);
   /* Initialize frequency of each character to 0 */
   for(i=0; i<20; i++){
      frequency[i] = 0;
   }
   /* Find total number of occurrences of each character */
   for(i=0; i<length; i++){
      /* If the current character is lowercase alphabet */
      if(string[i]>='a' && string[i]<='z'){
         frequency[string[i] - 97]++;
      }
      else if(string[i]>='A' && string[i]<='Z'){
         frequency[string[i] - 65]++;
      }
   }
   /* Print the frequency of all characters in the string */
   printf("\nFrequency of all characters in string: \n");
   for(i=0; i<20; i++){
      /* If current character exists in given string */
      if(frequency[i] != 0){
         printf("'%c' = %d\n", (i + 97), frequency[i]);
      }
   }
   return 0;
}
When the above program is executed, it produces the following result −
enter the string:
Tutorials Point
Frequency of all characters in string:
'a' = 1
'i' = 2
'l' = 1
'n' = 1
'o' = 2
'p' = 1
'r' = 1
's' = 1
't' = 3
File Objects in Java

The File object represents the actual file/directory on the disk. Here are the list of constructors to
create File Object in Java −
Assuming an object is present in the given location, the first argument to the command line will be
considered as the path and the below code will be executed −
import java.io.File;
public class Demo{
   public static void main(String[] args){
      String file_name =args[0];
      File my_file = new File(file_name);
      System.out.println("File name is :"+my_file.getName());
      System.out.println("The path to the file is: "+my_file.getPath());
      System.out.println("The absolute path to the file is:" +my_file.getAbsolutePath());
      System.out.println("The parent directory is :"+my_file.getParent());
      if(my_file.exists()){
         System.out.println("Is the file readable"+my_file.canRead());
         System.out.println("The size of the file in bytes is "+my_file.length());
      }
   }
}
The details about the file will be displayed here.
A class named Demo contains the main function, and a string is defined, that holds the first
argument passed in the command line. The details of the file are printed on the screen, this includes
name of the file, file path, the absolute path of the file, and the parent directory of the file.
Tryit Editor v3.7

Tryit: HTML layout
Check if strings are rotations of each other or not in Python

Suppose we have two strings s and t, we have to check whether t is a rotation of s or not.
So, if the input is like s = "hello", t = "llohe", then the output will be True.
To solve this, we will follow these steps −
if size of s is not same as size of t, thenreturn False
return False
temp := s concatenate with s again
if count of t in temp > 0, thenreturn True
return True
return False
Let us see the following implementation to get better understanding −
Live Demo
def solve(s, t):
   if len(s) != len(t):
      return False
 
   temp = s + s
 
   if temp.count(t)> 0:
      return True
   return False

s = "hello"
t = "llohe"
print(solve(s, t))
"hello", "llohe"

True
Calculate range of data types using C++ - GeeksforGeeks

12 Jan, 2018
C++ program for printing the range data type like int, char, short.
Signed Data Types
METHOD
1.) calculate total number of bits by multiplying sizeof with 8 (say n)
2.) Calculate  -2^(n-1) for minimum range
3.) Calculate  (2^(n-1))-1 for maximum range

// CPP program to calculate // range of signed data type#include <bits/stdc++.h>#define SIZE(x) sizeof(x) * 8using namespace std;  // function to calculate range of//unsigned data typevoid printSignedRange(int count){    int min = pow(2, count - 1);    int max = pow(2, count - 1) - 1;    printf("%d to %d", min * (-1), max);}  // DRIVER programint main(){    cout << "signed char: ";    printSignedRange(SIZE(char));    cout << "\nsigned int: ";    printSignedRange(SIZE(int));    cout << "\nsigned short int: ";    printSignedRange(SIZE(short int));      return 0;}
Output:
signed char: -128 to 127
signed int: -2147483648 to 2147483647
signed short int: -32768 to 32767

Unsigned Data Types
METHOD
1.)Find number of bits by multiplying result of sizeof with 8 say n
2.)minimum range is always zero for unsigned data type
3.)for maximum range calculate 2^n-1

// CPP program to calculate range // of given unsigned data type#include <bits/stdc++.h>#define SIZE(x) sizeof(x) * 8using namespace std;  // function to calculate range // of given unsigned data typevoid UnsignedRange(int count){    // calculate 2^number of bits    unsigned int max =  pow(2, count) - 1;      cout << "0 to " << max;}  // DRIVER programint main(){    cout << "unsigned char: ";    UnsignedRange(SIZE(unsigned char));    cout << "\nunsigned int: ";    UnsignedRange(SIZE(unsigned int));    cout << "\nunsigned short int: ";    UnsignedRange(SIZE(unsigned short));    return 0;}
Output:
unsigned char: 0 to 255
unsigned int: 0 to 4294967295
unsigned short int: 0 to 65535

cpp-data-types
cpp-puzzle
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Sorting a Map by value in C++ STL
How to create a draggable HTML element with JavaScript and CSS?

To create a draggable HTML element with JavaScript and CSS, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .dragDiv {
      position: absolute;
      z-index: 9;
      text-align: center;
      border: 1px solid #d3d3d3;
      padding: 30px;
      cursor: move;
      z-index: 10;
      background-color: rgb(108, 24, 177);
      color: #fff;
      font-size: 20px;
      font-weight: 500;
   }
</style>
<body>
<h1>Draggable DIV Element Example</h1>
<h2>Click and drag the below element to move it around</h2>
<div class="dragDiv">
This div can be moved around
</div>
<script>
   dragElement(document.querySelector(".dragDiv"));
   function dragElement(ele) {
      var pos1 = 0,
      pos2 = 0,
      pos3 = 0,
      pos4 = 0;
      if (document.querySelector(ele.id + "header")) {
         document.getElementById(
            ele.id + "header"
         ).onmousedown = dragMouseDown;
      }
      else {
         ele.onmousedown = dragMouseDown;
      }
      function dragMouseDown(e) {
         e = e || window.event;
         e.preventDefault();
         pos3 = e.clientX;
         pos4 = e.clientY;
         document.onmouseup = closeDragElement;
         document.onmousemove = elementDrag;
      }
      function elementDrag(e) {
         e = e || window.event;
         e.preventDefault();
         pos1 = pos3 - e.clientX;
         pos2 = pos4 - e.clientY;
         pos3 = e.clientX;
         pos4 = e.clientY;
         ele.style.top = ele.offsetTop - pos2 + "px";
         ele.style.left = ele.offsetLeft - pos1 + "px";
      }
      function closeDragElement() {
         document.onmouseup = null;
         document.onmousemove = null;
      }
   }
</script>
</body>
</html>
The above code will produce the following output −
On moving the div around by dragging −
How to include Functions from other files in Node.js ? - GeeksforGeeks

29 Jun, 2020
Code reusability is an important pillar in modern day programming. Code Reuse means the practice of using an existing code for a new function or software. In this article, we would learn how to use functions from other files in Node.js. 
This functionality can be easily implemented using the inbuilt export and require functions of Node.js.
Export: The module.exports in Node.js is used to export any literal, function or object as a module. It is used to include JavaScript file into Node.js applications. The module is similar to variable that is used to represent the current module and exports is an object that is exposed as a module.
Require() function: It is an inbuilt function and is the easiest way to include functions that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the export object.
Let us consider the following basic example:
Filename: cal.js
function sum(x, y) {    return (x + y);}  function sub(x, y) {    return (x - y);}  function mul(x, y) {    return (x * y);}  module.exports = { add, sub, mul, div };
In the above example, we use the module.exports function so that we can use it in other files. The functions are enclosed within curly brackets( { } ) according to the format to export multiple functions at a time.
Suppose we wanted to use these functions in main.js, then it can be easily done using the following code:
Filename: main.js
//requiring cal.js fileconst cal = require("./cal.js")    //Using the functions from cal.js const sum = cal.sum(2, 2);console.log(sum);   const sub = cal.sub(10, 5);console.log(sub);   const product = cal.mul(2, 3);console.log(product);
This will import the cal.js file and its functions into the main.js file.
Run main.js file using the following command:
node main.js
Output:
4
5
6

Node.js-Misc
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
Mongoose find() Function
How to connect Node.js with React.js ?
Mongoose Populate() Method
Node.js Export Module
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Set heights and widths of forms with Bootstrap

Use classes like .input-lg and .col-lg-* to set the height and width of forms.
You can try to run the following code to set the form height and width −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <form role = "form">
         <div class = "form-group">
            <input class = "form-control input-lg" type = "text" placeholder =".input-lg">
         </div>
         <div class = "form-group">
            <input class = "form-control" type = "text" placeholder = "Default input">
         </div>
         <div class = "form-group">
            <input class = "form-control input-sm" type = "text" placeholder = ".input-sm">
         </div>
         <div class = "form-group"></div>
         <div class = "form-group">
            <select class = "form-control input-lg">
               <option value = "">.input-lg</option>
            </select>
         </div>
         <div class = "form-group">
            <select class = "form-control">
               <option value = "">Default select</option>
            </select>
         </div>
         <div class = "form-group">
            <select class = "form-control input-sm">
               <option value = "">.input-sm</option>
            </select>
         </div>
         <div class = "row">
            <div class = "col-lg-2">
               <input type = "text" class = "form-control" placeholder = ".col-lg-2">
            </div>
            <div class = "col-lg-3">
               <input type = "text" class = "form-control" placeholder = ".col-lg-3">
            </div>
            <div class = "col-lg-4">
               <input type = "text" class = "form-control" placeholder = ".col-lg-4">
            </div>
         </div>
      </form>
   </body>
</html>
How to fill array values in Java?

Let us first create an int array −
int[] arr = new int[10];
Now, fill array values. Here, the numbers get added from the index 2 to 7 −
Arrays.fill(arr, 2, 7, 100);
 Live Demo
import java.util.Arrays;
public class Demo {
   public static void main(String[] args) {
      int[] arr = new int[10];
      System.out.println("Array = "+Arrays.toString(arr));
      Arrays.fill(arr, 2, 7, 100);
      System.out.println("Fill = "+Arrays.toString(arr));
   }
}
Array = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Fill = [0, 0, 100, 100, 100, 100, 100, 0, 0, 0]
Build a GUI Application to Get Live Stock Price using Python - GeeksforGeeks

19 Jan, 2021
The stock price is the highest amount someone is willing to pay for the stock. In this article, we are going to write code for getting live share prices for each company and bind it with GUI Application.
Yahoo_fin: This module is used to scrape historical stock price data, as well as to provide current information on market caps, dividend yields, and which stocks comprise the major exchanges. To install this module type the below command in the terminal.
pip install yahoo_fin
Below is what the GUI looks like:-
Let’s write code to get stock data.
Import the yahoo_fin module.
Python3
from yahoo_fin import stock_info
Use stock_info.get_live_price() method to get live stock price.
Python3
stock_info.get_live_price("AMZN")
  
Output: 
3198.93994140625
Note: please visit this site to get company Symbol like Amazon is AMZN, Reliance is RELFF.
 
This Script implements the above Implementation into a GUI.
Python3
from yahoo_fin import stock_infofrom tkinter import *  def stock_price():     price = stock_info.get_live_price(e1.get())    Current_stock.set(price)  master = Tk()Current_stock = StringVar() Label(master, text="Company Symbol : ").grid(row=0, sticky=W)Label(master, text="Stock Result:").grid(row=3, sticky=W) result2 = Label(master, text="", textvariable=Current_stock,                ).grid(row=3, column=1, sticky=W) e1 = Entry(master)e1.grid(row=0, column=1) b = Button(master, text="Show", command=stock_price)b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5) mainloop()
Output:
abhigoya
Python Tkinter-exercises
Python-tkinter
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
PHP program to find the maximum and the minimum in array - GeeksforGeeks

24 Jun, 2021
Given an array of integers, find the maximum and minimum in it.Examples:  
Input : arr[] = {2, 3, 1, 6, 7}
Output : Maximum integer of the given array:7
         Minimum integer of the given array:1

Input  : arr[] = {1, 2, 3, 4, 5}
Output : Maximum integer of the given array : 5
         Minimum integer of the given array : 1
 
Approach 1 (Simple) : We simply traverse through the array, find its maximum and minimum.  
PHP
<?php// Returns maximum in arrayfunction getMax($array){   $n = count($array);   $max = $array[0];   for ($i = 1; $i < $n; $i++)       if ($max < $array[$i])           $max = $array[$i];    return $max;      } // Returns maximum in arrayfunction getMin($array){   $n = count($array);   $min = $array[0];   for ($i = 1; $i < $n; $i++)       if ($min > $array[$i])           $min = $array[$i];    return $min;      } // Driver code$array = array(1, 2, 3, 4, 5);echo(getMax($array));echo("\n");echo(getMin($array));?>
Output:  
5
1
Approach 2 (Using Library Functions) : We use library functions to find minimum and maximum.
Max():max() returns the parameter value considered “highest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned.  Min():min() returns the parameter value considered “lowest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned.
Max():max() returns the parameter value considered “highest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned.  
Min():min() returns the parameter value considered “lowest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned.
 
PHP
<?php$array = array(1, 2, 3, 4, 5);echo(max($array));echo("\n");echo(min($array));?>
Output:  
5
1
 
sweetyty
PHP-array
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Count how many times the given digital clock shows identical digits in C++

Suppose we have a digital clock of type HH:MM. Which shows the time in hours and minutes
only. We are given a number of hours and minutes as input. The goal is to count the number of times all digits are the same. H=M.
This happens 3 times a day, first at 00:00 midnight, then at 11:11 and last at 22:22. As time is represented in 24 hour format.
Input: 12 hours 22 minutes.
2
Explanation − For times 00:00 and 11:11. Twice in 12 hours.
Input: 48 hours 22 minutes.
5
Explanation − For times 00:00 and 11:11, 22:22 .
Variables hours and minutes store the input.
Function countIdentical(int hours, int minutes) takes minutes and hours and return count
of no. of times all HH;MM digits are the same.
For 00:00 initialize count as 1.
For each hour as 11 and 22 and minutes as 11 and 22 increment count by 1.
Return the result after the loop ends.
Count is the desired result.
Print the count.
 Live Demo
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// examples- 11:11 11hrs 11 mins, 22:22
int countIdentical(int hours, int minutes){
   // Initialized to 1 because of 00:00
   int i, count=1;
   // For double digit hours
   for (i = 0; i <= 99 && i < hours; i = i + 11) {
      // Double digit minutes
      if ((i % 10) < minutes)
      count++;
   }
   return count;
}
int main(){
   int hours = 48;
   int minutes = 22;
   cout <<"Times when all digits are identical in HH:MM :"
   << countIdentical(hours, minutes);
   return 0;
}
Times when all digits are identical in HH:MM : 6
Angular 6 - CLI

Angular CLI makes it easy to start with any Angular project. Angular CLI comes with commands that help us create and start on our project very fast. Let us now go through the commands available to create a project, a component and services, change the port, etc.
To work with Angular CLI, we need to have it installed on our system. Let us use the following command for the same −
npm install -g @angular/cli

To create a new project, we can run the following command in the command line and the project will be created.
ng new PROJECT-NAME
cd PROJECT-NAME
ng serve //

ng serve // will compile and you can see the output of your project in the browser −
http://localhost:4200/

4200 is the default port used when a new project is created. You can change the port with the following command −
ng serve --host 0.0.0.0 --port 4201

The following table lists down a few important commands required while working with Angular 4 projects.
Whenever a new module, a component, or a service is created, the reference of the same is updated in the parent module app.module.ts.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Python Program for Merge Sort

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given an array, we need to sort it using the concept of merge sort
Here we place the maximum element at the end. This is repeated until the array is sorted.
Now let’s observe the solution in the implementation below −
#merge function
def merge(arr, l, m, r):
   n1 = m - l + 1
   n2 = r- m
   # create arrays
   L = [0] * (n1)
   R = [0] * (n2)
   # Copy data to arrays
   for i in range(0 , n1):
      L[i] = arr[l + i]
   for j in range(0 , n2):
      R[j] = arr[m + 1 + j]
   i = 0 # first half of array
   j = 0 # second half of array
   k = l # merges two halves
   while i < n1 and j < n2 :
      if L[i] <= R[j]:
         arr[k] = L[i]
         i += 1
      else:
         arr[k] = R[j]
         j += 1
      k += 1
   # copy the left out elements of left half
   while i < n1:
      arr[k] = L[i]
      i += 1
      k += 1
   # copy the left out elements of right half
   while j < n2:
      arr[k] = R[j]
      j += 1
      k += 1
# sort
def mergeSort(arr,l,r):
   if l < r:
      # getting the average
      m = (l+(r-1))/2
      # Sort
      mergeSort(arr, l, m)
      mergeSort(arr, m+1, r)
      merge(arr, l, m, r)
# main
arr = [2,5,3,8,6,5,4,7]
n = len(arr)
mergeSort(arr,0,n-1)
print ("Sorted array is")
for i in range(n):
   print (arr[i],end=" ")
Sorted array is
2 3 4 5 5 6 7 8
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can make a Python Program for Merge Sort
Sort the words in lexicographical order in Python

17 Aug, 2018
Given a strings, we need to sort the words in lexicographical order (dictionary order).
Examples :
Input :  "hello python program how are you"
Output :  are
          hello
          how
          program
          python
          you

Input :   "Coders loves the algorithms"
Output :  Coders
          algorithms
          loves
          the

Note: The words which have first letter is capital letter they will print according alphabetical manner.
Approach :Approach used in this program is very simple. Split the strings using split() function. After that sort the words in lexicographical order using sort(). Iterate the words through loop and print each word, which are already sorted.
# Python program to sort the words in lexicographical# order  def sortLexo(my_string):      # Split the my_string till where space is found.    words = my_string.split()          # sort() will sort the strings.    words.sort()      # Iterate i through 'words' to print the words    # in alphabetical manner.    for i in words:        print( i )   # Driver code if __name__ == '__main__':          my_string = "hello this is example how to sort " \              "the word in alphabetical manner"    # Calling function    sortLexo(my_string)
Output :
alphabetical
example
hello
how
in
is
manner
sort
the
this
to
word

lexicographic-ordering
python-string
Python
Sorting
Technical Scripter
Sorting
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()
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm
How to create a copy of an object in PHP?

01 Dec, 2021
An object copy is created by using the clone keyword (which calls the object’s __clone() method if possible). An object’s __clone() method cannot be called directly. When an object is cloned, PHP will perform a shallow copy of all of the object’s properties. Any properties that are references to other variables will remain references.Syntax: 
$copy_object_name = clone $object_to_be_copied
Program 1: Program to create copy of an object. 
php
<?php // Program to create copy of an object // Creating classclass GFG {    public $data1;    public $data2;    public $data3;} // Creating object$obj = new GFG(); // Creating clone or copy of object$copy = clone $obj; // Set values of $obj object$obj->data1 = "Geeks";$obj->data2 = "for";$obj->data3 = "Geeks"; // Set values of copied object$copy->data1 = "Computer ";$copy->data2 = "science ";$copy->data3 = "portal"; // Print values of $obj objectecho "$obj->data1$obj->data2$obj->data3\n"; // Print values of $copy objectecho "$copy->data1$copy->data2$copy->data3\n"; ?>
GeeksforGeeks
Computer science portal
 
Example 2: Below program distinguishes clone from assignment ( = ) operator. 
php
<?php // Program to create copy of an object // Creating classclass GFG {    public $data1;    public $data2;    public $data3;     } // Creating object$obj = new GFG(); // Creating clone or copy of object$copy = clone $obj; // Creating object without clone keyword$obj_ref = $obj; // Set values of $obj object$obj->data1 = "Geeks";$obj->data2 = "for";$obj->data3 = "Geeks"; // Set values of copied object$copy->data1 = "Python ";$copy->data2 = "for ";$copy->data3 = "Machine learning"; // Print values of $obj objectecho "$obj->data1$obj->data2$obj->data3\n"; // Print values of $copy objectecho "$copy->data1$copy->data2$copy->data3\n"; // Print values of without clone objectecho "$obj_ref->data1$obj_ref->data2$obj_ref->data3\n"; ?>
GeeksforGeeks
Python for Machine learning
GeeksforGeeks
 
Note: It is clear that cloned object have different values than original object but original and referenced object created by using ‘=’ operator have same value. References:https://www.php.net/manual/en/language.oop5.cloning.php
surindertarika1234
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
How does the functools cmp_to_key function works in Python?

12 Nov, 2020
There has been a change in Python’s sorted() function, it now takes three values namely, the iterable, key, and reverse. Out of these last two are optional but this article emphasizes the key part of the sorted() function. What key does is, it helps in the comparison of iterable elements while sorting.  Python already had cmp() function that used to compare two values and return 1, -1, or 0. But as of Python 3.0 and above, this function has been deprecated and a new function cmp_to_key() has been introduced. The following article discusses the application and explanation of this function.
cmp_to_key() uses a key to compare elements
It is built into functools module, thus functools has to be imported first in order to use the function
Used with tools that accept key functions such as min(), max(), sorted() etc.
Takes only one argument which strictly should be a callable
This function returns a special key that can be used to compare elements
Syntax:
functools.cmp_to_key(callable)
Each element is compared with every other element of the list until a sorted list is obtained
Every element apparently calls mycmp() function with the other element of the list
mycmp() function returns a key after comparing the numbers
This key is eventually helping sorted() to arrange elements in ascending order
Below is the Implementation.
Example 1: Program that sorts a list using a key provided by cmp_to_key() function
Python3
import functools    def mycmp(a, b):    print("comparing ", a, " and ", b)    if a > b:        return 1    elif a < b:        return -1    else:        return 0    print(sorted([1, 2, 4, 2], key=functools.cmp_to_key(mycmp)))
Output:
comparing  2  and  1
comparing  4  and  2
comparing  2  and  4
comparing  2  and  2
comparing  2  and  4
[1, 2, 2, 4]

Example 2: Program that prints maximum and minimum numbers from a list using key provided by cmp_to_key() function
Python3
import functools    def mycmp(a, b):    print("comparing ", a, " and ", b)    if a > b:        return 1    elif a < b:        return -1    else:        return 0    print(min([45, 78, 813], key=functools.cmp_to_key(mycmp)))print(max([45, 78, 813], key=functools.cmp_to_key(mycmp)))
Output:
comparing  78  and  45
comparing  813  and  45
45
comparing  78  and  45
comparing  813  and  78
813

Python functools-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
Python OOPs Concepts
How To Convert Python Dictionary To JSON?
Stream findFirst() in Java with examples

06 Dec, 2018
Stream findFirst() returns an Optional (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.
Syntax :
Optional<T> findFirst()

Where, Optional is a container object which
may or may not contain a non-null value 
and T is the type of objects and the function
returns an Optional describing the first element 
of this stream, or an empty Optional if the stream is empty.

Exception : If the element selected is null, NullPointerException is thrown.
Note : findAny() is a terminal-short-circuiting operation of Stream interface. This method returns first element satisfying the intermediate operations.
Example 1 : findFirst() function on Stream of Integers.
// Java code for Stream findFirst()// which returns an Optional describing// the first element of this stream, or// an empty Optional if the stream is empty.import java.util.*;  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating a List of Integers        List<Integer> list = Arrays.asList(3, 5, 7, 9, 11);          // Using Stream findFirst()        Optional<Integer> answer = list.stream().findFirst();          // if the stream is empty, an empty        // Optional is returned.        if (answer.isPresent()) {            System.out.println(answer.get());        }        else {            System.out.println("no value");        }    }}
Output :
3

Example 2 : findFirst() function on Stream of Strings.
// Java code for Stream findFirst()// which returns an Optional describing// the first element of this stream, or// an empty Optional if the stream is empty.import java.util.*;  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating a List of Strings        List<String> list = Arrays.asList("GeeksforGeeks", "for",                                          "GeeksQuiz", "GFG");          // Using Stream findFirst()        Optional<String> answer = list.stream().findFirst();          // if the stream is empty, an empty        // Optional is returned.        if (answer.isPresent()) {            System.out.println(answer.get());        }        else {            System.out.println("no value");        }    }}
Output :
GeeksforGeeks

Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Stack Class in Java
Multi-Line Comment in Shell Script

09 Feb, 2022
Comments are quite a crucial part of a program or a code-base. It helps in understanding the code, improves code-readability, and also helps in enhancing the structure of the program. We often write single-line comments in our programs as they are quite self-explanatory and require few words to describe the flow of the program or any message about the particular section.  There are rare cases where we want several lines of messages or comment on an entire code block for debugging or any other reasons. We need to have a multiline comment in our program. 
There are two different ways to use multi-line comment in Shell Scripts:
Method 1: Using <<comment:
In Shell or Bash shell, we can comment on multiple lines using << and name of comment.  we start a comment block with << and name anything to the block and wherever we want to stop the comment, we will simply type the name of the comment.
<<comment
 "Code" or "Comments"
comment
The word “comment” can be anything but it should be the same for ending the comment block.
#!/bin/bash
echo "Sample code"
x=4
if [[ $x -le 10 ]];then
    echo "Less than 10"
if

<<com
echo"This doesn't echo"

echo"Even this doesn't"
com
echo "OK, this is echoing after <<com !"
Output:
Method 2: Using  : ‘ : 
There is also another way to comment in Bash using : ‘ operator.
: '

Code or Comment here
 '
Code:
#!/bin/bash
echo "Sample code"
x=4
if [[ $x -le 10 ]];then
    echo "Less than 10"
if

: '
echo"This doesn't echo"

echo"Even this doesn't"
 '
echo "OK, this is working with : '"
Output:
So this script also comments multiple lines, we need to be careful here with including a space before the end block ‘ , otherwise it would not work. It also applies to the start comment block : ‘, there is a space in between those characters.
rkbhola5
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
TCP Server-Client implementation in C
Docker - COPY Instruction
UDP Server-Client implementation in C
scp command in Linux with Examples
echo command in Linux with Examples
Matplotlib.axes.Axes.contour() in Python

13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.contour() function in axes module of matplotlib library is used to Plot contours. contourdraw contour lines.
Syntax:
Axes.contour(self, *args, data=None, **kwargs)
contour([X, Y, ] Z, [levels], **kwargs)
Parameters: This method accept the following parameters that are described below:
X, Y: These parameter are the coordinates of the values in Z.
Z : This parameter is the height values over which the contour is drawn.
levels : This parameter is used to determine the numbers and positions of the contour lines / regions.
Returns: This returns the following:
c :This returns the QuadContourSet.
Below examples illustrate the matplotlib.axes.Axes.contour() function in matplotlib.axes:
Example-1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerimport matplotlib  delta = 0.15x = np.arange(-0.5, 2.5, delta)y = np.arange(-1.0, 3.0, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(-X**2 - Y**2) - np.exp(-(X - 1)**2 - (Y - 1)**2))  fig1, ax1 = plt.subplots()CS1 = ax1.contour(X, Y, Z)  fmt = {}strs = ['1', '2', '3', '4', '5', '6', '7']for l, s in zip(CS1.levels, strs):    fmt[l] = sax1.clabel(CS1, CS1.levels, inline = True,           fmt = fmt, fontsize = 10)  ax1.set_title('matplotlib.axes.Axes.contour() Example')plt.show()
Output:
Example-2:
# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.cm as cmimport matplotlib.pyplot as plt  delta = 0.25x = np.arange(-5.0, 5.0, delta)y = np.arange(-3.3, 5.5, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(-X**2 - Y**2) - np.exp(-(X - 1)**2 - (Y - 1)**2)) * 3  fig, ax = plt.subplots()im = ax.imshow(Z, interpolation ='bilinear', origin ='lower',               cmap ="Greens", extent =(-3, 3, -2, 2))  levels = np.arange(-1.2, 1.6, 0.2)CS = ax.contour(Z, levels, origin ='lower', cmap ='Blues',                linewidths = 2, extent =(-3, 3, -2, 2))zc = CS.collections[6]plt.setp(zc, linewidth = 4)  ax.clabel(CS, levels, inline = 1, fmt ='% 1.1f',          fontsize = 14)ax.set_title('matplotlib.axes.Axes.contour() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Tuple Library - tie

It constructs a tuple object whose elements are references to the arguments in args, in the same order.
Following is the declaration for std::tie.
	
template<class... Types>
   tuple<Types&...> tie (Types&... args) noexcept;
template<class... Types>
   tuple<Types&...> tie (Types&... args) noexcept;
template<class... Types>
   constexpr tuple<Types&...> tie (Types&... args) noexcept;
args − It contains list of elements that the constructed tuple shall contain.
It returns a tuple with lvalue references to args.
No-throw guarantee − this member function never throws exceptions.
None introduced by this call.
In below example for std::tie.
#include <iostream>
#include <tuple>

int main () {
   int myint;
   char mychar;

   std::tuple<int,float,char> mytuple;

   mytuple = std::make_tuple (10, 2.6, 'a');

   std::tie (myint, std::ignore, mychar) = mytuple;

   std::cout << "myint contains: " << myint << '\n';
   std::cout << "mychar contains: " << mychar << '\n';

   return 0;
}
The output should be like this −
myint contains: 10
mychar contains: a

 Print
 Add Notes
 Bookmark this page