code-rag-bench/online-tutorials huggingface dataset:
How to check whether a key exist in JavaScript object or not?

There are a couple of ways to find whether a key exist in javascript object or not.
Let's say we have an 'employee' object as shown below.
   var employee = {
      name: "Ranjan",
      age: 25
   }
Now we need to check whether 'name' property exist in employee object or not.
We can use 'in' operator on object to check its properties. The 'in' operator also looks about inherited property if it does not find any actual properties of the object.
In the following example when 'toString' is checked whether present or not, the 'in' operator scrutinizes through the properties of the object. Once it confirmed its absence, it comes to the base properties of the object. Since, 'toString' is a base property it displays 'true' as shown in the output.
Live Demo
<html>
<body>
<script>
   var employee = {
      name: "Ranjan",
      age: 25
   }
   document.write("name" in employee);
   document.write("</br>");
   document.write("salary" in employee);
   document.write("</br>");
   document.write("toString" in employee);
</script>
</body>
</html>
true
false
true
This method scrutinizes through the object only for actual properties but not for any kind of inherited properties. If there are actual properties, this method displays either true or false based on their availability.
In the following example we also searched for inherited properties such as 'toString' so it displays false as shown in the output.
Live Demo
<html>
<body>
<script>
   var employee = {
      name: "Ranjan",
      age: 25
   }
   document.write(employee.hasOwnProperty('toString'));
   document.write("</br>");
   document.write(employee.hasOwnProperty('name'));
   document.write("</br>");
   document.write(employee.hasOwnProperty('salary'));
</script>
</body>
</html>
false
true
false
How to create a new image from a JPEG file using the imagecreatefromjpeg() function in PHP?

imagecreatefromjpeg() is an inbuilt function in PHP that is used to create a new image from a JPEG file. It returns an image identifier representing the image obtained from the given filename.
resource imagecreatefromjpeg(string $filename)
imagecreatefromjpeg() uses only one parameter, $filename, that holds the name of the
image or path to the JPEG image.
imagecreatefromjpeg() returns an image resource identifier on success, and it gives an error on false.
<?php
   // Load an image from local drive/file
   $img = imagecreatefromjpeg('C:\xampp\htdocs\test\1.jpeg');
   
   // it will show the loaded image in the browser
   header('Content-type: image/jpg');
   
   imagejpeg($img);
   
   imagedestroy($img);
?>
<?php
   // Load a JPEG image from local drive/file
   $img = imagecreatefromjpeg('C:\xampp\htdocs\test\1(a).jpeg');
   
   // Flip the image
   imageflip($img, 1);
   
   // Save the GIF image in the given path.
   imagejpeg($img,'C:\xampp\htdocs\test\1(b).png');
   imagedestroy($img);
?>
Explanation − In Example 2, we loaded the jpeg image from the local path using the imagecreatefromjpeg() function. Thereafter, we used the imageflip() function to flip the image.
<?php
   function LoadJpeg($imgname) {
      /* Attempt to open */
      $im = @imagecreatefromjpeg($imgname);
     
      /* See if it failed */
      if(!$im) {
         /* Create a black image */
         $im = imagecreatetruecolor(700, 300);
         $bgc = imagecolorallocate($im, 0, 0, 255);
         $tc = imagecolorallocate($im, 255,255, 255);
         imagefilledrectangle($im, 0, 0, 700, 300, $bgc);
         
         /* Output an error message */
         imagestring($im, 20, 80, 80, 'Error loading ' . $imgname, $tc);
      }
      return $im;
   }
   header('Content-Type: image/jpeg');
   $img = LoadJpeg('bogus.image');
   imagejpeg($img);
   imagedestroy($img);
?>
Python | Linear search on list or tuples

08 Jun, 2022
Let us see a basic linear search operation on Python lists and tuples. A simple approach is to do a linear search, that is 
Start from the leftmost element of the list and one by one compare x with each element of the list.
If x matches with an element, return True.
If x doesn’t match with any of the elements, return False.
 Example #1: Linear Search on Lists 
Python
# Search function with parameter list name# and the value to be searched  def search(List, n):     for i in range(len(List)):        if List[i] == n:            return True    return False  # list which contains both string and numbers.List = [1, 2, 'sachin', 4, 'Geeks', 6] # Driver Coden = 'Geeks' if search(List, n):    print("Found")else:    print("Not Found")
Found
Note: that lists are mutable but tuples are not. 
Example #2: Linear Search in Tuple 
Python
# Search function with parameter list name# and the value to be searched  def search(Tuple, n):     for i in range(len(Tuple)):        if Tuple[i] == n:            return True    return False  # list which contains both string and numbers.Tuple = (1, 2, 'sachin', 4, 'Geeks', 6)  # Driver Coden = 'Geeks' if search(Tuple, n):    print("Found")else:    print("Not Found")
Found
talktoanmol
Picked
Python list-programs
Python tuple-programs
Python
Python Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | addslashes() Function

03 Apr, 2018
The addslashes() function is an inbuilt function in PHP and it returns a string with backslashes in front of predefined characters. It does not take any specified characters in the parameter.
The predefined characters are:
single quote (‘)double quote (“)backslash (\)NULL
single quote (‘)
double quote (“)
backslash (\)
NULL
Note: The addslashes() function is different from addcslashes() function accepts specified characters before which be want to add slashes but the addslashes() function doesnot accepts any character in parameters, rather it adds slashes before some specified characters.
Syntax:
addslashes($string)

Parameters: The addslashes() function accepts only one parameter $string which specifies the input string which is needed to be escaped. We can also say that this parameter specifies a string in which we want to add backslashes before the pre-defined characters.
Return value: It returns the escaped string with backslashes in front of the pre-defined characters which is passed in the parameter.
Examples:
Input : $string = "Geek's"
Output : Geek\'s

Input : $string='twinkle loves "coding"'
Output : twinkle loves \"coding\"

Below programs illustrate the addslashes() function in PHP:
Program 1:
<?php// PHP program to demonstrate the // working of addslashes() function   // Input String$str = addslashes('twinkle loves "coding"');   // prints the escaped stringecho($str); ?>
Output:
twinkle loves \"coding\"

Program 2:
<?php // PHP program to demonstrate the// working of addslashes() function   // Input String$str = addslashes("Geek's");   // prints the escaped stringecho($str); ?>
Output:
Geek\'s
Reference:http://php.net/manual/en/function.addslashes.php
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Remove Prefix From Field in SQL Server?

28 Nov, 2021
In SQL, certain words are reserved. These are called Keywords or Reserved Words. These words cannot be used as identifiers i.e. as column names in SQL. But, there is an exception to this rule too. In this article, we will discuss how to use Reserved Words as column names in SQL and how to remove prefixes from a field. For this article, we will be using the Microsoft SQL Server as our database.
Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks
Query:
CREATE DATABASE GeeksForGeeks
Output:
Step 2: Use the GeeksForGeeks database. For this use the below command
Query:
USE GeeksForGeeks
Output:
Step 3: Create a table of FLIGHT inside the database GeeksForGeeks. This table has 3 columns namely PASSENGER_NAME, SEAT_NO and DESTINATION containing the names, seat number, salaries, and destination of the passengers traveling in a flight.
Query:
CREATE TABLE FLIGHT(
PASSENGER_NAME VARCHAR(20),
SEAT_NO INT,
DESTINATION VARCHAR(10));
Output:
Step 4: Describe the structure of the table FLIGHT.
Query:
EXEC SP_COLUMNS FLIGHT;
Output:
Step 5: Insert 5 rows into the FLIGHT table.
Query:
INSERT INTO FLIGHT VALUES('MR. MR. VINAYAK',11,'DEL');
INSERT INTO FLIGHT VALUES('MR. MR. SINGH',06,'BOM');
INSERT INTO FLIGHT VALUES('MR. MR. KHAN',32,'KOL');
INSERT INTO FLIGHT VALUES('MR. MR. SHARMA',25,'CHD');
INSERT INTO FLIGHT VALUES('MR. MR. KUMAR',16,'LKO');
Output:
Step 6: Display all the rows of the FLIGHT table.
Query:
SELECT * FROM FLIGHT;
Output:
Step 7: As evident from the FLIGHT table, an extra MR. has been added at the start of all entries of the PASSENGER_NAME column due to clerical error. To remove this prefix of ‘MR. ‘, we need to use the keywords UPDATE, SET, RIGHT, LEN, and WHERE. The following command updates the entry of the column starting with ‘MR. ‘ with a substring of the name extracted using RIGHT keyword. The substring starts from an index equal to the length of the prefix(length of ‘MR. ‘=4) to the end of the string.
Syntax:
UPDATE TABLE_NAME
SET COLUMN_NAME = RIGHT(COLUMN_NAME,LEN
COLUMN_NAME)-LENGTH OF PREFIX TO BE REMOVED)
WHERE COLUMN_NAME LIKE 'PREFIX%';
Query:
UPDATE FLIGHT
SET PASSENGER_NAME = RIGHT
(PASSENGER_NAME,LEN(PASSENGER_NAME)-4)
WHERE PASSENGER_NAME LIKE 'MR. %';
Output:
Step 8: Display all the rows of the corrected FLIGHT table.
Query:
SELECT * FROM FLIGHT;
Output:
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Inner Join and Outer Join in SQL

24 Dec, 2021
1. Inner Join : It is a type of join operation in SQL. Inner join is an operation that returns combined tuples between two or more tables where at least one attribute is in common. If there is no attribute in common between tables then it will return nothing. Syntax: 
select * 
from table1 INNER JOIN table2
on table1.column_name = table2.column_name;
OR  
select *
from table1 JOIN table2
on table1.column_name = table2.column_name;
2. Outer Join : It is a type of Join operation in SQL. Outer join is an operation that returns combined tuples from a specified table even if the join condition fails. There are three types of outer join in SQL i.e. 
Left Outer JoinRight Outer JoinFull Outer Join
Left Outer Join
Right Outer Join
Full Outer Join
Syntax of Left Outer Join:  
select *
from table1 LEFT OUTER JOIN table2
on table1.column_name = table2.column_name;
Syntax of Right Outer Join:  
select *
from table1 RIGHT OUTER JOIN table2
on table1.column_name = table2.column_name;
Syntax of Full Outer Join:  
select *
from table1 FULL OUTER JOIN table2
on table1.column_name = table2.column_name;
Below is a table of differences between INNER JOIN and OUTER JOIN: 
harshalsls41069
DBMS-Join
Picked
DBMS
Difference Between
GATE CS
SQL
Write From Home
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Print Name of Distinct Employee Whose DOB is Between a Given Range

19 Apr, 2021
Query in SQL is like a statement that performs a task. Here, we need to write a query that will print the name of the distinct employee whose DOB is in the given range.
We will first create a database named “geeks” then we will create a table “department” in that database.
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
USE geeks;
We have the following department table in our geeks database :
CREATE TABLE department(
    ID int,
    NAME Varchar(20),
    Gender Varchar(5),
    DateOfBirth Date);
You can use the below statement to query the description of the created table:
EXEC sp_columns department;
The date data type uses the format ‘YYYY-MM-DD‘. Use the below statement to add data to the department table:
INSERT INTO department VALUES (1,'Neha','F','1994-06-03');
INSERT INTO department VALUES (2,'Harsh','M','1996-03-12');
INSERT INTO department VALUES (3,'Harsh','M','1995-05-01');
INSERT INTO department VALUES (4,'Rupali','F',1996-11-11');
INSERT INTO department VALUES (5,'Rohan','M','1992-03-08');
To verify the contents of the table use the below statement:
SELECT * FROM department
Here, we will assume the DOB range to be from 1995-01-01 to 1996-12-31.
Now we will use the below syntax to query for the name of the Distinct Employee whose DOB is between a given range:
Syntax:
SELECT DISTINCT column_name1 FROM table_name 
WHERE column_name2 between value1 and value2;
So the query for our table goes as shown below:
SELECT DISTINCT NAME FROM department 
WHERE DateOfBirth between '1995-01-01' and '1996-12-31';
Output:
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | Defining Constants

11 Aug, 2021
In a production level code it is very important to keep information as either variables or constants rather than using them explicitly. A PHP constant is nothing but an identifier for a simple value that tends not to change over time(such as the domain name of a website eg. www.geeksforgeeks.org). It is ideal to keep all the constants in a single PHP script so the maintenance is made easier. A valid constant name must start with an alphabet or underscore and requires no ‘$’. It is to be noted, constants are irrespective of their scope i.e constants are automatically of global scope.In order to create a constant in PHP, we must use the define() method. 
Syntax:  
bool define(identifier, value, case-insensitivity)
Parameters: The function has two required parameters and one optional parameter.  
identifier: Specifies the name to be assigned to the constant.
value: Specifies the value to be assigned to the constant.
case-insensitivity(Optional): Specifies whether the constant identifier should be case-insensitive. By default it is set to false i.e. case-sensitive.  
Return Type: This method returns TRUE on success and FALSE on Failure.Below are some examples to illustrate working of define() function:  
Below program illustrates defining case-insensitive constants: 
PHP
<?php     // case-insensitive constants  define("Constant","Hello Geeks!",TRUE);  echo constant;  echo Constant;?>
Output : 
Hello Geeks!  // Case Insensitive thus value is echoed
Hello Geeks!
Below program illustrates defining case-sensitive constants: 
PHP
<?php   // case-sensitive constant  define("Constant","Hello Geeks!");  echo constant;  echo Constant;?>
Output : 
constant   // Case Sensitive thus value not echoed
Hello Geeks! 
The PHP compiler will also throw a warning for above program along with the output as: “PHP Notice: Use of undefined constant constant- assumed ‘constant’ in line 5”.  
Summary: 
Constants are identifiers that can be assigned values(string, boolean, array, integer, float or NULL) which generally don’t change overtime.
Constants are irrespective of scope and always populate the global scope.
define() method is used to define constants.
defined() method is used to check if a constant is defined.
constant() method is used to return the value of a constant and NULL if not the constant is not defined. 
sweetyty
PHP-basics
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Get random dictionary pair

30 Jun, 2021
Sometimes, while working with dictionaries, we can have a situation in which we need to find a random pair from the dictionary. This type of problem can come in games such as lotteries etc. Let’s discuss certain ways in which this task can be performed.  
Method #1 : Using random.choice() + list() + items()The combination of above methods can be used to perform this task. The choice function performs the task of random value selection and list method is used to convert the pairs accessed using items() into a list over which choice function can work. Warning, if the dictionary contains many values, repeatedly converting it to a list may cause performance issues. 
Python3
# Python3 code to demonstrate working of# Get random dictionary pair in dictionary# Using random.choice() + list() + items()import random # Initialize dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Get random dictionary pair in dictionary# Using random.choice() + list() + items()res = key, val = random.choice(list(test_dict.items())) # printing resultprint("The random pair is : " + str(res))
The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2}
The random pair is : ('is', 2)
 
 Method #2 : Using popitem() This function is generally used to remove an item from a dictionary and remove it. The logic why this function can be used to perform this task is that the ordering in a dictionary does not depend on the order in which the items were inserted. However, it is important to note that, in newer versions of Python the order will always be the same for the same set of items. 
Python3
# Python3 code to demonstrate working of# Get random dictionary pair in dictionary# Using popitem() # Initialize dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Get random dictionary pair in dictionary# Using popitem()res = test_dict.popitem() # printing resultprint("The random pair is : " + str(res))
The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2}
The random pair is : ('is', 2)
 
erif89
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java - String split() Method

This method has two variants and splits this string around matches of the given regular expression.
Here is the syntax of this method −
public String[] split(String regex)

Here is the detail of parameters −
regex − the delimiting regular expression.
regex − the delimiting regular expression.
It returns the array of strings computed by splitting this string around matches of the given regular expression.
It returns the array of strings computed by splitting this string around matches of the given regular expression.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("Welcome-to-Tutorialspoint.com");
      System.out.println("Return Value :" );      
      
      for (String retval: Str.split("-")) {
         System.out.println(retval);
      }
   }
}
This will produce the following result −
Return Value :
StringTokenizer countTokens() Method in Java with Examples

28 Jan, 2019
The countTokens() method of StringTokenizer class calculate the number of times that this tokenizer’s nextToken method can be called before the method generates any further exception.Note: The current position is not advanced during the process.
Syntax:
public int countTokens()
Parameters: The method does not take any parameters.
Return Value: The method is used to return the number of tokens remaining in the string using the current delimiter set.
Below programs illustrate the working of countTokens() Method of StringTokenizer:Example 1:
// Java code to illustrate countTokens() method  import java.util.*;  public class StringTokenizer_Demo1 {    public static void main(String args[])    {          // Creating a StringTokenizer        StringTokenizer str_arr            = new StringTokenizer(                "Lets practice at GeeksforGeeks");          // Counting the tokens        int count = str_arr.countTokens();        System.out.println("Total number of Tokens: "                           + count);          // Print the tokens        for (int i = 0; i < count; i++)            System.out.println("token at [" + i + "] : "                               + str_arr.nextToken());    }}
Total number of Tokens: 4
token at [0] : Lets
token at [1] : practice
token at [2] : at
token at [3] : GeeksforGeeks

Example 2:
// Java code to illustrate countTokens() method  import java.util.*;  public class StringTokenizer_Demo2 {    public static void main(String args[])    {          // Creating a StringTokenizer        StringTokenizer str_arr            = new StringTokenizer(                "Welcome to GeeksforGeeks");          // Counting the tokens        int count = str_arr.countTokens();        System.out.println("Total number of Tokens: "                           + count);          // Print the tokens        for (int i = 0; i < count; i++)            System.out.println("token at [" + i + "] : "                               + str_arr.nextToken());    }}
Total number of Tokens: 3
token at [0] : Welcome
token at [1] : to
token at [2] : GeeksforGeeks

Java - util package
Java-Functions
Java-StringTokenizer
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Queue Interface In Java
Multidimensional Arrays in Java
How to add an element to an Array in Java?
HashMap in Java with Examples
Stack Class in Java
PriorityQueue in Java
Math pow() method in Java with Example
Initialize an ArrayList in Java
List Interface in Java with Examples
How to Delete Duplicate Records in Oracle Database?

14 Sep, 2021
To delete the duplicate records we need to first find all the distinct records. In duplicate records, every data is the same except row_id because row_id is the physical address that the record occupies. So we find the distinct row id where data are distinct in each column and then delete all the rows with row_id that are not in the above query.
Here we will see, how to delete duplicate records in Oracle. For this purpose of demonstration, we will be creating a Table Demo.
Firstly, we create a table and fill data in it, with some records being duplicates using:
Query:
CREATE TABLE Demo( PersonID int, LastName varchar(255), FirstName varchar(255));
INSERT INTO Demo VALUES (1, 'Geek1', 'Geeksforgeeks');
INSERT INTO Demo VALUES (2, 'Geek2', 'Geeksforgeeks');
INSERT INTO Demo VALUES (3, 'Geek3', 'Geeksforgeeks');
INSERT INTO Demo VALUES (1, 'Geek1', 'Geeksforgeeks');
INSERT INTO Demo VALUES (2, 'Geek2', 'Geeksforgeeks');
INSERT INTO Demo VALUES (2, 'Geek2', 'Geeksforgeeks');
Output:
Now, we will find all the distinct records having no duplicates row using:
Query:
SELECT * FROM Demo 
WHERE rowid IN 
( SELECT MAX(rowid)  
FROM Demo
GROUP BY PersonID, LastName, FirstName);
Output:
Now. delete all the rows with rowid that are not in the above query using:
Query:
DELETE Demo  
WHERE rowid NOT IN 
  (SELECT MAX(rowid)  
FROM Demo
GROUP BY PersonID, LastName, FirstName);
Output:
The final table with duplicates removed is following:
Oracle
Picked
SQL
Oracle
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Check whether a string is valid json or not

15 Mar, 2019
Given a string, the task is to check whether a string is valid json object or not. Let’s try to understand the problem using different examples.
Code #1 :
# Python code to demonstrate# checking whether string# is valid json or not  import json  ini_string = "{'akshat' : 1, 'nikhil' : 2}"  # printing initial ini_stringprint ("initial string", ini_string)  # checking for stringtry:    json_object = json.loads(ini_string)    print ("Is valid json? true")except ValueError as e:    print ("Is valid json? false")
initial string {'akshat' : 1, 'nikhil' : 2}
Is valid json? false

 Code #2:
# Python code to demonstrate# checking whether string# is valid json or not  import json  #ini_string = '{"Geek" : 1,"forGeeks" : 2}'  a = '{"name":"John", "age":31, "Salary":25000}'b = '{ "Subjects": {"Maths":85, "Physics":90}}'  #printing initial ini_stringprint ("initial strings given - \n", a, "\n", b)  #checking for stringtry:    json_object1 = json.loads(a)    json_object2 = json.loads(b)    print ("Is valid json? true")      except ValueError as e:    print ("Is valid json? false")
initial strings given - 
 {"name":"John", "age":31, "Salary":25000} 
 { "Subjects": {"Maths":85, "Physics":90}}
Is valid json? true

JSON
Python
Python Programs
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
IntStream filter() in Java with examples

06 Dec, 2018
IntStream filter(IntPredicate predicate) returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation. These operations are always lazy i.e, executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate.
Syntax :
IntStream filter(IntPredicate predicate)

Where, IntStream is a sequence of primitive int-valued elements.
IntPredicate represents a predicate (boolean-valued function) 
of one int-valued argument and the function returns the new stream.

Example 1 : filter() method on IntStream.
// Java code for IntStream filter// (IntPredicate predicate) to get a stream// consisting of the elements of this// stream that match the given predicate.import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.of(3, 5, 6, 8, 9);          // Using IntStream filter(IntPredicate predicate)        // to get a stream consisting of the        // elements that gives remainder 2 when        // divided by 3        stream.filter(num -> num % 3 == 2)            .forEach(System.out::println);    }}
Output :
5
8

Example 2 : filter() method on IntStream.
// Java code for IntStream filter// (IntPredicate predicate) to get a stream// consisting of the elements of this// stream that match the given predicate.import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.of(-2, -1, 0, 1, 2);          // Using IntStream filter(IntPredicate predicate)        // to get a stream consisting of the        // elements that are greater than 0        stream.filter(num -> num > 0)            .forEach(System.out::println);    }}
Output :
1
2

Java - util package
Java-Functions
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java
Remove extra spaces in string JavaScript?

To remove extra spaces, you need to use trim() along with regular expressions. Following is our
string with spaces before applying trim() −
var sentence="My name is John Smith ";
Now, we will remove the extra spaces as in the below code −
var sentence="My name is John Smith ";
console.log("The actual value=");
console.log(sentence);
var originalSentence = sentence.replace(/\s+/g,'').trim();
var afterRemovingTheSpace=originalSentence.trim();
console.log("After removing the spaces=");
console.log(afterRemovingTheSpace);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo90.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo90.js
The actual value=
My name is John Smith
After removing the spaces=
MynameisJohnSmith
How to embed an interactive Matplotlib plot on a webpage?

To show a plot on a webpage such that the plot could be interactive, we can take the following steps −
Install Bokeh and import figure, show, and output_file.
Configure the default output state to generate the output saved to a file when:func:'show' is called.
Create a new Figure for plotting.
Render the images loaded from the given URLs.
Immediately display a Bokeh object or application.
from bokeh.plotting import figure, show, output_file

output_file('image.html')
p = figure(x_range=(0, 1), y_range=(0, 1))

p.image_url(url=['bird.jpg'], x=0, y=1, w=0.8, h=0.6)
show(p)
When we execute the code, it will show the following image on your default browser.
You can move the image around on the browser, as the plot is interactive
D3.js easeLinear() Function - GeeksforGeeks

29 Sep, 2020
The d3.easeLinear() function in d3.js is used to linear easing the transition effect to a particular element. This linear easing function returns an identity function.
Syntax:
d3.easeLinear

Parameter: This function does not accept any parameters.
Return Values: This function does not return any value.
Approach: 
D3.js transition function will be used for applying different easing effects on a particular element. First, create an SVG element and append it to the body of the HTML page, then create a circle and append it to the SVG. Set some attributes of the circle to give it nice color and size and apply the d3.transition function followed by ease() function and give the d3.easeLinear as a parameter to ease function. 
Below given are a few examples of the function given above.
Example 1:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport"         content="width=device-width,                 initial-scale=1.0">      <script src="https://d3js.org/d3.v4.min.js"></script>  </head>  <body>    <h3 style="color:green">GeeksforGeeks</h3>    <svg width="500px" height="500px">    </svg>      <script>        var svg = d3.select("svg");                  svg.append("circle")            .attr("r", 30)            .attr("cy",40)            .attr("cx",30)            .attr("fill", "green")            .transition()            // Use of easeLinear            .ease(d3.easeLinear)            .duration(2000)            .attr("cy",40)            .attr("cx",200);    </script></body>  </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport"         content="width=device-width,                 initial-scale=1.0">      <script src="https://d3js.org/d3.v4.min.js"></script>  </head>  <body>    <h1 style="color:green">GeeksforGeeks</h1>      <svg width="500px" height="500px">    </svg>      <script>        var svg = d3.select("svg")                    .attr("transform","translate(0,-50)");          svg.append("rect")            .attr("x", 10)            .attr("y",50)            .attr("width",150)            .attr("height",50)            .attr("fill", "green")            .transition()            // Ease linear            .ease(d3.easeLinear)            .attr("x", 100)            .attr("y",100)            .attr("width",100)            .attr("height",10)            .duration(2000);    </script></body>  </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 Open URL in New Tab using JavaScript ?
How to read a local text file using JavaScript?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Align labels and groups of form controls in a horizontal layout with Bootstrap

Use the .form-horizontal class in Bootstrap to align labels and groups of form controls in a horizontal layout.
You can try to run the following code to implement .form-horizontal class:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <form class = "form-horizontal" role = "form">
         <div class = "form-group">
            <label class = "sr-only" for = "name">Name</label>
            <input type = "text" class = "form-control" id = "name" placeholder = "Enter Name">
         </div>
         <div class = "form-group">
            <label class = "sr-only" for = "name">Name</label>
            <input type = "number" class = "form-control" id = "name" placeholder = "Enter Age">
         </div>
         <button type = "submit" class = "btn btn-primary">Submit</button>
      </form>
   </body>
</html>
Defining a Python function at runtime - GeeksforGeeks

29 Dec, 2020
In Python,we can define a python function at runtime execute with the help of FunctionType(). First we import types module then perform compile() function and pass parameter exec and after that with the help FunctionType() define the function at runtime.
Example 1: Function to print GEEKSFORGEEKS.
Python3
# importing the modulefrom types import FunctionType  # functttion during run-timef_code = compile('def gfg(): return "GEEKSFORGEEKS"', "<string>", "exec")f_func = FunctionType(f_code.co_consts[0], globals(), "gfg")  # calling the functionprint(f_func())
Output:
GEEKSFORGEEKS

Example 2: Function to add 2 numbers. 
Python3
# importing the modulefrom types import FunctionType  # function at run-timef_code = compile('def gfg(a, b): return(a + b) ', "<int>", "exec")f_func = FunctionType(f_code.co_consts[0], globals(), "gfg")  val1 = 3999val2 =4999  # calliong the functionprint(f_func(val1, val2))
Output: 
8998
Python function-programs
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
Exception Handling Basics in C++

In C++, Exception Handling is a process to handle runtime errors. Exception is an event which is thrown at runtime in C++. All exceptions are derived from std::exception class. It is a runtime error which can be handled. It prints exception message and terminates the program, if we don't handle the exception.
Exceptions are defined in C++ standard as <exception> class that we can use inside our programs. The arrangement of parent-child class hierarchy has been shown below:
Common exception classes in C++ are:
There are 3 keywords in exception handling: try, catch and throw.
In C++, exception handling is performed using try/catch statement. The code that may occur exception is used to place by Try block. Catch block is used to handle the exception.
#include <iostream>
using namespace std;
class Sample1 {
   public:
   Sample1()
   {
      cout << "Construct an Object of sample1" << endl;
   }
   ~Sample1()
   {
      cout << "Destruct an Object of sample1" << endl;
   }
};
class Sample2 {
   public:
   Sample2()
   {
      int i=7;
      cout << "Construct an Object of sample2" << endl;
      throw i;
   }
   ~Sample2()
   {
      cout << "Destruct an Object of sample2" << endl;
   }
};
int main() {
   try {
      Sample1 s1;
      Sample2 s2;
   } catch(int i) {
      cout << "Caught " << i << endl;
   }
}
Construct an Object of sample1
Construct an Object of sample2
Destruct an Object of sample1
Caught 7
We can define our own exceptions by inheriting and overriding exception class functionalities.
#include <iostream>
#include <exception>
using namespace std;
struct DivideByZero : public exception {
   const char * what () const throw () {
      return "My Exception";
   }
};
int main() {
   try {
      throw DivideByZero();
   } catch(DivideByZero& e) {
      cout << "Exception caught" << endl;
      cout << e.what() << endl;
   } catch(exception& e) {
   }
}
Exception caught
My Exception
what() = A public method provided by exception class and it has been
overridden by all the child exception classes. It returns the cause of an
exception.
PHP | array_combine() Function - GeeksforGeeks

09 Aug, 2019
The array_combine() is an inbuilt function in PHP which is used to combine two arrays and create a new array by using one array for keys and another array for values. That is all elements of one array will be the keys of new array and all elements of the second array will be the values of this new array.
Examples:
Input : $array1 = ("Ram", "Akash", "Rishav"); 
        $array2 = ('24', '30', '45');
Output :
        Array
        (
          [Ram] => 24
          [Akash] => 30
          [Rishav] => 45
        )

Input : $array1 = ("65824", "92547", "12045");
        $array2 = ('1', '2', '3');
Output :
        Array
        (
          [65824] => 1
          [92547] => 2
          [12045] => 3
        )

Syntax:
array_combine( $keys_array, $values_array )
Parameters: This function accepts two parameters and both are mandatory. The function parameters as listed below:
$keys_array: This is an array of keys. If illegal values are passed as the key, then it will be converted into a string.
$values_array: This is an array of values that is to be used in the new array.
Return Value: This function returns a new combined array, in which the elements from first array $keys_array represents keys in new array and the elements from second array $values_array represents the corresponding values in the new array. This function returns false if the number of elements in the two arrays are not same.
Below program illustrates the array_combine() function in PHP:
<?php  // PHP program to illustrate the working// of array_combine() functionfunction Combine($array1, $array2) {    return(array_combine($array1, $array2));}  // Driver Code$array1 = array("Ram", "Akash", "Rishav");$array2 = array('24', '30', '45');  print_r(Combine($array1, $array2));?>
Output:
Array
(
    [Ram] => 24
    [Akash] => 30
    [Rishav] => 45
)

Note: The total number of elements in both of the arrays must be equal for the function to execute successfully otherwise it will throw an error.
Reference: https://www.php.net/manual/en/function.array-combine.php
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
C++ Math

C++ has many functions that allows you to perform mathematical tasks on numbers.
The max(x,y) function can be used to find the highest value of x and
y:
And the min(x,y) function can be used to find the lowest value of 
x 
and y:
Other functions, such as sqrt (square root), round (rounds a number) and log 
(natural logarithm), can be found in the <cmath> header 
file:
A list of other popular Math functions (from the <cmath> library) can be found in the table below:
Use the correct function to print the highest value of x and y.
int x = 5;
int y = 10;
cout << (x, y);

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
What are JavaScript Identifiers?

JavaScript Identifiers are names given to variables, functions, etc. It is the same as identifiers in other programming languages like C, C++, Java, etc. Let’s see identifiers for variable names.
The following are legal variable names −
val
val1
result
While naming your variables in JavaScript, keep the following rules in mind.
You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 5demo is an invalid variable name but _5demo is a valid one.
JavaScript variable names are case-sensitive. For example, Name and name are two different variables.
Finding Mode in a Binary Search Tree in JavaScript

Mode of a set of data is simply the number that occurs for most number of times in that set of data. For instance, 3 is the mode of dataset 2, 3, 1, 3, 4, 2, 3, 1 as it occurs for most number of times.
A tree DS is a valid Binary Search Tree if it fulfils the following conditions −
The left subtree of a node contains only nodes with keys less than or equal to the node's key.
The left subtree of a node contains only nodes with keys less than or equal to the node's key.
The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
Both the left and right subtrees must also be binary search trees.
Both the left and right subtrees must also be binary search trees.
We are required to write a JavaScript function that takes in a BST root as the only argument. The BST may or most probably contain duplicates. We are required to find and return the mode of the data stored by the tree.
The code for this will be −
 Live Demo
class Node{
   constructor(data) {
      this.data = data;
      this.left = null;
      this.right = null;
   };
};
class BinarySearchTree{
   constructor(){
      // root of a binary seach tree
      this.root = null;
   }
   insert(data){
      var newNode = new Node(data);
      if(this.root === null){
         this.root = newNode;
      }else{
         this.insertNode(this.root, newNode);
      };
   };
   insertNode(node, newNode){
      if(newNode.data < node.data){
         if(node.left === null){
            node.left = newNode;
         }else{
            this.insertNode(node.left, newNode);
         };
      } else {
         if(node.right === null){
            node.right = newNode;
         }else{
            this.insertNode(node.right,newNode);
         };
      };
   };
};
const BST = new BinarySearchTree();
BST.insert(1);
BST.insert(3);
BST.insert(3);
BST.insert(2);
BST.insert(3);
BST.insert(2);
const findMode = function(root) {
   let max = 1;
   const hash = {};
   const result = [];
   const traverse = node => {
      if (hash[node.data]) {
         hash[node.data] += 1;
         max = Math.max(max, hash[node.data]);
      } else {
         hash[node.data] = 1;
      };
      node.left && traverse(node.left);
      node.right && traverse(node.right);
   };
   if(root){
      traverse(root);
   };
   for(const key in hash) {
      hash[key] === max && result.push(key);
   };
   return +result[0];
};
console.log(findMode(BST.root));
And the output in the console will be −
3
Overriding in C#

Runtime polymorphism has method overriding that is also known as dynamic binding or late binding. It is implemented by abstract classes and virtual functions. Abstract classes contain abstract methods, which are implemented by the derived class.
Let us see an example of abstract classes that implement runtime polymorphism and works with Overriding −
using System;

namespace PolymorphismApplication {
   abstract class Shape {
      public abstract int area();
   }

   class Rectangle: Shape {
      private int length;
      private int width;

      public Rectangle( int a = 0, int b = 0) {
         length = a;
         width = b;
      }

      public override int area () {
         Console.WriteLine("Rectangle class area :");
         return (width * length);
      }
   }

   class RectangleTester {
      static void Main(string[] args) {
         Rectangle r = new Rectangle(10, 7);
         double a = r.area();
         Console.WriteLine("Area: {0}",a);
         Console.ReadKey();
      }
   }
}
Creating a Vector of sequenced elements in R Programming – seq() Function

04 Jun, 2020
seq() function in R Language is used to create a sequence of elements in a Vector. It takes the length and difference between values as optional argument.
Syntax:seq(from, to, by, length.out)
Parameters:from: Starting element of the sequenceto: Ending element of the sequenceby: Difference between the elementslength.out: Maximum length of the vector
Example 1:
# R Program to illustrate# the use of seq() Function  # Creating vector using seq()vec1 <- seq(1, 10, by = 2)  vec2 <- seq(1, 10, length.out = 7)  # Printing vectorsprint(vec1)print(vec2)
Output:
[1] 1 3 5 7 9
[1]  1.0  2.5  4.0  5.5  7.0  8.5 10.0

Example 2:
# R Program to illustrate# the use of seq() Function  # Creating vector using seq()vec1 <- seq(10, 1, by = -2)  vec2 <- seq(10, 1, length.out = 4)  # Printing vectorsprint(vec1)print(vec2)
Output:
[1] 10  8  6  4  2
[1] 10  7  4  1

R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 QListWidget – Setting Word Wrap

06 Aug, 2020
In this article we will see how we can word wrap property of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds the item text word-wrapping policy. If this property is true then the item text is wrapped where necessary at word-breaks; otherwise it is not wrapped at all. This property is false by default.
In order to do this we will use setWordWrap method with the list widget object.
Syntax : list_widget.setWordWrap(True)
Argument : It takes bool as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for components    def UiComponents(self):          # creating a QListWidget        list_widget = QListWidget(self)          # setting geometry to it        list_widget.setGeometry(50, 70, 150, 60)          # list widget items        item1 = QListWidgetItem("PyQt5 Geeks for Geeks")        item2 = QListWidgetItem("B")        item3 = QListWidgetItem("C")          # adding items to the list widget        list_widget.addItem(item1)        list_widget.addItem(item2)        list_widget.addItem(item3)          # setting wordwrap property        list_widget.setWordWrap(True)          # creating a label        label = QLabel("GeesforGeeks", self)          # setting geometry to the label        label.setGeometry(230, 80, 280, 80)          # making label multi line        label.setWordWrap(True)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.