code-rag-bench/online-tutorials huggingface dataset:
GATE | GATE-CS-2004 | Question 90 - GeeksforGeeks

28 Jul, 2021
The recurrence equation
T(1) = 1
T(n) = 2T(n - 1) + n, n ≥ 2 
evaluates to
a. 2n + 1– n – 2b. 2n – nc. 2n + 1 – 2n – 2d. 2n + n(A) a(B) b(C) c(D) dAnswer: (A)Explanation: If draw recursion tree, we can notice that total work done is,T(n) = n + 2(n-1) + 4(n-2) + 8(n-3) + 2n-1 * (n – n + 1)T(n) = n + 2(n-1) + 4(n-2) + 8(n-3) + 2n-1 * 1
To solve this series, let us use our school trick, we multiply T(n) with 2 and subtract after shifting terms.
2*T(n) =     2n + 4(n-1) + 8(n-2) + 16(n-3) + 2n 
  T(n) = n + 2(n-1) + 4(n-2) + 8(n-3) + 2n-1 * 1
We get
2T(n) - T(n) =  -n + 2 + 4 + 8 + ..... 2n
T(n) = -n + 2n+1 - 2 [Applying GP sum formula for 2, 4, ...]
     = 2n+1 - 2 - n
Alternate Way to solve is to use hit and try method.
Given T(n) = 2T(n-1) + n and T(1) = 1

For n = 2, T(2) = 2T(2-1) + 2 
                = 2T(1) + 2 
                = 2.1 + 2 = 4

Now when you will put n = 2 in all options, 
only 1st option 2^(n+1) - n - 2 satisfies it. 
Quiz of this Question
OnkarMarbhal
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
Set the height of an image with CSS

The height property is used to set the height of an image. This property can have a value in length or in %. While giving value in %, it applies it in respect of the box in which an image is available.
You can try to run the following code to set the height of an image −
<html>
   <head>
   </head>
   <body>
      <img style = "border:2px solid green; height:100px;" src="/css/images/logo.png" />
      <br />
      <img style="border:2px solid green; height:50%;" src="/css/images/logo.png" />
   </body>
</html>
\ln - Tex Command

\ln - Used to draw natural logarithm symbol.
{ \ln }
\ln command draws natural logarithm symbol.

\ln

ln



\ln

ln


\ln

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Check if a number is Palindrome in C++

Here we will see, how to check whether a number is a palindrome or not. The palindrome numbers are the same in both directions. For example, a number 12321 is a palindrome, but 12345 is not a palindrome.
The logic is very straight forward. We have to reverse the number, and if the reversed number is the same as the actual number, then that is a palindrome, otherwise not. Let us see the algorithm to get a better idea.
isPalindrome(n) −
input − The number n
output − true, if the number is a palindrome, otherwise, false
begin
   temp := n
   rev := 0
   while n > 0, do
      rev := rev * 10 + (n mod 10)
      n := n / 10
   done
   if rev = temp, then
      return true
   return false
end
 Live Demo
#include <iostream>
using namespace std;
bool isPalindrome(int number) {
   int temp = number;
   int rev = 0;
   while(number > 0){
      rev = 10 * rev + number % 10; //take the last digit, and attach with the rev number /= 10;
   }
   if(rev == temp)
      return true;
   return false;
}
int main() {
   int n = 12321;
   if(isPalindrome(n)){
      cout << n << " is palindrome number";
   } else {
      cout << n << " is not a palindrome number";
   }
}
12321 is palindrome number
C++ | Misc C++ | Question 8 - GeeksforGeeks

28 Jun, 2021
#include<iostream>using namespace std;int main (){       int cin;       cin >> cin;       cout << "cin" << cin;       return 0;}
Thanks to Gokul Kumar for contributing this question.(A) error in using cin keyword(B) cin+junk value(C) cin+input(D) Runtime errorAnswer: (B)Explanation:Quiz of this Question
C++-Misc C++
Misc C++
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
fork() in C
Command line arguments in C/C++
Function Pointer in C
Substring in C++
Different methods to reverse a string in C/C++
C++ | Exception Handling | Question 3
C++ | new and delete | Question 4
C++ | Operator Overloading | Question 10
C++ | Virtual Functions | Question 2
C++ | Virtual Functions | Question 4
Java Program to split a string using Regular Expression

Let’s say we have the following string.
String str = "{Java is a programming language} {James Gosling developed it.}";
Above, the string is enclosed with parentheses. We can split a string with these parentheses using the split() method.
String[] strSplit = str.split("[{}]");
The following is an example.
 Live Demo
public class Demo {
   public static void main(String[] args) throws Exception {
      String str = "{Java is a programming language} {James Gosling developed it.}";
      String[] strSplit = str.split("[{}]");
      System.out.println("Splitting String...");
      for (int i = 0; i < strSplit.length; i++)
      System.out.println(strSplit[i]);
   }
}
Splitting String...
Java is a programming language
James Gosling developed it.
How to sum up elements of a C++ vector?

Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum.
Begin
   Declare v of vector type.
      Initialize some values into v vector in array pattern.
      Print “Sum of all the elements are:”.
      Call accumulate(v.begin(),v.end(),0) to calculate the sum of all
      values of v vector.
      Print the result of sum.
End.
 Live Demo
#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int main() {
   vector<int> v = {2,7,6,10};
   cout<<"Sum of all the elements are:"<<endl;
   cout<<accumulate(v.begin(),v.end(),0);
}
Sum of all the elements are:
25
CSS3 Diagonal Gradient

Diagonal starts at top left and right button. You can try to run the following code to implement diagonal gradients in CSS3 −
Live Demo
<html>
   <head>
      <style>
         #grad1 {
            height: 100px;
            background: -webkit-linear-gradient(left top, red , blue);
            background: -o-linear-gradient(bottom right, red, blue);
            background: -moz-linear-gradient(bottom right, red, blue);
            background: linear-gradient(to bottom right, red , blue);
         }
      </style>
   </head>
   <body>
      <div id = "grad1"></div>
   </body>
</html>
Python program to check if binary representation is palindrome?

Here we use different python inbuilt function. First we use bin() for converting number into it’s binary for, then reverse the binary form of string and compare with originals, if match then palindrome otherwise not.
Input: 5
Output: palindrome

Binary representation of 5 is 101
Reverse it and result is 101, then compare and its match with originals.
So its palindrome
Palindromenumber(n)
/* n is the number */
Step 1: input n
Step 2: convert n into binary form.
Step 3: skip the first two characters of a string.
Step 4: them reverse the binary string and compare with originals.
Step 5: if its match with originals then print Palindrome, otherwise not a palindrome.

# To check if binary representation of a number is pallindrome or not
defpalindromenumber(n): 
   # convert number into binary bn_number = bin(n)      
   # skip first two characters of string
   # Because bin function appends '0b' as 
   # prefix in binary 
   #representation of a number bn_number = bn_number[2:]
   # now reverse binary string and compare it with original
   if(bn_number == bn_number[-1::-1]):
      print(n," IS A PALINDROME NUMBER")
   else:
      print(n, "IS NOT A PALINDROME NUMBER")
# Driver program
if __name__ == "__main__":
   n=int(input("Enter Number ::>"))
   palindromenumber(n)
Enter Number ::>10
10 IS NOT A PALINDROME NUMBER
Enter Number ::>9
9 IS A PALINDROME NUMBER
C program to Calculate Body Mass Index (BMI)

Given with the weight and height of a person and the task is to find the BMI i.e. body mass index of his body and display it.
For calculating the body mass index we require two things −
Weight
Height
BMI can be calculated using the formula given below −
BMI = (mass or weight) / (height*height)
Where weight is in kg and height is in meters
Input 1-: weight = 60.00
   Height = 5.1
Output -: BMI index is : 23.53
Input 2-: weight = 54.00
   Height = 5.4
Output -: BMI index is : 9.3
Approach used below is as follows −
Input weight(kg) and height(meter) in float variables
Apply the formula to compute the body mass index
Print the BMI
Start
Step 1-> Declare function to calculate BMI
   float BMI(float weight, float height)
      return weight/height*2
step 2-> In main()
   Set float weight=60.00
   Set float height=5.1
   Set float bmi = BMI(weight,height)
   Print BMI
Stop
 Live Demo
#include<stdio.h>
//function to calculate BMI index
float BMI(float weight, float height) {
   return weight/height*2;
}
int main() {
   float weight=60.00;
   float height=5.1;
   float bmi = BMI(weight,height);
   printf("BMI index is : %.2f ",bmi);
   return 0;
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
BMI index is : 23.53
Command line arguments in C/C++

It is possible to pass some values from the command line to your C programs when
they are executed. These values are called command line arguments and many
times they are important for your program especially when you want to control your
program from outside instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments where
argc refers to the number of arguments passed, and argv[] is a pointer array which
points to each argument passed to the program. Following is a simple example which
checks if there is any argument supplied from the command line and take action
accordingly −
 Live Demo
#include <stdio.h>
int main( int argc, char *argv[] ) {
   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }
}
$./a.out testing
The argument supplied is testing
$./a.out testing1 testing2
Too many arguments supplied.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a
pointer to the first command line argument supplied, and *argv[n] is the last
argument. If no arguments are supplied, argc will be one, and if you pass one
argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument
itself has a space then you can pass such arguments by putting them inside double
quotes "" or single quotes ''. Let us re-write above example once again where we will
print program name and we also pass a command line argument by putting inside
double quotes −
 Live Demo
#include <stdio.h>
int main( int argc, char *argv[] ) {
   printf("Program name %s\n", argv[0]);
   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }
}
$./a.out "testing1 testing2"
Progranm name ./a.out
The argument supplied is testing1 testing2
How to catch all JavaScript errors?

To catch all JavaScript errors, use onerror() method. The onerror event handler was the first feature to facilitate error handling in JavaScript. The error event is fired on the window object whenever an exception occurs on the page.
The onerror event handler provides three pieces of information to identify the exact nature of the error −
Error message − The same message that the browser would display for the given error
URL − The file in which the error occurred
Line number− The line number in the given URL that caused the error
 Live Demo
You can try to run the following code to catch JavaScript errors −
<html>
   <head>
      <script>
         <!--
            window.onerror = function (msg, url, line) {
               alert("Message : " + msg );
               alert("url : " + url );
               alert("Line number : " + line );
            }
         //-->
      </script>
   </head>
   <body>
      <p>Click the following to see the result:</p>

      <form>
         <input type = "button" value = "Click Me" onclick = "myFunc();" />
      </form>
   </body>
</html>
React Native - WebView

In this chapter, we will learn how to use WebView. It is used when you want to render web page to your mobile app inline.
The HomeContainer will be a container component.
import React, { Component } from 'react'
import WebViewExample from './web_view_example.js'

const App = () => {
   return (
      <WebViewExample/>
   )
}
export default App;
Let us create a new file called WebViewExample.js inside the src/components/home folder.
import React, { Component } from 'react'
import { View, WebView, StyleSheet }

from 'react-native'
const WebViewExample = () => {
   return (
      <View style = {styles.container}>
         <WebView
         source = {{ uri:
         'https://www.google.com/?gws_rd=cr,ssl&ei=SICcV9_EFqqk6ASA3ZaABA#q=tutorialspoint' }}
         />
      </View>
   )
}
export default WebViewExample;

const styles = StyleSheet.create({
   container: {
      height: 350,
   }
})
The above program will generate the following output.

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Function call by reference in C

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.
To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.
/* function definition to swap the values */
void swap(int *x, int *y) {

   int temp;
   temp = *x;    /* save the value at address x */
   *x = *y;      /* put y into x */
   *y = temp;    /* put temp into y */
  
   return;
}

Let us now call the function swap() by passing values by reference as in the following example −
#include <stdio.h>

int main () {

   /* local variable definition */
   int a = 100;
   int b = 200;
 
   printf("Before swap, value of a : %d\n", a );
   printf("Before swap, value of b : %d\n", b );
 
   /* calling a function to swap the values */
   swap(&a, &b);
 
   printf("After swap, value of a : %d\n", a );
   printf("After swap, value of b : %d\n", b );
 
   return 0;
}
void swap(int *x, int *y) {

   int temp;

   temp = *x; /* save the value of x */
   *x = *y;    /* put y into x */
   *y = temp; /* put temp into y */
  
   return;
}
Let us put the above code in a single C file, compile and execute it, to produce the following result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

It shows that the change has reflected outside the function as well, unlike call by value where the changes do not reflect outside the function.
 Print
 Add Notes
 Bookmark this page
Python Pandas - Create a Subset DataFrame using Indexing Operator

The indexing operator is the square brackets for creating a subset dataframe. Let us first create a Pandas DataFrame. We have 3 columns in the DataFrame
dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})
Creating a subset with a single column
dataFrame[['Product']]
Creating a subset with multiple columns
dataFrame[['Opening_Stock','Closing_Stock']]
Following is the complete code
import pandas as pd

dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})

print"DataFrame...\n",dataFrame

print"\nDisplaying a subset using indexing operator:\n",dataFrame[['Product']]

print"\nDisplaying a subset with multiple columns:\n",dataFrame[['Opening_Stock','Closing_Stock']]
This will produce the following output
DataFrame...
   Closing_Stock   Opening_Stock   Product
0          200             300     SmartTV
1          500             700     ChromeCast
2         1000            1200     Speaker
3          900            1500     Earphone

Displaying a subset using indexing operator:
       Product
0      SmartTV
1   ChromeCast
2      Speaker
3     Earphone

Displaying a subset with multiple columns:
   Opening_Stock   Closing_Stock
0          300             200
1          700             500
2         1200            1000
3         1500             900
How to set MySQL default value NONE?

To set the default value in MySQL, you need to use the DEFAULT keyword. Let us first create a table −
mysql> create table DemoTable
(
   ClientCountryName varchar(100) DEFAULT 'NONE'
);
Query OK, 0 rows affected (0.65 sec)
We have set DEFAULT above for values not entered while insertion. Now, let us insert some records in the table using the insert command. We haven’t inserted values here for some of the rows. The DEFAULT gets set there −
mysql> insert into DemoTable values('US');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('UK');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('AUS');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------------------+
| ClientCountryName |
+-------------------+
| US                |
| NONE              |
| UK                |
| NONE              |
| AUS               |
+-------------------+
5 rows in set (0.00 sec)
How to use title tag in HTML Page?

The title is essential in all the HTML Documents. To define the title of a document, use the <title> tag. The title of a document is visible on the web browser toolbar and the search engine results in display title for an HTML page.
Just keep in mind that you should add <title>...</title> tag inside <head>...</head> tag.
You can try the following code to insert a title in an HTML page. The title will be visible on the web browser toolbar
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Title Tag</title>
   </head>

   <body>
      <p>The content of the documents gets added here.</p>
   </body>
</html>
The content of the documents gets added here.
Longest Palindromic Substring in Python

Suppose we have a string S. We have to find the longest palindromic substring in S. We are assuming that the length of the string S is 1000. So if the string is “BABAC”, then the longest palindromic substring is “BAB”.
To solve this, we will follow these steps
Define one square matrix of order same as the length of string, and fill it with False
Set the major diagonal elements as true, so DP[i, i] = True for all i from 0 to order – 1
start := 0
for l in range 2 to length of S + 1for i in range 0 to length of S – l + 1end := i + lif l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := iotherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i
for i in range 0 to length of S – l + 1end := i + lif l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := iotherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i
end := i + l
if l = 2, thenif S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := i
if S[i] = S[end - 1], thenDP[i, end - 1] = True, max_len := l, and start := i
DP[i, end - 1] = True, max_len := l, and start := i
otherwiseif S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i
if S[i] = S[end - 1] and DP[i + 1, end - 2], thenDP[i, end - 1] = True, max_len := l, and start := i
DP[i, end - 1] = True, max_len := l, and start := i
return a substring of from index start to start + max_len
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def longestPalindrome(self, s):
      dp = [[False for i in range(len(s))] for i in range(len(s))]
      for i in range(len(s)):
         dp[i][i] = True
      max_length = 1
      start = 0
      for l in range(2,len(s)+1):
         for i in range(len(s)-l+1):
            end = i+l
            if l==2:
               if s[i] == s[end-1]:
                  dp[i][end-1]=True
                  max_length = l
                  start = i
            else:
               if s[i] == s[end-1] and dp[i+1][end-2]:
                  dp[i][end-1]=True
                  max_length = l
                  start = i
      return s[start:start+max_length]
ob1 = Solution()
print(ob1.longestPalindrome("ABBABBC"))
"ABBABBC"
"BBABB"
Easy Interactive Plot — Pandas plotly backend | by Cornellius Yudha Wijaya | Towards Data Science

Pandas offer an easy way to explore data (EDA). One example is how we could create a plot just from the Pandas Series or Data Frame without importing any visualization module. Here I show you in the case below.
#I only use seaborn to import sample datasetimport pandas as pd, seaborn as snstips = sns.load_dataset('tips')tips['tip'].plot(kind = 'hist')
Just by using .plot attribute, we could produce a matplotlib plot by default. Although, in this article what I would show is how we could create an interactive plotly plot with a similar line as above. The example result is shown below.
If you want to learn more about EDA with Pandas, there is an article by Pararawendy Indarjo here that nicely covers what you could do with Pandas, Still, in this article, I would only focus on creating an interactive plot.
Plotly is a module that improves any visualization to become more interactive. On 26 May 2020, Plotly release version 4.8.0 which supports Pandas plotting. This is a new feature that I personally excited to use. The backend is plotly-express powered, which is another package within plotly to create a fast, interactive plot. Below is an example of plotly express usage during data analysis.
import plotly.express as pxfig = px.histogram(tips['tip'])fig.show()
Now rather than importing the plotly.express, Plotly Version 4.8.0 has provided a backend to use it in the Pandas Series or Data Frame. To implement this, you need to install the Plotly module first.
#If you never install Plotlypip install plotly#If you have install Plotly previouslypip install -U plotly
With the Plotly module installed, we need to set up the environment first by using the following code.
pd.options.plotting.backend = "plotly"
With that, we already change our pandas plot backend from the default matplotlib to the plotly module. Let us try various plots we could create.
Scatter Plot
tips.plot.scatter(x = 'tip', y='total_bill')
Box Plot
tips['tip'].plot.box()
Horizontal Bar Plot
#The y axis in the Plotly bar plot is the index, that is why I set up another column as the indextips.set_index('sex')['size'].plot.barh()
Facet Plot
tips[['tip', 'smoker']].plot.box(facet_col = 'smoker')
That is a few plots that supported through Pandas Plotly Backend. To be precise, currently only scatter, line, area, bar, barh, hist and box plot is available. If you want to read more about it, you could refer to the documentation here.
In this article, I just show how to create an easy interactive plot using Plotly from Pandas Series and Data Frame. This feature is still brand new at the time of this article creation, but I am sure in the future, the function would implement many more plots that we could use.
If you are not subscribed as a Medium Member, please consider subscribing through my referral.
Delete all the nodes from the list that are greater than x in C++

In this tutorial, we are going to learn how to delete all prime nodes from a singly linked list.
Let's see the steps to solve the problem.
Write struct with data and next pointer.
Write struct with data and next pointer.
Write a function to insert the node into the singly linked list.
Write a function to insert the node into the singly linked list.
Initialize the singly linked list with dummy data.
Initialize the singly linked list with dummy data.
Iterate over the singly linked list. Find whether the current node data is greater than x or not.
Iterate over the singly linked list. Find whether the current node data is greater than x or not.
If the current data is greater than x, then delete the node.
If the current data is greater than x, then delete the node.
Write a function to delete the node. Consider the following three cases while deleting the node.If the node is head node, then move the head to next node.If the node is middle node, then link the next node to the previous nodeIf the node is end node, then remove the previous node link.
Write a function to delete the node. Consider the following three cases while deleting the node.
If the node is head node, then move the head to next node.
If the node is head node, then move the head to next node.
If the node is middle node, then link the next node to the previous node
If the node is middle node, then link the next node to the previous node
If the node is end node, then remove the previous node link.
If the node is end node, then remove the previous node link.
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   Node* next;
};
Node* getNewNode(int data) {
   Node* newNode = new Node;
   newNode->data = data;
   newNode->next = NULL;
   return newNode;
}
void deleteGreaterNodes(Node** head_ref, int x) {
   Node *temp = *head_ref, *prev;
   if (temp != NULL && temp->data > x) {
      *head_ref = temp->next;
      free(temp);
      temp = *head_ref;
   }
   while (temp != NULL) {
      while (temp != NULL && temp->data <= x) {
         prev = temp;
         temp = temp->next;
      }
      if (temp == NULL) {
         return;
      }
      prev->next = temp->next;
      delete temp;
      temp = prev->next;
   }
}
void printLinkedList(Node* head) {
   while (head) {
      cout << head->data << " -> ";
      head = head->next;
   }
}
int main() {
   Node* head = getNewNode(1);
   head->next = getNewNode(2);
   head->next->next = getNewNode(3);
   head->next->next->next = getNewNode(4);
   head->next->next->next->next = getNewNode(5);
   head->next->next->next->next->next = getNewNode(6);
   int x = 3;
   cout << "Linked List before deletion:" << endl;
   printLinkedList(head);
   deleteGreaterNodes(&head, x);
   cout << "\nLinked List after deletion:" << endl;
   printLinkedList(head);
   return 0;
}
If you execute the above program, then you will get the following result.
Linked List before deletion:
1 -> 2 -> 3 -> 4 -> 5 -> 6 ->
Linked List after deletion:
1 -> 2 -> 3 ->
If you have any queries in the tutorial, mention them in the comment section.
What are Complex Data types in JavaScript?

Complex Data Type in JavaScript includes the typeof operator. The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.
You can try to run the following code to learn how to work with typeof operator in JavaScript −
<html>
   <body>
      <script>
         <!--
            var a = 10;
            var b = "String";
            var linebreak = "<br />";

            result = (typeof b == "string" ? "B is String" : "B is Numeric");
            document.write("Result => ");
            document.write(result);
            document.write(linebreak);

            result = (typeof a == "string" ? "A is String" : "A is Numeric");
            document.write("Result => ");
            document.write(result);
            document.write(linebreak);
         //-->
      </script>
   </body>
</html>
HTML <textarea> placeholder Attribute

The placeholder attribute of the <textarea> element is used to set a placeholder text in the textarea. A placeholder is considered as a hint, like “Enter you name”, “Enter mobile number”, “Write in 100 words”, etc.
Following is the syntax−
<textarea placeholder="text">
Above, text is the hint you want to set for the textarea as a placeholder text.
Let us now see an example to implement the placeholder attribute of the <textarea> element−
 Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Interview Questions</h2>
<p>Q1</p>
<textarea rows="6" cols="70" placeholder="Why do you want go for the Editor Job Profile? (100 words)">
</textarea>
<p>Q2</p>
<textarea rows="6" cols="70" placeholder="Do you have any previous publishing experience? (100 words)">
</textarea>
</body>
</html>
In the above example, we have set two textarea−
<p>Q1</p>
<textarea rows="6" cols="70" placeholder="Why do you want go for the Editor Job Profile? (100 words)">
</textarea>
<p>Q2</p>
<textarea rows="6" cols="70" placeholder="Do you have any previous publishing experience? (100 words)">
</textarea>
To display a placeholder text, the placeholder attribute is used, for example−
placeholder="Why do you want go for the Editor Job Profile? (100 words)"
MySQL Server port number?

If you will install MySQL on your system, then you will get the default MySQL server port number i.e. 3306.
To know the MySQL server port number, you can use the following query. Here, we have used the SHOW VARIABLES command. The query is as follows −
mysql> SHOW VARIABLES WHERE Variable_Name = 'port';
The following is the output −
+---------------+-------+
| Variable_Name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.04 sec)
What is the Count property of ArrayList class in C#?

The Count property in the ArrayList class counts the number of elements in the ArrayList.
Firstly, add elements to the ArrayList −
ArrayList arrList = new ArrayList();

arrList.Add(98);
arrList.Add(55);
arrList.Add(65);
arrList.Add(34);
Then get the count of the array list −
arrList.Count
The following is the code to implement Count property in C# −
 Live Demo
using System;
using System.Collections;

class Demo {
   public static void Main() {
      ArrayList arrList = new ArrayList();

      arrList.Add(98);
      arrList.Add(55);
      arrList.Add(65);
      arrList.Add(34);

      Console.WriteLine("Count = " + arrList.Count);

   }
}
Count = 4
MATLAB - Division (Left, Right) of Matrics

You can divide two matrices using left (\) or right (/) division operators. Both the operand matrices must have the same number of rows and columns.
Create a script file with the following code −
a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c = a / b
d = a \ b
When you run the file, it displays the following result −
c =

   -0.52542   0.68644   0.66102
   -0.42373   0.94068   1.01695
   -0.32203   1.19492   1.37288

d =

   -3.27778  -1.05556  -4.86111
   -0.11111   0.11111  -0.27778
   3.05556   1.27778   4.30556


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
<mat-select> in Angular Material

13 Apr, 2021
Introduction:Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. <mat-select> tag is used to display the options in a dropdown.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatSelectModule’ from ‘@angular/material/select’ in the app.module.ts file.
Then use <mat-select> tag to group all the items inside this group tag.
Inside the <mat-select> tag we need to use <mat-option> tag for every item.
We can also disable options using the disabled property.
Once done with the above steps then serve or start the project.
Code Implementation:
app.module.ts: 
Javascript
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatSelectModule,MatFormFieldModule }     from '@angular/material';     import { AppComponent } from './example.component';     @NgModule({   declarations: [AppComponent],   exports: [AppComponent],   imports: [     CommonModule,     FormsModule,     MatSelectModule,    MatFormFieldModule    ], }) export class AppModule {}
app.component.html:
HTML
<mat-form-field appearance="fill">  <mat-label>Choose a technology</mat-label>  <mat-select>    <mat-option value="html"> HTML </mat-option>    <mat-option value="css" disabled>CSS (disabled)</mat-option>    <mat-option value="js">JAVASCRIPT</mat-option>  </mat-select></mat-form-field>
Output:
Reference: https://material.angular.io/components/select/overview
Angular-material
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python | Check for Whitespace in List

23 Jan, 2020
Sometimes, we might have a problem in which we need to check if the List of strings has any of blank spaces. This kind of problem can be in Machine Learning domain to get specific type of data set. Let’s discuss certain ways in which this kind of problem can be solved.
Method #1 : Using regex + any()This kind of problem can be solved using the regex utility offered by python. By feeding the appropriate regex string in search(), we can check presence of space in a string and iterate through entire list using any().
# Python3 code to demonstrate working of# Check for Whitespace in List# Using regex and any()import re  # initializing list test_list = ["Geeks forGeeks", "is", "best"]  # printing original listprint("The original list is : " + str(test_list))  # Check for Whitespace in List# Using regex and any()res = any(bool(re.search(r"\s", ele)) for ele in test_list)  # printing result print("Does any string contain spaces ? " + str(res))
The original list is : ['Geeks forGeeks', 'is', 'best']
Does any string contain spaces ? True

 
Method #2 : Using in operator + any()This task can also be performed using in operator. Just required to check for a space in the string. The verdict returned is true even if a single space is found in any of string of list and false otherwise.
# Python3 code to demonstrate working of# Check for Whitespace in List# Using in operator + any()import re  # initializing list test_list = ["Geeks forGeeks", "is", "best"]  # printing original listprint("The original list is : " + str(test_list))  # Check for Whitespace in List# Using in operator + any()res = any('' in ele for ele in test_list)  # printing result print("Does any string contain spaces ? " + str(res))
The original list is : ['Geeks forGeeks', 'is', 'best']
Does any string contain spaces ? True

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
now() function in Python

15 Oct, 2020
Python library defines a function that can be primarily used to get current time and date. now() function Return the current local date and time, which is defined under datetime module.
Syntax : datetime.now(tz)
Parameters :tz : Specified time zone of which current time and date is required. (Uses Greenwich Meridian time by default.)
Returns : Returns the current date and time in time format.
 Code #1 :
# Python3 code to demonstrate# Getting current time using # now().  # importing datetime module for now()import datetime  # using now() to get current timecurrent_time = datetime.datetime.now()  # Printing value of now.print ("Time now at greenwich meridian is : "                                    , end = "")print (current_time)
Output :
Time now at greenwich meridian is : 2018-03-29 10:26:23.473031

 
now() has different attributes, same as attributes of time such as year, month, date, hour, minute, second.
Code #2 : Demonstrate attributes of now().
# Python3 code to demonstrate# attributes of now()  # importing datetime module for now()import datetime  # using now() to get current timecurrent_time = datetime.datetime.now()  # Printing attributes of now().print ("The attributes of now() are : ")  print ("Year : ", end = "")print (current_time.year)  print ("Month : ", end = "")print (current_time.month)  print ("Day : ", end = "")print (current_time.day)  print ("Hour : ", end = "")print (current_time.hour)  print ("Minute : ", end = "")print (current_time.minute)  print ("Second : ", end = "")print (current_time.second)  print ("Microsecond : ", end = "")print (current_time.microsecond)
The attributes of now() are : 
Year : 2018
Month : 3
Day : 26
Hour : 20
Minute : 9
Second : 4
Microsecond : 499806

 
Sometimes, the need is just to get the current time of a particular timezone. now() takes timezone as input to give timezone oriented output time. But these time zones are defined in pytz library.
Code #3 : Use of now() to handle specific timezone.
# Python3 code to demonstrate# attributes of now() for timezone  # for now()import datetime  # for timezone()import pytz  # using now() to get current timecurrent_time = datetime.datetime.now(pytz.timezone('Asia / Calcutta'))  # printing current time in indiaprint ("The current time in india is : ")print (current_time) 
Output:
The current time in india is : 
2018-03-29 03:09:33.878000+05:30

Note : Above code won’t work on online IDE due to absence of pytz module. Application :While developing any real world application, we might need to show real time of any timezone. now() function can do the work here very efficiently and easily.
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
turtle.bgpic() function in Python

28 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to set a background image or return name of the current background image. It requires only one argument “picname”. This argument can be used in different ways as follows :
If picname is a filename, set the corresponding image as background.
If picname is “nopic”, delete background image, if present.
If picname is None, return the filename of the current backgroundimage.
Syntax :
turtle.bgpic(picname=None)

Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle  # check background imageprint(turtle.bgpic())
Output :
nopic

Example 2 :
Python3
# import packageimport turtle  # set background imageturtle.bgpic("gfg.png")
Output :
Example 3 :
Python3
# import packageimport turtle  # set background imageturtle.bgpic("gfg.png")  # loop for motionfor i in range(20):    turtle.forward(5+5*i)    turtle.right(90)  # delete background imageturtle.bgpic("nopic")
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Create dictionary from the list

When it is required to create dictionary from a list, the ‘fromkeys’ method in the ‘dict’ method is used.
Below is a demonstration of the same −
my_list = ['Hi', 'Will', 'how', 'Python', 'cool']
print("The list is ")
print(my_list)

my_dict = dict.fromkeys(my_list, "my_value")
print(my_dict)
The list is
['Hi', 'Will', 'how', 'Python', 'cool']
{'Hi': 'my_value', 'Will': 'my_value', 'how': 'my_value', 'Python': 'my_value', 'cool': 'my_value'}
A list of strings is defined and is displayed on the console.
A list of strings is defined and is displayed on the console.
The ‘fromkeys’ method present in ‘dict’ is used to convert the elements of the list to dictionary keys.
The ‘fromkeys’ method present in ‘dict’ is used to convert the elements of the list to dictionary keys.
The value for every key is specified here itself.
The value for every key is specified here itself.
This is assigned to a variable.
This is assigned to a variable.
It is displayed as output on the console.
It is displayed as output on the console.
How to remove connected remote desktop user sessions using PowerShell?

We can remove connected RDP sessions using PowerShell and for that, we can use the cmd command “reset session” in PowerShell.  Let’s see the supported parameters for it.
PS C:\> reset session /?
Reset the session subsytem hardware and software to known initial values.

RESET SESSION {sessionname | sessionid} [/SERVER:servername] [/V]

sessionname         Identifies the session with name sessionname.
sessionid           Identifies the session with ID sessionid.
/SERVER:servername  The server containing the session (default is current).
/V                  Display additional information.
We can provide here session ID or Name and also the remote server name.
Suppose we have below active sessions on a remote computer called Test1-Win2k12,
We can disconnect the remote sessions using Session Name or the Session ID. First, we will disconnect the remote sessions with session ID 1.
reset session 1 /server:test1-win2k12
When we query the session again,
query session /server:Test1-win2k12
Now we will disconnect the session called rdp-tcp#0 using the SessionName,
reset session rdp-tcp#0 /server:test1-win2k12
Let’s query the session again and it should get disconnected from the remote server.
Matplotlib.axes.Axes.set_frame_on() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_frame_on() function in axes module of matplotlib library is used to set whether the axes rectangle patch is drawn or not.
Syntax: Axes.set_axis_on(self)
Parameters: This method accept only one parameters.
b: This parameter contains a boolean value and it is used for drawing the axes rectangle patch.
Returns:This method does not returns anything.
Note: If True is used, it does not effect any thing.Below examples illustrate the matplotlib.axes.Axes.set_frame_on() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt   x = np.arange(-5, 5, 0.01)y1 = -3 * x*x + 10 * x + 10y2 = 3 * x*x + x   fig, ax = plt.subplots()ax.plot(x, y1, x, y2, color ='black')ax.fill_between(x, y1, y2, where = y2 >y1,               facecolor ='green', alpha = 0.8)ax.fill_between(x, y1, y2, where = y2 <= y1,               facecolor ='black', alpha = 0.8)  ax.set_frame_on(False)ax.set_title('matplotlib.axes.Axes.set_frame_on() Example')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt   x = np.arange(16)y = np.sin(x / 3)   fig, ax = plt.subplots()   ax.step(x, y + 2, label ='pre (default)')ax.plot(x, y + 2, 'o--', color ='black', alpha = 0.3)   ax.step(x, y + 1, where ='mid', label ='mid')ax.plot(x, y + 1, 'o--', color ='black', alpha = 0.3)   ax.step(x, y, where ='post', label ='post')ax.plot(x, y, 'o--', color ='black', alpha = 0.3)   ax.grid(axis ='x', color ='0.95')ax.legend(title ='Parameter where:')ax.set_frame_on(False)ax.set_title('matplotlib.axes.Axes.set_frame_on() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Remove Leading Zeroes from a String in Java using regular expressions

The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String.
Following is the regular expression to match the leading zeros of a string −
The ^0+(?!$)";
To remove the leading zeros from a string pass this as first parameter and “” as second parameter.
The following Java program reads an integer value from the user into a String and removes the leading zeroes from it using the Regular expressions.
 Live Demo
import java.util.Scanner;
public class LeadingZeroesRE {
   public static String removeLeadingZeroes(String str) {
      String strPattern = "^0+(?!$)";
      str = str.replaceAll(strPattern, "");
      return str;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter an integer: ");
      String num = sc.next();
      String result = LeadingZeroesRE.removeLeadingZeroes(num);
      System.out.println(result);
   }
}
Enter an integer:
000012336000
12336000