code-rag-bench/online-tutorials huggingface dataset:
React.js Render Props - GeeksforGeeks

16 Mar, 2021
The Render Props is a  technique in ReactJS for sharing code between React components using a prop whose value is a function. Child component takes render props as a function and calls it instead of implementing its own render logic. In brief, we pass a function from the parent component to the child component as a render props, and the child component calls that function instead of implementing its own logic.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'  class App extends React.Component {  render() {    return (      <div>        <h1>Render Props Example</h1>        <SampleRenderProps />      </div>    )  }}  // Child component getting render propsclass RenderPropsComponent extends React.Component {  render() {    return (      <div>        <h2>I am Child Component</h2>        {this.props.render()}      </div>    )  }}  // Parent component sending render props to the childclass SampleRenderProps extends React.Component {  render() {    return (      <RenderPropsComponent        // Passing render props to the child component        render={() => {          return (            <div>              <h3>                I am coming from render props               </h3>            </div>          )        }}      />    )  }}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Picked
ReactJS-Basics
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
JavaScript Date parse() Method - GeeksforGeeks

22 Nov, 2021
Below is the example of Date parse() method.  
Example:  
javascript
<script>    // Taking a date string as input.    var date = "February 18, 2018 12:30 PM";          // Calling parse function on input date string.    var msec = Date.parse(date);    document.write(msec);</script>                   
Output:  
1518937200000
The date.parse() method is used to know the exact number of milliseconds that have passed since midnight, January 1, 1970, till the date we provide.Syntax:  
Date.parse(datestring);
Parameters: This method accept a single parameter as mentioned above and described below:  
datestring: This parameter holds the date as a string.
Return Values: It returns an integer value representing the number of a millisecond between midnight January 1, 1970, and the date provided. If by any means, the machine can’t recognize the string or the input string is invalid, it will return “NaN” instead of an integer.More codes for the above method are as follows: Program 1: If the input string of date is not correct, it return NaN i.e, not a number.  
javascript
<script>     // Taking wrong date string as input.    var date = "February 48, 2018 12:30 PM";         // calling parse function.    var msec = Date.parse(date);    document.write(msec);     </script>                   
Output:  
NaN
Program 2: If the input string of date is not correct, it return NaN i.e, not a number.  
javascript
<script>     // Taking wrong date string as input.    var date = "June 22, 2012";         // Calling parse function.    var msec = Date.parse(date);    document.write(msec);     </script>                   
Output:  
1340303400000
Note: Once we get the millisecond count between two dates, we can easily find the number of hours, days, months, years, etc by simple maths calculation.Supported Browsers: The browsers supported by JavaScript Date parse() method are listed below:  
Google Chrome 1 and above
Internet Explorer 3  and above
Mozilla Firefox 1 and above
Opera 3 and above
Safari 1 and above
 
kalrap615
ysachin2314
javascript-date
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
C# | How to get the Standard Input Stream through Console - GeeksforGeeks

28 Jan, 2019
Given a normal console, the task is to get the Standard Input Stream through this Console in C#.
Approach: This can be done using the In property in the Console class of the System package in C#.
Program: Getting the Standard Input Stream
// C# program to illustrate the// Console.In Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {          // Get the Standard Input Stream        Console.WriteLine("Standard Input Stream: {0}",                                          Console.In);    } }}
Output:
Note: The TextReader represents a reader that can read a sequential series of characters.
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Arrays
CSS | margin-inline Property - GeeksforGeeks

19 Feb, 2021
The margin-inline property is used to define the logical inline start and end margin of an element. This property helps to place margin depending on the element’s writing mode, directionality, and text orientation.Syntax:  
margin-inline: length | auto | initial | inherit | unset;
Property values:  
length: It sets a fixed value defined in px, cm, pt. Negative values are also allowed. 0px is the default value.
auto: It is used when it is desired that the browser determines the width of the left margin.
initial: It is used to set the value of the margin-left property to its default value.
inherit: It is used when it is desired that the element inherit the margin-left property of its parent as its own.
unset: It is used unset the default margin-block.
Below examples illustrate the margin-inline property in CSS:Example 1:  
html
<!DOCTYPE html><html> <head>    <title>CSS | margin-inline Property</title>    <style>        h1 {            color: green;        }                 div {            background-color: yellow;            width: 110px;            height: 110px;        }        .geek {            background-color: purple;            writing-mode: vertical-rl;            margin-inline: 25px 10px;        }    </style></head> <body>    <center>        <h1>Geeksforgeeks</h1>        <b>CSS | margin-inline Property</b>        <br><br>        <div>            <b class="geek">Cascading Stylesheet</b>        </div>     </center></body> </html>                   
Output:  
Example 2:  
html
<!DOCTYPE html><html> <head>    <title>CSS | margin-inline Property</title>    <style>        h1 {            color: green;        }                 div {            background-color: yellow;            width: 110px;            height: 110px;        }        .geek {            background-color: purple;            writing-mode: vertical-rl;            margin-inline: auto;        }    </style></head> <body>    <center>        <h1>Geeksforgeeks</h1>        <b>CSS | margin-inline Property</b>         <br><br>        <div>            <b class="geek">Cascading Stylesheet</b>        </div>    </center></body> </html>                           
Output:  
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/margin-inline Supported Browsers: The browser supported by margin-inline property are listed below:  
Internet Explorer
Mozilla Firefox
 
arorakashish0911
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
get_log driver method - Selenium Python - GeeksforGeeks

03 Dec, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. 
This article revolves around get_log driver method in Selenium. get_log method is used to get the log for a given log type.
Syntax – 
driver.get_log(log_type)
Example – Now one can use get_log method as a driver method as below – 
driver.get("https://www.geeksforgeeks.org/")
driver.get_log("browser")
To demonstrate, get_log method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. let’s get log of type browser
Program – 
Python3
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get browser logdriver.get_log("browser")
Output – Screenshot of log –  
 
Akanksha_Rai
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
wcsncpy() function in C++ with example - GeeksforGeeks

05 Oct, 2018
The wcsncpy() function is defined in cwchar.h header file. The wcsncpy() function copies a specified number of wide characters from source to destination.
Syntax:
wchar_t *wcsncpy(wchar_t *dest, 
                 const wchar_t *src, 
                 size_t n);

Parameters: This method accepts the following three parameters:
dest: specifies the pointer to the destination array.
src: specifies the pointer to the source array.
n: represents the number of character to copy.
Return Value: This function returns the modified destination.
Below programs illustrate the above function:-
Example 1:
// c++ program to demonstrate// example of wcsncpy() function.  #include <bits/stdc++.h>using namespace std;  int main(){    // initialize the source string    wchar_t src[] = L"A Computer Science portal for geeks";      // maximum length of the destination string    wchar_t dest[40];      // copy the source to destination using wcsncpy    wcsncpy(dest, src, 19);      // Print the copied destination    wcout << "Destination string is : " << dest;      return 0;}
Destination string is : A Computer Science

Example 2:-
// c++ program to demonstrate// example of wcsncpy() function.  #include <bits/stdc++.h>using namespace std;  int main(){    // initialize the source string    wchar_t src[] = L"GeeksforGeeks";      // maximum length of the destination string    wchar_t dest[40];      // copy the source to destination using wcsncpy    wcsncpy(dest, src, 5);      // Print the copied destination    wcout << "Destination string is : " << dest;      return 0;}
Destination string is : Geeks

CPP-Library
C++
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++
Inline Functions in C++
Pair in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Queue in C++ Standard Template Library (STL)
MoviePy – Iterating frames of Video File Clip - GeeksforGeeks

18 Oct, 2021
In this article we will see how we can iterate frames of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. A video is basically combination of lots of frame for each time there is a specific frame, in order to get the frame at given time we use get_frame method. Iterating frames means to traversing the frame a frame is represented in the form of numpy ndarray. 
In order to do this we will use iter_frames method with the VideoFileClip objectSyntax : clip.iter_frames()Argument : It takes no argumentReturn : It returns Clip.iter_frames 
Below is the implementation  
Python3
# Import everything needed to edit video clipsfrom moviepy.editor import *   # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.mp4")    # getting only first 5 secondsclip = clip.subclip(0, 5) # iterating framesframes = clip.iter_frames() # counter to count the framescounter = 0 # using loop to transverse the framesfor value in frames:         # incrementing the counter    counter += 1     # printing the value of the counterprint("Counter Value ", end = " : ")print(counter)            # showing  clipclip.ipython_display(width = 360)
Output :  
Counter Value  : 150
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4
 
Another example  
Python3
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip("geeks.mp4") # getting only first 5 secondsclip = clip.subclip(0, 5)  # iterating framesframes = clip.iter_frames() # counter to count the framescounter = 0 # using loop to transverse the framesfor value in frames:         # incrementing the counter    counter += 1     # printing the value of the counterprint("Counter Value ", end = " : ")print(counter) # showing  clipclip.ipython_display(width = 360)
Output :  
Counter Value  : 300
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
                                                                                                                       
MoviePy - Done.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4
 
 
gabaa406
Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
numpy.real() function - Python - GeeksforGeeks

11 Jun, 2020
numpy.real() function return the real part of the complex argument.
Syntax : numpy.real(arr)
Parameters :arr : [array_like] Input array.
Return : [ndarray or scalar] The real component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float.
Code #1 :
# Python program explaining# numpy.real() function       # importing numpy as geek import numpy as geek    arr = geek.array([1 + 3j, 5 + 7j, 9 + 11j])   gfg = arr.real   print (gfg)
Output :
[1. 5. 9.]

 Code #2 :
# Python program explaining# numpy.real() function       # importing numpy as geek import numpy as geek    arr = geek.array([2 + 3j, 5 + 6j, 8 + 9j])   gfg = arr.real   print (gfg)
Output :
[2. 5. 8.]

Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
What is the use of next() function in Express.js ? - GeeksforGeeks

18 Dec, 2021
Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client’s different incoming requests. In this article, we will discuss, the use of the next() function in every middleware of the express.js.
There are lots of middleware functions in Express.js like the Express.js app.use() function, and many more. The app.use() middleware is basically used to define the handler of the particular request made by the client.
Syntax:
app.use(path,(req,res,next))
Parameters: It accepts the two parameters as mentioned above and described below:
path: It is the path for which the middleware function is being called. It can be a string representing a path or path pattern or a regular expression pattern to match the paths.
callback: It is the callback function that contains the request object, response object, and next() function to call the next middleware function if the response of the current middleware is not terminated. In the second parameter, we can also pass the function name of the middleware.
Installing Module: Install the express module using the following command.
npm install express
Project structure: It will look like this.
Example 1: Server without next() function
Filename: index.js
Javascript
// Importing the express moduleconst express = require("express");const app = express() // Creating First Middlewareapp.use("/", (req, res, next) => {    console.log("Hello");    // There is no next() function calls here}) // Creating second middlewareapp.get("/", (req, res, next) => {    console.log("Get Request")}) // Execution the serverapp.listen(3000, () => {    console.log("Server is Running")})
Run index.js file using below command:
node index.js
Output: Without the next() function the middleware doesn’t call the next middleware even they request a path of the same
Server is Running
Hello
Example 2: Server with next() function
Filename: index.js
Javascript
// Importing the express moduleconst express = require("express");const app = express() // Creating First Middlewareapp.use("/", (req, res, next) => {    console.log("Hello");    // The next() function called    next();}) // Creating second middlewareapp.get("/", (req, res, next) => {    console.log("Get Request")}) // Execution the serverapp.listen(3000, () => {    console.log("Server is Running")})
Run index.js file using the below command:
node index.js
Output:
Server is Running
Hello
Get Request
 
simmytarika5
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose find() Function
Mongoose Populate() Method
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
Python - Convert Delimiter separated list to Number - GeeksforGeeks

05 Jul, 2021
Given a String with delimiter separated numbers, concatenate to form integer after removing delimiter.
Input : test_str = “1@6@7@8”, delim = ‘@’ Output : 1678 Explanation : Joined elements after removing delim “@”Input : test_str = “1!6!7!8”, delim = ‘!’ Output : 1678 Explanation : Joined elements after removing delim “!”  
Method #1 : Using loop + split() + int()
This is one of the ways in which this task can be performed. In this, we split the string on delimiter and then run a loop to concat, at end result is converted to int().
Python3
# Python3 code to demonstrate working of# Convert Delimiter separated list to Number# Using loop + split() + join() # initializing stringtest_str = "1@6@7@8@5@8@9" # printing original stringprint("The original string is : " + str(test_str)) # initializing Delimiterdelim = "@" # spliting to get list of string numberstemp = test_str.split(delim)res = ''for ele in temp:    res = res + ele # converting result into integerres = int(res) # printing resultprint("Constructed integer : " + str(res))
The original string is : 1@6@7@8@5@8@9
Constructed integer : 1678589
Method #2 : Using join() + split() + int()
This is one another way in which this task can be performed. In this, we perform final concatenation using join() and int() to get final result.
Python3
# Python3 code to demonstrate working of# Convert Delimiter separated list to Number# Using join() + split() + int() # initializing stringtest_str = "1@6@7@8@5@8@9" # printing original stringprint("The original string is : " + str(test_str)) # initializing Delimiterdelim = "@" # join used over splitted result# final result casted using int()res = int("".join(test_str.split(delim))) # printing resultprint("Constructed integer : " + str(res))
The original string is : 1@6@7@8@5@8@9
Constructed integer : 1678589
gabaa406
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Public vs Private Access Modifiers in Java

22 Feb, 2021
Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessible from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access modifiers. So access modifiers are used to set accessibility of classes, methods, and other members.
Public Access Modifiers :
If a class is declared as public then we can access that class from anywhere.
In the below example we are creating a package pack1 inside that package we declare a class A which is public and inside that class, we declare a method m1 which is also public. Now we create another package pack2 and inside that pack2 we import pack1 and declare a class B and in class B main method we create an object of type class A and trying to access the data of method m1.
Java
// Java program to showcase the example// of public access modifier  // import required packagesimport java.io.*;import java.util.*;  // declaring a public classpublic class A {      // declaring method m1    public void m1() { System.out.println("GFG"); }}  class B {        // main method    public static void main(String[] args)    {        // creating an object of type class A        A a = new A();                // accessing the method m1()        a.m1();    }}
GFG

If class A is not public while compiling B class we will get compile-time error saying pack1. A is not public in pack1 and can’t be accessed from the outside package.
Similarly, if a member or method or interface is declared as public then we can access that member from anywhere.
Private Access Modifiers:
This modifier is not applicable for top-level classes or interfaces. It is only applicable to constructor, methods, and fields inside the classes. 
If a variable or methods or constructor is declared as private then we can access them only from within the class i.e from outside the class we can’t access them.
Java
// Java program to showcase the example// of private access modifier  // import required packagesimport java.io.*;  import java.util.*;  // helper classclass A {        // helper method    private void m1() { System.out.println("GFG"); }}  // driver classclass B {        // main method    public static void main(String[] args)    {        // creating an object of type class A        A a = new A();                // accessing the method m1()        a.m1();    }}
Java-Modifier
Picked
Technical Scripter 2020
Difference Between
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Useful String functions

30 Jun, 2019
A string in Perl is a scalar variable and start with a ($) sign and it can contain alphabets, numbers, special characters. The string can consist of a single word, a group of words or a multi-line paragraph. The String is defined by the user within a single quote (‘) or double quote (“).
Perl provides various functions to manipulate the string like any other programming language.Example:
# Perl program to demonstrate  # string length function     # string my $s = "geeksforgeeks";     # using length function & # displaying length print("Length: ", length($s));    # Converting to Uppercaseprint("\nTo Upper Case: "); print(uc($s), "\n"); 
Length: 13
To Upper Case: GEEKSFORGEEKS

Some string functions of Perl are as follows:
Perl-function
Perl-String
Perl-String-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays
Perl Tutorial - Learn Perl With Examples
Perl | Boolean Values
Perl | length() Function
Perl | Subroutines or Functions
Use of print() and say() in Perl
Hello World Program in Perl
Perl | ne operator
Perl | Basic Syntax of a Perl Program
Perl | eq operator
How can we implement cut, copy and paste functionality of JTextField in Java?

A JTextField is a subclass of JTextComponent class that allows the editing of a single line of text. We can implement the functionality of cut, copy and paste in a JTextField component by using cut(), copy() and paste() methods. These are pre-defined methods in a JTextFeild class.
public void cut()
public void copy()
public void paste()
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JTextFieldCutCopyPasteTest extends JFrame {
   private JTextField textField;
   private JButton cutButton, copyButton, pasteButton;
   public JTextFieldCutCopyPasteTest() {
      setTitle("JTextField CutCopyPaste Test");
      setLayout(new FlowLayout());
      textField = new JTextField(12);
      cutButton = new JButton("Cut");
      pasteButton = new JButton("Paste");
      copyButton = new JButton("Copy");
      cutButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textField.cut();
         }
      });
      copyButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textField.copy();
         }
      });
      pasteButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent le) {
            textField.paste();
         }
      });
      textField.addCaretListener(new CaretListener() {
         public void caretUpdate(CaretEvent ce) {
            System.out.println("All text: " + textField.getText());
            if (textField.getSelectedText() != null)
               System.out.println("Selected text: " + textField.getSelectedText());
            else
               System.out.println("Selected text: ");
         }
      });
      add(textField);
      add(cutButton);
      add(copyButton);
      add(pasteButton);
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) {
      new JTextFieldCutCopyPasteTest();
   }
}
Runtime Type Identification in Java

22 Feb, 2021
Runtime Type Identification in Java can be defined as determining the type of an object at runtime. It is extremely essential to determine the type for a method that accepts the parameter of type java.lang. Unlike C++ Java does not support Runtime Type Identification (RTTI) but it provides few methods to find objects at runtime.
Some essential points regarding Runtime Type Identification in Java are following:
Determining the type of object at run time not only reduces error but also results in robustness.
It is also useful before typecasting any object into another type to avoid run time exception.
It is used to implement the type-specific feature on methods that accept types like objects or any interfaces.
The java.lang.Object.getClass() method is used to determine the type of object at run time.
Syntax:
public final Class getClass()
Return Type: Returns the Class objects that represent the runtime class of this object.
Example 1:
Java
// Java Program to determine Runtime type  import java.io.*;  public class Example1 {    public static void main(String[] args)    {        // Creating the obj        Object obj = new String("Learn_programming");          Class abc = obj.getClass();          // Print the class of obj        System.out.println("Class of Object obj is : "                           + abc.getName());    }}
Class of Object obj is : java.lang.String

Example 2:
Java
// Java program to determine object class at run time   import java.io.*;  public class Example2 {      public static void main(String[] args)       {         // create a new Integer      Integer num = new Integer(100);        // print num       System.out.println("" + num);        // print the class of num      System.out.println("" + num.getClass());      }   }  
Output:
100
class java.lang.Integer
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program for Range sum queries without updates

12 Jun, 2022
Given an array arr of integers of size n. We need to compute sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times. Examples:
Input : arr[] = {1, 2, 3, 4, 5}
        i = 1, j = 3
        i = 2, j = 4
Output :  9
         12         

Input : arr[] = {1, 2, 3, 4, 5}
        i = 0, j = 4 
        i = 1, j = 2 
Output : 15
          5
Python3
# Python program to find sum between two indexes# when there is no update. def find_ans(ar, j, k):    l = len(ar)    for i in range(1, l):        ar[i] = ar[i] + ar[i-1]     print(ar[k] - ar[j-1])    return;  pr = [1, 2, 3, 4, 5]ar = pr[:]find_ans(ar, 1, 3)ar = pr[:]find_ans(ar, 2, 4) # Code Contributed by Mohit Gupta_OMG <(0_o)>
9
12
Time Complexity: O(n), where n represents the size of the given array.Auxiliary Space: O(n), where n represents the size of the given array.
Please refer complete article on Range sum queries without updates for more details!
tamanna17122007
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList clone() Method in Java

10 Dec, 2018
The Java.util.LinkedList.clone() method is used to create a shallow copy of the mentioned linked list. It just creates a copy of the list.
Syntax:
LinkedList.clone()
Parameters: This method does not take any parameters.
Return Value: This function returns a copy of the instance of Linked list.
Below program illustrate the Java.util.LinkedList.clone() method:
// Java code to illustrate clone() methodimport java.io.*;import java.util.LinkedList;  public class LinkedListDemo {          public static void main(String args[]) {              // Creating an empty LinkedList        LinkedList<String> list = new LinkedList<String>();              // Use add() method to add elements in the list        list.add("Geeks");        list.add("for");        list.add("Geeks");        list.add("10");        list.add("20");              // Displaying the list        System.out.println("First LinkedList:" + list);              // Creating another linked list and copying        LinkedList sec_list = new LinkedList();        sec_list = (LinkedList) list.clone();                  // Displaying the other linked list        System.out.println("Second LinkedList is:" + sec_list);    }}
First LinkedList:[Geeks, for, Geeks, 10, 20]
Second LinkedList is:[Geeks, for, Geeks, 10, 20]

Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Abstraction in Java
HashSet in Java
Program to check whether two sentences are similar or not in Python

Suppose we have two sentences s and t. We have to check whether they are similar or not. Here sentence has only English letters. Two sentences are said to be similar when it is possible to add an arbitrary sentence (possibly empty) inside one of these given sentences such that the two sentences become equal.
So, if the input is like s = "we live at city Kolkata" t = "city Kolkata", then the output will be True because we can get s from t by adding sentence "we live in".
To solve this, we will follow these steps −
s1 := a list of words in s
s1 := a list of words in s
s2 := a list of words in t
s2 := a list of words in t
if size of s1 > size of s2, thenswap s1 and s2
if size of s1 > size of s2, then
swap s1 and s2
swap s1 and s2
while s1 is not empty, doif s2[0] is same as s1[0], thendelete first word from s2delete first word from s1otherwise when last word of s2 is same as last word of s1, thendelete last word from s2delete last word from s1otherwise,return false
while s1 is not empty, do
if s2[0] is same as s1[0], thendelete first word from s2delete first word from s1
if s2[0] is same as s1[0], then
delete first word from s2
delete first word from s2
delete first word from s1
delete first word from s1
otherwise when last word of s2 is same as last word of s1, thendelete last word from s2delete last word from s1
otherwise when last word of s2 is same as last word of s1, then
delete last word from s2
delete last word from s2
delete last word from s1
delete last word from s1
otherwise,return false
otherwise,
return false
return false
return true
return true
Let us see the following implementation to get better understanding −
def solve(s, t):
   s1 = s.split()
   s2 = t.split()
   if len(s1) > len(s2):
      s1,s2 = s2,s1
   while(s1):
      if(s2[0]==s1[0]):
         s2.pop(0)
         s1.pop(0)
      elif(s2[-1]==s1[-1]):
         s2.pop()
         s1.pop()
      else:
         return(False)
   return(True)

s = "we live at city Kolkata"
t = "city Kolkata"
print(solve(s, t))
"we live at city Kolkata", "city Kolkata"

True
How to create a default constructor in Java?

A no-arg constructor doesn’t accepts any parameters, it instantiates the class variables with their respective default values (i.e. null for objects, 0.0 for float and double, false for Boolean, 0 for byte, short, int and, long).
There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation.
While defining the constructors you should keep the following points in mind.
A constructor does not have return type.
The name of the constructor is same as the name of the class.
A constructor cannot be abstract, final, static and Synchronized.
You can use the access specifiers public, protected & private with constructors.
Live Demo
class NumberValue {
   private int num;
   public void display() {
      System.out.println("The number is: " + num);
   }
}
public class Demo {
   public static void main(String[] args) {
      NumberValue obj = new NumberValue();
      obj.display();
   }
}
The number is: 0
Live Demo
public class Student {
   public final String name;
   public final int age;  
   public Student(){
      this.name = "Raju";
      this.age = 20;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}
Name of the Student: Raju
Age of the Student: 20
Walrus Operator in Python 3.8 - GeeksforGeeks

26 Aug, 2019
Python 3.8 is still in development. But many alpha versions have been released. One of the latest features in Python 3.8 is the Walrus Operator. In this article, we’re going to discuss the Walrus operator and explain it with an example.
Introduction
Walrus-operator is another name for assignment expressions. According to the official documentation, it is a way to assign to variables within an expression using the notation NAME := expr. The Assignment expressions allow a value to be assigned to a variable, even a variable that doesn’t exist yet, in the context of expression rather than as a stand-alone statement.
Code :
a = [1, 2, 3, 4]if (n := len(a)) > 3:    print(f"List is too long ({n} elements, expected <= 3)")
Output :
Here’s instead of using “len(a)” in two places we have assigned it to a variable called “n”, which can be used later. This helps us to resolve code duplication and improves readability.
Example –
Let’s try to understand Assignment Expressions more clearly with the help of an example using both Python 3.7 and Python 3.8. Here we have a list of dictionaries called “sample_data”, which contains the userId, name and a boolean called completed.
sample_data = [    {"userId": 1,  "name": "rahul", "completed": False},    {"userId": 1, "name": "rohit", "completed": False},    {"userId": 1,  "name": "ram", "completed": False},    {"userId": 1,  "name": "ravan", "completed": True}]  print("With Python 3.8 Walrus Operator:") for entry in sample_data:     if name := entry.get("name"):        print(f'Found name: "{name}"')  print("Without Walrus operator:")for entry in sample_data:    name = entry.get("name")    if name:        print(f'Found name: "{name}"')
Output:
Programming Language
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Programming Languages to Learn in 2022
Difference between Shallow and Deep copy of a class
Kotlin Array
C# | Data Types
Advantages and Disadvantages of OOP
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Program to calculate the Round Trip Time (RTT) - GeeksforGeeks

27 Sep, 2021
Round trip time(RTT) is the length of time it takes for a signal to be sent plus the length of time it takes for an acknowledgment of that signal to be received. This time, therefore, consists of the propagation times between the two-point of the signal. 
On the Internet, an end-user can determine the RTT to and from an IP(Internet Protocol) address by pinging that address. The result depends on various factors:- 
The data rate transfer of the source’s internet connection.
The nature of transmission medium.
The physical distance between source and destination.
The number of nodes between source and destination.
The amount of traffic on the LAN(Local Area Network) to which end-user is connected.
The number of other requests being handled by intermediate nodes and the remote server.
The speed with which the intermediate node and the remote server function.
The presence of Interference in the circuit.
Examples:  
Input : www.geeksforgeeks.org
Output : Time in seconds : 0.212174892426

Input : www.cricbuzz.com
Output : Time in seconds : 0.55425786972
Python
# Python program to calculate RTT import timeimport requests # Function to calculate the RTTdef RTT(url):     # time when the signal is sent    t1 = time.time()     r = requests.get(url)     # time when acknowledgement of signal    # is received    t2 = time.time()     # total time taken    tim = str(t2-t1)     print("Time in seconds :" + tim) # driver program# url addressurl = "http://www.google.com"RTT(url)
Output: 
  Time in seconds :0.0579478740692
This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
jeevanyasa
Computer Networks
Python
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Socket Programming in Python
Caesar Cipher in Cryptography
UDP Server-Client implementation in C
Socket Programming in Java
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Program to Check Whether a Number is Positive or Negative or zero - GeeksforGeeks

29 Aug, 2020
Given a number. The task is to check whether the number is positive or negative or zero.
Examples:
Input: 5
Output: Positive

Input: -5
Output: Negative

Approach:
We will use the if-elif statements in Python. We will check whether the number is greater than zero or smaller than zero or equal to zero.
Below is the implementation.
Python3
# Python program to check whether# the number is positive, negative# or equal to zero  def check(n):          # if the number is positive    if n > 0:        print("Positive")              # if the number is negative    elif n < 0:        print("Negative")              # if the number is equal to    # zero    else:        print("Equal to zero")          # Driver Codecheck(5)check(0)check(-5)
Output:
Positive
Equal to zero
Negative

python-basics
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to check whether an image is loaded or not ? - GeeksforGeeks

12 May, 2022
While inserting images in HTML pages sometimes the image may fail to load due to:
Getting the image URL wrong
poor internet connection
So we may want to check if the image is not loading due to these reasons. To check we can use the below methods
Method 1: 
Using attributes of <img> to check whether an image is loaded or not. The attributes we will use are: 
onload: The onload event is triggered when an image is loaded and is executed
onerror: The onerror event is triggered if an error occurs during the execution
Example: 
html
<!DOCTYPE html><html>  <head>    <title>Image load check</title>  </head>  <body>    <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png"     onload="javascript: alert('The image has been loaded')"     onerror="javascript: alert('The image has failed to load')" />  </body></html>
Output:
when image is successfully loaded
when image loading fails
Method 2: 
Using the image complete property in HTML DOM
This property returns a boolean value  if the image is loaded it returns true else it returns false
Example: 
html
<!DOCTYPE html><html>  <head>    <title>Checking if image is loaded</title>  </head>  <script type="text/javascript">  window.addEventListener("load", event => {  var image = document.querySelector('img');  var load = image.complete;  alert(load);});  </script>  <body>    <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png">  </body></html>
Here the variable load checks if the image is loaded or not. If an image is loaded then true is alerted else false is alerted.
Output:
when image is successfully loaded
when image load fails
Supported Browsers:
Google Chrome
Firefox
Internet Explorer
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
sumitgumber28
ankita_saini
HTML-Attributes
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?