code-rag-bench/online-tutorials huggingface dataset:
Perl defined Function

This function returns true if EXPR has a value other than the undef value, or checks the value of $_ if EXPR is not specified. This can be used with many functions to detect a failure in operation, since they return undef if there was a problem. A simple Boolean test does not differentiate between false, zero, an empty string, or the string .0., which are all equally false.
If EXPR is a function or function reference, then it returns true if the function has been defined. When used with entire arrays and hashes, it will not always produce intuitive results. If a hash element is specified, it returns true if the corresponding value has been defined, but does not determine whether the specified key exists in the hash.
Following is the simple syntax for this function −
defined EXPR

defined

This function returns 0 if EXPR contains undef and 1 if EXPR contains a valid value or reference.
Following is the example code showing its basic usage −
#!/usr/bin/perl

$var1 = "This is defined";

if( defined($var1) ) {
   print "$var1\n";
}
if( defined($var2) ) {
   print "var2 is also defined\n";
} else {
   print "var2 is not defined\n";
}
When above code is executed, it produces the following result −
This is defined
var2 is not defined


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Watchdog timer in Arduino

A watchdog timer is an essential part of any microcontroller. It resets the program if the program gets stuck anywhere. Very briefly, this is how the watchdog timer works −
The timer keeps incrementing.
The timer keeps incrementing.
The program has to ensure that it keeps resetting the timer, i.e. does not allow it to overflow.
The program has to ensure that it keeps resetting the timer, i.e. does not allow it to overflow.
If the timer overflows, it means that the program was stuck somewhere and therefore was unable to reset the timer. An interrupt is generated on timer overflow which resets the microcontroller.
If the timer overflows, it means that the program was stuck somewhere and therefore was unable to reset the timer. An interrupt is generated on timer overflow which resets the microcontroller.
To implement watchdog timer in Arduino, we use the avr wdt library.
The code is given below −
#include<avr/wdt.h>
void setup() {
   Serial.begin(9600);
   wdt_disable(); //Disable WDT
   delay(3000);
   wdt_enable(WDTO_2S); //Enable WDT with a timeout of 2 seconds
   Serial.println("WDT Enabled");
}
void loop() {
   for(int i = 0; i<5; i++)
   {
      Serial.println("Looping");
      delay(1000);
      wdt_reset(); //Reset the watchdog
   }
   while(1); //Watchdog timer should get triggered here
}
As you can see, we initialize Serial and first disable watchdog timer. Then a delay of 3 seconds is introduced. The program won't reset here, because the watchdog is disabled. Now, the watchdog timer with a timeout of 2 seconds is enabled. It means, if the program doesn't reset this timer within every 2 seconds, then the watchdog will get triggered and restart the microcontroller.
Within the loop, we first print to the Serial for 5 seconds, making sure to reset the watchdog every second. The program works fine so far. Then, we enter into an infinite while loop. Over here, since we are not resetting the wdt, it will get triggered and restart the Arduino.
Note that the preset watchdog timeout values are available from 15 ms to 8 s.
Difference between Exception and Error in Java

Exceptions and errors both are subclasses of Throwable class. The error indicates a problem that mainly occurs due to the lack of system resources and our application should not catch these types of problems. Some of the examples of errors are system crash error and out of memory error. Errors mostly occur at runtime that's they belong to an unchecked type. 
Exceptions are the problems which can occur at runtime and compile time. It mainly occurs in the code written by the developers.  Exceptions are divided into two categories such as checked exceptions and unchecked exceptions. 
public class ErrorExample {
   public static void main(String[] args){
      recursiveMethod(10)
   }
   public static void recursiveMethod(int i){
      while(i!=0){
         i=i+1;
         recursiveMethod(i);
      }
   }
}
Exception in thread "main" java.lang.StackOverflowError
   at ErrorExample.ErrorExample(Main.java:42)
public class ExceptionExample {
   public static void main(String[] args){
      int x = 100;
      int y = 0;
      int z = x / y;
   }
}
java.lang.ArithmeticException: / by zero
   at ExceptionExample.main(ExceptionExample.java:7)
How to get almost increasing sequence of integers in JavaScript ?

A sequence of numbers is said to be in a strictly increasing sequence if every succeeding element in the sequence is greater than its preceding element.
We are required to write a JavaScript function that takes in an array of Numbers as the only argument. The function should check whether we can form a strictly increasing sequence of the numbers by removing no more than one element from the array.
Following is the code −
const almostIncreasingSequence = (arr = []) => {
   if (isIncreasingSequence(arr)) {
      return true;
   };
   for (let i = 0; i < arr.length > 0; i++) {
      let copy = arr.slice(0);
      copy.splice(i, 1);
      if (isIncreasingSequence(copy)) {
         return true;
      };
   };
   return false;
};
const isIncreasingSequence = (arr = []) => {
   for (let i = 0; i < arr.length - 1; i++) {
      if (arr[i] >= arr[i + 1]) {
         return false;
      };
   };
   return true;
};
console.log(almostIncreasingSequence([1, 3, 2, 1]));
console.log(almostIncreasingSequence([1, 3, 2]));
Following is the output on console −
false
true
Difference Between get() and load() in Hibernate

In hibernate, get() and load() are two methods which is used to fetch data for the given identifier. They both belong to Hibernate session class. Get() method return null, If no row is available in the session cache or the database for the given identifier whereas load() method throws object not found exception. 
1
Basic 
It  is used to fetch data from the database for the given identifier  
It  is also used to fetch data from the database for the given identifier 
2
Null Object 
It object not found for the given identifier then it will return null object 
It will throw object not found exception 
3
Lazy or Eager loading 
It returns fully initialized object so this method eager load the object  
It always returns proxy object so this method is lazy load the object  
4
Performance 
It is slower than load() because it return fully initialized object which impact the performance of the application 
It is slightly faster.
5.
Use Case
If you are not sure that object exist then use get() method 
If you are sure that object exist then use load() method 
@Entity
public class User {
   @Id
   Integer id;
   String name;
   public Integer getId() {
      return id;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.util.HibernateUtil;
public class GetExample {
   public static void main(String[] args) {
      //get session factory to start transcation
      SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
      Session session = sessionFactory.openSession();
      Transaction tx = session.beginTransaction();
      //Get Example
      User user = (User) session.get(User.class, new Integer(2));
      System.out.println("User ID= "+user.getId());
      System.out.println("User Name= "+user.getName());
      //Close resources
      tx.commit();
      sessionFactory.close();
   }
}
@Entity
public class User {
   @Id
   Integer id;
   String name;
   public Integer getId() {
      return id;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.util.HibernateUtil;
public class LoadExample {
   public static void main(String[] args) {
      //get session factory to start transcation
      SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
      Session session = sessionFactory.openSession();
      Transaction tx = session.beginTransaction();
      //Load Example
      User user = (User) session.load(User.class, new Integer(2));
      System.out.println("User ID= "+user.getId());
      System.out.println("User Name= "+user.getName());  
      //Close resources
      tx.commit();
      sessionFactory.close();
   }
}
C program to display the prime numbers in between two intervals

Enter two numbers at console during runtime. Then, declare the flag variable which is used to check whether the number is prime or not with the help of for loop condition.
Whenever, the flag is zero, it prints the prime number and if flag is one, it exists from the loop.
Following is the C program to display the prime numbers in between two intervals −
 Live Demo
#include <stdio.h>
int main(){
   int number1,number2,i,j,flag;
   printf("enter the two intervals:");
   scanf("%d %d",&number1,&number2);
   printf("prime no’s present in between %d and %d:",number1,number2);
   for(i=number1+1;i<number2;i++){// interval between two numbers
      flag=0;
      for(j=2;j<=i/2;++j){ //checking number is prime or not
         if(i%j==0){
            flag=1;
            break;
         }
      }
      if(flag==0)
         printf("%d\n",i);
   }
   return 0;
}
You will see the following output −
enter the two intervals:10 50
the number of prime numbers present in between 10 and 50:11
13
17
19
23
29
31
37
41
43
47
Consider another example, wherein, we are trying to remove the prime numbers in between two numbers.
Following is the C program to display the numbers in between two intervals excluding prime numbers −
 Live Demo
#include <stdio.h>
int main(){
   int number1,number2,i,j,flag;
   printf("enter the two intervals:");
   scanf("%d %d",&number1,&number2);
   printf("the numbers that are present after removing prime numbers in between %d and %d:\n",number1,number2);
   for(i=number1+1;i<number2;i++){// interval between two numbers
      flag=1;
      for(j=2;j<=i/2;++j){ //checking number is prime or not
         if(i%j==0){
            flag=0;
            break;
         }
      }
      if(flag==0)
         printf("%d\n",i);
   }
   return 0;
}
You will see the following output −
enter the two intervals:10 20
the numbers that are present after removing prime numbers in between 10 and 20:
12
14
15
16
18
How to use the submit button in HTML forms?

Submit button automatically submits a form on click. Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc.
Let’s learn about how to use the submit button in HTML forms. It is also created using HTML <input> tag but type attribute is set to button.
You can try to run the following code to use submit button to submit and reset a form. Under the action, attribute add the file, where you want to reach after clicking Submit button. Using get and post method, you can send the values to the PHP file added in action attribute.
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <form action="/new.php">
         Student Name:<br>
         <input type="text" name="sname">
         <br>
         Student Subject:<br>
         <input type="text" name="ssubject">
         <br>
         <input type="submit" value="Submit">
         <input type="reset" value="Reset">
      </form>
   </body>
</html>
Node.js Stream readable.pipe() Method - GeeksforGeeks

13 May, 2022
The readable.pipe() method in a Readable Stream is used to attach a Writable stream to the readable stream so that it consequently switches into flowing mode and then pushes all the data that it has to the attached Writable. 
Syntax:
readable.pipe( destination, options )
Parameters: This method accept two parameters as mentioned above and described below:
destination: This parameter holds the destination of writing data.
options: This parameter holds the pipe options.
Return Value: It returns the stream.Writable destination, allowing for a chain of pipes if it is a Duplex or a Transform stream. Below examples illustrate the use of readable.pipe() method in Node.js: 
Example 1: 
javascript
// Node.js program to demonstrate the    // readable.pipe() method  // Accessing fs modulevar fs = require("fs"); // Create a readable streamvar readable = fs.createReadStream('input.txt'); // Create a writable streamvar writable = fs.createWriteStream('output.txt'); // Calling pipe methodreadable.pipe(writable); console.log("Program Ended");
Output:
Program Ended
So, after the piping method the file named “output.text” must contain the data that was in the file “input.text”. 
Example 2: 
javascript
// Node.js program to demonstrate    // the chaining of streams using// readable.pipe() method  // Accessing fs and zlib modulevar fs = require("fs");var zlib = require('zlib'); // Compress the file input.text to// input.txt.gz using pipe() methodfs.createReadStream('input.text')   .pipe(zlib.createGzip())   .pipe(fs.createWriteStream('input.text.gz'));   console.log("File Compressed.");
Output:
File Compressed.
Reference: https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options.
gigicampagnola
Node.js-Stream-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
How to read and write Excel file in Node.js ?
Express.js res.render() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
PyQt5 – Set fix window size for height or width - GeeksforGeeks

26 Mar, 2020
When we create a window, by default the window size is resizable although, we can use setFixedSize() method to set the fixed size of the window but if we want to set only fix length of height or width only we cant use this method. We want to set one length fixed and other be variable in order to do so we have to use setFixedWidth() method to set fix length of width and setFizedHeight() method to set fix length of height.
Syntax :
self.setFixedWidth(width)
self.setFixedHeight(height)

Argument : Both take integer as argument.
Action performed:setFixedWidth() sets the constant width.setFixedWidth() sets the constant height.
Code for fixed width –
# importing the required libraries  from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()            # set the title        self.setWindowTitle("Python")          width = 500                  # setting  the fixed width of window        self.setFixedWidth(width)            # creating a label widget        self.label_1 = QLabel("Fixed width", self)          # moving position        self.label_1.move(0, 0)          # setting up the border        self.label_1.setStyleSheet("border :3px solid black;")          # resizing label        self.label_1.resize(120, 80)          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output : Code for fixed height –
# importing the required libraries  from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()            # set the title        self.setWindowTitle("Python")          height = 400        # setting  the fixed height of window        self.setFixedHeight(height)            # creating a label widget        self.label_1 = QLabel("Fixed height", self)          # moving position        self.label_1.move(0, 0)          # setting up the border        self.label_1.setStyleSheet("border :3px solid black;")          # resizing label        self.label_1.resize(120, 80)          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python program to multiply two matrices - GeeksforGeeks

23 Apr, 2022
Given two matrix the task is that we will have to create a program to multiply two matrices in python. Examples:  
Input : X = [[1, 7, 3],
             [3, 5, 6],
             [6, 8, 9]]
       Y = [[1, 1, 1, 2],
           [6, 7, 3, 0],
           [4, 5, 9, 1]]
 
Output : [55, 65, 49, 5]
         [57, 68, 72, 12]
         [90, 107, 111, 21]
 
Using Simple Nested Loops In this program we have to use nested for loops to iterate through each row and each column. 
Python3
# Program to multiply two matrices using nested loops # take a 3x3 matrixA = [[12, 7, 3],    [4, 5, 6],    [7, 8, 9]] # take a 3x4 matrix   B = [[5, 8, 1, 2],    [6, 7, 3, 0],    [4, 5, 9, 1]]     result = [[0, 0, 0, 0],        [0, 0, 0, 0],        [0, 0, 0, 0]] # iterating by row of Afor i in range(len(A)):     # iterating by column by B    for j in range(len(B[0])):         # iterating by rows of B        for k in range(len(B)):            result[i][j] += A[i][k] * B[k][j] for r in result:    print(r)
Output:  
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N.
Auxiliary Space: O(M*N), as we are using a result matrix which is extra space.
Method 2: Matrix Multiplication Using Nested List. We use zip in Python. 
Python3
# Program to multiply two matrices using list comprehension # take a 3x3 matrixA = [[12, 7, 3],    [4, 5, 6],    [7, 8, 9]] # take a 3x4 matrixB = [[5, 8, 1, 2],    [6, 7, 3, 0],    [4, 5, 9, 1]] # result will be 3x4result = [[sum(a * b for a, b in zip(A_row, B_col))                        for B_col in zip(*B)]                                for A_row in A] for r in result:    print(r)
Output:  
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N.
Auxiliary Space: O(M*N), as we are using a result matrix which is extra space.Method 3: Matrix Multiplication (Vectorized implementation).  
Python3
# Program to multiply two matrices (vectorized implementation) # Program to multiply two matrices (vectorized implementation)import numpy as np# take a 3x3 matrixA = [[12, 7, 3],    [4, 5, 6],    [7, 8, 9]] # take a 3x4 matrixB = [[5, 8, 1, 2],    [6, 7, 3, 0],    [4, 5, 9, 1]] # result will be 3x4 result= [[0,0,0,0],        [0,0,0,0],        [0,0,0,0]] result = np.dot(A,B) for r in result:    print(r)
Output:  
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N.
Auxiliary Space: O(M*N), as we are using a result matrix which is extra space.
psbishnu1
anikakapoor
rohitsingh07052
Python matrix-program
Matrix
Python
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sudoku | Backtracking-7
Inplace rotate square matrix by 90 degrees | Set 1
Count all possible paths from top left to bottom right of a mXn matrix
Min Cost Path | DP-6
Printing all solutions in N-Queen Problem
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Matplotlib.figure.Figure.clear() in Python

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The clear() method figure module of matplotlib library is used to Clear the figure.
Syntax: clear(self, keep_observers=False)
Parameters: This accept the following parameters that are described below:
keep_observers: This parameter is the boolean value.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.figure.Figure.clear() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt      fig, ax = plt.subplots()  ax.set_xlabel('x-axis')ax.set_ylabel('y-axis')  ax.plot([1, 2, 3])ax.grid(True)  fig.clear(True)   fig.suptitle('matplotlib.figure.Figure.clear() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt      t = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t)   fig, [ax, ax1] = plt.subplots(2, 1,                               sharex = True)   ax.set_ylabel('y-axis')ax.plot(t, s)ax.grid(True)ax.set_title('Sample Example',             fontsize = 12,             fontweight ='bold')   ax1.set_ylabel('y-axis')ax1.plot(t, s)ax1.grid(True)  fig.clear(False)   fig.suptitle('matplotlib.figure.Figure.clear() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
numpy.logical_or() in Python

29 Nov, 2018
numpy.logical_or(arr1, arr2, out=None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None, ufunc ‘logical_or’) : This is a logical function and it helps user to find out the truth value of arr1 OR arr2 element-wise. Both the arrays must be of same shape.
Parameters :
arr1 : [array_like]Input array.arr2 : [array_like]Input array.
out : [ndarray, optional]Output array with same dimensions as Input array, placed with result.
**kwargs : allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.
where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone.
Return :
An array with Boolean results of arr1 OR arr2 element-wise(of the same shape).  

 Code 1 : Working
# Python program explaining# logical_or() functionimport numpy as np  # inputarr1 = [1, 3, False, 4]arr2 = [3, 0, True, False]  # outputout_arr = np.logical_or(arr1, arr2)  print ("Output Array : ", out_arr)
Output :
Output Array :  [ True  True  True  True]

 Code 2 : Value Error if input array’s have different shapes
# Python program explaining# logical_or() functionimport numpy as np  # inputarr1 = [8, 2, False, 4]arr2 = [3, 0, False, False, 8]  # outputout_arr = np.logical_or(arr1, arr2)  print ("Output Array : ", out_arr)
Output :
ValueError: operands could not be broadcast together with shapes (4,) (5,)  
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.logical_or.html#numpy.logical_or.
Python numpy-Logic Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
PHP | imagefill() Function

23 Aug, 2019
The imagefill() function is an inbuilt function in PHP which is used to fill the image with the given color. This function performs a flood fill starting at the given coordinate (top left is 0, 0) with the given color in the image.
Syntax:
bool imagefill( $image, $x, $y, $color )
Parameters:This function accepts four parameters as mentioned above and described below:
$image: It is returned by one of the image creation functions, such as imagecreatetruecolor(). It is used to create size of image.
$x: This parameter is used to set x-coordinate of starting point.
$y: This parameter is used to set y-coordinate of starting point.
$color: It sets the color of image. A color identifier created by imagecolorallocate() function.
Return Value: This function returns True on success of False on failure.
Below programs illustrate the imagefill() function in PHP:
Program 1:
<?php  // Create an image of given size$image = imagecreatetruecolor(500, 400);  // Sets background to green$green = imagecolorallocate($image, 0, 153, 0);imagefill($image, 0, 0, $green);  header('Content-type: image/png');imagepng($image);imagedestroy($image);?>
Output:
Program 2:
<?php    // It create the size of image or blank image.$image = imagecreatetruecolor(500, 300);    // Set the background color of image.$bg = imagecolorallocate($image, 205, 220, 200);    // Fill background with above selected color.imagefill($image, 0, 0, $bg);   // Set the color of an ellipse.$col_ellipse = imagecolorallocate($image, 0, 102, 0);    // Function to draw the filled ellipse.imagefilledellipse($image, 250, 150, 400, 250, $col_ellipse);    // Output of the image.header("Content-type: image/png");imagepng($image);    ?>
Output:
Related Articles:
PHP | imagecolorallocatealpha() Function
PHP | imagearc() Function
PHP | imageellipse() Function
Reference: http://php.net/manual/en/function.imagefill.php
Image-Processing
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Insert multiple values into multiple tables using a single statement in SQL Server

12 Feb, 2022
The T-SQL function OUTPUT, which was introduced in 2005, can be used to insert multiple values into multiple tables in a single statement. The output values of each row that was part of an INSERT, UPDATE or DELETE operation are returned by the OUTPUT clause.
Syntax:
INSERT INTO Table1 (Col1, Col2)
OUTPUT inserted.Col1, inserted.Col2
INTO Table2
VALUES()
GO
Example: In this example, we are creating 2 sample tables using the below queries:
CREATE TABLE GeekTable1 (Id1 INT, Name1 VARCHAR(200), City1 VARCHAR(200))
GO
CREATE TABLE GeekTable2 (Id2 INT, Name2 VARCHAR(200), City2 VARCHAR(200))
GO
Now, let us Insert values into two tables together:
INSERT INTO GeekTable1 (Id1, Name1, City1)
OUTPUT inserted.Id1, inserted.Name1, inserted.City1
INTO GeekTable2
VALUES(1,'Komal','Delhi'), (2, 'Khushi','Noida')
GO
Select data from both the tables:
SELECT * FROM GeekTable1 ;
GO
SELECT * FROM GeekTable2 ;
GO
Output: When we run the above query, we will see that there are two rows each in the table:
GeekTable1:
GeekTable2:
armaantojain
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
MySQL | Group_CONCAT() Function
SQL | GROUP BY
Difference between DDL and DML in DBMS
Difference between DELETE and TRUNCATE
isinf() function in C++

27 Sep, 2018
This function is defined in <cmath.h> .The isinf() function is use to determine whether the given number is infinity or not i.e positive infinity or negative infinity both. This function returns 1 if the given number is infinite otherwise this function returns zero.
Syntax:
bool isinf( float arg );
or
bool isinf( double arg );
or
bool isinf( long double arg );
Parameter: This function takes a mandatory parameter x which represents the given floating point value.
Return: This function returns 1 if the given number is infinite else return zero.
Below programs illustrate the isinf() function in C++:
Example 1:- To show infinite case which returns 1
// c++ program to demonstrate// example of isnormal() function.  #include <bits/stdc++.h>  using namespace std;  int main(){      float f = 6.0F;      // check for +ve infinite value    cout << "isinf(6.0/0.0) is = " << isinf(f/0.0) << endl;      // check for -ve infinite value    f = -1.2F;    cout << "isinf(-1.2/0.0) is = " << isinf(f/0.0) << endl;      return 0;}
isinf(6.0/0.0) is = 1
isinf(-1.2/0.0) is = 1

Explanation: In example 1 the floating point number represents infinity that’s why function returns 1.
Example 2:- To show non-infinite case which returns 0
// c++ program to demonstrate// example of isinf() function.  #include <bits/stdc++.h>using namespace std;  int main(){   cout << "isinf(0.0) is = " << isinf(0.0) << endl;     cout << "isinf(sqrt(-1.0)) is = " << isinf(sqrt(-1.0)) << endl;     return 0;}
isinf(0.0) is = 0
isinf(sqrt(-1.0)) is = 0

Exception: In example 2 the given floating point number is not representing infinity that’s why function returns zero.
CPP-Library
cpp-numerics-library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Inheritance in C++
Priority Queue in C++ Standard Template Library (STL)
The C++ Standard Template Library (STL)
Sorting a vector in C++
Substring in C++
C++ Classes and Objects
Python | Test if String contains Alphabets and Spaces - GeeksforGeeks

17 Dec, 2021
Sometimes, while testing of credibility of string being a part of containing just alphabets, an exception of spaces has to be mentioned explicitly and becomes a problem. This can occur in domains that deal with data. Lets discuss certain ways in which this task can be performed.
Method #1 : Using all() + isspace() + isalpha() This is one of the way in which this task can be performed. In this, we compare the string for all elements being alphabets or space only.
Python3
# Python3 code to demonstrate working of # Test if String contains Alphabets and Spaces# Using isspace() + isalpha() + all()import re   # initializing stringtest_str = 'geeksforgeeks is best for geeks'   # printing original stringprint("The original string is : " + test_str)   # Test if String contains Alphabets and Spaces# Using isspace() + isalpha() + all()res = test_str != '' and all(chr.isalpha() or chr.isspace() for chr in test_str)   # printing result print("Does String contain only space and alphabets : " + str(res))
The original string is : geeksforgeeks is best for geeks
Does String contain only space and alphabets : True
 
Method #1 : Using regex This problem can also be solved by employing regex to include only space and alphabets in a string.
Python3
# Python3 code to demonstrate working of # Test if String contains Alphabets and Spaces# Using regeximport re   # initializing stringtest_str = 'geeksforgeeks is best for geeks'   # printing original stringprint("The original string is : " + test_str)   # Test if String contains Alphabets and Spaces# Using regexres = bool(re.match('[a-zA-Z\s]+$', test_str))   # printing result print("Does String contain only space and alphabets : " + str(res))
The original string is : geeksforgeeks is best for geeks
Does String contain only space and alphabets : True
 
arorakashish0911
Python string-programs
Python
Python Programs
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 ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to cut only the first character in MySQL string?

To cut only the first character, use the substr() function with UPDATE command. The syntax is as follows.
UPDATE yourTableName set yourColumnName=substr(yourColumnName,2);
To understand the above syntax, let us first create a table. The query to create a table is as follows.
mysql> create table CutStringDemo
-> (
-> Value varchar(100)
-> );
Query OK, 0 rows affected (0.66 sec)
Now you can insert some records in the table using insert command. The query is as follows.
mysql> insert into CutStringDemo values(',12,3456');
Query OK, 1 row affected (0.14 sec)

mysql> insert into CutStringDemo values(',23,9867');
Query OK, 1 row affected (0.16 sec)

mysql> insert into CutStringDemo values(',20,3212');
Query OK, 1 row affected (0.12 sec)

mysql> insert into CutStringDemo values(',23456,1234');
Query OK, 1 row affected (0.14 sec)
Now you can display all records from the table using select statement. The query is as follows.
mysql> select *from CutStringDemo;
The following is the output.
+-------------+
| Value       |
+-------------+
| ,12,3456    |
| ,23,9867    |
| ,20,3212    |
| ,23456,1234 |
+-------------+
4 rows in set (0.00 sec)
Now let us cut the first character from the column Value. The query is as follows.
mysql> update CutStringDemo set Value=substr(Value,2);
Query OK, 4 rows affected (0.20 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Now you can check that the first character has been removed from the column Value or not. To display all records from the table, use the SELECT statement. The query is as follows.
mysql> select *from CutStringDemo;
The following is the output displaying that the first character successfully removed.
+------------+
| Value      |
+------------+
| 12,3456    |
| 23,9867    |
| 20,3212    |
| 23456,1234 |
+------------+
4 rows in set (0.00 sec)
Explain union operation in relational algebra (DBMS)?

Query is a question or requesting information. Query language is a language which is used to retrieve information from a database.
Query language is divided into two types −
Procedural language
Procedural language
Non-procedural language
Non-procedural language
Information is retrieved from the database by specifying the sequence of operations to be performed.
For Example − Relational algebra.
Structure Query language (SQL) is based on relational algebra.
Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output.
The different types of relational algebra operations are as follows −
Select operation
Select operation
Project operation
Project operation
Rename operation
Rename operation
Union operation
Union operation
Intersection operation
Intersection operation
Difference operation
Difference operation
Cartesian product operation
Cartesian product operation
Join operation
Join operation
Division operation
Division operation
Union, intersection, difference, cartesian, join, division comes under binary operation (operate on two tables).
Union operation combines values in R1, R2 by removing duplicate ones.
∏regno(R1) ∪ ∏regno(R2)
It displays all the regno of R1 and R2.
Consider two tables R1 and R2 −
Table R1 is as follows −
Table R2 is as follows −
To display all the regno of R1 and R2, use the following command −
∏regno(R1) ∪ ∏regno(R2)
To retrieve branch and section of student from table R1 and R2, use the below mentioned command −
∏ branch, section (R1) ∪ ∏ branch, section (R2)
No repletion allowed for entry.
Union All − It is used for duplicate entries. The common entries will be shown if the common intersection is used.
How to get the return value from a function in a class in Python?

The following code shows how to get return value from a function in a Python class
class Score():
    def __init__(self):
        self.score = 0
        self.num_enemies = 5
        self.num_lives = 3

    def setScore(self, num):
        self.score = num
    def getScore(self):
         return self.score
    def getEnemies(self):
        return self.num_enemies
    def getLives(self):
        return self.num_lives
       
s = Score()
s.setScore(9)
print s.getScore()
print s.getEnemies()
print s.getLives()
9
5
3
Difference between Context Free Grammar and Regular Grammar - GeeksforGeeks

31 May, 2021
Noam Chomsky has divided grammar into four types :
Type
Name
0
1
2
3
Chomsky Hierarchy
1. Context Free Grammar :
Language generated by Context Free Grammar is accepted by Pushdown Automata
It is a subset of Type 0 and Type 1 grammar and a superset of Type 3 grammar.
Also called phase structured grammar.
Different context-free grammars can generate the same context-free language.
Classification of Context Free Grammar is done on the basis of the number of parse trees.
Only one parse tree->Unambiguous.
More than one parse tree->Ambiguous.
Productions are in the form –
A->B;
A∈N i.e A is a non-terminal.
B∈V*(Any string).
Example –
S –> AB
A –> a
B –> b
2. Regular Grammar :
It is accepted by Finite State Automata.
It is a subset of Type 0 ,Type 1 and Type 2 grammar.
The language it generates is called Regular Language.
Regular languages are closed under operations like Union, Intersection, Complement etc.
They are the most restricted form of grammar.
Productions are in the form –
V –> VT / T (left-linear grammar)
  (or)
V –> TV /T (right-linear grammar)
Example –
1. S –> ab. 
2. S -> aS | bS | ∊ 
Difference Between Context Free Grammar and Regular Grammar:
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Phases of a Compiler
Preemptive and Non-Preemptive Scheduling
Differences between IPv4 and IPv6
Introduction of Process Synchronization
Regular Expressions, Regular Grammar and Regular Languages
Difference between DFA and NFA
Introduction of Finite Automata
Difference between Mealy machine and Moore machine
Pumping Lemma in Theory of Computation
How can we apply AUTO_INCREMENT to a column?

AUTO_INCREMENT means that the column will get the value automatically. To illustrate it we have created a table ‘employees’ as follows −
mysql> Show Create Table employees\G

*************************** 1. row ***************************
Table: employees

Create Table: CREATE TABLE `employees` (
   `Id` int(11) NOT NULL AUTO_INCREMENT,
   `Name` varchar(35) DEFAULT NULL,
   PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

1 row in set (0.00 sec)
From the above result set, we can see that column id is given the auto-increment option. Now, when we will insert the value in Name field, the id field will get the values automatically −
mysql> Insert Into employees(Name) Values('Ram');
Query OK, 1 row affected (0.09 sec)

mysql> Insert Into employees(Name) Values('Shyam');
Query OK, 1 row affected (0.03 sec)

mysql> Insert Into employees(Name) Values('Mohan');
Query OK, 1 row affected (0.04 sec)

mysql> Insert Into employees(Name) Values('Sohan');
Query OK, 1 row affected (0.04 sec)

mysql> Select * from employees;

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Ram   |
| 2  | Shyam |
| 3  | Mohan |
| 4  | Sohan |
+----+-------+

4 rows in set (0.00 sec)
HTML5 - time

A time (hour, minute, seconds, fractional seconds) encoded according to ISO 8601.
<!DOCTYPE HTML>

<html>
   <body>

      <form action = "/cgi-bin/html5.cgi" method = "get">
         Time : <input type = "time" name = "newinput" />
         <input type = "submit" value = "submit" />
      </form>

   </body>
</html>

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Implement Dynamic SQL query inside a MySQL stored procedure?

For dynamic SQL query in a stored procedure, use the concept of PREPARE STATEMENT. Let us first create a table −
mysql> create table DemoTable2033
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (1.61 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2033(Name) values('Chris');
Query OK, 1 row affected (0.85 sec)

mysql> insert into DemoTable2033(Name) values('Bob');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable2033(Name) values('David');
Query OK, 1 row affected (0.24 sec)

mysql> insert into DemoTable2033(Name) values('Mike');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2033;
This will produce the following output −
+----+-------+
| Id | Name  |
+----+-------+
| 1  | Chris |
| 2  | Bob   |
| 3  | David |
| 4  | Mike  |
+----+-------+
4 rows in set (0.00 sec)
Following is the query to create a stored procedure and implement dynamic SQL −
mysql> delimiter //
mysql> create procedure dynamic_query()
   -> begin
   -> set @query=concat("select *from DemoTable2033 where Id=3");
   -> prepare st from @query;
   -> execute st;
   -> end
   -> //
Query OK, 0 rows affected (0.13 sec)

mysql> delimiter ;
Call the stored procedure −
mysql> call dynamic_query();
This will produce the following output −
+----+-------+
| Id | Name  |
+----+-------+
| 3  | David |
+----+-------+
1 row in set (0.04 sec)
Query OK, 0 rows affected (0.05 sec)
Tryit Editor v3.6 - Show React

import { useState } from "react";
import ReactDOM from "react-dom/client";
import Todos from "./Todos";

const App = () => {
  const [count, setCount] = useState(0);
  const [todos, setTodos] = useState(["todo 1", "todo 2"]);

  const increment = () => {
    setCount((c) => c + 1);
  };

  return (
    <>
      <Todos todos={todos} />
      <hr />
      <div>
        Count: {count}
        <button onClick={increment}>+</button>
      </div>
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport"
      content="width=device-width, initial-scale=1" />
Check if sum of divisors of two numbers are same in Python

Suppose we have two numbers p and q. We have to check whether the sum of all divisors of these tow numbers are same or not.
So, if the input is like p = 559, q = 703, then the output will be True the divisors of 559 is 1, 13, 43 and 703 is 1, 19, 37. The sum of the divisors are 57.
To solve this, we will follow these steps −
Define a function divSum() . This will take n
total := 1
i := 2
while i * i <= n, doif n divisible by i, thentotal := total + i + the floor of (n / i)i := i + 1
if n divisible by i, thentotal := total + i + the floor of (n / i)
total := total + i + the floor of (n / i)
i := i + 1
return total
From the main method return true when divSum(p) is same as divSum(q), otherwise false
Let us see the following implementation to get better understanding −
Live Demo
from math import floor
 
def divSum(n):
   total = 1
   i = 2
   while i * i <= n:
      if n % i == 0:
         total += i + floor(n / i)
      i += 1
 
   return total
   
def solve(p, q):
   return divSum(p) == divSum(q)

p = 559
q = 703
print(solve(p, q))
559, 703

True
turtle.speed() function in Python - GeeksforGeeks

20 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
The turtle.speed() method is used to change the speed of the turtle by the value of the argument that it takes. Return or set the turtle’s speed.
Syntax :
turtle.speed(speed=None)

Note:
The turtle’s speed lies in the range 0-10.
If input is a number greater than 10 or smaller than 0.5, speed is set to 0.
Speedstrings  are mapped to speedvalues in the following way:‘fastest’ :  0‘fast’    :  10‘normal’  :  6‘slow’    :  3‘slowest’ :  1
‘fastest’ :  0
‘fast’    :  10
‘normal’  :  6
‘slow’    :  3
‘slowest’ :  1
Speeds from 1 to 10 enforce increasingly faster animation of line drawing and turtle turning.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle  # slowest speedturtle.speed(1)  # turtle movementturtle.forward(150)
Output :
Example 2 :
Python3
# import packageimport turtle   # loop for patternfor i in range(10):      # set turtle speed  turtle.speed(10-i)      # motion for pattern  turtle.forward(50+10*i)  turtle.right(90)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
PostgreSQL - STRING_AGG() Function - GeeksforGeeks

01 Jun, 2020
The STRING_AGG() function in PostgreSQL is an aggregate function that is used to concatenate a list of strings and place a separator between them.
Syntax: STRING_AGG ( expression, separator [order_by_clause] )
Let’s analyze the above syntax. The above function accepts two arguments and an optional ORDER BY clause.
expression is any valid expression that can resolve to a character string.
separator is the separator for concatenated strings.
Now let’s look into some examples.For examples we will be using the sample database (ie, dvdrental).
Example 1:We will query for a list of actor’s names for each film from the film table using the below command:
SELECT
    f.title,
    STRING_AGG (
    a.first_name || ' ' || a.last_name,
        ', '
       ORDER BY
        a.first_name,
        a.last_name
    ) actors
FROM
    film f
INNER JOIN film_actor fa USING (film_id)
INNER JOIN actor a USING (actor_id)
GROUP BY
    f.title;
Output:
Example 2:In this example we will an email list for each country from the country table. The email in each list separated by a semi-colon.To do so we use the below command:
SELECT
    country,
    STRING_AGG (email, ';') email_list
FROM
    customer
INNER JOIN address USING (address_id)
INNER JOIN city USING (city_id)
INNER JOIN country USING (country_id)
GROUP BY
    country
ORDER BY
    country;
Output:
postgreSQL-aggregate-functions
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - REPLACE Function
PostgreSQL - Copy Table
PostgreSQL - CREATE SCHEMA
PostgreSQL - Rename Table
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Identity Column