code-rag-bench/online-tutorials huggingface dataset:
HTML canvas clearRect() Method

The clearRect() method in HTML canvas is used to clear the pixels in a given rectangle. The <canvas> element allows you to draw graphics on a web page using JavaScript. Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively.
Following is the syntax −
ctx.clearRect(p,q,width,height);
Above,
p: The x-coordinate of the upper-left corner of the rectangle to clear
q: The y-coordinate of the upper-left corner of the rectangle to clear
width: Width of the rectangle to clear
height: Height of the rectangle to clear
Let us now see an example to implement the clearRect() method of canvas−
 Live Demo
<!DOCTYPE html>
<html>
<body>
<canvas id="newCanvas" width="500" height="350" style="border:2px solid blue;">
</canvas>
<script>
var c = document.getElementById("newCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "gray";
ctx.fillRect(0, 0, 500, 350);
ctx.clearRect(250, 100, 50, 100);
</script>
</body>
</html>
How to do conditional update in MongoDB?

Use update() for conditional update in MongoDB. Let us first create a collection with documents −
> db.demo402.insertOne({id:101,"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e61214efac4d418a0178585")
}
> db.demo402.insertOne({id:102,"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e612150fac4d418a0178586")
}
> db.demo402.insertOne({id:103,"Name":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e612152fac4d418a0178587")
}
Display all documents from a collection with the help of find() method −
> db.demo402.find();
This will produce the following output −
{ "_id" : ObjectId("5e61214efac4d418a0178585"), "id" : 101, "Name" : "Chris" }
{ "_id" : ObjectId("5e612150fac4d418a0178586"), "id" : 102, "Name" : "David" }
{ "_id" : ObjectId("5e612152fac4d418a0178587"), "id" : 103, "Name" : "Mike" }
Following is the query to perform conditional update in MongoDB −
> db.demo402.update({id:102},
... {
...    $set: { Name: "Robert" }
... },
... {upsert: true }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo402.find();
This will produce the following output −
{ "_id" : ObjectId("5e61214efac4d418a0178585"), "id" : 101, "Name" : "Chris" }
{ "_id" : ObjectId("5e612150fac4d418a0178586"), "id" : 102, "Name" : "Robert" }
{ "_id" : ObjectId("5e612152fac4d418a0178587"), "id" : 103, "Name" : "Mike" }
C# program to get max occurred character in a String

To get the maximum occurred character in a string, loop until the length of the given string and find the occurrence.
With that, set a new array to calculate −
for (int i = 0; i < s.Length; i++)
   a[s[i]]++;
}
The values we used above −
String s = "livelife!";
int[] a = new int[maxCHARS];
Now display the character and the occurrence −
for (int i = 0; i < maxCHARS; i++)
   if (a[i] > 1) {
      Console.WriteLine("Character " + (char) i);
      Console.WriteLine("Occurrence = " + a[i] + " times");
   }
Let us see the complete code −
 Live Demo
using System;

class Program {

   static int maxCHARS = 256;

   static void display(String s, int[] a) {
      for (int i = 0; i < s.Length; i++)
      a[s[i]]++;
   }

   public static void Main() {
      String s = "livelife!";
      int[] a = new int[maxCHARS];
      display(s, a);
   
      for (int i = 0; i < maxCHARS; i++)
      if (a[i] > 1) {
         Console.WriteLine("Character " + (char) i);
         Console.WriteLine("Occurrence = " + a[i] + " times");
      }
   }
}
Character e
Occurrence = 2 times
Character i
Occurrence = 2 times
Character l
Occurrence = 2 times
How to plot two dotted lines and set marker using Matplotlib?

In this program, we will plot two lines using the matplot library. Before starting to code, we need to first import the matplotlib library using the following command −
Import matplotlib.pyplot as plt
Pyplot is a collection of command style functions that make matplotlib work like MATLAB.
Step 1: Import matplotlib.pyplot
Step 2: Define line1 and line2 points.
Step 3: Plot the lines using the plot() function in pyplot.
Step 4: Define the title, X-axis, Y-axis.
Step 5: Display the plots using the show() function.
import matplotlib.pyplot as plt

line1_x = [10,20,30]
line1_y = [20,40,10]

line2_x = [10,20,30]
line2_y= [40,10,30]

plt.xlabel('X AXIS')
plt.ylabel('Y AXIS')

plt.plot(line1_x ,line1_y , color='blue', linewidth = 3, label = 'line1-dotted',linestyle='dotted')
plt.plot(line2_x ,line2_y, color='red', linewidth = 5, label = 'line2-dashed', linestyle='dotted')

plt.title("PLOTTING DOTTED LINES")
plt.legend()

plt.show()
The variables line1_x, line_y and line2_x, line2_y are the coordinates of our lines. The linewidth parameter in the plot function is basically the width/thickness of the line we are plotting. The plt.legend() function in the program is used to place legends like x-axis, y-axis names on the graph.
Tk - Mega Widgets

Mega widgets include many complex widgets which is often required in some large scale Tk applications. The list of available mega widgets are as shown below −
Widget for displaying dialog boxes.
Widget that allows users to choose numbers.
Widget that combines an entry with a list of choices available to the use.
Tabbed widget that helps to switch between one of several pages, using an index tab.
Widget to provide visual feedback to the  progress of a long operation like file upload.
Widget to display and allow browsing through a hierarchy of items more in form of tree.
Scrolling widgets without a text or canvas widgets.
Scale widget to choose a numeric value through sliders.
A simple Tk example is shown below using some mega widgets.
#!/usr/bin/wish

ttk::treeview .tree -columns "Creator Year" -displaycolumns "Year Creator" 
.tree heading Creator -text "Creator" -anchor center
.tree heading Year -text "Year" -anchor center
pack .tree
.tree insert {} end -id Languages -text "Languages"
.tree insert Languages end -text C -values [list "Dennis Ritchie" "1990"]
proc scaleMe {mywidget scaleValue} {
   $mywidget configure -length $scaleValue
} 
pack [scale .s2  -from 100.0 -to 200.0 -length 100 -background yellow -borderwidth 5
   -font{Helvetica -18 bold} -foreground red -width 40 -relief ridge -orien horizontal
   -variable a -command "scaleMe .s2" ]
pack [ttk::progressbar .p1 -orient horizontal -length 200 -mode indeterminate -value 90]
pack [ttk::progressbar .p2 -orient horizontal -length 200 -mode determinate -variable a
   -maximum 75 -value 20]
When we run the above program, we will get the following output −
 Print
 Add Notes
 Bookmark this page
How to Fix Race Condition using Atomic Functions in Golang? - GeeksforGeeks

19 May, 2020
Two or more processes executing in a system with an illusion of concurrency and accessing shared data may try to change the shared data at the same time. This condition in the system is known as a race condition. To see the sample code for Race Condition in Golang, you can refer to this article.Atomic package in Golang provides the low-level locking mechanisms for synchronizing access to pointers and integers etc. The atomic/sync package functions are used to fix the race condition.
Example:
// Golang program to fix the race// condition using atomic packagepackage main  import (    "fmt"    "runtime"    "sync"    "sync/atomic")  // All goroutines will increment  variable c// waitgroup is waiting for the completion// of program.var (    c         int32    waitgroup sync.WaitGroup)  func main() {      // with the help of Add() function add    // one for each goroutine    // a count of total 3    waitgroup.Add(3)      // increment with the help    // of increment() function    go increment("geeks")    go increment("for")    go increment("geeks")      // waiting for completion    // of goroutines.    waitgroup.Wait()      // print the counter    fmt.Println("Counter:", c)  }  func increment(name string) {      // Done() function used    // to tell that it is done.    defer waitgroup.Done()      for range name {          // Atomic Functions        // for fix race condition        atomic.AddInt32(&c, 1)          // enter thread in the line by line        runtime.Gosched()    }}
Output:
Counter: 13

Here, you can see we are using atomic.AddInt32() function to synchronize the addition of the integer values so that only one goroutine is allowed to complete the add operation at a time. Remember one thing, always check the output of such a program using the online compiler as you might get the same output every time(means no race condition) due to the deterministic nature. So use the local compiler like Visual Studio or CMD to see the results.
Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Formatting in Golang
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Golang Maps
Arrays in Go
Slices in Golang
How to convert a string in lower case in Golang?
How to compare times in Golang?
How to Trim a String in Golang?
Inheritance in GoLang
Tryit Editor v3.7

Tryit: HTML elements can also refer to more than one class
Reluctant quantifiers Java Regular expressions

Greedy quantifiers are the default quantifiers. A greedy quantifier matches as much as possible from the input string (longest match possible) if match not occurred it leaves the last character and matches again.
Whereas a reluctant or, non-greedy quantifier matches as little as possible, initially the non-greedy quantifier matches the first character if match not occurred it adds another character from the input string and tries to match.
If you place a "?" after a greedy quantifier it becomes reluctant or non-greedy quantifier. Following is the list of reluctant quantifiers −
 Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[0-9]+?";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      while (matcher.find()) {
         System.out.print("Pattern found from " + matcher.start()+ " to " + (matcher.end()-1)+"::");
         System.out.print(matcher.group());
         System.out.println();
      }
   }
}
Enter input text:
12345678
Pattern found from 0 to 0::1
Pattern found from 1 to 1::2
Pattern found from 2 to 2::3
Pattern found from 3 to 3::4
Pattern found from 4 to 4::5
Pattern found from 5 to 5::6
Pattern found from 6 to 6::7
Pattern found from 7 to 7::8
Clojure - Loop Statement

The loop special form is not like a ‘for’ loop. The usage of loop is the same as the let binding. However, loop sets a recursion point. The recursion point is designed to use with recur, which means loop is always used with recur. To make a loop happen, the number of arguments (arity) specified for recurs must coincide with the number of bindings for the loop. That way, recur goes back to the loop.
Following is the general syntax of the loop statement.
loop [binding]
(condition
   (statement)
   (recur (binding)))

Following is the diagrammatic representation of this loop.
Following is an example of a ‘for-in’ statement.
(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello World
(defn Example []
   (loop [x 10]
      (when (> x 1)
         (println x)
         (recur (- x 2))))) 
(Example)
In the above example, we are first binding the value of ‘x’ to 10 using the loop statement. We then use the when condition clause to see if the value of ‘x’ is less than 1. We then print the value of ‘x’ to the console and use the recur statement to repeat the loop. The loop is repeated after the value of ‘x’ is decremented by 2.
The above code produces the following output.
10
8
6
4
2

 Print
 Add Notes
 Bookmark this page
How to Install Scipy in Python on Windows? - GeeksforGeeks

09 Sep, 2021
Scipy is a python library that is useful in solving many mathematical equations and algorithms. It is designed on the top of Numpy library that gives more extension of finding scientific mathematical formulae like Matrix Rank, Inverse, polynomial equations, LU Decomposition, etc. Using its high-level functions will significantly reduce the complexity of the code and helps in better analyzing the data.
In this article, we will look into various methods of installing Scipy library on Windows.
The only thing that you need for installing Scipy module on Windows are:
Python 
PIP or Conda (depending upon user preference)
If you want the installation to be done through conda, you can use the below command:
conda install scipy
Type y for yes when prompted.
You will get a similar message once the installation is complete
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
Users who prefer to use pip can use the below command to install Scipy package on Windows:
pip install scipy
You will get a similar message once the installation is complete:
Note: As you can see in the above image, there are a couple of dependencies that are not resolved. This can be resolved by upgrading the PIP using the below command for proper functioning of Scipy library:
python --upgrade pip
pip install --use-feature=2020-resolver
To verify if Scipy has been successfully installed in your system run the below code in a python IDE of your choice:
Python3
import scipyscipy.__version__
If successfully installed you will get the following output.
Blogathon-2021
how-to-install
Picked
Python-scipy
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Import JSON Data into SQL Server?
How to Install Tkinter in Windows?
SQL - Multiple Column Ordering
How to pass data into table from a form using React Components
How to Create a Table With Multiple Foreign Keys in SQL?
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
How do you pass a command line argument in Java program?

After writing a Java program you need to compile it using the command javac and run it using the command java. Consider the following code −
public class Sample{
   public static void main(String[] args){
      int a = 20;
      int b = 30;
      int c = a+b;
      System.out.println("Sum of the two numbers is "+c);
   }
}
You can compile and run it from the command line as shown below −
Here, we are hard coding (fixing to a specific value) the values of a and b which is not recommendable. To handle this, you can accept parameters from the user using classes from I/O package or Scanner.
Another way is to use command line arguments.
The main method accepts an array of values of the type String Java from the user.
public class{
   public static void main(String[] args){
   }
}
You can pass them at the time of execution right after the class name separated with spaces as −
java ClassName 10 20 30
In the following Java program, we are accepting two integer values from the command line. And, we are extracting these two from the String array in the main method and converting them to integer −
public class Sample{
   public static void main(String[] args){
      int a = Integer.parseInt(args[0]);
      int b = Integer.parseInt(args[1]);
      int c = a+b;
      System.out.println("Sum of the two numbers is "+c);
   }
}
You can compile and, run the program by passing the values at execution line through command prompt as shown below −
C# Hexadecimal ("X") Format Specifier

The hexadecimal ("X") format specifier is used to convert a number to a string of hexadecimal digits.
Set the case of the format specifier for uppercase or lowercase characters to be worked on hexadecimal digits greater than 9.
Let us understand this with an example −
“X” for PQR, whereas “x” for pqr
 Live Demo
using System;
using System.Numerics;
using System.Globalization;
class Demo {
   static void Main() {
      int num;
      num = 345672832;
      Console.WriteLine(num.ToString("X"));
      Console.WriteLine(num.ToString("X2"));
      num = 0x307e;
      Console.WriteLine(num.ToString("x"));
      Console.WriteLine(num.ToString("X"));
   }
}
149A8C80
149A8C80
307e
307E
How to resolve - Relative path is not supported in PowerShell DSC?

“Relative path is not supported” error generally occurs with the PowerShell DSC when we download a file from online or Website and we use “File” DscResource for that.
In the below example, we are downloading the PowerShell 7.1.4 version from GitHub using DSC to the local computer and we get the error below.
Configuration FileCopy{
   Node LocalHost{

      File CopyFromBlob{
         SourcePath = "https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/PowerShell-7.1.4-win-x86.msi"
         DestinationPath = "C:\Temp\"
         Ensure = 'Present'
      }
   }
}
FileCopy -OutputPath C:\Temp\dsc\FileCopy
Start-DscConfiguration -Path C:\Temp\dsc\FileCopy -Wait -Force
Relative path is not supported. The related file/directory is:
https://github.com/PowerShell/PowerShell/releases/download/v7.1.
4/PowerShell-7.1.4-win-x86.msi.
   + CategoryInfo : InvalidArgument: (:) [], CimException
   + FullyQualifiedErrorId : MI RESULT 4
   + PSComputerName : LocalHost
To resolve this error, we can either use the “Script“ DSC resource or we need to download and Install the additional DSC resource “xRemoteFile” to download the file online.
To install the “xRemoteFile” resource use the below command.
Find-DscResource xRemoteFile | Install-Module -Force -Verbose
Once the command is installed, we can use the below configuration.
Configuration FileCopy{

   Import-DscResource -ModuleName xPSDesiredStateConfiguration
   Node LocalHost{
      xRemoteFile FileDownload{
         URI = "https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/PowerShell-7.1.4-win-x86.msi"
         DestinationPath = "C:\Temp\PowerShell-7.1.4-win-x86.msi"
      }
   }
}
FileCopy -OutputPath C:\Temp\dsc\FileCopy
Start-DscConfiguration -Path C:\Temp\dsc\FileCopy -Wait -Force
You can also use the inbuilt Script DSC resource as shown below.
Configuration FileCopy{
   Node LocalHost{
      Script DownloadFile{
         GetScript = {""}
         SetScript = {
            Invoke-WebRequest -
            Uri "https://github.com/PowerShell/PowerShell/releases/download/v7.1.4/PowerShell-7.1.4-win-x86.msi"
               -OutFile C:\Temp\PowerShell-7.1.4-win-x86.msi
         }
         TestScript = {
            If(!(Test-Path C:\Temp\PowerShell-7.1.4-win-x86.msi)){return $false}
            else{return $true}
         }
      }
   }
}
How can I filter string value with starting letter?

Let’s say the following is our String List −
List list = Arrays.asList("Jonny", "David", "Tony", "Jacob", "Smith", "Bravo", "Gayle", "John");
Now filter the string value with starting letter −
Stream stream = list.stream().filter(name -> name.startsWith("J"));
The following is an example to filter string value with starting letter −
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      List list = Arrays.asList("Jonny", "David", "Tony", "Jacob", "Smith",
         "Bravo", "Gayle", "John");
      System.out.println("List with elements...");
      for (String res : list) {
         System.out.print(res+" ");
      }
      Stream stream = list.stream().filter(name -> name.startsWith("J"));
      System.out.println("\nGetting strings beginning with letter J =
       "+stream.collect(Collectors.toList()));
   }
}
List with elements...
Jonny David Tony Jacob Smith Bravo Gayle John
Getting strings beginning with letter J = [Jonny, Jacob, John]
Capture picture from iOS camera using Swift

To capture pictures from a camera in swift we can use AVFoundation which is a framework in iOS SDK, but we should try to avoid using it until we need a lot of custom features in our camera application. In this example, we’ll only capture a picture from the camera and display it on the view. We’ll be using image picker in this example instead of AVFoundation.
First, create a project and add an image view on its view Controller in the storyboard. Create the outlet in its class. Now inside the ViewController class conform it to −
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate
After that create an objc function.
@objc func openCamera(){
}
Now in your View did load, add a tap gesture recognizer to your view controller, which should call an openCamera function when the screen is tapped.
override func viewDidLoad() {
   super.viewDidLoad()
   let gesture = UITapGestureRecognizer(target: self, action: #selector(openCamera))
   self.view.addGestureRecognizer(gesture)
}
Now In the function add following lines of code.
@objc func openCamera() {
   let imgPicker = UIImagePickerController()
   imgPicker.delegate = self
   imgPicker.sourceType = .camera
   imgPicker.allowsEditing = false
   imgPicker.showsCameraControls = true
   self.present(imgPicker, animated: true, completion: nil)
}
Once you have done the above steps, now we’ll implement the didFinishPickingMediaWithInfo method of UIImagePickerControllerDelegate and inside this method, we’ll get the image that the user captures up from the camera.
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey :
Any]) {
   if let img = info[UIImagePickerController.InfoKey.editedImage] as?
   UIImage {
         self.imgV.image = img
         self.dismiss(animated: true, completion: nil)
      }
      else {
         print("error")
      }
   }
}
Now, we need to add camera usage description key in our info.plist and give a description of why our application wants to use the camera. When we run this on an iPhone and capture image, this is the result that’s produced. Also, note that this application can not be run on a simulator.
Fortran - If-then-else construct

An if... then statement can be followed by an optional else statement, which executes when the logical expression is false.
The basic syntax of an if... then... else statement is −
if (logical expression) then      
   statement(s)  
else
   other_statement(s)
end if
However, if you give a name to the if block, then the syntax of the named if-else statement would be, like −
[name:] if (logical expression) then      
   ! various statements           
   . . . 
   else
   !other statement(s)
   . . . 
end if [name]
If the logical expression evaluates to true, then the block of code inside the if...then statement will be executed, otherwise the block of code inside the else block will be executed.
program ifElseProg
implicit none
   ! local variable declaration
   integer :: a = 100
 
   ! check the logical condition using if statement
   if (a < 20 ) then
   
   ! if condition is true then print the following 
   print*, "a is less than 20"
   else
   print*, "a is not less than 20"
   end if
       
   print*, "value of a is ", a
	
end program ifElseProg
When the above code is compiled and executed, it produces the following result −
a is not less than 20
value of a is 100

 Print
 Add Notes
 Bookmark this page
Date yyyymmdd format in Shell Script - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Getting date yyyymmdd format in Shell Script is something tricky. I have spent almost 15 minutes to get this format, this may be helpful for someone to save their time.
The syntax for getting today’s date in yyyymmdd format in the shell script.
$date +%Y%m%d
20190928 -- output
We can also send parameter to date command to get the day before dates, for instance, yesterday, the day before yesterday and so on.
#Yesterday date
$date --date="1 days ago" +%Y%m%d
20190927  --output

#2 days before date
$date --date="2 days ago" +%Y%m%d
20190926  --output

#!/bin/bash

FORMATE_DATE='date --date="2 days ago" +%Y%m%d'

echo "The day before yesterday - ${FORMATE_DATE}"
Output:
$./date_format.sh
The day before yesterday - 20190926

Done!
Happy Learning 🙂

Shell Script How to write logs in a Separate File
How add files to S3 Bucket using Shell Script
How to Format JSON Output PrettyPrinter Example
DateTime API in Java 8 Example
Binary Literals Java 7 Example Tutorials
How to convert Timestamp to Date in Java
How to Convert Java Int to String
How to convert Java Map to JSON
Modes of Python Program
Python String to int Conversion Example
AngularJs lowercase Filter Example
Java 8 – Convert java.util.Date to java.time.LocalDate

Shell Script How to write logs in a Separate File
How add files to S3 Bucket using Shell Script
How to Format JSON Output PrettyPrinter Example
DateTime API in Java 8 Example
Binary Literals Java 7 Example Tutorials
How to convert Timestamp to Date in Java
How to Convert Java Int to String
How to convert Java Map to JSON
Modes of Python Program
Python String to int Conversion Example
AngularJs lowercase Filter Example
Java 8 – Convert java.util.Date to java.time.LocalDate
Sum of subset differences in C++

In this problem, we are given a set S of n number. Our task is to create a program to find the sum of subset difference which is the difference of last and first elements of subset.
The formula is,
sumSubsetDifference = Σ [last(s) - first(s)]
s are subsets of the set S.
Let’s take an example to understand the problem,
Input −
S = {1, 2, 9} n = 3
Output −
Explanation − All subset are −
{1}, last(s) - first(s) = 0
{2}, last(s) - first(s) = 0
{9}, last(s) - first(s) = 0
{1, 2}, last(s) - first(s) = 1
{1, 9}, last(s) - first(s) = 8
{2, 9}, last(s) - first(s) = 7
{1, 2, 9}, last(s) - first(s) = 8
Sum = 1 + 8 + 7 + 8 = 24
A simple solution to the problem is to find the difference between last and first for all subsets and then add them to get the sum output. This is not most effective solution, so lets discuss a more efficient solution.
For a set S of n elements, the sum can also be computed using the number of all subsets starting from an element of the array. And the summing it for find the result.
So,
sumSetDifference(S) = Σ [last(s) - Σfirst(s)]
So, for a set S with elements {s1, s2, s3, ... sn}.
Subset starting with s1 can be made using the combination of elements with {s2, s3, ... sn}. This will gives 2n-1 sets.
Similarly for subset starting with s2 gives 2n-2 sets.
Generalizing it, subset starting with Si given 2n-i.
So, the sum of first element of all subsets is −
SumFirst = a1.2n-1 + a2.2n-2 + a3.2n-3 + ... + an.2n-n
Similarly, we will calculate the sumLast fixing the last element.
SumLast = a1.2n-n + a1.2n - (n-1) + a3.2n - (n-2) + ... + an.2n - (n-(n-1))
Program to illustrate the above solution,
 Live Demo
#include<iostream>
#include<math.h>
using namespace std;
int CalcSumFirst(int S[], int n) {
   int sum = 0;
   for (int i = 0; i < n; i++)
      sum = sum + (S[i] * pow(2, n-i-1));
   return sum;
}
int CalcSumLast(int S[], int n) {
   int sum = 0;
   for (int i = 0; i < n; i++)
      sum = sum + (S[i] * pow(2, i));
   return sum;
}
int main() {
   int S[] = {1, 4, 9, 6};
   int n = 4;
   int sumSetDiff = CalcSumLast(S, n) - CalcSumFirst(S, n);
   printf("The sum of subset differences is %d", sumSetDiff);
   return 0;
}
The sum of subset differences is 45
JavaScript Comparison and Logical Operators

Comparison and Logical operators are used to test for true or 
false.
Comparison operators are used in logical statements to determine equality or difference between variables or values. 
Given that x = 5, the table below explains the comparison operators:
Comparison operators can be used in conditional statements to compare values 
and take action depending on the result:
You will learn more about the use of conditional statements in the next chapter of this tutorial.
Logical operators are used to determine the logic between variables or values.
Given that x = 6 and y = 3, the table below explains the logical operators: 
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.
If the variable age is a value below 18, the value of the variable voteable 
will be "Too young", otherwise the value of voteable will be "Old enough".
Comparing data of different types may give unexpected results.
When comparing a string with a number, JavaScript will convert the string to 
a number when doing the comparison. An empty string converts to 0. A non-numeric 
string converts to NaN which is always false.
When comparing two strings, "2" will be greater than "12", because 
(alphabetically) 1 is less than 2.
To secure a proper result, variables should be converted to the proper type 
before comparison:
Choose the correct comparison operator to alert true, when x is greater than y.
x = 10;
y = 5;
alert(x  y);

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

DivisionByZeroError class is a subclass of ArithmeticError class. This type of error occurs when division operation involves value of denominator as zero. This can also occur when a modulo operator (%) has 0 as second operator, and intdiv() function having second argument as 0.
In first example, we try to perform modulo division of 10 and 0 using % operator to induce DivisionByZeroError.
 Live Demo
<?php
try {
   $a = 10;
   $b = 0;
   $result = $a%$b;
   echo $result;
}
catch (DivisionByZeroError $e) {
   echo $e->getMessage();
}
?>
This will produce following result −
Modulo by zero
If call to intdiv() function with 0 as second argument also raises DivisionByZeroError as follows
 Live Demo
<?php
try {
   $a = 10;
   $b = 0;
   $result = intdiv($a,$b);
   echo $result;
}
catch (DivisionByZeroError $e) {
   echo $e->getMessage();
}
?>
This will produce following result −
Division by zero
Division operator (/) having 0 as denominator, however fails to raise error, instead raises warning because division results in PHP constant INF
 Live Demo
<?php
try {
   $a = 10;
   $b = 0;
   $result = $a/$b;
   echo $result;
}
catch (DivisionByZeroError $e) {
   echo $e->getMessage();
}
?>
This will produce following result −
PHP Warning: Division by zero in C:\xampp\php\test.php on line 5
INF
Difference between Object and Class in Java

Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class.
Class - A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support.
In the following example, Pummy is a class and myPuppy is an object.
 Live Demo
public class Puppy {
   public Puppy(String name) {
      // This constructor has one parameter, name.
      System.out.println("Passed Name is :" + name );
   }
   public static void main(String []args) {
      // Following statement would create an object myPuppy
      Puppy myPuppy = new Puppy( "tommy" );
   }
}
If we compile and run the above program, then it will produce the following result.
Passed Name is :tommy
GATE | GATE CS 2021 | Set 2 | Question 20 - GeeksforGeeks

13 Aug, 2021
Consider the following ANSI C program.
#include < stdio.h >
int main( ) 
{
    int arr[4][5];
    int  i, j;
    for (i=0; i<4; i++) 
    ​​​​​​{
        for (j=0; j<5; j++) 
        {
            arr[i][j] = 10 * i + j;
        }
    }
    printf("%d", *(arr[1]+9));
    return 0;
} 
What is the output of the above program?(A) 14(B) 20(C) 24(D) 30Answer: (C)Explanation: 
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQs 2021 (Set1 and Set2) with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0027:02 / 1:05:22•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=I43aLH5qEBc" 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
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
std::rank in C++ with Examples - GeeksforGeeks

08 Jun, 2020
The std::rank template of C++ STL is present in the <type_traits> header file. The std::rank template of C++ STL is used to find the rank of type T. This function return the rank of type T.
Header File:
#include<type_traits>

Template Class:
template<class T>
struct rank;

template<class T>
inline constexpr
       std::size_t rank_v
        = rank<T>::value;

Syntax:
std::rank<T>::value

Parameter: The std::rank template accepts a single parameter T(Trait class) and returns the rank of it.
Return Value: The template std::rank return the rank of type T.
Below is the program to demonstrate std::rank:
Program:
// C++ program to illustrate std::rank#include <bits/stdc++.h>#include <type_traits>using namespace std;  // Driver Codeint main(){      cout << "rank of following type:"         << endl;    cout << "int: "         << rank<int>::value         << endl;      cout << "int[]: "         << rank<int[]>::value         << endl;      cout << "int[][10]: "         << rank<int[][10]>::value         << endl;      cout << "int[10][10]: "         << rank<int[10][10]>::value         << endl;      return 0;}
rank of following type:
int: 0
int[]: 1
int[][10]: 2
int[10][10]: 2

Reference: http://www.cplusplus.com/reference/type_traits/rank/
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Inline Functions in C++
Pair in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Queue in C++ Standard Template Library (STL)
OpenCV | Loading Video - GeeksforGeeks

26 Aug, 2019
This article aims to learn how to display a video in OpenCV. To do so is a simple task just like displayed as a single image. But here, this display of frames have to be read in a loop as a part of the sequence.
Lets’s understand the complete process line by line in detail.
CvCapture* capture = cvCreateFileCapture("...input\\video_file.avi");
cvCreateFileCapture() function takes name/path of the AVI file of the video (to be loaded as a parameter). Then a pointer to a CvCapture structure is returned. All the information about the video file is contained in this structure. The CvCapture structure gets initialised to the beginning of the video when created in this way.
Code :
frame = cvQueryFrame(capture);
The reading from video file begins once it is inside the while(1) loop. A pointer to a CvCapture structure is taken as an argument by the cvQueryFrame(). Then the next video frame is taken into the memory which is actually a part of CvCapture structure. And that particular frame requires the pointer. cvQueryFrame uses the already allocated memory present in the CvCapture structure, unlike the cvLoadImage that allocates actual memory for the image. Thus, calling a cvReleaseImage() is not necessary for this “frame” pointer. When the CvCapture structure is released, the frame image memory will be freed.
Code :
c = cvWaitKey(10);  if (c == 27)    break;
Waiting for 10ms after the frame is displayed. c will be set to the ASCII value of the pressed key if a user hits that particular key. Otherwise, it is set to ‘-1’. If ESC key (having an ASCII value of 27) is pressed by the user, then the code will exit the read loop. Otherwise, after 10ms are passed, the loop is executed again.
// Using OpenCV to display video  #include <highlevelmonitorconfigurationapi.h>#include <opencv2\highgui\highgui.hpp>#include <opencv2\opencv.hpp>  using namespace cv;using namespace std;  iint main(int argc, char** argv){    // creating window    cvNamedWindow("Display_video", CV_WINDOW_AUTOSIZE);      // loading video    CvCapture* capture = cvCreateFileCapture("..input\\tree.avi");    IplImage* frame;      while (1) {        frame = cvQueryFrame(capture);          if (!frame)            break;          cvShowImage("Display_video", frame);          char c = cvWaitKey(0);          if (c == 27)            break;    }    cvReleaseCapture(&capture);      // destroying window    cvDestroyWindow("Display_video");}
Output :
VIDEO OUTPUT IN THE DISPLAY WINDOW
In the code above we are actually controlling the speed of the video in a very intelligent manner, we are just relying on the timer in cvWaitKey() for controlling the pace of frames to load.
OpenCV
Advanced Computer Subject
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Markov Decision Process
Fuzzy Logic | Introduction
Q-Learning in Python
Principal Component Analysis with Python
Vector in C++ STL
Arrays in C/C++
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
Arraylist lastIndexOf() in Java with example - GeeksforGeeks

26 Nov, 2018
The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object.
Syntax :
lastIndexOf(element)
Parameter : The element whose last index is to be returned.
Returns :It returns the last occurrence of the element passed in the parameter. It returns -1 if the element is not found.
Program to demonstrate the working of lastIndexOf():
// Java code to demonstrate the working of// lastIndexOf() method in ArrayList  // for ArrayList functionsimport java.util.ArrayList;  public class GFG {    public static void main(String[] args)    {          // creating an Empty Integer ArrayList        ArrayList<Integer> arr = new ArrayList<Integer>(7);          // using add() to initialize values        arr.add(10);        arr.add(20);        arr.add(30);        arr.add(40);        arr.add(30);        arr.add(30);        arr.add(40);          System.out.println("The list initially " + arr);          // last index of 30          int element = arr.lastIndexOf(30);        if (element != -1)            System.out.println("the lastIndexof of" +                              " 30 is " + element);        else            System.out.println("30 is not present in" +                                         " the list");          // last index of 100        element = arr.lastIndexOf(100);        if (element != -1)            System.out.println("the lastIndexof of 100" +                                       " is " + element);        else            System.out.println("100 is not present in" +                                            " the list");    }}
Output :
The list initially [10, 20, 30, 40, 30, 30, 40]
the lastIndexof of 30 is 5
100 is not present in the list

Java - util package
Java-ArrayList
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Stream In Java
Interfaces in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java
Initializing a List in Java
Python | Pandas Series.min() - GeeksforGeeks

11 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.min() function return the mode of the underlying data in the given Series object. This function always returns Series even if only one value is returned.
Syntax: Series.min(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Parameter :axis : Axis for the function to be applied on.skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.numeric_only : Include only float, int, boolean columns.**kwargs : Additional keyword arguments to be passed to the function.
Returns : min : scalar or Series (if level specified)
Example #1: Use Series.min() function to find the minimum value among the underlying data in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.min() function to find the minimum value of the given series object.
# return the minimum value in the # series objectresult = sr.min()  # Print the resultprint(result)
Output :As we can see in the output, the Series.min() function has successfully returned the minimum value of the given series object. Example #2: Use Series.min() function to find the minimum value among the underlying data in the given series object. The given series object also contains some missing values.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, 16.8, 20.124, None, 18.1002, 19.5])  # Print the seriesprint(sr)
Output :
Now we will use Series.min() function to find the minimum value of the given series object. we are going to skip the missing values while finding the minimum value.
# return the minimum value in the # series objectresult = sr.min(skipna = True)  # Print the resultprint(result)
Output :As we can see in the output, the Series.min() function has successfully returned the minimum value of the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python Program for cube sum of first n natural numbers - GeeksforGeeks

09 Oct, 2018
Print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till n-th term.
Examples:
Input : n = 5
Output : 225
13 + 23 + 33 + 43 + 53 = 225

Input : n = 7
Output : 784
13 + 23 + 33 + 43 + 53 + 
63 + 73 = 784

# Simple Python program to find sum of series# with cubes of first n natural numbers  # Returns the sum of series def sumOfSeries(n):    sum = 0    for i in range(1, n+1):        sum +=i*i*i              return sum     # Driver Functionn = 5print(sumOfSeries(n))  # Code Contributed by Mohit Gupta_OMG <(0_o)>
Output :
225

Time Complexity : O(n)An efficient solution is to use direct mathematical formula which is (n ( n + 1 ) / 2) ^ 2
For n = 5 sum by formula is
       (5*(5 + 1 ) / 2)) ^ 2
          = (5*6/2) ^ 2
          = (15) ^ 2
          = 225

For n = 7, sum by formula is
       (7*(7 + 1 ) / 2)) ^ 2
          = (7*8/2) ^ 2
          = (28) ^ 2
          = 784

# A formula based Python program to find sum# of series with cubes of first n natural # numbers  # Returns the sum of series def sumOfSeries(n):    x = (n * (n + 1)  / 2)    return (int)(x * x)       # Driver Functionn = 5print(sumOfSeries(n))  # Code Contributed by Mohit Gupta_OMG <(0_o)>
Output:
225

Time Complexity : O(1)How does this formula work?We can prove the formula using mathematical induction. We can easily see that the formula holds true for n = 1 and n = 2. Let this be true for n = k-1.
Let the formula be true for n = k-1.
Sum of first (k-1) natural numbers = 
            [((k - 1) * k)/2]2

Sum of first k natural numbers = 
          = Sum of (k-1) numbers + k3
          = [((k - 1) * k)/2]2 + k3
          = [k2(k2 - 2k + 1) + 4k3]/4
          = [k4 + 2k3 + k2]/4
          = k2(k2 + 2k + 1)/4
          = [k*(k+1)/2]2
The above program causes overflow, even if result is not beyond integer limit. Like previous post, we can avoid overflow upto some extent by doing division first.
# Efficient Python program to find sum of cubes # of first n natural numbers that avoids # overflow if result is going to be withing # limits.  # Returns the sum of series def sumOfSeries(n):    x = 0    if n % 2 == 0 :         x = (n/2) * (n+1)    else:        x = ((n + 1) / 2) * n              return (int)(x * x)     # Driver Functionn = 5print(sumOfSeries(n))  # Code Contributed by Mohit Gupta_OMG <(0_o)>
Output:
225

Please refer complete article on Program for cube sum of first n natural numbers for more details!
maths-cube
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert string dictionary to dictionary
Iterate over characters of a string in Python
Python Program for factorial of a number
Python | Convert set into a list
Python | Convert a list into a tuple
Python | Check if a variable is string
Add a key:value pair to dictionary in Python
Appending to list in Python dictionary
Python program to find sum of elements in list
Python program to find largest number in a list
C library function - pow()

The C library function double pow(double x, double y) returns x raised to the power of y i.e. xy.
Following is the declaration for pow() function.
double pow(double x, double y)
x − This is the floating point base value.
x − This is the floating point base value.
y − This is the floating point power value.
y − This is the floating point power value.
This function returns the result of raising x to the power y.
The following example shows the usage of pow() function.
#include <stdio.h>
#include <math.h>

int main () {
   printf("Value 8.0 ^ 3 = %lf\n", pow(8.0, 3));

   printf("Value 3.05 ^ 1.98 = %lf", pow(3.05, 1.98));
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Value 8.0 ^ 3 = 512.000000
Value 3.05 ^ 1.98 = 9.097324


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page