code-rag-bench/online-tutorials huggingface dataset:
How to wait for a keypress in R ? - GeeksforGeeks

17 Jun, 2021
R Programming language is robust and user-friendly, as it displays annotations and contexts for the desired input streams. We can pause the execution of a script and wait for the enter key to be pressed by the user into the console. This can be done using various standard methods in base R. 
In order to prompt to print on the console after the Enter key is pressed, we can use the readline() method in base R. The readline() method in R language reads a line from the terminal. The output is returned as a character vector of length one. The leading, as well as the trailing spaces, are stripped from the returned output.
Syntax:
readline(prompt = “”)
prompt – the string displayed upon prompting the user for input. Mostly terminates with a ” ” (space) character.
Example:
R
# read line readline(prompt="Press [enter] to proceed")
Output
The invisible method in R is used to return a (temporarily) invisible copy of an object. It returns an arbitrary object which assigns the values but does not print it on the console when they are not assigned.
Syntax:
invisible (x)
Example:
R
# read line invisible(readline(prompt="Press [enter] to proceed"))
Output
scan() method in base R is used to scan and read data into the working space. It read the input data into a vector or list or from file object establishing the file connection stream. This method fails when we enter any character string, that cannot be treated as a number. 
Example:
R
str <- "Press [enter] to proceed"print (str)  # scan a new numbernum <- scan(n=1)
Output
Picked
R-Functions
R-Input/Output
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
How to change the order of bars in bar chart in R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Data Visualization in R
Python | Morphological Operations in Image Processing (Closing) | Set-2

25 Apr, 2022
In the previous article, the Opening operator was specified which was applying the erosion operation after dilation. It helps in removing the internal noise in the image. Closing is similar to the opening operation. In closing operation, the basic premise is that the closing is opening performed in reverse. It is defined simply as a dilation followed by an erosion using the same structuring element used in the opening operation.
Syntax: cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel)
Parameters:-> image: Input Image array.-> cv2.MORPH_CLOSE: Applying the Morphological Closing operation.-> kernel: Structuring element.
Below is the Python code explaining Closing Morphological Operation –
Python3
# Python program to illustrate# Closing morphological operation# on an image  # organizing imports  import cv2  import numpy as np    # return video from the first webcam on your computer.  screenRead = cv2.VideoCapture(0)  # loop runs if capturing has been initialized.while(1):    # reads frames from a camera    _, image = screenRead.read()          # Converts to HSV color space, OCV reads colors as BGR     # frame is converted to hsv    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)          # defining the range of masking    blue1 = np.array([110, 50, 50])    blue2 = np.array([130, 255, 255])          # initializing the mask to be    # convoluted over input image    mask = cv2.inRange(hsv, blue1, blue2)      # passing the bitwise_and over    # each pixel convoluted    res = cv2.bitwise_and(image, image, mask = mask)          # defining the kernel i.e. Structuring element    kernel = np.ones((5, 5), np.uint8)          # defining the closing function     # over the image and structuring element    closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)         # The mask and closing operation    # is shown in the window     cv2.imshow('Mask', mask)    cv2.imshow('Closing', closing)          # Wait for 'a' key to stop the program     if cv2.waitKey(1) & 0xFF == ord('a'):        break  # De-allocate any associated memory usage  cv2.destroyAllWindows()  # Close the window / Release webcam screenRead.release()
Input Frame:
Mask:
Output:
anikakapoor
awdheshkumar2
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Node.js vs Vue.js

21 Oct, 2020
Node.js: It is a JavaScript runtime environment, which is built on Chrome’s V8 JavaScript engine. It is developed by Ryan Dahl who is a Software Engineer working at Google Brain, he also developed Deno JavaScript and TypeScript runtime. Node.js is cross-platform and open-source which executes JavaScript code on the server-side, i.e. outside the web browser. Due to its single-threaded nature, it is mainly used for event-driven, non-blocking servers, a non-blocking I/O model makes it lightweight and efficient, hence it is best for data-intensive real-time applications. It is used by traditional web-sites and back-end API services. It is designed with a real-time, push-based architecture that runs across distributed devices. The HTTP (Hypertext Transfer Protocol) module provides a set of classes and functions for building an HTTP server. We use native Node like file-system, path, and URL for this basic HTTP server.
Vue.js: It is an open-source progressive JavaScript framework that is mainly used for building UIs and single-page applications. It is created by Evan who was funded by the community on Patreon to develop VueJS. It is compatible with most modern technologies and because of the gentle learning curve and scalability, it gained a lot of popularity. VueJS follows the Model-View-ViewModel (MVVM) architectural pattern, where ViewModel has a ‘Vue’ instance and View and Model are bound by two-way data binding. It utilizes a virtual DOM and in terms of API and design Vue is easy to learn as compared with AngularJS. As the concerns of routing and state were handled in ReactJS, in the same way Vue handles it by associate libraries.
Difference between Node.js and Vue.js:
if(gfg) {
console.log("Geeks for Geeks"); }

<h1 v-if="gfg">Geeks for Geeks</h1>

bunnyram19
Node.js-Misc
Vue.JS
Difference Between
JavaScript
Node.js
Web Technologies
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
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Difference between Process and Thread
Difference between Clustered and Non-clustered index
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
What is buffer in Node.js ?

16 Aug, 2021
Pure JavaScript is great with Unicode encoded strings, but it does not handle binary data very well. It is not problematic when we perform an operation on data at browser level but at the time of dealing with TCP stream and performing a read-write operation on the file system is required to deal with pure binary data. To satisfy this need Node.js use Buffer, So in this article, we are going to know about buffer in Node.js.
Buffers in Node.js: The Buffer class in Node.js is used to perform operations on raw binary data. Generally, Buffer refers to the particular memory location in memory. Buffer and array have some similarities, but the difference is array can be any type, and it can be resizable. Buffers only deal with binary data, and it can not be resizable. Each integer in a buffer represents a byte. console.log() function is used to print the Buffer instance.
Methods to perform the operations on Buffer:
Filename: index.js
Javascript
// Different Method to create Buffervar buffer1 = Buffer.alloc(100);var buffer2 = new Buffer('GFG');var buffer3 = Buffer.from([1, 2, 3, 4]); // Writing data to Bufferbuffer1.write("Happy Learning"); // Reading data from Buffervar a = buffer1.toString('utf-8');console.log(a); // Check object is buffer or notconsole.log(Buffer.isBuffer(buffer1)); // Check length of Bufferconsole.log(buffer1.length); // Copy buffervar bufferSrc = new Buffer('ABC');var bufferDest = Buffer.alloc(3);bufferSrc.copy(bufferDest); var Data = bufferDest.toString('utf-8');console.log(Data); // Slicing datavar bufferOld = new Buffer('GeeksForGeeks');var bufferNew = bufferOld.slice(0, 4);console.log(bufferNew.toString()); // concatenate two buffervar bufferOne = new Buffer('Happy Learning ');var bufferTwo = new Buffer('With GFG');var bufferThree = Buffer.concat([bufferOne, bufferTwo]);console.log(bufferThree.toString());
Run the index.js file using the following command:
node index.js
Output:
Happy Learning
true
100
ABC
Geek
Happy Learning With GFG
Reference: https://nodejs.org/api/buffer.html
simmytarika5
akshaysingh98088
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Matplotlib.axes.Axes.twinx() in Python

21 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.twinx() function in axes module of matplotlib library is used to create a twin Axes sharing the xaxis.
Syntax: Axes.twinx(self)
Parameters: This method does not accepts any parameters.
Return value: This method is used to returns the following.
ax_twin : This returns the newly created Axes instance.
Below examples illustrate the matplotlib.axes.Axes.twinx() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np    def GFG1(temp):    return (5. / 9.) * (temp - 32)  def GFG2(ax1):    y1, y2 = ax1.get_ylim()    ax_twin .set_ylim(GFG1(y1), GFG1(y2))    ax_twin .figure.canvas.draw()  fig, ax1 = plt.subplots()ax_twin = ax1.twinx()  ax1.callbacks.connect("ylim_changed", GFG2)ax1.plot(np.linspace(-40, 120, 100))ax1.set_xlim(0, 100)  ax1.set_ylabel('Fahrenheit')ax_twin .set_ylabel('Celsius')  fig.suptitle('matplotlib.axes.Axes.twinx()\ function Example\n\n', fontweight ="bold")  plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt  # Create some mock datat = np.arange(0.01, 10.0, 0.001)data1 = np.exp(t)data2 = np.sin(0.4 * np.pi * t)  fig, ax1 = plt.subplots()  color = 'tab:blue'ax1.set_xlabel('time (s)')ax1.set_ylabel('exp', color = color)ax1.plot(t, data1, color = color)ax1.tick_params(axis ='y', labelcolor = color)  ax2 = ax1.twinx()  color = 'tab:green'ax2.set_ylabel('sin', color = color)ax2.plot(t, data2, color = color)ax2.tick_params(axis ='y', labelcolor = color)  fig.suptitle('matplotlib.axes.Axes.twinx() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to add leading zeros to a number

To add leading zeros to a number, you need to format the output. Let’s say we need to add 4 leading zeros to the following number with 3 digits.
int val = 290;
For adding 4 leading zeros above, we will use %07d i.e. 4+3 = 7. Here, 3, as shown above, is the number with 3 digits.
String.format("%07d", val);
The following is the final example.
 Live Demo
import java.util.Formatter;
public class Demo {
    public static void main(String args[]) {
       int val = 290;
       System.out.println("Integer: "+val);
       String formattedStr = String.format("%07d", val);
       System.out.println("With leading zeros = " + formattedStr);
    }
}
Integer: 290
With leading zeros = 0000290
Python | shutil.copyfileobj() method

12 Oct, 2021
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of chowning and removal of files and directories.shutil.copyfileobj() method in Python is used to copy the contents of a file-like object to another file-like object. By default this method copy data in chunks and if want we can also specify the buffer size through length parameter. This method copies the content of the file from the current file position to the end of the file. 
Syntax: shutil.copyfileobj(fsrc, fdst[, length])Parameters: fsrc: A file-like object representing the source file to be copied fdst: A file-like object representing the destination file, where fsrc will be copied. length (optional): An integer value denoting buffer size. File-like object are mainly StringIO objects, connected sockets and actual file objects. Return Type: This method does not return any value.  
Code: Use of shutil.copyfileobj() method to copy the contents of source file-like object to destination file-like object  
Python3
# Python program to explain shutil.copyfileobj() method   # importing shutil moduleimport shutil # Source filesource = 'file.txt' # Open the source file# in read mode and# get the file objectfsrc = open(source, 'r')  # destination filedest = 'file_copy.txt' # Open the destination file# in write mode and# get the file objectfdst = open(dest, 'w')  # Now, copy the contents of# file object f1 to f2# using shutil.copyfileobj() methodshutil.copyfileobj(fsrc, fdst) # We can also specify# the buffer size by passing# optional length parameter# like shutil.copyfileobj(fsrc, fdst, 1024)   print("Contents of file object copied successfully") # Close file objectsf1.close()f2.close()
Contents of file object copied successfully
 
Reference: https://docs.python.org/3/library/shutil.html 
gabaa406
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
MONTH() function in MySQL

02 Dec, 2020
MONTH() function in MySQL is used to find a month from the given date. It returns 0 when the month part for the date is 0 otherwise it returns month value between 1 and 12.
Syntax :
MONTH(date)
Parameter : 
This function accepts one parameter 
date : The date or DateTime from which we want to extract the month.
Returns : It returns the value range from 1 to 12.
Example-1 : 
Finding the Current Month Using MONTH() Function.
SELECT MONTH(NOW()) AS Current_Month;
Output :
Example-2 : 
Finding the Month from given DateTime Using Month() Function.
SELECT MONTH('2015-09-26 08:09:22') AS MONTH;
Output :
Example-3 : 
Finding the Month from given DateTime Using Month () Function when the date is NULL.
SELECT MONTH(NULL) AS Month ;
Output :
Example-4 : 
The MONTH function can also be used to find the total product sold for every month. To demonstrate create a table named.
Product :
CREATE TABLE Product(
   Product_id INT AUTO_INCREMENT,  
   Product_name VARCHAR(100) NOT NULL,
   Buying_price DECIMAL(13, 2) NOT NULL,
   Selling_price DECIMAL(13, 2) NOT NULL,
   Selling_Date Date NOT NULL,
   PRIMARY KEY(Product_id)
);
Now insert some data to the Product table :
INSERT INTO  
   Product(Product_name, Buying_price, Selling_price, Selling_Date)
VALUES
   ('Audi Q8', 10000000.00, 15000000.00, '2018-01-26' ),
   ('Volvo XC40', 2000000.00, 3000000.00, '2018-04-20' ),
   ('Audi A6', 4000000.00, 5000000.00, '2018-07-25' ),
   ('BMW X5', 5000500.00, 7006500.00, '2018-10-18'  ),
   ('Jaguar XF', 5000000, 7507000.00, '2019-01-27'  ),
   ('Mercedes-Benz C-Class', 4000000.00, 6000000.00, '2019-04-01'  ),
   ('Jaguar F-PACE', 5000000.00, 7000000.00, '2019-12-26'  ),
   ('Porsche Macan', 6500000.00, 8000000.00, '2020-04-16' ) ;
So, Our table looks like :
Now, we are going to find the number of products sold per month by using the MONTH () function.
SELECT  
   MONTH (Selling_Date) month,  
   COUNT(Product_id) Product_Sold
FROM Product
GROUP BY MONTH (Selling_Date)
ORDER BY MONTH (Selling_Date);
Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Sub queries in From Clause
Window functions in SQL
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
What is Temporary Table in SQL?
SQL using Python
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Convert Rows to Columns in SQL Server
SQL Query to Compare Two Dates
Tryit Editor v3.7

Tryit: HTML image - full URL
Playit

div#myBox {  position:absolute;  background-color:red;  z-index:auto;}
PHP $argv

When a PHP script is run from command line, $argv superglobal array contains arguments passed to it. First element in array $argv[0] is always the name of script. This variable is not available if register_argc_argv directive in php.ini is disabled.
Following script is executed from command line.
 Live Demo
<?php
var_dump($argv);
?>
array(1) {
   [0]=>
   string(8) "main.php"
}
In another example as follows, addition of command line arguments is performed
<?php
$add=$argv[1]+$argv[2];
echo "addition = " . $add;
?>
Output
C:\xampp\php>php test1.php 10 20
addition = 30
Copy all elements of ArrayList to an Object Array in Java

All the elements of an ArrayList can be copied into an Object Array using the method java.util.ArrayList.toArray(). This method does not have any parameters and it returns an Object Array that contains all the elements of the ArrayList copied in the correct order.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List<String> aList = new ArrayList<String>();
      aList.add("Nathan");
      aList.add("John");
      aList.add("Susan");
      aList.add("Betty");
      aList.add("Peter");
      Object[] objArr = aList.toArray();
      System.out.println("The array elements are: ");
      for (Object i : objArr) {
         System.out.println(i);
      }
   }
}
The array elements are:
Nathan
John
Susan
Betty
Peter
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to this ArrayList. A code snippet which demonstrates this is as follows −
List<String> aList = new ArrayList<String>();
aList.add("Nathan");
aList.add("John");
aList.add("Susan");
aList.add("Betty");
aList.add("Peter");
The method ArrayList.toArray() is used to copy all the elements of the ArrayList into an Object Array. Then the Object Array elements are displayed using a for loop. A code snippet which demonstrates this is as follows −
Object[] objArr = aList.toArray();
System.out.println("The array elements are: ");
for (Object i : objArr) {
   System.out.println(i);
}
How to remove Y-axis labels in R?

When we create a plot in R, the Y-axis labels are automatically generated and if we want to remove those labels, the plot function can help us. For this purpose, we need to set ylab argument of plot function to blank as ylab="" and yaxt="n" to remove the axis title. This is a method of base R only, not with ggplot2 package.
x<-rnorm(10)
y<-rnorm(10)
plot(x,y)
plot(x,y,ylab="",yaxt="n")
Error connecting SAP while sapjco3.jar file is in my library path

You need to copy sapjco3.dll in a folder in your Java library path as he t library is not sapjco3.jar and it is a sapjco3.dll file.
You can call in your application usingfollowing:
System.getProperty("java.library.path")
Following approaches can be used:
First is by copying sapjco3.dll into one of the folder which are already in your library path like: C:\WINNT\system32
Second would be to use the same path in Java library path using any of the following options:
By accessing System.setProperty ("java.library.path","C:\path\to\folder\with\dll\") before accessing the SAPJCo
By accessing System.setProperty ("java.library.path","C:\path\to\folder\with\dll\") before accessing the SAPJCo
You can set Java command line like this -Djava.library.path=C:\path\to\folder\with\dll\
You can set Java command line like this -Djava.library.path=C:\path\to\folder\with\dll\
Java Program to generate random number with restrictions

To generate random number with resctrictions, here we are taking an example of a phone number from
India with the country code 91.
First, we have set the first 2 numbers i.e. the country code. The variables are declared for each digit. We have also fixed the first digit of the number as 9 after country code 91:
Random num = new Random();
int num0, num1, num2, num3, num4, num5, num6, num7, num8, num9, num10, num11;
num0 = 9;
num1 = 1;
num2 = 9;
Now, for rest of the numbers, use the nextInt() of the Random. The parameter consists of the bound set
for random numbers:
num3 = num.nextInt(9) + 10;
num4 = num.nextInt(10);
num5 = num.nextInt(5) + 11;
num6 = num.nextInt(10);
num7 = num.nextInt(3);
num8 = num.nextInt(5);
num9 = num.nextInt(10);
import java.util.Random;
public class Main {
   public static void main(String[] args) {
      Random num = new Random();
      int num0, num1, num2, num3, num4, num5, num6, num7, num8, num9, num10, num11;
      num0 = 9;
      num1 = 1;
      num2 = 9;
      num3 = num.nextInt(9) + 10;
      num4 = num.nextInt(10);
      num5 = num.nextInt(5) + 11;
      num6 = num.nextInt(10);
      num7 = num.nextInt(3);
      num8 = num.nextInt(5);
      num9 = num.nextInt(10);
      System.out.print("Random (Country code 91 for India) = ");
      System.out.print(num0);
      System.out.print(num1);
      System.out.print("-" + num2);
      System.out.print(num3);
      System.out.print(num4);
      System.out.print(num5);
      System.out.print(num6);
      System.out.print(num7);
      System.out.print(num8);
      System.out.print(num9);
   }
}
Random (Country code 91 for India) = 91-9114158010
Longest Harmonious Subsequence in C++

Suppose we have an integer array; we have to find the length of its longest harmonious subsequence among all its possible subsequences. As we know a harmonious sequence array is an array where the difference between its maximum value and its minimum value is exactly 1.
So, if the input is like [1,3,2,2,5,2,3,7], then the output will be 5, as the longest harmonious subsequence is [4,3,3,3,4].
To solve this, we will follow these steps −
Define one map m
Define one map m
for n in nums −(increase m[n] by 1)
for n in nums −
(increase m[n] by 1)
(increase m[n] by 1)
for key-value pair (k,v) in m −it := position of (k+1) in mif 'it' is in m, then −max_:= maximum of max_ and value of it
for key-value pair (k,v) in m −
it := position of (k+1) in m
it := position of (k+1) in m
if 'it' is in m, then −max_:= maximum of max_ and value of it
if 'it' is in m, then −
max_:= maximum of max_ and value of it
max_:= maximum of max_ and value of it
return max_
return max_
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int findLHS(vector<int>& nums) {
      unordered_map<int, int> m;
      for (const int n : nums)
         ++m[n];
      int max_{ 0 };
      for (const auto & [ k, v ] : m) {
         auto it = m.find(k + 1);
         if (it != m.end())
            max_ = max(max_, v + it->second);
      }
      return max_;
   }
};
main(){
   Solution ob;
   vector<int> v = {2,4,3,3,6,3,4,8};
   cout << (ob.findLHS(v));
}
{2,4,3,3,6,3,4,8}
5
How do we check if a String contains a substring (ignoring case) in Java?

The contains() method of the String class accepts Sting value as a parameter, verifies whether the current String object contains the specified String and returns true if it does (else false).
The toLoweCase() method of the String class converts all the characters in the current String into lower case and returns.
To find whether a String contains a particular sub string irrespective of case −
Get the String.
Get the String.
Get the Sub String.
Get the Sub String.
Convert the string value into lower case letters using the toLowerCase() method, store it as fileContents.
Convert the string value into lower case letters using the toLowerCase() method, store it as fileContents.
Convert the string value into lower case letters using the toLowerCase() method, store it as subString.
Convert the string value into lower case letters using the toLowerCase() method, store it as subString.
Invoke the contains() method on the fileContents by passing subString as a parameter to it.
Invoke the contains() method on the fileContents by passing subString as a parameter to it.
Assume we have a file named sample.txt in the D directory with the following content −
Tutorials point originated from the idea that there exists a class of readers who respond better to on-line content
and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
At Tutorials point we provide high quality learning-aids for free of cost.
Following Java example reads a sub string from the user an verifies whether the file contains the given sub string irrespective of case.
 Live Demo
import java.io.File;
import java.util.Scanner;
public class SubStringExample {
   public static String fileToString(String filePath) throws Exception{
      String input = null;
      Scanner sc = new Scanner(new File(filePath));
      StringBuffer sb = new StringBuffer();
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(input);
      }
      return sb.toString();
   }
   public static void main(String args[]) throws Exception {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the sub string to be verified: ");
      String subString = sc.next();
      String fileContents = fileToString("D:\\sample.txt");
      //Converting the contents of the file to lower case
      fileContents = fileContents.toLowerCase();
      //Converting the sub string to lower case
      subString = subString.toLowerCase();
      //Verify whether the file contains the given sub String
      boolean result = fileContents.contains(subString);
      if(result) {
         System.out.println("File contains the given sub string.");
      } else {
         System.out.println("File doesnot contain the given sub string.");
      }
   }
}
Enter the sub string to be verified:
comforts of their drawing rooms.
File contains the given sub string.
Python program to find the most occurring character and its count

In this article, we will learn about the solution and approach to solve the given problem statement.
Given an input string we need to find the most occurring character and its count.
Create a dictionary using Counter method having strings as keys and their frequencies as values.
Create a dictionary using Counter method having strings as keys and their frequencies as values.
Find the maximum occurrence of a character i.e. value and get the index of it.
Find the maximum occurrence of a character i.e. value and get the index of it.
Now let’s see the implementation below −
from collections import Counter
   def find(input_):
   # dictionary
   wc = Counter(input_)
   # Finding maximum occurrence
   s = max(wc.values())
   i = wc.values().index(s)
   print (wc.items()[i])
# Driver program
if __name__ == "__main__":
   input_ = 'Tutorialspoint'
   find(input_)
(‘t’,3)
All the variables and functions are declared in the global scope as shown below −
In this article, we learnt about the approach to find the most occurring character and its count.
C# | Copy() Method - GeeksforGeeks

21 Jun, 2019
In C#, Copy() is a string method. It is used to create a new instance of String with the same value for a specified String. The Copy() method returns a String object, which is the same as the original string but represents a different object reference. To check its reference, use assignment operation, which assigns an existing string reference to an additional object variable.
Syntax:
public static string Copy(string str)

Explanation : This method accepts single parameter str which is the original string to be copied. And it returns the string value, which is the new string with the same value as str. The type of Copy() method is System.String.
Example Program to illustrate the Copy() Method
// C# program to demonstrate the // use of Copy() methodusing System;class Program {          static void cpymethod()    {        string str1 = "GeeksforGeeks";        string str2 = "GFG";        Console.WriteLine("Original Strings are str1 = "            + "'{0}' and str2='{1}'", str1, str2);                          Console.WriteLine("");          Console.WriteLine("After Copy method");        Console.WriteLine("");          // using the Copy method        // to copy the value of str1         // into str2        str2 = String.Copy(str1);          Console.WriteLine("Strings are str1 = "        +"'{0}' and str2='{1}'", str1, str2);          // check the objects reference equal or not        Console.WriteLine("ReferenceEquals: {0}",            Object.ReferenceEquals(str1, str2));          // check the objects are equal or not        Console.WriteLine("Equals: {0}", Object.Equals(str1, str2));        Console.WriteLine("");          Console.WriteLine("After Assignment");        Console.WriteLine("");          // to str1 object reference assign to str2        str2 = str1;          Console.WriteLine("Strings are str1 = '{0}' "                    +"and str2 = '{1}'", str1, str2);          // check the objects reference equal or not        Console.WriteLine("ReferenceEquals: {0}",             Object.ReferenceEquals(str1, str2));          // check the objects are equal or not        Console.WriteLine("Equals: {0}", Object.Equals(str1, str2));      }          // Main Method    public static void Main()    {                  // calling method        cpymethod();    }}
Original Strings are str1 = 'GeeksforGeeks' and str2='GFG'

After Copy method

Strings are str1 = 'GeeksforGeeks' and str2='GeeksforGeeks'
ReferenceEquals: False
Equals: True

After Assignment

Strings are str1 = 'GeeksforGeeks' and str2 = 'GeeksforGeeks'
ReferenceEquals: True
Equals: True

Reference : https://msdn.microsoft.com/en-us/library/system.string.copy
nidhi_biet
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
Destructors in C#
C# | Delegates
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
Introduction to .NET Framework
C# | Abstract Classes
C# | Data Types
HashSet in C# with Examples
Different ways to sort an array in descending order in C#
How to plot a high resolution graph in Matplotlib?

We can use the resolution value, i.e., dots per inch, and the image format to plot a high-resolution graph in Matplotlib.
Create a dictionary with Column 1 and Column 2 as the keys and Values are like i and i*i, where i is from 0 to 10, respectively.
Create a dictionary with Column 1 and Column 2 as the keys and Values are like i and i*i, where i is from 0 to 10, respectively.
Create a data frame using pd.DataFrame(d); d created in step 1.
Create a data frame using pd.DataFrame(d); d created in step 1.
Plot the data frame with ‘o’ and ‘rx’ style.
Plot the data frame with ‘o’ and ‘rx’ style.
To save the file in pdf format, use savefig() method where the image name is myImagePDF.pdf, format="pdf".
To save the file in pdf format, use savefig() method where the image name is myImagePDF.pdf, format="pdf".
We can set the dpi value to get a high-quality image.
We can set the dpi value to get a high-quality image.
Using the saving() method, we can save the image with format=”png” and dpi=1200.
Using the saving() method, we can save the image with format=”png” and dpi=1200.
To show the image, use the plt.show() method.
To show the image, use the plt.show() method.
import pandas as pd
from matplotlib import pyplot as plt

d = {'Column 1': [i for i in range(10)], 'Column 2': [i * i for i in range(10)]}

df = pd.DataFrame(d)

df.plot(style=['o', 'rx'])
resolution_value = 1200
plt.savefig("myImage.png", format="png", dpi=resolution_value)
plt.show()
C++ Program to Implement Disjoint Set Data Structure

Disjoint set is basically as group of sets where no item can be in more than one set. It supports union and find operation on subsets.
Find(): It is used to find in which subset a particular element is in and returns the representative of that particular set.
Union(): It merges two different subsets into a single subset and representative of one set becomes representative of other.
Begin
   Assume k is the element
   makeset(k):
      k.parent = k.
   Find(x):
   If k.parent == k
      return k.
   else
   return Find(k.parent)
   Union (a,b):
      Take two set a and b as input.
      aroot = Find(a)
      broot = Find(b)
      aroot.parent = broot
End
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class DisjointSet { //to represent disjoint set
   unordered_map<int, int> parent;
   public:
   void makeSet(vector<int> const &wholeset){
   //perform makeset operation
      for (int i : wholeset) // create n disjoint sets
      (one for each item)
      parent[i] = i;
   }
   int Find(int l) { // Find the root of the set in which element l belongs
      if (parent[l] == l) // if l is root
         return l;
      return Find(parent[l]); // recurs for parent till we find root
   }
   void Union(int m, int n) { // perform Union of two subsets m and n  
      int x = Find(m);
      int y = Find(n);
      parent[x] = y;
   }
};
void print(vector<int> const &universe, DisjointSet &dis) {
   for (int i : universe)
   cout << dis.Find(i) << " ";
   cout << '\n';
}
int main() {
   vector<int> wholeset = { 6,7,1,2,3 }; // items of whole set
   DisjointSet dis; //initialize DisjointSet class
   dis.makeSet(wholeset); // create individual set of the items of wholeset
   dis.Union(7, 6); // 7,6 are in same set
   print(wholeset, dis);
   if (dis.Find(7) == dis.Find(6)) // if they are belong to same set or not.
      cout<<"Yes"<<endl;
   else
      cout<<"No";
   if (dis.Find(3) == dis.Find(4))
      cout<<"Yes"<<endl;
   else
      cout<<"No";
   return 0;
}
6 6 1 2 3
Yes
No
Mahotas - RGB to LAB Conversion - GeeksforGeeks

08 Jul, 2021
In this article we will see how we can covert rgb image to CIE L*a*b* in mahotas. An RGB image, sometimes referred to as a truecolor image, is stored in MATLAB as an m-by-n-by-3 data array that defines red, green, and blue color components for each individual pixel. The CIELAB color space (also known as CIE L*a*b* or sometimes abbreviated as simply “Lab” color space) is a color space defined by the International Commission on Illumination (CIE) in 1976.
In this tutorial we will use “lena” image, below is the command to load it.
mahotas.demos.load('lena')
Below is the lena image 
In order to do this we will use mahotas.colors.rgb2sepiamethod  
Syntax : mahotas.colors.rgb2lab(img)Argument :It takes image object as argumentReturn : It returns image object  
Below is the implementation  
Python3
# importing required librariesimport mahotasimport mahotas.demosfrom pylab import gray, imshow, showimport numpy as np  # loading imageimg = mahotas.demos.load('lena')   # showing imageprint("Image")imshow(img)show() # rgb to labnew_img = mahotas.colors.rgb2lab(img) # showing new imageprint("New Image")imshow(new_img)show()
Strong : 
Image
New Image
Another example  
Python3
# importing required librariesimport mahotasimport numpy as npimport matplotlib.pyplot as pltimport os  # loading imageimg = mahotas.imread('dog_image.png')       # filtering imageimg = img[:, :, :3] # showing imageprint("Image")imshow(img)show() # rgb to labnew_img = mahotas.colors.rgb2lab(img) # showing new imageprint("New Image")imshow(new_img)show()
Strong : 
Image
 
New Image
 
simranarora5sos
sagartomar9927
Python-Mahotas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Python OOPs Concepts
Read a file line by line in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Stack in Python
Reading and Writing to text files in Python
Python Classes and Objects
Chaining comparison operators in Python

Sometimes we need to use more than one condition checking in a single statement. There are some basic syntax for these kind of checking is x < y < z, or if x < y and x < z etc.
Like other languages, there are some basic comparison operators in Python. These comparison operators are <, <=, >, >=, ==, !=, is, is not, in, not in.
The precedence of these operators are same, and the precedence is lesser than arithmetic, bitwise and shifting operators.
These operators can be arranged arbitrarily. They will be used as a chain. So for an example, if the expression is x < y < z, then it is similar to the x < y and y < z. So from this example, we can see if the operands are p1, p2,..., pn, and the operators are OP1, OP2,..., OPn-1, then it will be same as p1 OP1 p2 and p2 OP2 p3, , pn-1 OPn-1pn
So there are some examples on the chaining features of comparison operators.
 Live Demo
a = 10
b = 20
c = 5
# c < a < b is same as c <a and a < b
print(c < a)
print(a < b)
print(c < a < b)
# b is not in between 40 and 60
print(40 <= b <= 60)
# a is 10, which is greater than c
print(a == 10 > c)
True
True
True
False
True

 Live Demo
u = 5
v = 10
w = 15
x = 0
y = 7
z = 15
# The w is same as z but not same as v, v is greater than x, which is less than y
print(z is w is not v > x < y)
# Check whether w and z are same and x < z > y or not
print(x < w == z > y)
True
True
sum() function in Python

18 May, 2022
Sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list.
Syntax:
sum(iterable, start)  
iterable : iterable can be anything list , tuples or dictionaries ,
 but most importantly it should be numbers.
start : this start is added to the sum of 
numbers in the iterable. 
If start is not given in the syntax , it is assumed to be 0.
Possible two syntaxes:
sum(a)
a is the list , it adds up all the numbers in the 
list a and takes start to be 0, so returning 
only the sum of the numbers in the list.
sum(a, start)
this returns the sum of the list + start 

Below is the Python implementation of the sum()
# Python code to demonstrate the working of # sum()   numbers = [1,2,3,4,5,1,4,5]  # start parameter is not providedSum = sum(numbers)print(Sum)  # start = 10Sum = sum(numbers, 10)print(Sum)
Output:
25
35

Error and Exceptions
TypeError : This error is raised in the case when there is anything other then numbers in the list.
# Python code to demonstrate the exception of # sum()arr = ["a"]  # start parameter is not providedSum = sum(arr)print(Sum)  # start = 10Sum = sum(arr, 10)print(Sum)
Runtime Error :
Traceback (most recent call last):
  File "/home/23f0f6c9e022aa96d6c560a7eb4cf387.py", line 6, in 
    Sum = sum(arr)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

So the list should contain numbers
Practical Application: Problems where we require sum to be calculated to do further operations such as finding out the average of numbers.
# Python code to demonstrate the practical application# of sum()  numbers = [1,2,3,4,5,1,4,5]  # start = 10Sum = sum(numbers)average= Sum/len(numbers) print (average)
Output:
3

Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Python OOPs Concepts
Introduction To PYTHON
unordered_map end( ) function in C++ STL

19 Sep, 2018
The unordered_map::end() is a built-in function in C++ STL which returns an iterator pointing to the position past the last element in the container in the unordered_map container. In an unordered_map object, there is no guarantee that which specific element is considered its first element. But all the elements in the container are covered since the range goes from its begin to its end until invalidated.
Syntax:
iterator unordered_map_name.end(n)
Parameters : This function accepts one parameter n which is an optional parameter that specifies the bucket number. If it is set, the iterator retrieves points to the past-the-end element of a bucket, otherwise, it points to the past-the-end element of the container.
Return value: The function returns an iterator to the element past the end of the container.
Below programs illustrates the above-mentioned function:
Program 1:
// CPP program to demonstrate the// unordered_map::end() function// returning all the elements of the multimap#include <iostream>#include <string>#include <unordered_map>using namespace std;  int main(){    unordered_map<string, int> marks;      // Declaring the elements of the multimap    marks = { { "Rohit", 64 }, { "Aman", 37 }, { "Ayush", 96 } };      // Printing all the elements of the multimap    cout << "marks bucket contains : " << endl;    for (int i = 0; i < marks.bucket_count(); ++i) {          cout << "bucket #" << i << " contains:";          for (auto iter = marks.begin(i); iter != marks.end(i); ++iter) {            cout << "(" << iter->first << ", " << iter->second << "), ";        }          cout << endl;    }    return 0;}
marks bucket contains : 
bucket #0 contains:
bucket #1 contains:
bucket #2 contains:
bucket #3 contains:(Aman, 37), (Rohit, 64), 
bucket #4 contains:(Ayush, 96),

Program 2:
// CPP program to demonstrate the// unordered_map::end() function// returning the elements along// with their bucket number#include <iostream>#include <string>#include <unordered_map>  using namespace std;  int main(){    unordered_map<string, int> marks;      // Declaring the elements of the multimap    marks = { { "Rohit", 64 }, { "Aman", 37 }, { "Ayush", 96 } };      // Printing all the elements of the multimap    for (auto iter = marks.begin(); iter != marks.end(); ++iter) {          cout << "Marks of " << iter->first << " is "             << iter->second << " and his bucket number is "             << marks.bucket(iter->first) << endl;    }      return 0;}
Marks of Ayush is 96 and his bucket number is 4
Marks of Aman is 37 and his bucket number is 3
Marks of Rohit is 64 and his bucket number is 3

CPP-Functions
cpp-unordered_map
cpp-unordered_map-functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Inheritance in C++
vector erase() and clear() in C++
Substring in C++
The C++ Standard Template Library (STL)
C++ Classes and Objects
Object Oriented Programming in C++
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
2D Vector In C++ With User Defined Size
Python | N largest values in dictionary

26 Aug, 2019
Many times while working with Python dictionary, we can have a particular problem to find the N maxima of values in numerous keys. This problem is quite common while working with web development domain. Let’s discuss several ways in which this task can be performed.
Method #1 : itemgetter() + items() + sorted()
The combination of above method is used to perform this particular task. In this, we just reverse sort the dictionary values expressed using itemgetter() and accessed using items().
# Python3 code to demonstrate working of# N largest values in dictionary# Using sorted() + itemgetter() + items()from operator import itemgetter  # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 4, 'best' : 6, 'for' : 7, 'geeks' : 3 }  # Initialize N N = 3  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # N largest values in dictionary# Using sorted() + itemgetter() + items()res = dict(sorted(test_dict.items(), key = itemgetter(1), reverse = True)[:N])  # printing resultprint("The top N value pairs are  " + str(res))
The original dictionary is : {'best': 6, 'gfg': 1, 'geeks': 3, 'for': 7, 'is': 4}
The top N value pairs are  {'for': 7, 'is': 4, 'best': 6}

 
Method #2 : Using nlargest()This task can be performed using the nlargest function. This is inbuilt function in heapq library which internally performs this task and can be used to do it externally. Has the drawback of printing just keys not values.
# Python3 code to demonstrate working of# N largest values in dictionary# Using nlargestfrom heapq import nlargest  # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 4, 'best' : 6, 'for' : 7, 'geeks' : 3 }  # Initialize N N = 3  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # N largest values in dictionary# Using nlargestres = nlargest(N, test_dict, key = test_dict.get)  # printing resultprint("The top N value pairs are  " + str(res))
The original dictionary is : {'gfg': 1, 'best': 6, 'geeks': 3, 'for': 7, 'is': 4}
The top N value pairs are  ['for', 'best', 'is']

Python dictionary-programs
Python
Python Programs
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()
Python program to convert a list to string
Defaultdict in Python
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Java program to calculate mode in Java

In statistics math, a mode is a value that occurs the highest numbers of time. For Example, assume a set of values 3, 5, 2, 7, 3. The mode of this value set is 3 as it appears more than any other number.
1.Take an integer set A of n values.
2.Count the occurrence of each integer value in A.
3.Display the value with the highest occurrence.
Live Demo
public class Mode {
   static int mode(int a[],int n) {
      int maxValue = 0, maxCount = 0, i, j;

      for (i = 0; i < n; ++i) {
         int count = 0;
         for (j = 0; j < n; ++j) {
            if (a[j] == a[i])
            ++count;
         }

         if (count > maxCount) {
            maxCount = count;
            maxValue = a[i];
         }
      }
      return maxValue;
   }
   public static void main(String args[]){
      int n = 5;
      int a[] = {0,6,7,2,7};
      System.out.println("Mode ::"+mode(a,n));
   }
}
Mode ::7