code-rag-bench/online-tutorials huggingface dataset:
Designing Deterministic Finite Automata (Set 3) - GeeksforGeeks

15 Jun, 2021
Prerequisite: Designing finite automata, Designing Deterministic Finite Automata (Set 2) In this article, we will see some designing of Deterministic Finite Automata (DFA). 
Problem-1: Construction of a minimal DFA accepting set of string over {a, b} where each string containing ‘a’ as the substring. 
Explanation: The desired language will be like:  
L1 = {a, aa, ab, ba, ..............}
Here as we can see that each string of the language containing ‘a’ as the substring but the below language is not accepted by this DFA because some of the string of the below language does not contain ‘a’ as the substring.  
L2 = {b, bb, bbb, ..............}
The state transition diagram of the language containing ‘a’ as the substring will be like:  
In the above DFA, states ‘X’ and ‘Y’ are the initial and final state respectively, it accepts all the strings containing ‘a’ as the substring. Here as we see that on getting input as ‘b’ it remains in the state of ‘X’ itself but on getting ‘a’ as the input it transit to final state ‘Y’ and hence such string is accepted by above DFA. 
Problem-2: Construction of a minimal DFA accepting set of string over {a, b} where each string containing ‘ab’ as the substring. 
Explanation: The desired language will be like:  
L1 = {ab, aab, abb, bab, ..............}
Here as we can see that each string of the language containing ‘ab’ as the substring but the below language is not accepted by this DFA because some of the string of the below language does not contain ‘ab’ as the substring-  
L2 = {aba, bba, bbbaaa, ..............}
The state transition diagram of the language containing ‘ab’ as the substring will be like:  
In the above DFA, states ‘X’ and ‘Z’ are the initial and final state respectively, it accepts all the strings containing ‘ab’ as the substring. Here as we see that on getting ‘b’ as the input it remains in the state of initial state itself, on getting ‘a’ as the input it transit to state ‘Y’ and then on getting ‘b’ it finally transit to the final state ‘Z’ and hence this DFA is accepting all the language containing ‘ab’ as the substring. 
avipanwar6565
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Semaphores in Process Synchronization
Types of Network Topology
Difference between DFA and NFA
Turing Machine in TOC
Difference between Mealy machine and Moore machine
Conversion from NFA to DFA
Introduction of Pushdown Automata
Matplotlib.axis.Axis.axis_date() function in Python - GeeksforGeeks

05 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack.
The Axis.axis_date() function in axis module of matplotlib library is used to set up axis ticks and labels treating data along this axis as dates.  
Syntax: Axis.axis_date(self, tz=None) 
Parameters: This method accepts the following parameters. 
tz : This parameter is the timezone used to create date labels.
Return value: This method does not return any value. 
Below examples illustrate the matplotlib.axis.Axis.axis_date() function in matplotlib.axis:
Example 1:
Python3
# Implementation of matplotlib function from matplotlib.axis import Axisimport datetime as dtimport matplotlib.pyplot as pltfrom matplotlib.dates import DateFormatter, MinuteLocator  x = [16.7,16.8,17.1,17.4]y = [15,17,14,16]plt.plot(x, y)  plt.gca().yaxis.axis_date()  plt.title("Matplotlib.axis.Axis.axis_date()\Function Example", fontsize = 12, fontweight ='bold')  plt.show()
Output: 
Example 2: 
Python3
# Implementation of matplotlib function from matplotlib.axis import Axis  from datetime import datetime import matplotlib.pyplot as plt from matplotlib.dates import (     DateFormatter, AutoDateLocator, AutoDateFormatter, datestr2num )         days = [     '30/01/2019',     '31/01/2019',      '01/02/2019',     '02/02/2019',      '03/02/2019',      '04/02/2019'] data1 = [2, 5, 13, 6, 11, 7] data2 = [6, 3, 10, 3, 6, 5]     z = datestr2num([     datetime.strptime(day, '%d/%m/%Y').strftime('%m/%d/%Y')     for day in days ])     r = 0.25    figure = plt.figure(figsize =(8, 4)) axes = figure.add_subplot(111)     axes.bar(z - r, data1, width = 2 * r,          color ='g', align ='center',          tick_label = days)  axes.bar(z + r, data2, width = 2 * r,          color ='y', align ='center',           tick_label = days)     axes.xaxis.axis_date()  plt.title("Matplotlib.axis.Axis.axis_date()\Function Example", fontsize = 12, fontweight ='bold')   plt.show()
Output: 
 
Matplotlib-Axis Class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Python | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Python Pillow - Image Sequences

The Python Imaging Library (PIL) contains some basic support for Image sequences (animation formats). FLI/FLC, GIF and a few experimental formats are the supported sequence formats. TIFF files can contain more than one frame as well.
Opening a sequence file, PIL automatically loads the first frame in the sequence. To move between different frames, you can use the seek and tell methods.
from PIL import Image
img = Image.open('bird.jpg')
#Skip to the second frame
img.seek(1)
try:
   while 1:
      img.seek(img.tell() + 1)
      #do_something to img
except EOFError:
   #End of sequence
   pass
raise EOFError
EOFError

As we can see above, you’ll get an EOFError exception when the sequence ends.
Most drivers in the latest version of library only allow you to seek to the next frame (as in above example), to rewind the file, you may have to reopen it.
class ImageSequence:
   def __init__(self, img):
      self.img = img
   def __getitem__(self, ix):
      try:
         if ix:
            self.img.seek(ix)
         return self.img
      except EOFError:
         raise IndexError # end of sequence
for frame in ImageSequence(img):
   # ...do something to frame...

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Data Structures | Misc | Question 4 - GeeksforGeeks

28 Jun, 2021
The best data structure to check whether an arithmetic expression has balanced parentheses is a (GATE CS 2004)
(A) queue(B) stack(C) tree(D) listAnswer: (B)Explanation: There are three types of parentheses [ ] { } (). Below is an arbit c code segment which has parentheses of all three types.
void func(int c, int a[]){   return  ((c +2)  + arr[(c-2)]) ; }
Stack is a straightforward choice for checking if left and right parentheses are balanced. Here is a algorithm to do the same.
/*Return 1 if expression has balanced parentheses */bool areParenthesesBalanced(expression ){    for each character in expression   {      if(character == ’(’ || character == ’{’ || character == ’[’)         push(stack, character);      if(character == ’)’ || character == ’}’ || character == ’]’)       {         if(isEmpty(stack))             return 0; /*We are seeing a right parenthesis                         without a left pair*/           /* Pop the top element from stack, if it is not a pair             bracket of character then there is a mismatch.              This will happen for expressions like {(}) */         else if (! isMatchingPair(pop(stack), character) )            return 0;         }   }       if(isEmpty(stack))     return 1; /*balanced*/   else       return 0;  /*not balanced*/   } /* End of function to check parentheses */  /* Returns 1 if character1 and character2 are matching left   and right parentheses */bool isMatchingPair(character1, character2){   if(character1 == ‘(‘ && character2 == ‘)’)     return 1;   else If(character1 == ‘{‘ && character2 == ‘}’)     return 1;   else If(character1 == ‘[‘ && character2 == ‘]’)     return 1;   else      return 0;}
Quiz of this Question
Data Structures
Data Structures-Misc
Misc
Data Structures
Misc
Data Structures
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C program to implement Adjacency Matrix of a given Graph
Advantages and Disadvantages of Linked List
Difference between Singly linked list and Doubly linked list
FIFO vs LIFO approach in Programming
Multilevel Linked List
Advantages of vector over array in C++
Difference between data type and data structure
Data Structures | Array | Question 2
Bit manipulation | Swap Endianness of a number
Data Structures | Queue | Question 1
How to change MySQL column definition?

To change MySQL column definition, we can use modify or change clause with ALTER command. Let us first create a table with a column as ID, with int data type. We will modify the same column name with varchar data type.
Creating a table.
mysql> create table ModifyColumnDemo
   -> (
   -> id int
   -> );
Query OK, 0 rows affected (0.52 sec)
Now, let us write the syntax to change the column definition. The syntax is as follows −
alter table yourTableName modify column columnName data type;
Apply the above syntax to change the MySQL definition.
mysql> alter table ModifyColumnDemo modify column id varchar(10) not null;
Query OK, 0 rows affected (1.52 sec)
Records: 0  Duplicates: 0  Warnings: 0
Let us now check whether the column has been change with the new data type or not. For that, we will be using the DESC command.
mysql> desc ModifyColumnDemo;
The following is the output.
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | varchar(10) | NO   |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
1 row in set (0.15 sec)

You can see in the above output, we have changed the column definition with new datatype varchar.
How to use AutoCompleteTextView in Android App?

This example demonstrate about How to use AutoCompleteTextView in Android App.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.java
<? xml version= "1.0" encoding= "utf-8" ?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
   xmlns: tools = "http://schemas.android.com/tools"
   android :layout_width= "match_parent"
   android :layout_height= "match_parent"
   android :layout_margin= "16dp"
   android :orientation= "vertical"
   tools :context= ".MainActivity" >
   <android.support.v7.widget.AppCompatAutoCompleteTextView
      android :id= "@+id/autoTextView"
      android :layout_width= "match_parent"
      android :layout_height= "wrap_content"
      android :hint= "Enter fruit name"
      android :textColor= "#000000"
      android :textColorHint= "#000000" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.sample ;
import android.os.Bundle ;
import android.support.v7.app.AppCompatActivity ;
import android.support.v7.widget.AppCompatAutoCompleteTextView ;
import android.widget.ArrayAdapter ;
public class MainActivity extends AppCompatActivity {
   private String[] fruits = { "Apple" , "Banana" , "Cherry" , "Date" , "Grape" , "Kiwi" , "Mango" , "Pear" } ;
   @Override
   protected void onCreate (Bundle savedInstanceState) {
      super .onCreate(savedInstanceState) ;
      setContentView(R.layout. activity_main ) ;
      AppCompatAutoCompleteTextView autoTextView = findViewById(R.id. autoTextView ) ;
      ArrayAdapter<String> adapter = new ArrayAdapter<>( this,
      android.R.layout. select_dialog_item , fruits ) ;
      autoTextView.setThreshold( 1 ) ; //will start working from first character
      autoTextView.setAdapter(adapter) ;
   }
}
Step 4 − Add the following code to androidManifest.xml
<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
   package= "app.tutorialspoint.com.sample" >
   <uses-permission android :name= "android.permission.VIBRATE" />
   <application
      android :allowBackup= "true"
      android :icon= "@mipmap/ic_launcher"
      android:label= "@string/app_name"
      android:roundIcon= "@mipmap/ic_launcher_round"
      android:supportsRtl= "true"
      android:theme= "@style/AppTheme" >
      <activity android:name= ".MainActivity" >
         <intent-filter>
            <action android:name= "android.intent.action.MAIN" />
            <category android:name= "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
How to check whether a form or a control is invalid or not in Angular 10 ? - GeeksforGeeks

24 May, 2021
In this article, we are going to check whether a form is invalid or not in Angular 10. invalid property is used to report that the control or the form is invalid or not.
Syntax:
form.invalid 
Return Value:
boolean: the boolean value to check whether a form is invalid or not.
NgModule: Module used by the invalid property is:
FormsModule
Approach: 
Create the Angular app to be used.
In app.component.html make a form using ngForm directive.
In app.component.ts get the information using the invalid property.
Serve the angular app using ng serve to see the output.
Example 1:
app.component.ts
import { Component } from '@angular/core';import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms'  @Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.css']})export class AppComponent {  form = new FormGroup({    name: new FormControl(            ),    rollno: new FormControl() });  get name(): any {  return this.form.get('name');}  onSubmit(): void {  console.log("Form is invalid : ",this.form.invalid);}}
app.component.html
<form [formGroup]="form" (ngSubmit)="onSubmit()">  <input formControlName="name" placeholder="Name"><br><button type='submit'>Submit</button><br><br></form>
Output:
Reference: https://angular.io/api/forms/AbstractControlDirective#invalid
Angular10
AngularJS-Basics
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to Install Julia Programming Language on Linux ?

19 Feb, 2020
Julia is a programming language used for mathematical computations and scientific data analysis. Julia is an open-source high-performance language that is used to perform statistical calculations and general-purpose programming.
Julia programs can be written in any of the widely used text editors like Notepad, Notepad++, gedit, etc. or on any of the text-editors. One can also use an online IDE for writing Julia codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Julia Codes and performing various intriguing and useful operations, one must have Julia installed on their System. This can be done by following the step by step instructions provided below:
Before we begin with the installation of Julia, it is good to check if it might be already installed on your system. To check if your device is preinstalled with Julia or not, just go to the terminal and type:
julia
Julia can be downloaded and installed in Linux with the use of a package manager known as ‘Snaps’. Follow the steps given below to install Snaps and Julia in a Linux system using command-line: Step 1: Open Terminal, type the following command and press Enter.
sudo apt install snapd
 Step 2: Wait for the Snap package to unpack the files and install them in the registry. Step 3: Once the installation of Snap is over, clear the terminal and begin with the Julia Installation process. Step 4: Use the following command to install Julia and then press Enter. Step 5: Now Terminal will download Julia online and will begin with the installation process Step 6: Mounting Julia on the Destination Drive after completing the download. Step 7: Installation of Julia is now over, you can proceed with the next step to Start Julia compiler and begin with writing Julia programming codes. Step 8: Enter the following command to begin with the Julia compiler and to confirm if the installation is completed successfully. Type the following command and press Enter:
julia
 After completing the installation process, any IDE or text editor can be used to write Julia Codes and Run them on the IDE or the terminal with the use of command:
julia file_name.jl
Let’s consider a simple Hello World Program.
# Julia program to print Hello World    # print functionprintln("Hello World !") 
Output:
Julia-Basics
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Storing Output on a File in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Manipulating matrices in Julia
Exception handling in Julia
Creating array with repeated elements in Julia - repeat() Method
while loop in Julia
Tuples in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Generating sequenced Vectors in R Programming – sequence() Function

15 Jun, 2020
sequence() function in R Language is used to create a vector of sequenced elements. It creates vectors with specified length, and specified differences between elements. It is similar to seq() function.
Syntax: sequence(x)
Parameters:x: Maximum element of vector
Example 1:
# R program to create sequence of vectors  # Calling sequence() functionsequence(4)sequence(6)sequence(c(4, 6))
Output:
[1] 1 2 3 4
[1] 1 2 3 4 5 6
[1] 1 2 3 4 1 2 3 4 5 6

Example 2:
# R program to create sequence of vectors  # Calling sequence() functionsequence(1:4)  # Performing operationsx <- 2 * sequence(4)x
Output:
[1] 1 1 2 1 2 3 1 2 3 4
[1] 2 4 6 8

R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
How to Split Column Into Multiple Columns in R DataFrame?
Printing Output of an R Program
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
R Programming Language - Introduction
How to Change Axis Scales in R Plots?
Deleting MySQL Database Using PHP

If a database is no longer required then it can be deleted forever. You can use pass an SQL command to mysql_query to delete a database.
Try out following example to drop a database.
<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);
   
   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
   
   $sql = 'DROP DATABASE test_db';
   $retval = mysql_query( $sql, $conn );
   
   if(! $retval ) {
      die('Could not delete database db_test: ' . mysql_error());
   }
   
   echo "Database deleted successfully\n";
   
   mysql_close($conn);
?>
WARNING − its very dangerous to delete a database and any table. So before deleting any table or database you should make sure you are doing everything intentionally.
Its again a matter of issuing one SQL command through mysql_query function to delete any database table. But be very careful while using this command because by doing so you can delete some important information you have in your table.
Try out following example to drop a table −
<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);
   
   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
   
   $sql = 'DROP TABLE employee';
   $retval = mysql_query( $sql, $conn );
   
   if(! $retval ) {
      die('Could not delete table employee: ' . mysql_error());
   }
   
   echo "Table deleted successfully\n";
LocalDate ofEpochDay() method in Java with Examples

21 May, 2020
The ofEpochDay(long epochDay) method of LocalDate class in Java is used to obtain an instance of LocalDate from the epoch day count. Epoch day is 01-01-1970(DD-MM-YYYY). This is considered as a start of the epoch day. The method returns the LocalDate by adding the passed days into Epoch date i.e. 01-01-1970. Suppose 2 is passed as a parameter, the method will return 03-01-1970 (2 is added to ’01’ from the epoch day(DD)). Similarly, if 365 is passed then a whole new year will be added to the epoch date.
Syntax:
public static LocalDate ofEpochDay(long epochDay)

Parameters: This method accepts one parameter epochDay which is the conversion base.
Return Value: This method returns the localdate after conversion.
Exceptions: This method throws DateTimeException if the epoch day exceeds the supported date range.
Below programs illustrate the ofEpochDay(long epochDay) method in Java:
Program 1:
// Java program to demonstrate// LocalDate.ofEpochDay(long epochDay) method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {        // Create LocalDate object        LocalDate localdate            = LocalDate.ofEpochDay(100);          // Display full date        System.out.println("Date: "                           + localdate);    }}
Date: 1970-04-11

Program 2:
// Java program to demonstrate// LocalDate.ofEpochDay(long epochDay) method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {        // Create LocalDate object        LocalDate localdate            = LocalDate.ofEpochDay(365);          // Display date        System.out.println("Date: "                           + localdate);    }}
Date: 1971-01-01

References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#ofEpochDay(long)
Java-Functions
Java-LocalDate
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Properties keys() method in Java with Examples

30 Sep, 2019
The keys() method of Properties class is used to get the enumeration of the keys in this Properties object. This enumeration can be used to traverse and iterate the keys sequentially.
Syntax:
public Enumeration keys()
Parameters: This method accepts no parameters
Returns: This method returns an Enumeration of the keys of this Properties object sequentially.
Below programs show the implementation of int keys() method.
Program 1:
// Java code to show the implementation of// keys() method  import java.util.*;public class GfG {      // Main method    public static void main(String[] args)    {          // Create a properties and add some values        Properties properties = new Properties();        properties.put("Pen", 10);        properties.put("Book", 500);        properties.put("Clothes", 400);        properties.put("Mobile", 5000);          // Print Properties details        System.out.println("Properties: "                           + properties.toString());          // Creating an empty enumeration to store        Enumeration enu = properties.keys();          System.out.println("The enumeration of keys are:");          // Displaying the Enumeration        while (enu.hasMoreElements()) {            System.out.println(enu.nextElement());        }    }}
Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}
The enumeration of keys are:
Book
Mobile
Pen
Clothes

Program 2:
// Java program to demonstrate// keys() method.  import java.util.*;  public class GFG {      // Main method    public static void main(String[] args)    {          // Create a properties and add some values        Properties properties = new Properties();          // Inserting elements into the properties        properties.put("Geeks", 10);        properties.put("4", 15);        properties.put("Geeks", 20);        properties.put("Welcomes", 25);        properties.put("You", 30);          // Print Properties details        System.out.println("Current Properties: "                           + properties.toString());          // Creating an empty enumeration to store        Enumeration enu = properties.keys();          System.out.println("The enumeration of keys are:");          // Displaying the Enumeration        while (enu.hasMoreElements()) {            System.out.println(enu.nextElement());        }    }}
Current Properties: {You=30, Welcomes=25, 4=15, Geeks=20}
The enumeration of keys are:
You
Welcomes
4
Geeks

References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#keys–
Akanksha_Rai
Java - util package
Java-Functions
Java-Properties
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
PyCairo – Drawing Bezier curve

23 Jan, 2022
In this article we will learn how we can draw a simple bezier curve using PyCairo in python. A Bezier curve is a versatile mathematical curve that can be used to create a wide variety of different shapes in vector graphics. 
PyCairo : Pycairo is a Python module providing bindings for the cairo graphics library.This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format.  
SVG file is a graphics file that uses a two-dimensional vector graphic format created by the World Wide Web Consortium (W3C). It describes images using a text format that is based on XML. SVG files are developed as a standard format for displaying vector graphics on the web.
Steps of Implementation :
Import the Pycairo module.Create a SVG surface object and add context to it.Creating curve using curve_to ( )Setting context color and width
Import the Pycairo module.
Create a SVG surface object and add context to it.
Creating curve using curve_to ( )
Setting context color and width
Below is the Implementation :
Python3
# importing pycairoimport cairo # creating a SVG surface# here geek95 is file name & 700, 700 is dimensionwith cairo.SVGSurface("geek95.svg", 700, 700) as surface:     # creating a cairo context object for SVG surface    # using Context method    context = cairo.Context(surface)     # move the context to x,y position    context.move_to(50, 200)    # Drawing Curve    context.curve_to(150, 75, 225, 50, 350, 150)    # setting color of the context    context.set_source_rgb(1, 0, 0)    # setting width of the context    context.set_line_width(4)    # stroke out the color and width property    context.stroke() # printing message when file is savedprint("File Saved")
Output :
saurabh1990aror
Python-PyCairo
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
How to pass an array by reference in C++

If we pass the address of an array while calling a function, then this is called function call by reference. The function declaration should have a pointer as a parameter to receive the passed address, when we pass an address as an argument.
 Live Demo
#include <iostream>
using namespace std;
void show( int *num) {
   cout<<*num;
}
int main() {
   int a[] = {3,2,1,6,7,4,5,0,10,8};
   for (int i=0; i<10; i++) {
      show (&a[i]);
   }
   return 0;
}
32167450108
How to Calculate the determinant of a matrix using NumPy?

05 Sep, 2020
A special number that can be calculated from a square matrix is known as the Determinant of a square matrix. The Numpy provides us the feature to calculate the determinant of a square matrix using numpy.linalg.det() function.
Syntax:
numpy.linalg.det(array)

Example 1: Calculating Determinant of a 2X2 Numpy matrix using numpy.linalg.det() function
Python3
# importing Numpy packageimport numpy as np  # creating a 2X2 Numpy matrixn_array = np.array([[50, 29], [30, 44]])  # Displaying the Matrixprint("Numpy Matrix is:")print(n_array)  # calculating the determinant of matrixdet = np.linalg.det(n_array)  print("\nDeterminant of given 2X2 matrix:")print(int(det))
Output:
In the above example, we calculate the Determinant of the 2X2 square matrix.
Example 2: Calculating Determinant of a 3X3 Numpy matrix using numpy.linalg.det() function
Python3
# importing Numpy packageimport numpy as np  # creating a 3X3 Numpy matrixn_array = np.array([[55, 25, 15],                    [30, 44, 2],                    [11, 45, 77]])  # Displaying the Matrixprint("Numpy Matrix is:")print(n_array)  # calculating the determinant of matrixdet = np.linalg.det(n_array)  print("\nDeterminant of given 3X3 square matrix:")print(int(det))
Output:
In the above example, we calculate the Determinant of the 3X3 square matrix.
Example 3: Calculating Determinant of a 5X5 Numpy matrix using numpy.linalg.det() function
Python3
# importing Numpy packageimport numpy as np  # creating a 5X5 Numpy matrixn_array = np.array([[5, 2, 1, 4, 6],                    [9, 4, 2, 5, 2],                    [11, 5, 7, 3, 9],                    [5, 6, 6, 7, 2],                    [7, 5, 9, 3, 3]])  # Displaying the Matrixprint("Numpy Matrix is:")print(n_array)  # calculating the determinant of matrixdet = np.linalg.det(n_array)  print("\nDeterminant of given 5X5 square matrix:")print(int(det))
Output:
In the above example, we calculate the Determinant of the 5X5 square matrix.
Python numpy-Matrix Function
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 OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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
Python | datetime.timedelta() function
Difference between Inverted Index and Forward Index

Inverted Index and Forward Index are data structures used to search text in a document or set of documents.
Inverted Index stores the words as index and document name(s) as mapped reference(s).
Forward Index stores the document name as index and word(s) as mapped reference(s).
The following are some of the important differences between the Inverted Index and Forward Index.
Scan the document, prepare a list of unique words.
Scan the document, prepare a list of unique words.
Prepare a list of indexes of all unique words and map them to document search.
Prepare a list of indexes of all unique words and map them to document search.
Repeat the above steps for all the documents.
Repeat the above steps for all the documents.
Scan the document, prepare list of unique words.
Scan the document, prepare list of unique words.
Map all the words to document as an index.
Map all the words to document as an index.
Repeat the above steps for all the documents.
Repeat the above steps for all the documents.
Word Documents
-------------------------
Welcome doc1
Hello doc1, doc3
Hi doc2
-------------------------
Word Documents
-------------------------
doc1 Welcome, Hello
doc2 Hi
doc3 Hello
-------------------------
How to place the cursor (auto focus) in the text box when a page gets loaded with HTML?

Use the autofocus attribute to place the cursor in the text box when a page loads. The autofocus attribute is a Boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads. Here is an example −
<!DOCTYPE html>
<html>
   <body>

      <form action = "/new.php">
         Name: <input type = "text" name = "name" autofocus><br>
         Subject: <input type = "text" name = "sub"><br>
         <input type = "submit">
      </form>

   </body>
</html>
How to get the list of all drivers registered with the DriverManager using JDBC?

The java.sql.DriverManager class manages JDBC drivers in your application. This class maintains a list of required drivers and load them whenever it is initialized.
Therefore, you need to register the driver class before using it. However, you need to do it only once per application.
One way to register a driver class object to Driver manager is the registerDriver() method of the DriverManager class. To this method you need to pass the Driver object as a parameter.
//Instantiating a driver class Driver driver = new com.mysql.jdbc.Driver();
//Registering the Driver DriverManager.registerDriver(driver);
You can get the list of all the drivers registered with this DriverManager class using the getDrivers() method of it. This method returns an Enumeration containing the list of drivers.
//Retrieving the list of all the Drivers
Enumeration<Driver> e = DriverManager.getDrivers();
//Printing the list
while(e.hasMoreElements()) {
   System.out.println(e.nextElement().getClass());
}
Following JDBC program registers a bunch of JDBC drivers using the registerDriver() method and, displays the list of them using the getDrivers() method.
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Enumeration;
public class DriversList_DriverManager {
   public static void main(String args[])throws Exception {
      //Registering MySQL driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Registering SQLite driver
      DriverManager.registerDriver(new org.sqlite.JDBC());
      //Registering Oracle driver
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      //Registering Derby-client driver
      DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver());
      //Registering Derby-autoloaded driver
      DriverManager.registerDriver(new org.apache.derby.jdbc.AutoloadedDriver());
      //Registering HSQLDb-JDBC driver
      DriverManager.registerDriver(new org.hsqldb.jdbc.JDBCDriver());
      System.out.println("List of all the Drivers registered with the DriverManager:");
      //Retrieving the list of all the Drivers
      Enumeration<Driver> e = DriverManager.getDrivers();
      //Printing the list
      while(e.hasMoreElements()) {
         System.out.println(e.nextElement().getClass());
      }
      System.out.println();
   }
}
List of all the Drivers registered with the DriverManager:
class org.sqlite.JDBC
class org.apache.derby.jdbc.ClientDriver
class org.apache.derby.jdbc.AutoloadedDriver
class org.hsqldb.jdbc.JDBCDriver
class com.mysql.jdbc.Driver
class oracle.jdbc.driver.OracleDriver
Java program to convert a list to an array

The List object provides a method known as toArray(). This method accepts an empty array as argument, converts the current list to an array and places in the given array. To convert a List object to an array −
 Create a List object.
 Add elements to it.
 Create an empty array with size of the created ArrayList.
 Convert the list to an array using the toArray() method, bypassing the above-created array as an argument to it.
 Print the contents of the array.
Live Demo
import java.util.ArrayList;
public class ListToArray {
   public static void main(String args[]){
      ArrayList<String> list = new ArrayList<String>();
      list.add("Apple");
      list.add("Orange");
      list.add("Banana");

      System.out.println("Contents of list ::"+list);
      String[] myArray = new String[list.size()];
      list.toArray(myArray);

      for(int i=0; i<myArray.length; i++){
         System.out.println("Element at the index "+i+" is ::"+myArray[i]);
      }
   }
}
Contents of list ::[Apple, Orange, Banana]
Element at the index 0 is ::Apple
Element at the index 1 is ::Orange
Element at the index 2 is ::Banana
Exception handling and object destruction in C++

Destructors in C++ basically called when objects will get destroyed and release memory from the system. When an exception is thrown in the class, the destructor is called automatically before the catch block gets executed.
Begin
   Declare a class sample1.
      Declare a constructor of sample1.
         Print “Construct an Object of sample1”
      Declare a destructor of sample1.
         Print “Destruct an Object of sample1”
   Declare a class sample.
      Declare a constructor of sample2.
         Declare variable i of the integer datatype.
         Initialize i = 7.
         Print “Construct an Object of sample1”.
         Throw i.
      Declare a destructor of sample2.
         Print “Destruct an Object of sample2”
   Try:
      Declare an object s1 of class sample1.
      Declare an object s2 of class sample2.
   Ctach(int i)
      Print “Caught”.
      Print the value of variable i.
End.
 Live Demo
#include <iostream>
using namespace std;
class Sample1 {
   public:
      Sample1() {
         cout << "Construct an Object of sample1" << endl;
      }
      ~Sample1() {
         cout << "Destruct an Object of sample1" << endl;
      }
};
class Sample2 {
   public:
      Sample2() {
         int i =7;
         cout << "Construct an Object of sample2" << endl;
         throw i;
      }
      ~Sample2() {
         cout << "Destruct an Object of sample2" << endl;
      }
};
int main() {
   try {
      Sample1 s1;
      Sample2 s2;
   } catch(int i) {
      cout << "Caught " << i << endl;
   }
}
Construct an Object of sample1
Construct an Object of sample2
Destruct an Object of sample1
Caught 7
What is onclick event in JavaScript?

The onClick event is the most frequently used event type, which occurs when a user clicks the left button of the mouse.
You can put your validation, warning etc., against this event type.
Live Demo
<html>
   <head>
      <script>
         <!--
            function sayHello() {
               alert("Hello World")
            }
         //-->
      </script>
   </head>
   <body>
      <p>Click the following button and see result</p>
      <form>
         <input type="button" onclick="sayHello()" value="Say Hello" />
      </form>
   </body>
</html>
How to get the number of rows and columns of a JTable in Java Swing

To count the number of rows of a table, use the getRowCount() method −
table.getRowCount()
To count the number of columns of a table, use the getColumnCount() method −
table.getColumnCount()
The following is an example to get the number of rows and columns of a JTable −
package my;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      DefaultTableModel tableModel = new DefaultTableModel();
      JTable table = new JTable(tableModel);
      tableModel.addColumn("Language/ Technology");
      tableModel.addColumn("Text Tutorial");
      tableModel.addColumn("Video Tutorial");
      tableModel.addColumn("Views");
      // prevent from resizing
      table.getTableHeader().setResizingAllowed(false);
      tableModel.addRow(new Object[] { "F#", "Yes", "No", "7890"});
      tableModel.addRow(new Object[] { "Blockchain", "Yes", "No", "10600"});
      tableModel.addRow(new Object[] { "SharePoint", "Yes", "Yes", "4900"});
      tableModel.addRow(new Object[] { "AWS", "No", "Yes", "8900"});
      tableModel.addRow(new Object[] { "Python", "Yes", "No", "6789"});
      tableModel.addRow(new Object[] { "Scala", "Yes", "No", "3400"});
      tableModel.addRow(new Object[] { "Swift", "No", "Yes", "9676"});
      tableModel.addRow(new Object[] { "C#", "Yes", "Yes", "1300"});
      tableModel.addRow(new Object[] { "NodeJS", "No", "Yes", "2350"});
      tableModel.addRow(new Object[] { "MVC", "Yes", "No", "1500"});
      tableModel.addRow(new Object[] { "ASP.NET", "Yes", "Yes", "3400"});
      tableModel.addRow(new Object[] { "Java", "Yes", "No", "9686"});
      tableModel.addRow(new Object[] { "jQuery", "Yes", "Yes", "4500"});
      System.out.println("Table rows = "+table.getRowCount());
      System.out.println("Table columns = "+table.getColumnCount());
      Font font = new Font("Verdana", Font.PLAIN, 12);
      table.setFont(font);
      JFrame frame = new JFrame();
      frame.setSize(600, 400);
      frame.add(new JScrollPane(table));
      frame.setVisible(true);
   }
}
This will produce the following output displaying the table with rows and columns −
The count of rows and columns are displayed in the console as shown below −
Java Examples - Debug a java file

How to set destination of the class file?
Following example demonstrates how to debug a java file using =g option with javac command.
c:> javac demo.java -g

The above code sample will produce the following result.
Demo.java will debug.

 Print
 Add Notes
 Bookmark this page
Remove trailing zeros in decimal value with changing length in MySQL?

You can remove trailing zeros using TRIM() function. The syntax is as follows.
SELECT TRIM(yourColumnName)+0 FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table removeTrailingZeroInDecimal
   -> (
   -> Id int not null auto_increment,
   -> Amount decimal(5,2),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.01 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into removeTrailingZeroInDecimal(Amount) values(405.50);
Query OK, 1 row affected (0.22 sec)

mysql> insert into removeTrailingZeroInDecimal(Amount) values(23.05);
Query OK, 1 row affected (0.17 sec)

mysql> insert into removeTrailingZeroInDecimal(Amount) values(12.050);
Query OK, 1 row affected (0.14 sec)

mysql> insert into removeTrailingZeroInDecimal(Amount) values(125.23);
Query OK, 1 row affected (0.14 sec)

mysql> insert into removeTrailingZeroInDecimal(Amount) values(125.00);
Query OK, 1 row affected (0.15 sec)

mysql> insert into removeTrailingZeroInDecimal(Amount) values(126);
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from removeTrailingZeroInDecimal;
The following is the output.
+----+--------+
| Id | Amount |
+----+--------+
|  1 | 405.50 |
|  2 | 23.05  |
|  3 | 12.05  |
|  4 | 125.23 |
|  5 | 125.00 |
|  6 | 126.00 |
+----+--------+
6 rows in set (0.00 sec)
Here is the query to remove trailing zeros in decimal value. The query is as follows −
mysql> SELECT TRIM(Amount)+0 FROM removeTrailingZeroInDecimal;
The output displays the records without the trailing zeros.
+----------------+
| TRIM(Amount)+0 |
+----------------+
|          405.5 |
|          23.05 |
|          12.05 |
|         125.23 |
|            125 |
|            126 |
+----------------+
6 rows in set (0.00 sec)
Cypress - Data Driven Testing

Cypress data driven testing is achieved with the help of fixtures. Cypress fixtures are added to maintain and hold the test data for automation.
The fixtures are kept inside the fixtures folder (example.json file) in the Cypress project.Basically, it helps us to get data input from external files.
Cypress fixtures folder can have files in JavaScript Object Notation (JSON) or other formats and the data is maintained in "key:value" pairs.
All the test data can be utilised by more than one test. All fixture data has to be declared within the before hook block.
The syntax for Cypress data driven testing is as follows −
cy.fixture(path of test data)
cy.fixture(path of test data, encoding type)
cy.fixture(path of test data, opts)
cy.fixture(path of test data, encoding type, options)

Here,
path of test data is the path of test data file within fixtures folder.
path of test data is the path of test data file within fixtures folder.
encoding type − Encoding type (utf-8, asci, and so on) is used to read the file.
encoding type − Encoding type (utf-8, asci, and so on) is used to read the file.
Opts − Modifies the timeout for response. The default value is 30000ms. The wait
time for cy.fixture(), prior throws an exception.
Opts − Modifies the timeout for response. The default value is 30000ms. The wait
time for cy.fixture(), prior throws an exception.
Given below is the implementation of data driven testing with example.json in Cypress −
{
   "email": "abctest@gmail.com",
   "password": "Test@123"
}

The implementation of actual data driven testing in Cypress is as follows −
describe('Tutorialspoint Test', function () {
   //part of before hook
   before(function(){
      //access fixture data
      cy.fixture('example').then(function(signInData){
         this.signInData = signInData
      })
   })
   // test case
   it('Test Case1', function (){
      // launch URL
      cy.visit("https://www.linkedin.com/")
      //data driven from fixture
      cy.get('#session_key ')
      .type(this.signInData.email)
      cy.get('# session_password').type(this.signInData.password)
   });
});
Execution Results
The output is as follows
The output logs show the values abctest@gmail.com and Test@123 being fed to the Email and Password fields respectively. These data have been passed to the test from the fixtures.

    73 Lectures 
     12 hours 

 Rahul Shetty
 Print
 Add Notes
 Bookmark this page
How to create a Button in JavaFX?

In JavaFX the javafx.scene.control package provides various nodes (classes)
specially designed for UI applications and these are re-usable. You can customize
these and build view pages for your JavaFX applications. example: Button,
CheckBox, Label, etc.
A button is control in user interface applications, in general, on clicking the button it performs the respective action.
You can create a Button by instantiating the javafx.scene.control.Button class of this package and, you can set text to the button using the setText() method.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ButtonExample extends Application {
   @Override
   public void start(Stage stage) {
      //Creating a Button
      Button button = new Button();
      //Setting text to the button
      button.setText("Sample Button");
      //Setting the location of the button
      button.setTranslateX(150);
      button.setTranslateY(60);
      //Setting the stage
      Group root = new Group(button);
      Scene scene = new Scene(root, 595, 150, Color.BEIGE);
      stage.setTitle("Button Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}