code-rag-bench/online-tutorials huggingface dataset:
Prefix Sum of Matrix (Or 2D Array) in C++

In this problem, we are given a 2D array of integer values mat[][]. Our task is to print the prefix sum matrix of mat.
Prefix sum matrix: every element of the matrix is the sum elements above and left of it. i.e
prefixSum[i][j] = mat[i][j] + mat[i-1][j]...mat[0][j] + mat[i][j-1] +... mat[i][0].
Let’s take an example to understand the problem
Input: arr =[
   [4   6   1]
   [5   7   2]
   [3   8   9]
]
Output:[
   [4   10   11]
   [9   22   25]
   [12   33   45]
]
To solve this problem, one simple solution is finding prefixSum by traversing all elements till i,j position and add them. But it is a bit complex for the system.
A more effective solution will be using the formula for finding the values of elements of prefixSum matrix.
The general formula for element at ij position is
prefixSum[i][j] = prefixSum[i-1][j] + prefixSum[i][j-1] - prefixSum[i-1][j-1] + a[i][j]
Some specail cases are
For i = j = 0, prefixSum[i][j] = a[i][j]
For i = 0 and j > 0, prefixSum[i][j] = prefixSum[i][j-1] + a[i][j]
For i > 0 and j = 0, prefixSum[i][j] = prefixSum[i-1][j] + a[i][j]
The code to show the implementation of our solution
 Live Demo
#include <iostream>
using namespace std;
#define R 3
#define C 3
void printPrefixSum(int a[][C]) {
   int prefixSum[R][C];
   prefixSum[0][0] = a[0][0];
   for (int i = 1; i < C; i++)
   prefixSum[0][i] = prefixSum[0][i - 1] + a[0][i];
   for (int i = 0; i < R; i++)
   prefixSum[i][0] = prefixSum[i - 1][0] + a[i][0];
   for (int i = 1; i < R; i++) {
      for (int j = 1; j < C; j++)
      prefixSum[i][j]=prefixSum[i- 1][j]+prefixSum[i][j- 1]-prefixSum[i- 1][j- 1]+a[i][j];
   }
   for (int i = 0; i < R; i++) {
      for (int j = 0; j < C; j++)
      cout<<prefixSum[i][j]<<"\t";
      cout<<endl;
   }
}
int main() {
   int mat[R][C] = {
      { 1, 2, 3},
      { 4, 5, 6},
      { 7, 8, 9}
   };
   cout<<"The prefix Sum Matrix is :\n";
   printPrefixSum(mat);
   return 0;
}
The prefix Sum Matrix is :
1   3   6
5   12   21
12   27   45
jQuery UI Dialog buttons Option

19 Mar, 2021
jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Dialog buttons option is used to specify the buttons that should be displayed on the dialog. 
Syntax:
$( ".selector" ).dialog({
  buttons: [
    {
      text: "Ok",
      icon: "ui-icon-heart",
      click: function() {
        $( this ).dialog( "close" );
      }
    }
  ]
});
CDN Link: First, add jQuery UI scripts needed for your project.
<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>
Example:
HTML
<!doctype html><html lang="en">  <head>    <meta charset="utf-8">    <link href=    "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"    rel="stylesheet">      <script src="https://code.jquery.com/jquery-1.10.2.js"></script>      <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js">    </script>      <script>        $(function () {            $("#gfg").dialog({                autoOpen: false,                buttons: [                    {                        text: "Ok",                        click: function () {                            $(this).dialog("close");                        }                    }                ]            });            $("#geeks").click(function () {                $("#gfg").dialog("open");            });        });    </script></head>  <body style="text-align: center;">    <h1 style="color:green;">GeeksforGeeks</h1>    <h3>jQuery UI Dialog buttons Option</h3>      <button id="geeks">Open Dialog</button>      <div id="gfg" title="GeeksforGeeks">        Welcome to GeeksforGeeks    </div></body>  </html>
Output:
Reference: https://api.jqueryui.com/dialog/#option-buttons
HTML-Tags
jQuery-Methods
jQuery-UI
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to add options to a select element using jQuery?
jQuery | children() with Examples
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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 ?
Ruby redo and retry Statement

17 Sep, 2019
In Ruby, Redo statement is used to repeat the current iteration of the loop. redo always used inside the loop. The redo statement restarts the loop without evaluating the condition again.
# Ruby program of using redo statement  #!/usr/bin/rubyrestart = false  # Using for loopfor x in 2..20    if x == 15        if restart == false              # Printing values            puts "Re-doing when x = " + x.to_s            restart = true              # Using Redo Statement            redo        end    end    puts xend
Output:
2
3
4
5
6
7
8
9
10
11
12
13
14
Re-doing when x = 15
15
16
17
18
19
20
In above example, redo statement apply when x = 15.
To repeat the whole loop iteration from the start the retry statement is used. retry always used inside the loop.
Example #1:
# Ruby program of retry statement  # Using do loop10.times do |i|  begin    puts "Iteration #{i}"    raise if i > 2  rescue      # Using retry    retry  endend
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 3
Iteration 3
...
Example #2:
# Ruby program of retry statementdef geeks  attempt_again = true  p 'checking'  begin      # This is the point where the control flow jumps    p 'crash'    raise 'foo'      rescue Exception => e        if attempt_again          attempt_again = false        # Using retry      retry           end  endend
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Exceptional Split in String

22 Apr, 2020
Sometimes, while working with Strings, we may need to perform the split operation. The straight forward split is easy. But sometimes, we may have a problem in which we need to perform split on certain character but have exceptions. This discusses split on comma, with exception that comma should not be enclosed by brackets. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + strip()This is brute force way in which we perform this task. In this we construct the each element of list as words in String accounting for brackets and comma to perform split.
# Python3 code to demonstrate working of # Exceptional Split in String# Using loop + split()  # initializing stringtest_str = "gfg, is, (best, for), geeks"  # printing original stringprint("The original string is : " + test_str)  # Exceptional Split in String# Using loop + split()temp = ''res = []check = 0for ele in test_str:    if ele == '(':        check += 1    elif ele == ')':        check -= 1    if ele == ', ' and check == 0:        if temp.strip():            res.append(temp)        temp = ''    else:        temp += eleif temp.strip():    res.append(temp)  # printing result print("The string after exceptional split : " + str(res)) 
The original string is : gfg, is, (best, for), geeks
The string after exceptional split : ['gfg', ' is', ' (best, for)', ' geeks']

 
Method #2 : Using regex()This is yet another way in which this task can be performed. In this, we use a regex instead of manual brute force logic for brackets comma and omit that from getting split.
# Python3 code to demonstrate working of # Exceptional Split in String# Using regex()import re  # initializing stringtest_str = "gfg, is, (best, for), geeks"  # printing original stringprint("The original string is : " + test_str)  # Exceptional Split in String# Using regex()res = re.split(r', (?!\S\)|\()', test_str)  # printing result print("The string after exceptional split : " + str(res)) 
The original string is : gfg, is, (best, for), geeks
The string after exceptional split : ['gfg', ' is', ' (best, for)', ' geeks']

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Defaultdict in Python
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python Program for factorial of a number
Find One’s Complement of an Integer in C++

In this section, we will see how to find the 1’s complete of an integer. We can use the complement operator to do this task very fast, but it will make 32bit complemented value (4-bype integer). Here we want complement of n bit numbers.
Suppose we have a number say 22. The binary equivalent is 10110. The complemented value is 01001 which is same as 9. Now the question comes, how to find this value? At first we have to find number of bits of the given number. Suppose the count is c (here c = 5 for 22). We have to make 5 1s. So this will be 11111. To make this, we will shift 1 to the left c number of times, then subtract 1 from it. After shifting 1 to the left 5 times, it will be 100000, then subtract 1, so it will be 11111. After that perform XOR operation with the 11111 and 10110 to get the complement.
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int findComplement(int n) {
   int bit_count = floor(log2(n))+1;
   int ones = ((1 << bit_count) - 1);
   return ones ^ n;
}
int main() {
   int number = 22;
   cout << "One's Complement of " << number << " is: " << findComplement(number);
}
One's Complement of 22 is: 9
How can I install or enable innoDB in MySQL?

In order to enable innoDB in MySQ, you need to work around my.ini file. However, in MySQL version 8, the default storage engine is innoDB. Check the same from my.ini file −
You can even set this at the time of table creation −
mysql> create table DemoTable
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFirstName varchar(100),
   StudentLastName varchar(100),
   StudentAge int
   ) ENGINE=InnoDB;
Query OK, 0 rows affected (1.66 sec)
Let us now run a query to check the engine type of specific table −
mysql> select table_name,engine from information_schema.tables where table_name="DemoTable";
This will produce the following output −
+--------------+--------+
| TABLE_NAME   | ENGINE |
+--------------+--------+
| DemoTable    | InnoDB |
+--------------+--------+
1 row in set (0.16 sec)
C# | Math.Truncate() Method - GeeksforGeeks

02 Jul, 2021
In C#, Math.Truncate() is a math class method which is used to compute an integral part of a specified decimal number or double-precision floating-point number. This method can be overloaded by passing the different type of parameters to it as follows:
Math.Truncate(Decimal)
Math.Truncate(Double)
This method is used to compute an integral part of a specified decimal number.
Syntax: 
public static decimal Truncate(decimal dec)
Parameter:
dec: It is the specified number which is to be truncated and type of this parameter is System.Decimal.
Return Type: This method only return the integral part of dec and discard the fractional part. The type of this method is System.Decimal.
Example: 
C#
// C# Program to illustrate the// Math.Truncate(Decimal) Methodusing System;  class Geeks {      // Main Method    public static void Main()    {          // variables of Decimal type        Decimal dec = 45.89511m;        Decimal dec2 = 54569.478021m;          // using function and displaying result        Console.WriteLine(Math.Truncate(dec));        Console.WriteLine(Math.Truncate(dec2));    }}
Output: 
45
54569
This method is used to compute an integral part of a specified double precision floating point number.
Syntax: 
public static double Truncate(decimal dob)
Parameter:
dob: It is the specified number which is to be truncated and type of this parameter is System.Double.
Return Type: This method only returns an integral part of dob and discard the fractional part. The type of this method is System.Double.
Note: If dob is NaN, then method will return NaN value and If dob is PositiveInfinity, then method will return PositiveInfinity value. If dob is NegativeInfinity, then method will return NegativeInfinity value.
Example: 
C#
// C# Program to illustrate the// Math.Truncate(Double) Methodusing System;  class Geeks {      // Main Method    public static void Main()    {          // variables of Double type        Double dob = 45649.25649800;        Double dob2 = 2000150.2654459780;          // using function and displaying result        Console.WriteLine(Math.Truncate(dob));        Console.WriteLine(Math.Truncate(dob2));    }}
Output: 
45649
2000150
There can be other ways to truncate numbers like casting it to an int, but it does not always work. As compare to other Math methods, this is probably the most reliable way to perform the required tasks. 
sagartomar9927
CSharp-Math
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
Extension Method in C#
C# | Constructors
Introduction to .NET Framework
C# | Abstract Classes
C# | Class and Object
How to find similar words in vector of strings in R?

Sometimes strings in a vector of strings have spelling errors and we want to extract the similar words to avoid that spelling error because similar words are likely to represent the correct and incorrect form of a word. This can be done by using agrep with lapply function.
 Live Demo
x1<-c("India","United Kingdoms","Indiaa","Egyypt","United
Kingdom","Turkey","Egypt","Belaarus","Belarus")
lapply(x1,agrep,x1,value=TRUE)
[[1]]
[1] "India" "Indiaa"
[[2]]
[1] "United Kingdoms" "United Kingdom"
[[3]]
[1] "India" "Indiaa"
[[4]]
[1] "Egyypt" "Egypt"
[[5]]
[1] "United Kingdoms" "United Kingdom"
[[6]]
[1] "Turkey"
[[7]]
[1] "Egyypt" "Egypt"
[[8]]
[1] "Belaarus" "Belarus"
[[9]]
[1] "Belaarus" "Belarus"
 Live Demo
x2<-c("Alhadi","Umair","Omar","Alhadi","Shanti","Shant","Umaer","Peter","Rahul","Pattrick","P
eeter","Rahuls")
lapply(x2,agrep,x2,value=TRUE)
[[1]]
[1] "Al-hadi" "Alhadi"
[[2]]
[1] "Umair" "Umaer"
[[3]]
[1] "Omar"
[[4]]
[1] "Al-hadi" "Alhadi"
[[5]]
[1] "Shanti" "Shant"
[[6]]
[1] "Shanti" "Shant"
[[7]]
[1] "Umair" "Umaer"
[[8]]
[1] "Peter" "Peeter"
[[9]]
[1] "Rahul" "Rahuls"
[[10]]
[1] "Pattrick"
[[11]]
[1] "Peter" "Peeter"
[[12]]
[1] "Rahul" "Rahuls"
 Live Demo
x3<-c("Alabamaa","New Yorky","New
Yok","Alabma","Florida","Illinois","Texas","Illinoise")
lapply(x3,agrep,x3,value=TRUE)
[[1]]
[1] "Alabamaa"
[[2]]
[1] "New Yorky"
[[3]]
[1] "New Yorky" "New Yok"
[[4]]
[1] "Alabamaa" "Alabma"
[[5]]
[1] "Florida"
[[6]]
[1] "Illinois" "Illinoise"
[[7]]
[1] "Texas"
[[8]]
[1] "Illinois" "Illinoise"
How to call Private Constructor in Java

The method java.lang.Class.getDeclaredConstructor() can be used to obtain the constructor object for the private constructor of the class. The parameter for this method is a Class object array that contains the formal parameter types of the constructor.
A program that demonstrates this is given as follows −
 Live Demo
package Test;
import java.lang.reflect.*;
public class Demo {
   String str;
   Double d;
   public Demo(String str, Double d) {
      this.str = str;
      this.d = d;
   }
   public static void main(String[] args) {
      try {
         Demo obj = new Demo("Apple", 55.983);
         Class c = obj.getClass();
         Class[] arguments = new Class[2];
         arguments[0] = String.class;
         arguments[1] = Double.class;
         Constructor constructor = c.getDeclaredConstructor(arguments);
         System.out.println("Constructor = " + constructor.toString());
      } catch(NoSuchMethodException e) {
         System.out.println(e.toString());
      } catch(SecurityException e) {
         System.out.println(e.toString());
      }
   }
}
Constructor = public Test.Demo(java.lang.String,java.lang.Double)
Now let us understand the above program.
An object of class Demo is created in the main() method. Then the array arguments[] stores the String.Class and Double.Class objects. Finally, the method getDeclaredConstructor() can be used to obtain the constructor object and this is displayed. A code snippet which demonstrates this is as follows −
Demo obj = new Demo("Apple", 55.983);
Class c = obj.getClass();
Class[] arguments = new Class[2];
arguments[0] = String.class;
arguments[1] = Double.class;
Constructor constructor = c.getDeclaredConstructor(arguments);
System.out.println("Constructor = " + constructor.toString());
logb() function in C++ STL - GeeksforGeeks

18 Jul, 2018
The logb() is a builtin function in C++ STL which returns the logarithm of |x|, using FLT_RADIX as base for the logarithm. In general, the value of FLT_RADIX is 2, so logb() is equivalent to log2()(for positive values only).
Syntax:
logb(val)
Parameter: The function accepts a single mandatory parameter val which specifies the val whose logb() is to be calculated. The data-type can be of double, float, long double or int.
Return Type: The function returns the logarithm of |x|.
Below programs illustrate the above function:
Program 1:
// C++ program to illustrate// to implement logb() function// when data-type is integer#include <cmath>#include <iostream>using namespace std;int main(){    double result;    int x = -10;      result = logb(x);    cout << "logb(" << x << ") = "         << "log(|" << x << "|) = " << result << endl;      x = 10;      result = logb(x);    cout << "logb(" << x << ") = "         << "log(|" << x << "|) = " << result << endl;      return 0;}
logb(-10) = log(|-10|) = 3
logb(10) = log(|10|) = 3

Program2:
// C++ program to illustrate// to implement logb() function// when data-type is double#include <cmath>#include <iostream>  using namespace std;  int main(){    double x = 70.56, result;      result = logb(x);    cout << "logb(" << x << ") = "         << "log(|" << x << "|) = " << result << endl;      x = 17.6;      result = logb(x);    cout << "logb(" << x << ") = "         << "log(|" << x << "|) = " << result << endl;      return 0;}
logb(70.56) = log(|70.56|) = 6
logb(17.6) = log(|17.6|) = 4

Program3:
// C++ program to illustrate// to implement logb() function// when input is 0#include <cmath>#include <iostream>  using namespace std;  int main(){    double result;    int x = 0;      result = logb(x);    cout << "logb(" << x << ") = "         << "log(|" << x << "|) = " << result << endl;      return 0;}
logb(0) = log(|0|) = -inf

CPP-Functions
cpp-math
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Friend class and function in C++
Polymorphism in C++
List in C++ Standard Template Library (STL)
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
new and delete operators in C++ for dynamic memory
Destructors in C++
Queue in C++ Standard Template Library (STL)
How to subset an R data frame based on numerical and categorical column?

Subsetting is one of the commonly used technique which serves many different purposes
depending on the objective of analysis. To subset a data frame by excluding a column
with the help of dplyr package, we can follow the below steps −
Creating a data frame.
Subsetting the data frame based on numerical as well as categorical column at the
same time with the help of filter function of dplyr package.
Let's create a data frame as shown below −
 Live Demo
Level<-sample(c("Low","Medium","High"),20,replace=TRUE)
Score<-sample(1:10,20,replace=TRUE)
Dat<-data.frame(Level,Score)
Dat
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
  Level Score
1 High   4
2 Low    7
3 High   1
4 Medium 6
5 Medium 10
6 High   9
7 High 9
8 Low 3
9 Low 3
10 High 4
11 Low 5
12 Medium 3
13 High 8
14 High 10
15 High 5
16 Low 8
17 High 10
18 High 7
19 Low 10
20 Low 6
Loading dplyr package and subsetting Dat when Score column is greater than 5 and Level is equal to Low −
library(dplyr)
Level<-sample(c("Low","Medium","High"),20,replace=TRUE)
Score<-sample(1:10,20,replace=TRUE)
Dat<-data.frame(Level,Score)
Dat%>%filter(Score>5,Level=="Low")
 Level Score
1 Low 7
2 Low 8
3 Low 10
4 Low 6
Boolean Literals in Java

The Boolean literals have two values i.e. True and False.
The following is an example to display Boolean Literals.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      System.out.println("Boolean Literals");
      boolean one = true;
      System.out.println(one);
      one = false;
      System.out.println(one);
   }
}
Boolean Literals
true
false
In the above program, we have declared a boolean value and assigned the boolean literal “true”.
boolean one = true;
In the same way, we have added another boolean literal “false”.
one = false;
Both of the above values are displayed, which are the boolean literals.
Tryit Editor v3.7

Tryit: HTML color values
Ionic - Cordova Geolocation

This plugin is used for adding a geolocation plugin to the Ionic app.
There is a simple way to use the geolocation plugin. We need to install this plugin from the command prompt window.
C:\Users\Username\Desktop\MyApp>cordova plugin add cordova-plugin-geolocation

The following controller code is using two methods. The first one is the getCurrentPosition method and it will show us the current latitude and longitude of the user’s device. The second one is the watchCurrentPosition method that will return the current position of the device when the position is changed.
.controller('MyCtrl', function($scope, $cordovaGeolocation) {
   var posOptions = {timeout: 10000, enableHighAccuracy: false};
   $cordovaGeolocation
   .getCurrentPosition(posOptions)
	
   .then(function (position) {
      var lat  = position.coords.latitude
      var long = position.coords.longitude
      console.log(lat + '   ' + long)
   }, function(err) {
      console.log(err)
   });

   var watchOptions = {timeout : 3000, enableHighAccuracy: false};
   var watch = $cordovaGeolocation.watchPosition(watchOptions);
	
   watch.then(
      null,
		
      function(err) {
         console.log(err)
      },
	   function(position) {
         var lat  = position.coords.latitude
         var long = position.coords.longitude
         console.log(lat + '' + long)
      }
   );

   watch.clearWatch();
})
You might have also noticed the posOptions and watchOptions objects. We are using timeout to adjust maximum length of time that is allowed to pass in milliseconds and enableHighAccuracy is set to false. It can be set to true to get the best possible results, but sometimes it can lead to some errors. There is also a maximumAge option that can be used to show how an old position is accepted. It is using milliseconds, the same as timeout option.
When we start our app and open the console, it will log the latitude and longitude of the device. When our position is changed, the lat and long values will change.

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    185 Lectures 
     46.5 hours 

 Nikhil Agarwal
 Print
 Add Notes
 Bookmark this page
How to change backends in Matplotlib?

We can override the backend value using atplotlib.rcParams['backend'] variable.
Using get_backend() method, return the name of the current backend, i.e., default name.
Using get_backend() method, return the name of the current backend, i.e., default name.
Now override the backend name.
Now override the backend name.
Using get_backend() method, return the name of the current backend, i.e., updated name.
Using get_backend() method, return the name of the current backend, i.e., updated name.
import matplotlib
print("Before, Backend used by matplotlib is: ", matplotlib.get_backend())
matplotlib.rcParams['backend'] = 'TkAgg'
print("After, Backend used by matplotlib is: ", matplotlib.get_backend())
Before, Backend used by matplotlib is: GTK3Agg
After, Backend used by matplotlib is: TkAgg
Enter number of bars: 5
Tryit Editor v3.7

RWD Media Queries
Tryit: Typical media query breakpoints
Groovy - Logical Operators

Logical operators are used to evaluate Boolean expressions. Following are the logical operators available in Groovy −
The following code snippet shows how the various operators can be used.
class Example { 
   static void main(String[] args) { 
      boolean x = true; 
      boolean y = false; 
      boolean z = true; 
		
      println(x&&y); 
      println(x&&z); 
		
      println(x||z); 
      println(x||y); 
      println(!x); 
   } 
}
When we run the above program, we will get the following result. It can be seen that the results are as expected from the description of the operators as shown above.
false 
true 
true 
true 
false


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Check if a HashSet contains the specified element in C#

To check if a HashSet contains the specified element, the code is as follows −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      HashSet<int> set1 = new HashSet<int>();
      set1.Add(25);
      set1.Add(50);
      set1.Add(75);
      set1.Add(100);
      set1.Add(125);
      set1.Add(150);
      Console.WriteLine("Elements in HashSet1");
      foreach(int val in set1){
         Console.WriteLine(val);
      }
      HashSet<int> set2 = new HashSet<int>();
      set2.Add(30);
      set2.Add(60);
      set2.Add(100);
      set2.Add(150);
      set2.Add(200);
      set2.Add(250);
      Console.WriteLine("Elements in HashSet2");
      foreach(int val in set2){
         Console.WriteLine(val);
      }
      Console.WriteLine("Do they share common elements? "+set1.Overlaps(set2));
      Console.WriteLine("Does HashSet1 has element 60? "+set1.Contains(60));
      Console.WriteLine("Does HashSet2 has element 60? "+set2.Contains(60));
   }
}
This will produce the following output −
Elements in HashSet1
25
50
75
100
125
150
Elements in HashSet2
30
60
100
150
200
250
Do they share common elements? True
Does HashSet1 has element 60? False
Does HashSet2 has element 60? True
 Live Demo
Let us now see another example;
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      HashSet<string> hashSet = new HashSet<string>();
      hashSet.Add("Tim");
      hashSet.Add("Jack");
      hashSet.Add("Matt");
      hashSet.Add("Steve");
      hashSet.Add("David");
      hashSet.Add("Kane");
      hashSet.Add("Gary");
      Console.WriteLine("Elements in HashSet");
      foreach(string val in hashSet){
         Console.WriteLine(val);
      }
      if (hashSet.Contains("Matt"))
         Console.WriteLine("The element Matt is in the HashSet");
      else
         Console.WriteLine("The element Matt is not in the HashSet");
   }
}
This will produce the following output −
Elements in HashSet
Tim
Jack
Matt
Steve
David
Kane
Gary
The element Matt is in the HashSet
How to add legend to imshow() in Matplotlib?

To add legend to imshow() in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create random data using numpy.
Initialize a color map.
Get the unique data points from sample data, step 2.
Plot each color with different labels and color, to place on the legend.
Place a legend at the upper right corner within a box.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt, cm

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = np.random.rand(3, 3)
cmap = cm.YlOrBr
unique_data = np.unique(data)
i = 0

for entry in unique_data:
   mycolor = cmap(entry * 255 / (max(unique_data) - min(unique_data)))
   plt.plot(0, 0, "-", color=mycolor, label="%d"%i)
   i += 1

plt.imshow(data, cmap=cmap)
plt.legend(loc="upper right", bbox_to_anchor=(1.25, 1.0))

plt.show()
Can we use "this" keyword in a static method in java?

The static methods belong to the class and they will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as reference).
public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Contents of the static method");
   }
   public static void main(String args[]){
      Sample.demo();
   }
}
Contents of the static method
The "this" keyword is used as a reference to an instance. Since the static methods doesn’t have (belong to) any instance you cannot use the "this" reference within a static method. If you still, try to do so a compile time error is generated.
public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Contents of the static method"+this.num);
   }
   public static void main(String args[]){
      Sample.demo();
   }
}
Sample.java:4: error: non-static variable this cannot be referenced from a static context
   System.out.println("Contents of the static method"+this.num);
                                                      ^
1 error
C++ Program to Solve Knapsack Problem Using Dynamic Programming

This is a C++ program to solve 0-1 knapsack problem using dynamic programming. In 0-1 knapsack problem, a set of items are given, each with a weight and a value. We need to determine the number of each item to include in a collection so that the total weight is less than or equal to the given limit and the total value is large as possible.
Begin
Input set of items each with a weight and a value
Set knapsack capacity
Create a function that returns maximum of two integers.
Create a function which returns the maximum value that can be put in a knapsack of capacity W
int knapSack(int W, int w[], int v[], int n)
int i, wt;
int K[n + 1][W + 1]
for i = 0 to n
for wt = 0 to W
if (i == 0 or wt == 0)
   Do K[i][wt] = 0
else if (w[i - 1] <= wt)
   Compute: K[i][wt] = max(v[i - 1] + K[i - 1][wt - w[i - 1]], K[i -1][wt])
else
   K[i][wt] = K[i - 1][wt]
   return K[n][W]
   Call the function and print.
End
#include <iostream>
using namespace std;
int max(int x, int y) {
   return (x > y) ? x : y;
}
int knapSack(int W, int w[], int v[], int n) {
   int i, wt;
   int K[n + 1][W + 1];
   for (i = 0; i <= n; i++) {
      for (wt = 0; wt <= W; wt++) {
         if (i == 0 || wt == 0)
         K[i][wt] = 0;
         else if (w[i - 1] <= wt)
            K[i][wt] = max(v[i - 1] + K[i - 1][wt - w[i - 1]], K[i - 1][wt]);
         else
        K[i][wt] = K[i - 1][wt];
      }
   }
   return K[n][W];
}
int main() {
   cout << "Enter the number of items in a Knapsack:";
   int n, W;
   cin >> n;
   int v[n], w[n];
   for (int i = 0; i < n; i++) {
      cout << "Enter value and weight for item " << i << ":";
      cin >> v[i];
      cin >> w[i];
   }
   cout << "Enter the capacity of knapsack";
   cin >> W;
   cout << knapSack(W, w, v, n);
   return 0;
}
Enter the number of items in a Knapsack:4
Enter value and weight for item 0:10
50
Enter value and weight for item 1:20
60
Enter value and weight for item 2:30
70
Enter value and weight for item 3:40
90
Enter the capacity of knapsack100
40
Aggregate Functions in DBMS

Aggregate functions in DBMS take multiple rows from the table and return a value according to the query.
All the aggregate functions are used in Select statement.
Syntax − 
SELECT <FUNCTION NAME> (<PARAMETER>) FROM <TABLE NAME>
This function returns the average value of the numeric column that is supplied as a parameter.
Example: Write a query to select average salary from employee table.
Select AVG(salary) from Employee
The count function returns the number of rows in the result. It does not count the null values.
Example: Write a query to return number of rows where salary > 20000.
Select COUNT(*) from Employee where Salary > 20000;
Types −
COUNT(*): Counts all the number of rows of the table including null.
COUNT(*): Counts all the number of rows of the table including null.
COUNT( COLUMN_NAME): count number of non-null values in column.
COUNT( COLUMN_NAME): count number of non-null values in column.
COUNT( DISTINCT COLUMN_NAME): count number of distinct values in a column.
COUNT( DISTINCT COLUMN_NAME): count number of distinct values in a column.
The MAX function is used to find maximum value in the column that is supplied as a parameter. It can be used on any type of data.
Example − Write a query to find the maximum salary in employee table.
Select MAX(salary) from Employee
This function sums up the values in the column supplied as a parameter.
Example: Write a query to get the total salary of employees.
Select SUM(salary) from Employee
The STDDEV function is used to find standard deviation of the column specified as argument.
Example − Write a query to find standard deviation of salary in Employee table.
Select STDDEV(salary) from Employee
The VARIANCE Function is used to find variance of the column specified as argument.
Example −
Select VARIANCE(salary) from Employee
Convert an int to ASCII character in C/C++

In C or C++ the character values are stored as ASCII values. To convert int to ASCII we can add the ASCII of character ‘0’ with the integer. Let us see an example to convert int to ASCII values.
#include<stdio.h>
int intToAscii(int number) {
   return '0' + number;
}
main() {
   printf("The ASCII of 5 is %d\n", intToAscii(5));
   printf("The ASCII of 8 is %d\n", intToAscii(8));
}
The ASCII of 5 is 53
The ASCII of 8 is 56
SAS - DO Index Loop

This DO Index loop uses a index variable for its start and end value. The SAS statements are repeatedly executed until the final value of the index variable is reached.
DO indexvariable = initialvalue to finalvalue ;
. . . SAS statements . . . ;
END;

DATA MYDATA1;
SUM = 0;
DO VAR = 1 to 5;
   SUM = SUM+VAR;
END;

PROC PRINT DATA = MYDATA1;
RUN;
When the above code is executed, it produces the following result



    50 Lectures 
     5.5 hours 

 Code And Create

    124 Lectures 
     30 hours 

 Juan Galvan

    162 Lectures 
     31.5 hours 

 Yossef Ayman Zedan

    35 Lectures 
     2.5 hours 

 Ermin Dedic

    167 Lectures 
     45.5 hours 

 Muslim Helalee
 Print
 Add Notes
 Bookmark this page
Python | Find yesterday's, today's and tomorrow's date - GeeksforGeeks

17 Dec, 2019
Prerequisites: datetime module
We can handle Data objects by importing the module datetime and timedelta to work with dates.
datetime module helps to find the present day by using the now() or today() method.
timedelta class from datetime module helps to find the previous day date and next day date.
Syntax for timedelta:
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
timedelta class is used because manipulating the date directly with increment and decrement will lead to a false Date. For example, if the present date is 31th of December, incrementing the date directly will only lead to the 32nd of December which is false. If we want to manipulate the Date directly first we have check day month and year combined and them increment accordingly. But, all this mess can be controlled by using timedelta class.
Syntax to find a present-day date:
datetime.now()
Returns: A datetime object containing the current local date and time.
Syntax to find a previous-day and next-day date:
previous-day = datetime.now()-timedelta(1)
next-day = datetime.now()+timedelta(1)
Example:
# Python program to find yesterday,# today and tomorrow    # Import datetime and timedelta# class from datetime modulefrom datetime import datetime, timedelta    # Get today's datepresentday = datetime.now() # or presentday = datetime.today()  # Get Yesterdayyesterday = presentday - timedelta(1)  # Get Tomorrowtomorrow = presentday + timedelta(1)    # strftime() is to format date according to# the need by converting them to stringprint("Yesterday = ", yesterday.strftime('%d-%m-%Y'))print("Today = ", presentday.strftime('%d-%m-%Y'))print("Tomorrow = ", tomorrow.strftime('%d-%m-%Y'))
Yesterday =  10-12-2019
Today =  11-12-2019
Tomorrow =  12-12-2019

Python datetime-program
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python Classes and Objects
Array class in C++

Array class in C++ are efficient enough and also it knows its own size.
size() = To return the size of array i.e. returns the no of elements of the array.
max_size() = To return maximum number of elements of the array.
get(), at(), operator[] = To get access of the array elements.
front() = To return front element of the array.
back() = To return last element of the array.
empty() = Returns true if array size is true otherwise false.
fill() = To fill the entire array with a particular value.
swap() = To swap the elements of one array to another.
Here is an example to implements all the operations as mentioned above −
#include<iostream>
#include<array>
using namespace std;

int main() {
   array<int,4>a = {10, 20, 30, 40};
   array<int,4>a1 = {50, 60, 70, 90};
   cout << "The size of array is : ";
   //size of the array using size()
   cout << a.size() << endl;
   //maximum no of elements of the array
   cout << "Maximum elements array can hold is : ";
   cout << a.max_size() << endl;
   // Printing array elements using at()
   cout << "The array elements are (using at()) : ";
   for ( int i=0; i<4; i++)
      cout << a.at(i) << " ";
      cout << endl;
   // Printing array elements using get()
   cout << "The array elements are (using get()) : ";
   cout << get<0>(a) << " " << get<1>(a) << " "<<endl;
   cout << "The array elements are (using operator[]) : ";
   for ( int i=0; i<4; i++)
      cout << a[i] << " ";
      cout << endl;
   // Printing first element of array
   cout << "First element of array is : ";
   cout << a.front() << endl;
   // Printing last element of array
   cout << "Last element of array is : ";
   cout << a.back() << endl;
   cout << "The second array elements before swapping are : ";
   for (int i=0; i<4; i++)
      cout << a1[i] << " ";
      cout << endl;
   // Swapping a1 values with a
   a.swap(a1);
   // Printing 1st and 2nd array after swapping
   cout << "The first array elements after swapping are : ";
   for (int i=0; i<4; i++)
      cout << a[i] << " ";
      cout << endl;
      cout << "The second array elements after swapping are : ";
   for (int i = 0; i<4; i++)
      cout << a1[i] << " ";
      cout << endl;
   // Checking if it is empty
   a1.empty()? cout << "Array is empty":
   cout << "Array is not empty";
   cout << endl;
   // Filling array with 1
   a.fill(1);
   // Displaying array after filling
   cout << "Array content after filling operation is : ";
   for ( int i = 0; i<4; i++)
      cout << a[i] << " ";
      return 0;
}
The size of array is : 4
Maximum elements array can hold is : 4
The array elements are (using at()) : 10 20 30 40
The array elements are (using get()) : 10 20
The array elements are (using operator[]) : 10 20 30 40
First element of array is : 10
Last element of array is : 40
The second array elements before swapping are : 50 60 70 90
The first array elements after swapping are : 50 60 70 90
The second array elements after swapping are : 10 20 30 40
Array is not empty
Array content after filling operation is : 1 1 1 1
What is String Title case in C#?

The ToTitleCase method is used to capitalize the first letter in a word. Title case itself means to capitalize the first letter of each major word.
Let us see an example to get the title case −
 Live Demo
using System;
using System.Globalization;

class Demo {
   static void Main() {
      string str = "jack sparrow";
      string res = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str);
      Console.WriteLine(res);
   }
}
Jack Sparrow
Above, we have set the input string to the ToTitleCase() method. The CultureInfo.TextInfo property is used to provide the culture-specific casing information for strings −
CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str);
A C/C++ Function Call Puzzle - GeeksforGeeks

06 Jul, 2021
Consider the following program. Predict the output of it when compiled with C and C++ compilers.
C
void func(){    /* definition */} int main(){    func();    func(2);}
The above program compiles fine in C, but doesn’t compile in C++.
In C++, func() is equivalent to func(void) In C, func() is equivalent to func(...)
Refer this for details and this for more programs that compile in C, but not in C++.
This article is compiled by Rahul Mittalal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
singhbishalkumarsingh
CPP-Functions
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Command line arguments in C/C++
rand() and srand() in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Exception Handling in C++
Vector in C++ STL
Inheritance in C++
Iterators in C++ STL
Initialize a vector in C++ (6 different ways)
Socket Programming in C/C++
GATE | GATE CS 2013 | Question 65

10 Sep, 2021
What is the maximum number of reduce moves that can be taken by a bottom-up parser for a grammar with no epsilon- and unit-production (i.e., of type A -> є and A -> a) to parse a string with n tokens?(A) n/2(B) n-1(C) 2n-1(D) 2nAnswer: (B)Explanation: Given in the question, a grammar with no epsilon- and unit-production (i.e., of type A -> є and A -> a).
To get maximum number of Reduce moves, we should make sure than in each sentential form only one terminal is reduced. Since there is no unit production, so last 2 tokens will take only 1 move.
So To Reduce input string of n tokens, first Reduce n-2 tokens using n-2 reduce moves and then Reduce last 2 tokens using production which has . So total of n-2+1 = n-1 Reduce moves.
Suppose the string is abcd. ( n = 4 ).
We can write the grammar which accepts this string as follows:
S->aB
B->bC
C->cd 
The Right Most Derivation for the above is:
S -> aB ( Reduction 3 )
-> abC ( Reduction 2 )
-> abcd ( Reduction 1 )
We can see here that no production is for unit or epsilon. Hence 3 reductions here.
We can get less number of reductions with some other grammar which also does’t produce unit or epsilon productions,
S->abA
A-> cd
The Right Most Derivation for the above as:
S -> abA ( Reduction 2 )
-> abcd ( Reduction 1 )
Hence 2 reductions.
But we are interested in knowing the maximum number of reductions which comes from the 1st grammar. Hence total 3 reductions as maximum, which is ( n – 1) as n = 4 here.
Thus, Option B.
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Sn5eIxvrNBc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
Ankit87
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE-CS-2001 | Question 50
GATE | Gate IT 2005 | Question 52
Difference between Iterators and Pointers in C/C++ with Examples - GeeksforGeeks

04 Aug, 2021
Pointer: A pointer is a variable which contains the address of another variable, i.e., address of the memory location of the variable. Like any variable or constant, we must declare a pointer before using it to store any variable address.Syntax:  
type* var_name;
Example: 
C
// The output of this program can be different// in different runs. Note that the program// prints address of a variable and a variable// can be assigned different address in different// runs.#include <stdio.h> int main(){    int x;     // Prints address of x    printf("%p", &x);     return 0;}
0x7ffcac5ae824
 
Iterator: An iterator is any object that, pointing to some element in a range of elements (such as an array or a container), has the ability to iterate through the elements of that range. Syntax:  
type_container :: iterator var_name;
Example: 
CPP
// C++ program to demonstrate iterators#include <iostream>#include <vector>using namespace std;int main(){    // Declaring a vector    vector<int> v = { 1, 2, 3 };     // Declaring an iterator    vector<int>::iterator i;     int j;     cout << "Without iterators = ";     // Accessing the elements without using iterators    for (j = 0; j < 3; ++j) {        cout << v[j] << " ";    }     cout << "\nWith iterators = ";     // Accessing the elements using iterators    for (i = v.begin(); i != v.end(); ++i) {        cout << *i << " ";    }     // Adding one more element to vector    v.push_back(4);     cout << "\nWithout iterators = ";     // Accessing the elements without using iterators    for (j = 0; j < 4; ++j) {        cout << v[j] << " ";    }     cout << "\nWith iterators = ";     // Accessing the elements using iterators    for (i = v.begin(); i != v.end(); ++i) {        cout << *i << " ";    }     return 0;}
Without iterators = 1 2 3 
With iterators = 1 2 3 
Without iterators = 1 2 3 4 
With iterators = 1 2 3 4
 
Difference between Iterators and Pointers: Iterators and pointers are similar in that we can dereference them to get a value. However, there are key differences as follows: 
 
hp21
varshagumber28
C-Pointers
cpp-iterator
cpp-pointer
Pointers
C Language
C++
Difference Between
Pointers
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
rand() and srand() in C/C++
Substring in C++
fork() in C
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Virtual Function in C++