code-rag-bench/online-tutorials huggingface dataset:
Count ways to express a number as sum of exactly two numbers

19 May, 2021
Given a positive integer N. The task is to find the number of ways in which you can express N as a sum of exactly two numbers A and B (N = A + B) where A > 0, B > 0 and B > A.
Examples: 
Input: N = 8
Output: 3
Explanation:
N = 8 can be expressed as (1, 7), (2, 6), (3, 5)

Input: N = 14
Output: 6 
Approach: 
An observation here is that for every number N, if we take a number A which is less than N/2, then there must be a number B which is greater than N/2 and A + B = N.  
This leads to a simple solution of finding the count of numbers for either B or A. Hence, the floor value of (N-1)/2 will lead to the solution.  
C++
Java
Python3
C#
Javascript
// C++ program to Count ways to// express a number as sum of// two numbers.#include <bits/stdc++.h>using namespace std; // Function returns the count// of ways express a number// as sum of two numbers.int CountWays(int n){    int ans = (n - 1) / 2;         return ans;} // Driver codeint main(){   int N = 8;        cout << CountWays(N);}
// Java program to count ways to// express a number as sum of// two numbers.class GFG{ // Function returns the count// of ways express a number// as sum of two numbers.static int CountWays(int n){    int ans = (n - 1) / 2;         return ans;} // Driver codepublic static void main(String[] args){    int N = 8;    System.out.print(CountWays(N));}} // This code is contributed by Rajput-Ji
# Python3 program to Count ways to# express a number as sum of# two numbers. # Function returns the count# of ways express a number# as sum of two numbers.def CountWays(n) :    ans = (n - 1) // 2    return ans # Driver codeN = 8print(CountWays(N)) # This code is contributed by Sanjit_Prasad
// C# program to count ways to// express a number as sum of// two numbers.using System;class GFG{ // Function returns the count// of ways express a number// as sum of two numbers.static int CountWays(int n){    int ans = (n - 1) / 2;         return ans;} // Driver codepublic static void Main(){    int N = 8;    Console.Write(CountWays(N));}} // This code is contributed by Code_Mech
<script> // Javascript program to count ways to// express a number as sum of// two numbers. // Function returns the count// of ways express a number// as sum of two numbers.function CountWays(n){    let ans = Math.floor((n - 1) / 2);           return ans;} // Driver Code         let N = 8;    document.write(CountWays(N));         </script>
3
 
Time complexity: O(N) 
Sanjit_Prasad
Rajput-Ji
Code_Mech
souravghosh0416
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Count ways to reach the n'th stair
Fizz Buzz Implementation
Count all possible paths from top left to bottom right of a mXn matrix
Product of Array except itself
Insert a character after every n characters in JavaScript

14 May, 2021
Here given a string and the task is to insert a character after every n characters in that string. Here are 2 examples discussed below.
Approach 1: In this approach, the string is broken into chunks by using substr() method and pushed to an array by push() method. The array of chunks is returned which then joined using join() method on any character.
Example:
html
<!DOCTYPE HTML> <html>     <head>        <title>            Insert a character after          every n characters in JavaScript        </title>        <script src="https://code.jquery.com/jquery-3.5.0.js">         </script>    </head>    <body style = "text-align:center;">         <h1 style = "color: green">             GeeksForGeeks         </h1>        <p id = "GFG_UP">        </p>         <button onclick = "gfg_Run()">            Click Here        </button>        <p id = "GFG_DOWN">        </p>         <script>            var el_up = document.getElementById("GFG_UP");            var el_down = document.getElementById("GFG_DOWN");            var str = "A computer science portal for Geeks";            el_up.innerHTML = "Click on the button to perform the operation.<br>'" + str + "'";            function partition(str, n) {                var return = [];                var i, l;                for(i = 0, l = str.length; i < l; i += n) {                   return.push(str.substr(i, n));                }                return return;            };            function gfg_Run() {                el_down.innerHTML = partition(str, 5).join('@');            }        </script>    </body> </html>
Output:
Approach 2: In this approach, a RegExp is used which selects the parts of string and then joined on any character using join() method.
Example:
html
<!DOCTYPE HTML> <html>     <head>        <title>            Insert a character after         every n characters in JavaScript        </title>        <script src="https://code.jquery.com/jquery-3.5.0.js">          </script>    </head>    <body style = "text-align:center;">         <h1 style = "color: green">             GeeksForGeeks         </h1>        <p id = "GFG_UP">        </p>         <button onclick = "gfg_Run()">            Click Here        </button>        <p id = "GFG_DOWN">        </p>         <script>            var el_up = document.getElementById("GFG_UP");            var el_down = document.getElementById("GFG_DOWN");            var str = "A computer science portal for Geeks";            el_up.innerHTML = "Click on the button to perform the operation.<br>'" + str + "'";            function gfg_Run() {               el_down.innerHTML = str.match(/.{1, 5}/g).join('@');            }        </script>    </body> </html>
Output:
surinderdawra388
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scatter Plot with Marginal Histograms in Python with Seaborn

11 Dec, 2020
Prerequisites: Seaborn 
Scatter Plot with Marginal Histograms is basically a joint distribution plot with the marginal distributions of the two variables. In data visualization, we often plot the joint behavior of two random variables (bi-variate distribution) or any number of random variables. But if data is too large, overlapping can be an issue. Hence, to distinguish between variables it is useful to have the probability distribution of each variable on the side along with the joint plot. This individual probability distribution of a random variable is referred to as its marginal probability distribution. 
In seaborn, this is facilitated with jointplot(). It represents the bi-variate distribution using scatterplot() and the marginal distributions using histplot(). 
Import seaborn library
Load dataset of your choice
Use jointplot() on variables of your dataset
Example 1: 
Python3
# importing and creating alias for seabornimport seaborn as sns  # loading tips datasettips = sns.load_dataset("tips")  # plotting scatterplot with histograms for features total bill and tip.sns.jointplot(data=tips, x="total_bill", y="tip")
Output : 
<seaborn.axisgrid.JointGrid at 0x26203152688>
jointplot_with_histograms
Example 2: Using kind=”reg” attribute you can add a linear regression fit and univariate KDE curves.
Python3
import seaborn as sns  tips = sns.load_dataset("tips")  # here "*" is used as a marker for scatterplotsns.jointplot(data=tips, x="total_bill", y="tip", kind="reg", marker="*")
Output :
scatterplot with a linear regression fit
Example3: To add conditional colors to the scatterplot you can use hue attribute but it draws separate density curves (using kdeplot()) on the marginal axes.
Python3
import seaborn as sns  tips = sns.load_dataset("tips")  sns.jointplot(data=tips, x="total_bill", y="tip", hue="time")
Output : 
scatterplot3
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
VBScript | Introduction

07 Jun, 2022
 
The VBScript stands for Visual Basics Script language. Basically it is the combination of Visual Basic programming language and JavaScript language. VBScript was invented and maintained by Microsoft. It is used to develop dynamic web pages. It is much lighter compared to Visual Basic programming language but works as a scripting language like JavaScript. To run VBScript on the client-side, the client must have to use Internet Explorer because other browsers are still not supported by the VBScript. 
VBScript currently runs on below mentioned environments:
Internet Information Server (IIS) – It is a Microsoft web server.
Windows Script Host(WSH) – It is a native hosting environment of Windows operating system.
Internet Explorer (IE) – It is the simplest hosting environment where we can run VBScript code.
Prerequisite: To run VBScript script locally we need only two things:
Text Editor (Any VBScript editors like Notepad++, Text Hawk, EditPlus, etc.)
Microsoft Edge
Note: All the VBScript editors are actually HTML editors that supports VBScript. Setup for VBScript:
Step 1: Open your text editor and create a basic HTML file (for example: index.html) and paste the below code inside that file. 
html
<!DOCTYPE html><html>    <head>        <title>VBScript Introduction</title>    </head>    <body>           <!-- Paste VBScript Here -->    </body></html>
Step 2: Paste the below code inside the body tag of your HTML code, or you can paste it inside the head tag. Exactly the same as you have done with JavaScript. 
javascript
<script type="text/vbscript">    document.write("Hello geeks, greeting from GeeksforGeeks")</script>
Step 3: Combine both the code and run it on Microsoft Edge and you will get the below output in the console. 
html
<!DOCTYPE html><html><head>    <title>VBScript Introduction</title></head> <body>    <script type="text/vbscript">        document.write("Welcome to GeeksforGeeks")    </script></body></html>
Output:
Welcome to GeeksforGeeks 
Note: To use in client-side, client have to use Microsoft Edge. 
Troubleshoot: If your VBScript code is not working then use the following steps:
Press F12 key or use Right click to open Inspect Element.
Click on “Emulation” to open Emulation setting.
Change the Document mode from Default to 10.
 
Disadvantages:
The VBScript code will be processed by Microsoft Edge only. Other browsers except Microsoft Edge (like Chrome, Firefox, Safari, Opera etc) will not process the VBScript code.
The VBScript code will run only Windows Operating System platform. Other operating systems (like Linux, Mac, etc) will not run.
The VBScript code is used as a default scripting language of ASP.
satyamm09
VBScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Month length() method in Java

22 Mar, 2019
The length() method is a built-in method of the Month ENUM which is used to get the number of days in this month instance. The number of days in a month can be 28, 30 or 31. Number of days in February in a leap year is 29.
This method accepts a boolean flag variable which indicates whether this Year is a leap year or not.
Syntax:
public int length(boolean leapYear)

Parameters: This method accepts a single parameter leapYear, which indicates whether this year is a leapYear or not.
Return Value: This method returns the length of this month in number of days present in it.
Below programs illustrate the above method:
Program 1:
import java.time.*;import java.time.Month;import java.time.temporal.ChronoField;  class monthEnum {    public static void main(String[] args)    {        // Create a month instance        Month month = Month.MAY;          // Print the length of this Month        System.out.println(month.length(false));    }}
31

Program 2:
import java.time.*;import java.time.Month;import java.time.temporal.ChronoField;  class monthEnum {    public static void main(String[] args)    {        // Create a month instance        Month month = Month.FEBRUARY;          // Print the length of this Month        System.out.println(month.length(true));    }}
29

Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Month.html#length-boolean-
Java-Functions
Java-Month
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
p5.js | lerpColor() Function - GeeksforGeeks

26 Feb, 2020
The lerpColor() function is used to interpolate two colors to find a third color between them. The amount of interpolation between the two colors can be set using the amt parameters. The color interpolation depends on the current color mode.
Syntax:
lerpColor(c1, c2, amt)
Parameters: This function accepts three parameters as mentioned above and described below:
c1: It is a p5.Color which represents the first color from which the final color will be interpolated.
c2: It is a p5.Color which represents the second color to which the final color will be interpolated.
amt: It is a number between 0 and 1 which determines which color will be used more for the interpolation. A value near 0.1 would prefer the first color more and a value near 0.9 would prefer the second color for interpolation.
Return Value: It returns a p5.Color element with the interpolated color.
The example below illustrate the lerpColor() function in p5.js:
Example:
function setup() {  createCanvas(500, 350);  textSize(18);      text("From Color", 20, 20);  fromColor = color("red");    text("Lerped Color", 150, 20);    text("To Color", 300, 20);  toColor = color("blue");      text("Adjust this slider to change the"+             " amount of lerping", 20,  200)  alphaSlider = createSlider(0, 100, 50);  alphaSlider.position(20, 220);  alphaSlider.style('width', '250px');}  function draw() {  lerpedColor = lerpColor(fromColor, toColor, alphaSlider.value() / 100);    fill(fromColor);  rect(30, 30, 50, 100);    fill(lerpedColor);  rect(170, 30, 50, 100);    fill(toColor);  rect(310, 30, 50, 100);}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/lerpColor
JavaScript-p5.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
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
Roadmap to Become a Web Developer 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?
Check if the String contains only unicode letters or digits in Java

To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements.
The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit. It returns a boolean value, either true or false.
Declaration −The java.lang.Character.isLetter() method is declared as follows −
public static boolean isLetter(char ch)
The charAt() method returns a character value at a given index. It belongs to the String class in Java. The index must be between 0 to length()-1.
Declaration −The java.lang.String.charAt() method is declared as follows −
public char charAt(int index)
Let us see a program in Java to check whether a String contains only Unicode letters or digits.
public class Example {
   boolean check(String s) {
      if (s == null) // checks if the String is null {
         return false;
      }
      int len = s.length();
      for (int i = 0; i < len; i++) {
         // checks whether the character is neither a letter nor a digit
         // if it is neither a letter nor a digit then it will return false
         if ((Character.isLetterOrDigit(s.charAt(i)) == false)) {
            return false;
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "10@4"; // returns false due to special character presence
      String s1 = "13y4"; // returns true
      String s2 = "1000"; // returns true
      String s3= "abcd"; // returns true
      System.out.println("String "+s+" has only unicode letters or digits : "+e.check(s));
      System.out.println("String "+s1+" has only unicode letters or digits : "+e.check(s1));
      System.out.println("String "+s2+" has only unicode letters or digits : "+e.check(s2));
      System.out.println("String "+s3+" has only unicode letters or digits : "+e.check(s3));
   }
}
String 10@4 has only unicode letters or digits : false
String 13y4 has only unicode letters or digits : true
String 1000 has only unicode letters or digits : true
String abcd has only unicode letters or digits : true
Python | Decimal as_tuple() method - GeeksforGeeks

05 Sep, 2019
Decimal#as_tuple() : as_tuple() is a Decimal class method which returns named tuple representation of the Decimal value.
Syntax: Decimal.as_tuple()
Parameter: Decimal values
Return: tuple with values– sign– digits– exponent
Code #1 : Example for as_tuple() method
# Python Program explaining # as_tuple() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal(-1)  b = Decimal('0.142857')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.as_tuple() methodprint ("\n\nDecimal a with as_tuple() method : ", a.as_tuple())  print ("Decimal b with as_tuple() method : ", b.as_tuple())
Output :
Decimal value a :  -1
Decimal value b :  0.142857


Decimal a with as_tuple() method :  DecimalTuple(sign=1, digits=(1, ), exponent=0)
Decimal b with as_tuple() method :  DecimalTuple(sign=0, digits=(1, 4, 2, 8, 5, 7), exponent=-6)


Code #2 : Example for as_tuple() method
# Python Program explaining # as_tuple() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal('-3.14')  b = Decimal('321e + 5')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.as_tuple() methodprint ("\n\nDecimal a with as_tuple() method : ", a.as_tuple())  print ("Decimal b with as_tuple() method : ", b.as_tuple())
Output :
Decimal value a :  -3.14
Decimal value b :  3.21E+7


Decimal a with as_tuple() method :  DecimalTuple(sign=1, digits=(3, 1, 4), exponent=-2)
Decimal b with as_tuple() method :  DecimalTuple(sign=0, digits=(3, 2, 1), exponent=5)

Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Write a C program demonstrating examples on pointers

A pointer is a variable that stores the address of another variable.
Pointer saves the memory space.
Pointer saves the memory space.
The execution time of a pointer is faster because of direct access to memory location.
The execution time of a pointer is faster because of direct access to memory location.
With the help of pointers, the memory is accessed efficiently, i.e., memory is allocated and deallocated dynamically.
With the help of pointers, the memory is accessed efficiently, i.e., memory is allocated and deallocated dynamically.
Pointers are used with data structures.
Pointers are used with data structures.
int *p;
It means ‘p’ is a pointer variable that holds the address of another integer variable.
Address operator (&) is used to initialize a pointer variable.
For example,
int qty = 175;
int *p;
p= &qty;
To access the value of the variable, the indirection operator (*) is used.
 Live Demo
#include<stdio.h>
void main(){
   //Declaring variables and pointer//
   int a=2;
   int *p;
   //Declaring relation between variable and pointer//
   p=&a;
   //Printing required example statements//
   printf("Size of the integer is %d\n",sizeof (int));//4//
   printf("Address of %d is %d\n",a,p);//Address value//
   printf("Value of %d is %d\n",a,*p);//2//
   printf("Value of next address location of %d is %d\n",a,*(p+1));//Garbage value from (p+1) address//
   printf("Address of next address location of %d is %d\n",a,(p+1));//Address value +4//
   //Typecasting the pointer//
   //Initializing and declaring character data type//
   //a=2 = 00000000 00000000 00000000 00000010//
   char *p0;
   p0=(char*)p;
   //Printing required statements//
   printf("Size of the character is %d\n",sizeof(char));//1//
   printf("Address of %d is %d\n",a,p0);//Address Value(p)//
   printf("Value of %d is %d\n",a,*p0);//First byte of value a - 2//
   printf("Value of next address location of %d is %d\n",a,*(p0+1));//Second byte of value a - 0//
   printf("Address of next address location of %d is %d\n",a,(p0+1));//Address value(p)+1//
}
Size of the integer is 4
Address of 2 is 6422028
Value of 2 is 2
Value of next address location of 2 is 10818512
Address of next address location of 2 is 6422032
Size of the character is 1
Address of 2 is 6422028
Value of 2 is 2
Value of next address location of 2 is 0
Address of next address location of 2 is 6422029
When to use the ofNullable() method of Stream in Java 9?


The ofNullable() method is a static method of Stream class that returns a sequential Stream containing a single element if non-null, otherwise returns an empty. Java 9 has introduced this method to avoid NullPointerExceptions and also avoid null checks of streams. The main objective of using the ofNullable() method is to return an empty option if the value is null.
static <T> Stream<T> ofNullable(T t)
import java.util.stream.Stream;
public class OfNullableMethodTest1 {
   public static void main(String args[]) {
      System.out.println("TutorialsPoint");
      int count = (int) Stream.ofNullable(5000).count();
      System.out.println(count);
      System.out.println("Tutorix");
      count = (int) Stream.ofNullable(null).count();
      System.out.println(count);
   }
}
TutorialsPoint
1
Tutorix
0
import java.util.stream.Stream;
public class OfNullableMethodTest2 {
   public static void main(String args[]) {
      String str = null;
      Stream.ofNullable(str).forEach(System.out::println); // prints nothing in the console
      str = "TutorialsPoint";
      Stream.ofNullable(str).forEach(System.out::println); // prints TutorialsPoint
   }
}
TutorialsPoint
Explain in detail about the memory life cycle of JavaScript?

Regardless of the programming language, the memory cycle is almost same for any programming language.
1) Allocation of memory .
2) use the allocated memory(reading or writing)
3) Release the allocated memory when it is unnecessary.
The first and last parts are directly connected in low-level languages but are indirectly connected in high-level languages such as JavaScript.
JavaScript is called garbage collected language, that is when variables are declared, it will automatically allocate memory to them.When there are no more references for the declared variables, allocated memory will be released. 
In the following example javascript allocated memory for a number, a string and an object.
var n = 989;      // allocates memory for a number
var s = 'qwerty'; // allocates memory for a string

var o = {
        a: 1,
        b: null
        };        // allocates memory for an object and contained values
Using values basically means reading and writing in allocated memory.This can be done by reading or writing the         value of a variable or an object property or even passing an argument to a function.
Most of the memory management issues will come in this stage.The herculean task here is to figure out when the         allocated memory is not needed any longer.To sort out this issue most of the high level languages embed a piece of   software called  garbage collector.
The task of garbage collector is to track memory allocation and find when the allocated memory is of no longer           required so as to release it.Unfortunately this process is just an estimation because the general problem of knowing whether some piece of memory is needed is undecidable.(algorithm can't trace out) 
Javascript garbage collector uses some algorithms such as Reference-counting garbage collection to figure out the memory which is no longer in use.
How do I set the Selenium webdriver get timeout?

We can set the Selenium webdriver to get timeout. There are numerous methods to implement timeouts. They are listed below −
setScriptTimeout.
setScriptTimeout.
pageLoadTimeout.
pageLoadTimeout.
implicitlyWait.
implicitlyWait.
The setScriptTimeout is the method to set the time for the webdriver. This is usually applied for an asynchronous test to complete prior throwing an exception. The default value of timeout is 0.
This method is generally used for JavaScript commands in Selenium. If we omit setting time for the script, the executeAsyncScript method can encounter failure due to the more time consumed by the JavaScript to complete execution.
If the timeout time is set to negative, then the JavaScript can execute for an endless time.
driver.manage().timeouts().setScriptTimeout(5,TimeUnit.SECONDS);
The pageLoadTimeout is the method used to set the time for the entire page load prior to throwing an exception. If the timeout time is set to negative, then the time taken to load the page is endless.
This timeout is generally used with the navigate and manage methods.
driver.manage().timeouts().pageLoadTimeout(4, TimeUnit.SECONDS);
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class PageLoadWt{
   public static void main(String[] args)
   throws InterruptedException{
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //set time for page load
      driver.manage().timeouts().pageLoadTimeout(4, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      driver.quit();
   }
}
The implicitlyWait is the method applied to the webdriver to wait for elements to be available in the page. It is a global wait to every element. NoSuchElementException is thrown if an element is still not available after the wait time has elapsed.
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ImplicitWt{
   public static void main(String[] args)
   throws InterruptedException{
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //set implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      driver.quit();
   }
}
HTML - <address> Tag

The HTML <address> tag is used for indicating an address. The address usually renders in italic.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML address Tag</title>
   </head>

   <body>
      <address>
         600 Wisdon Apartments<br />
         Filmcity, Kondiura<br />
         New Delhi - 50027
      </address>
   </body>

</html>
This will produce the following result −
This tag supports all the global attributes described in HTML Attribute Reference
This tag supports all the event attributes described in HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
PHP - Function preg_match_all()

int preg_match_all (string pattern, string string, array pattern_array [, int order]);

The preg_match_all() function matches all occurrences of pattern in string.
It will place these matches in the array pattern_array in the order you specify using the optional input parameter order. There are two possible types of order −
PREG_PATTERN_ORDER − is the default if the optional order parameter is not included. PREG_PATTERN_ORDER specifies the order in the way that you might think most logical; $pattern_array[0] is an array of all complete pattern matches, $pattern_array[1] is an array of all strings matching the first parenthesized regexp, and so on.
PREG_PATTERN_ORDER − is the default if the optional order parameter is not included. PREG_PATTERN_ORDER specifies the order in the way that you might think most logical; $pattern_array[0] is an array of all complete pattern matches, $pattern_array[1] is an array of all strings matching the first parenthesized regexp, and so on.
PREG_SET_ORDER − will order the array a bit differently than the default setting. $pattern_array[0] will contain elements matched by the first parenthesized regexp, $pattern_array[1] will contain elements matched by the second parenthesized regexp, and so on.
PREG_SET_ORDER − will order the array a bit differently than the default setting. $pattern_array[0] will contain elements matched by the first parenthesized regexp, $pattern_array[1] will contain elements matched by the second parenthesized regexp, and so on.
Returns the number of matchings.
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
   $userinfo = "Name: <b>John Poul</b> <br> Title: <b>PHP Guru</b>";
   preg_match_all ("/<b>(.*)<\/b>/U", $userinfo, $pat_array);
   
   print $pat_array[0][0]." <br> ".$pat_array[0][1]."\n";
?>
This will produce the following result −
John Poul 
PHP Guru


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How to replace all occurrences of a string with another string in Python?

Pyhton has a method called replace in string class. It takes as input the string to be replaced and string to replace with. It is called on a string object. You can call this method in the following way to replace all 'no' with 'yes':
>>> 'no one knows how'.replace('no', 'yes')
'yes one kyesws how'
>>> "chihuahua".replace("hua", "hah")
'chihahhah'
The re module in python can also be used to get the same result using regexes. re.sub(regex_to_replace, regex_to_replace_with, string) can be used to replace the substring in string.
For example,
>>> import re
>>> re.sub('hua', 'hah', 'chihuahua')
'chihahhah'
re.sub is very powerful and can be used to make very subtle substitutions using regexes.
Insert default into not null column if value is null in MySQL?

You can use IFNULL() property or simple IF() with IS NULL property. The syntax is as follows −
INSERT INTO yourTableName(yourColumnName1,yourColumnName2)
VALUES('yourValue’',IF(yourColumnName1 IS NULL,DEFAULT(yourColumnName2),'yourMessage'));
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table Post
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,  
   -> UserName varchar(10),
   -> UserPostMessage varchar(50) NOT NULL DEFAULT 'Hi Good Morning !!!'
   -> );
Query OK, 0 rows affected (0.67 sec)
Now you can insert default into the not null column if the value is null. The query is as follows −
mysql> insert into Post(UserName,UserPostMessage)
   -> values('John',if(UserName IS NULL,DEFAULT(UserPostMessage),'Hello'));
Query OK, 1 row affected (0.21 sec)
mysql> insert into Post(UserName,UserPostMessage)
   -> values(NULL,if(UserName IS NULL,DEFAULT(UserPostMessage),'Hello'));
Query OK, 1 row affected (0.22 sec)
mysql> insert into Post(UserName,UserPostMessage)
   -> values('Carol',if(UserName IS NULL,DEFAULT(UserPostMessage),'Hello'));
Query OK, 1 row affected (0.14 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from Post;
The following is the output −
+----+----------+---------------------+
| Id | UserName | UserPostMessage     |
+----+----------+---------------------+
|  1 | John     | Hello               |
|  2 | NULL     | Hi Good Morning !!! |
|  3 | Carol    | Hello               |
+----+----------+---------------------+
3 rows in set (0.00 sec)
C++ program to implement Simpson’s 3/8 rule

In this tutorial, we will be discussing a program to implement SImpson’s 3⁄8 rule.
Simpson’s 3⁄8 rule is used for doing numerical integrations. The most common use case of this method is in performing numerical approximations of definite integrals.
In this, the parabolas on the graph are used for performing the approximations.
#include<iostream>
using namespace std;
//function that is to be integrated
float func_inte( float x){
   return (1 / ( 1 + x * x ));
}
//calculating the approximations
float func_calculate(float lower_limit, float upper_limit, int
interval_limit ){
   float value;
   float interval_size = (upper_limit - lower_limit) / interval_limit;
   float sum = func_inte(lower_limit) + func_inte(upper_limit);
   for (int i = 1 ; i < interval_limit ; i++) {
      if (i % 3 == 0)
         sum = sum + 2 * func_inte(lower_limit + i * interval_size);
      else
         sum = sum + 3 * func_inte(lower_limit + i * interval_size);
   }
   return ( 3 * interval_size / 8 ) * sum ;
}
int main(){
   int interval_limit = 8;
   float lower_limit = 1;
   float upper_limit = 8;
   float integral_res = func_calculate(lower_limit,
   upper_limit, interval_limit);
   cout << integral_res << endl;
   return 0;
}
0.663129
DirectX - Quaternion

The rotations of every graphic element are done with the help of xwing as per the rotations around the 3D axis, i.e., X, Y and Z axis. Xwing is something which is considered as a unique feature of rotating a particular object in quaternion. The only problem here is that it includes same dimensions with respect to matrices. For such a situation, a user or a developer will need a particular solution which would solve the problem.
Deriving a total rotation from the mentioned 3 separate values of each axis with reference to trigonometric formulae is something which should be discussed and it is included in further analysis.
Quaternion is matrix like structure which provides only one rotation. A quaternion is considered to be very easy to use from developer point of view. Consider for the following examples where where we declare vectors with mentioned below which describes the standard syntax −
Vector3 xwingPosition = new Vector3(18, 11, -3);
#Vector definition with three co-ordinates
Quaternion xwingRotation = Quaternion.Identity;
#Creation of identity with respect to rotation

Consider the CreateModel method where the user can change the world matrix for our xwing, with respect to correct location, and correct rotation −
Matrix worldMatrix = Matrix.CreateScale(0.07f, 0.0015f, 0.12 f) 
   * Matrix.CreateRotationY(MathHelper.Pi) 
   * Matrix.CreateTranslation(xwingPosition);

The mentioned code seems to be complex, but it is quite easy.
The mesh is translated to its correct position with the help of matrix.
The mesh is translated to its correct position with the help of matrix.
The xwing is rotated among the rotation stored in the xwingRotation quaternion.
The xwing is rotated among the rotation stored in the xwingRotation quaternion.
Once the above steps are achieved, it is rotated along 180 degrees to compensate the opposite direction stored inside the model. And finally, the model is scaled down so it fits nicely in our scene.
Once the above steps are achieved, it is rotated along 180 degrees to compensate the opposite direction stored inside the model. And finally, the model is scaled down so it fits nicely in our scene.
The code snippet for creating a dimension of camera is mentioned below −
private void UpdateCamera() { 
   Vector3 campos = new Vector3(0, 0.1f, 0.6f); 
}

The sample code which is created is mentioned below −
D3DXQUATERNION qZ;
   D3DXQUATERNION qY;
   D3DXQUATERNION qX;
   D3DXQUATERNION qOrient;
   D3DXQUATERNION qTotal;
   D3DXQuaternionIdentity(&qZ);
   D3DXQuaternionIdentity(&qY);
   D3DXQuaternionIdentity(&qX);
   D3DXQuaternionIdentity(&qOrient);
   D3DXVECTOR3 axisZ(0,0,1);
   D3DXVECTOR3 axisY(0,1,0);
   D3DXVECTOR3 axisX(1,0,0);
   D3DXQuaternionRotationAxis(&qZ,&axisZ,ga->getRotation().z);
   D3DXQuaternionRotationAxis(&qY,&axisY,ga->getRotation().y);
   D3DXQuaternionRotationAxis(&qX,&axisX,ga->getRotation().x);
   D3DXQuaternionNormalize(&qZ,&qZ);
   D3DXQuaternionNormalize(&qY,&qY);
   D3DXQuaternionNormalize(&qX,&qX);
qTotal=qY*qX*qZ;
   D3DXMATRIX rotation;
   D3DXMatrixRotationQuaternion(&rotation,&qTotal);
   world=scale*rotation*move;
 Print
 Add Notes
 Bookmark this page
How to get the value of src attribute in jQuery?

To get the value of src attribute in jQuery is quite easy. We will get the src attribute of the img tag. This attribute has the URL of the image. Let’s first see how we can add jQuery −
You can try to run the following code to learn how to get the value of src attribute in jQuery −
Live Demo
<html>

   <head>
      <title> Selector Example</title>

      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>

         $(document).ready(function() {
            alert($('#myimg').attr('src'));
         });

      </script>
   </head>

   <body>

      <p>Logo</p>
      <img src="/green/images/logo.png" id="myimg">
   </body>

</html>
How to display an image in HTML?

Use the <img> tag in HTML to display an image. The following are the attributes −
You can try to run the following code to add an image to a web document −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML img Tag</title>
   </head>
   <body>
      <img src = "https://www.tutorialspoint.com/html5/images/html5-mini-logo.jpg"
      alt = "Learn HTML5" height = "250" width = "270" />
   </body>
</html>
Write a program in C++ to replace all the 0’s with 5 in a given number

Given an integer N, the task is to replace all the 0’s that appear in the number with ‘5’. However, the number with leading ‘0’ cannot be replaced with ‘5’ as it remains unchanged. For example,
Input-1 −
N= 1007
Output −
1557
Explanation − The given number has 2 zeros which when replaced by ‘5’ results in the output as 1557.
Input-2 −
N = 00105
Output −
155
Explanation − Since the given number starts with the leading ‘0’ which can be ignored and the output after replacing the 0 in the middle with ‘5’ results the output as 155.
To replace all the 0’s in the given number with ‘5’ we can find and extract the last digit of the number. If the last digit of that number is ‘0’ then change and replace the value with ‘5’ and extract another digit. However, any leading ‘0’s in the given number must be ignored.
The problem can be solved using a recursion approach where we will first extract the last digit and then again call the same function while extracting the other digit of that number.
Take Input a number N.
Take Input a number N.
An Integer function converToFive(int N) takes a number as input and returns the modified number by replacing all 0’s with ‘5’.
An Integer function converToFive(int N) takes a number as input and returns the modified number by replacing all 0’s with ‘5’.
In a base case, if the number is ‘0’, then return 0, otherwise extract the last digit of that number and check,
In a base case, if the number is ‘0’, then return 0, otherwise extract the last digit of that number and check,
If the last digit of the number is ‘0’ then replace the value with ‘5’.
If the last digit of the number is ‘0’ then replace the value with ‘5’.
Return the recursive function which takes another digit of the number by dividing ‘10’ and multiplying by ‘10’.
Return the recursive function which takes another digit of the number by dividing ‘10’ and multiplying by ‘10’.
Return the output which extracts the last digit by adding it into it.
Return the output which extracts the last digit by adding it into it.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int convertToFive(int N) {
   if(N==0){
      return 0;
   }
   int last_digit= N%10;
   if(last_digit==0)
      last_digit=5;
   return convertToFive(N/10)*10 +last_digit;
}
int main() {
   int N= 14006;
   cout << convertToFive(N) << endl;
}
If we will run the above code, then it will print the output as,
14556
Since there are two 0s in the given number, after replacing the number 14006, it will become 14556.
Aggregate method in C#

Use the Aggregate method in C# to perform mathematical operations such as Sum, Min, Max, Average, etc.
Let us see an example to multiply array elements using Aggregate method.
Here is our array −
int[] arr = { 10, 15, 20 };
Now, use Aggregate() method −
arr.Aggregate((x, y) => x * y);
Here is the complete code −
 Live Demo
using System;
using System.Linq;
using System.IO;
public class Demo {
   public static void Main() {
      int[] arr = { 10, 15, 20 };
      // Multiplication
      int res = arr.Aggregate((x, y) => x * y);
      Console.WriteLine(res);
   }
}
3000
Why the main () method in Java is always static?

Java main() method is always static, so that compiler can call it without the creation of an object or before the creation of an object of the class.
In any Java program, the main() method is the starting point from where compiler starts program execution. So, the compiler needs to call the main() method.
If the main() is allowed to be non-static, then while calling the main() method JVM has to instantiate its class.
While instantiating it has to call the constructor of that class, There will be ambiguity if the constructor of that class takes an argument.
Static method of a class can be called by using the class name only without creating an object of a class.
The main() method in Java must be declared public, static and void. If any of these are missing, the Java program will compile but a runtime error will be thrown.
class Book {
   public static void getBookInfo() { //static method
      System.out.println("Welcome to TutorialsPoint Library");
   }
}
public class Test {
   public static void main(String[] args) {
      //Call static method of Book class using class name only
      Book.getBookInfo();
   }
}
Welcome to TutorialsPoint Library
Scala - Bitwise Operators

Try the following example program to understand all the Bitwise operators available in Scala Programming Language.
object Demo {
   def main(args: Array[String]) {
      var a = 60;           /* 60 = 0011 1100 */  
      var b = 13;           /* 13 = 0000 1101 */
      var c = 0;

      c = a & b;            /* 12 = 0000 1100 */ 
      println("a & b = " + c );

      c = a | b;            /* 61 = 0011 1101 */
      println("a | b = " + c );

      c = a ^ b;            /* 49 = 0011 0001 */
      println("a ^ b = " + c );

      c = ~a;               /* -61 = 1100 0011 */
      println("~a = " + c );

      c = a << 2;           /* 240 = 1111 0000 */
      println("a << 2 = " + c );

      c = a >> 2;           /* 215 = 1111 */
      println("a >> 2  = " + c );

      c = a >>> 2;          /* 215 = 0000 1111 */
      println("a >>> 2 = " + c );
   }
} 
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15


    82 Lectures 
     7 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    76 Lectures 
     5.5 hours 

 Bigdata Engineer

    69 Lectures 
     7.5 hours 

 Bigdata Engineer

    46 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Python 3 - File write() Method

The method write() writes a string str to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.
Following is the syntax for write() method −
fileObject.write( str )

str − This is the String to be written in the file.
This method does not return any value.
The following example shows the usage of write() method.
Assuming that 'foo.txt' file contains following text:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

#!/usr/bin/python3

# Open a file in read/write mode
fo = open("abc.txt", "r+")
print ("Name of the file: ", fo.name)

str = "This is 6th line"
# Write a line at the end of the file.
fo.seek(0, 2)
line = fo.write( str )

# Now read complete file from beginning.
fo.seek(0,0)
   for index in range(6):
      line = next(fo)
      print ("Line No %d - %s" % (index, line))

# Close opened file
fo.close()
When we run the above program, it produces the following result −
Name of the file:  foo.txt

Line No 0 - This is 1st line
Line No 1 - This is 2nd line
Line No 2 - This is 3rd line
Line No 3 - This is 4th line
Line No 4 - This is 5th line
Line No 5 - This is 6th line


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to create an empty dictionary in Python?

You can create empty dictionary object by giving no elements in curly brackets in assignment statement. Empty dictionary object is also created by dict() built-in function without any arguments
>>> L1
[]
>>> d1 = {}
>>> d1
{}
>>> d1 = dict()
>>> d1
{}