title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Basic Authentication in Node.js using HTTP Header | 11 Feb, 2021
Authentication of the client is the first step before starting any Application. The basic authentication in the Node.js application can be done with the help express.js framework. Express.js framework is mainly used in Node.js application because of its help in handling and routing different types of requests and responses made by the client using different Middleware.
HTTP WWW-Authenticate header is a response-type header and it serves as a support for various authentication mechanisms which are important to control access to pages and other resources as well.
Explanation of the Authentication:
Module Installation: Install the express module using the following command.
npm install express
Project structure:
Project Structure
Filename- index.js
Javascript
// Requiring moduleconst express = require("express");const fs = require("fs");var path = require('path'); const app = express(); function authentication(req, res, next) { var authheader = req.headers.authorization; console.log(req.headers); if (!authheader) { var err = new Error('You are not authenticated!'); res.setHeader('WWW-Authenticate', 'Basic'); err.status = 401; return next(err) } var auth = new Buffer.from(authheader.split(' ')[1], 'base64').toString().split(':'); var user = auth[0]; var pass = auth[1]; if (user == 'admin' && pass == 'password') { // If Authorized user next(); } else { var err = new Error('You are not authenticated!'); res.setHeader('WWW-Authenticate', 'Basic'); err.status = 401; return next(err); } } // First step is the authentication of the clientapp.use(authentication)app.use(express.static(path.join(__dirname, 'public'))); // Server setupapp.listen((3000), () => { console.log("Server is Running ");})
Run index.js using the following command:
node index.js
Open any browser with http://localhost:3000 location in a private window(in order to avoid a saved password and username). A pop will occur near the address bar. Fill in the username and password that are mention in the code.
If the entered username and password match the mention, then location index.html will render on the browser.
Explanation: The first middleware is used for checking the authentication of the client when the server start and the client enter the localhost address. Initially req.headers.authorization is undefined and next() callback function return 401 status code unauthorized access to the browser. The client fills the credentials and the credentials encrypted in base64 format. After that, it decrypts the base64 format data that contains username and password, then after checking the username and password is correct, the next() method calls the next middleware that is mention below the authentication middleware, otherwise the authentication form pop again and again.
Request Header Details:
mridulmanochagfg
Node.js-Misc
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Windows
JWT Authentication with Node.js
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
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 ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Feb, 2021"
},
{
"code": null,
"e": 427,
"s": 54,
"text": "Authentication of the client is the first step before starting any Application. The basic authentication in the Node.js application can be done with the help express.js framework. Express.js framework is mainly used in Node.js application because of its help in handling and routing different types of requests and responses made by the client using different Middleware. "
},
{
"code": null,
"e": 623,
"s": 427,
"text": "HTTP WWW-Authenticate header is a response-type header and it serves as a support for various authentication mechanisms which are important to control access to pages and other resources as well."
},
{
"code": null,
"e": 658,
"s": 623,
"text": "Explanation of the Authentication:"
},
{
"code": null,
"e": 735,
"s": 658,
"text": "Module Installation: Install the express module using the following command."
},
{
"code": null,
"e": 755,
"s": 735,
"text": "npm install express"
},
{
"code": null,
"e": 774,
"s": 755,
"text": "Project structure:"
},
{
"code": null,
"e": 792,
"s": 774,
"text": "Project Structure"
},
{
"code": null,
"e": 811,
"s": 792,
"text": "Filename- index.js"
},
{
"code": null,
"e": 822,
"s": 811,
"text": "Javascript"
},
{
"code": "// Requiring moduleconst express = require(\"express\");const fs = require(\"fs\");var path = require('path'); const app = express(); function authentication(req, res, next) { var authheader = req.headers.authorization; console.log(req.headers); if (!authheader) { var err = new Error('You are not authenticated!'); res.setHeader('WWW-Authenticate', 'Basic'); err.status = 401; return next(err) } var auth = new Buffer.from(authheader.split(' ')[1], 'base64').toString().split(':'); var user = auth[0]; var pass = auth[1]; if (user == 'admin' && pass == 'password') { // If Authorized user next(); } else { var err = new Error('You are not authenticated!'); res.setHeader('WWW-Authenticate', 'Basic'); err.status = 401; return next(err); } } // First step is the authentication of the clientapp.use(authentication)app.use(express.static(path.join(__dirname, 'public'))); // Server setupapp.listen((3000), () => { console.log(\"Server is Running \");})",
"e": 1878,
"s": 822,
"text": null
},
{
"code": null,
"e": 1920,
"s": 1878,
"text": "Run index.js using the following command:"
},
{
"code": null,
"e": 1934,
"s": 1920,
"text": "node index.js"
},
{
"code": null,
"e": 2160,
"s": 1934,
"text": "Open any browser with http://localhost:3000 location in a private window(in order to avoid a saved password and username). A pop will occur near the address bar. Fill in the username and password that are mention in the code."
},
{
"code": null,
"e": 2269,
"s": 2160,
"text": "If the entered username and password match the mention, then location index.html will render on the browser."
},
{
"code": null,
"e": 2935,
"s": 2269,
"text": "Explanation: The first middleware is used for checking the authentication of the client when the server start and the client enter the localhost address. Initially req.headers.authorization is undefined and next() callback function return 401 status code unauthorized access to the browser. The client fills the credentials and the credentials encrypted in base64 format. After that, it decrypts the base64 format data that contains username and password, then after checking the username and password is correct, the next() method calls the next middleware that is mention below the authentication middleware, otherwise the authentication form pop again and again."
},
{
"code": null,
"e": 2960,
"s": 2935,
"text": "Request Header Details: "
},
{
"code": null,
"e": 2977,
"s": 2960,
"text": "mridulmanochagfg"
},
{
"code": null,
"e": 2990,
"s": 2977,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 3014,
"s": 2990,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3022,
"s": 3014,
"text": "Node.js"
},
{
"code": null,
"e": 3041,
"s": 3022,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3058,
"s": 3041,
"text": "Web Technologies"
},
{
"code": null,
"e": 3156,
"s": 3058,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3191,
"s": 3156,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 3223,
"s": 3191,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 3293,
"s": 3223,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 3320,
"s": 3293,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 3345,
"s": 3320,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 3407,
"s": 3345,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3468,
"s": 3407,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3518,
"s": 3468,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3561,
"s": 3518,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Output of Java Program | Set 9 | 19 Sep, 2018
Difficulty level : Intermediate
Predict the output of following Java Programs.
Program 1:
class Gfg{ // constructor Gfg() { System.out.println("Geeksforgeeks"); } static Gfg a = new Gfg(); //line 8 public static void main(String args[]) { Gfg b; //line 12 b = new Gfg(); }}
Output:
Geeksforgeeks
Geeksforgeeks
Explanation:We know that static variables are called when a class loads and static variables are called only once. Now line 13 results to creation of object which inturn calls the constructor and “Geeksforgeeks” is printed second time.If in line 8 static variable would not have been used the object would have been called recursively infinitely leading to StackOverFlow error. See this for a sample run.
Program 2:
class Gfg{ static int num; static String mystr; // constructor Gfg() { num = 100; mystr = "Constructor"; } // First Static block static { System.out.println("Static Block 1"); num = 68; mystr = "Block1"; } // Second static block static { System.out.println("Static Block 2"); num = 98; mystr = "Block2"; } public static void main(String args[]) { Gfg a = new Gfg(); System.out.println("Value of num = " + a.num); System.out.println("Value of mystr = " + a.mystr); }}
Output:
Static Block 1
Static Block 2
Value of num = 100
Value of mystr = Constructor
Explanation:Static block gets executed when the class is loaded in the memory. A class can have multiple Static blocks, which are executed in the same sequence in which they have been written into the program.Note: Static Methods can access class variables without using object of the class. Since constructor is called when a new instance is created so firstly the static blocks are called and after that the constructor is called. If we would have run the same program without using object, the constructor would not have been called.
Program 3:
class superClass{ final public int calc(int a, int b) { return 0; }}class subClass extends superClass{ public int calc(int a, int b) { return 1; }}public class Gfg{ public static void main(String args[]) { subClass get = new subClass(); System.out.println("x = " + get.calc(0, 1)); }}
Output:
Compilation fails.
Explanation:The method calc() in class superClass is final and so cannot be overridden.
Program 4:
public class Gfg{ public static void main(String[] args) { Integer a = 128, b = 128; System.out.println(a == b); Integer c = 100, d = 100; System.out.println(c == d); }}
Output:
false
true
Explanation: In the source code of Integer object we will find a method ‘valueOf’ in which we can see that the range of the Integer object lies from IntegerCache.low(-128) to IntegerCache.high(127). Therefore the numbers above 127 will not give the expected output. The range of IntegerCache can be observed from the source code of the IntegerCache class. Please refer this for details.
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
al_architjain
Java-Output
Java
Program Output
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Arrow operator -> in C/C++ with Examples
Output of C Programs | Set 1
Output of Java Program | Set 1
delete keyword in C++
Output of C++ programs | Set 50 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Sep, 2018"
},
{
"code": null,
"e": 86,
"s": 54,
"text": "Difficulty level : Intermediate"
},
{
"code": null,
"e": 133,
"s": 86,
"text": "Predict the output of following Java Programs."
},
{
"code": null,
"e": 144,
"s": 133,
"text": "Program 1:"
},
{
"code": "class Gfg{ // constructor Gfg() { System.out.println(\"Geeksforgeeks\"); } static Gfg a = new Gfg(); //line 8 public static void main(String args[]) { Gfg b; //line 12 b = new Gfg(); }}",
"e": 381,
"s": 144,
"text": null
},
{
"code": null,
"e": 389,
"s": 381,
"text": "Output:"
},
{
"code": null,
"e": 418,
"s": 389,
"text": "Geeksforgeeks\nGeeksforgeeks\n"
},
{
"code": null,
"e": 823,
"s": 418,
"text": "Explanation:We know that static variables are called when a class loads and static variables are called only once. Now line 13 results to creation of object which inturn calls the constructor and “Geeksforgeeks” is printed second time.If in line 8 static variable would not have been used the object would have been called recursively infinitely leading to StackOverFlow error. See this for a sample run."
},
{
"code": null,
"e": 836,
"s": 825,
"text": "Program 2:"
},
{
"code": "class Gfg{ static int num; static String mystr; // constructor Gfg() { num = 100; mystr = \"Constructor\"; } // First Static block static { System.out.println(\"Static Block 1\"); num = 68; mystr = \"Block1\"; } // Second static block static { System.out.println(\"Static Block 2\"); num = 98; mystr = \"Block2\"; } public static void main(String args[]) { Gfg a = new Gfg(); System.out.println(\"Value of num = \" + a.num); System.out.println(\"Value of mystr = \" + a.mystr); }}",
"e": 1439,
"s": 836,
"text": null
},
{
"code": null,
"e": 1447,
"s": 1439,
"text": "Output:"
},
{
"code": null,
"e": 1525,
"s": 1447,
"text": "Static Block 1\nStatic Block 2\nValue of num = 100\nValue of mystr = Constructor"
},
{
"code": null,
"e": 2062,
"s": 1525,
"text": "Explanation:Static block gets executed when the class is loaded in the memory. A class can have multiple Static blocks, which are executed in the same sequence in which they have been written into the program.Note: Static Methods can access class variables without using object of the class. Since constructor is called when a new instance is created so firstly the static blocks are called and after that the constructor is called. If we would have run the same program without using object, the constructor would not have been called."
},
{
"code": null,
"e": 2075,
"s": 2064,
"text": "Program 3:"
},
{
"code": "class superClass{ final public int calc(int a, int b) { return 0; }}class subClass extends superClass{ public int calc(int a, int b) { return 1; }}public class Gfg{ public static void main(String args[]) { subClass get = new subClass(); System.out.println(\"x = \" + get.calc(0, 1)); }}",
"e": 2415,
"s": 2075,
"text": null
},
{
"code": null,
"e": 2423,
"s": 2415,
"text": "Output:"
},
{
"code": null,
"e": 2443,
"s": 2423,
"text": "Compilation fails. "
},
{
"code": null,
"e": 2531,
"s": 2443,
"text": "Explanation:The method calc() in class superClass is final and so cannot be overridden."
},
{
"code": null,
"e": 2544,
"s": 2533,
"text": "Program 4:"
},
{
"code": "public class Gfg{ public static void main(String[] args) { Integer a = 128, b = 128; System.out.println(a == b); Integer c = 100, d = 100; System.out.println(c == d); }}",
"e": 2753,
"s": 2544,
"text": null
},
{
"code": null,
"e": 2761,
"s": 2753,
"text": "Output:"
},
{
"code": null,
"e": 2772,
"s": 2761,
"text": "false\ntrue"
},
{
"code": null,
"e": 3159,
"s": 2772,
"text": "Explanation: In the source code of Integer object we will find a method ‘valueOf’ in which we can see that the range of the Integer object lies from IntegerCache.low(-128) to IntegerCache.high(127). Therefore the numbers above 127 will not give the expected output. The range of IntegerCache can be observed from the source code of the IntegerCache class. Please refer this for details."
},
{
"code": null,
"e": 3461,
"s": 3159,
"text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3586,
"s": 3461,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3600,
"s": 3586,
"text": "al_architjain"
},
{
"code": null,
"e": 3612,
"s": 3600,
"text": "Java-Output"
},
{
"code": null,
"e": 3617,
"s": 3612,
"text": "Java"
},
{
"code": null,
"e": 3632,
"s": 3617,
"text": "Program Output"
},
{
"code": null,
"e": 3637,
"s": 3632,
"text": "Java"
},
{
"code": null,
"e": 3735,
"s": 3637,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3754,
"s": 3735,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3769,
"s": 3754,
"text": "Stream In Java"
},
{
"code": null,
"e": 3787,
"s": 3769,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3807,
"s": 3787,
"text": "Collections in Java"
},
{
"code": null,
"e": 3831,
"s": 3807,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3872,
"s": 3831,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 3901,
"s": 3872,
"text": "Output of C Programs | Set 1"
},
{
"code": null,
"e": 3932,
"s": 3901,
"text": "Output of Java Program | Set 1"
},
{
"code": null,
"e": 3954,
"s": 3932,
"text": "delete keyword in C++"
}
]
|
Accenture Archives - GeeksforGeeks | Binary Search
Insertion Sort
N-th root of a number
Accenture Interview Experience 2021
Randomized Binary Search Algorithm
Accenture Interview Experience for Associate Software Engineer (Off-Campus) 2022
Accenture Interview Experience | Set 1 (On-Campus)
Program for replacing one digit with other
Accenture Interview Experience for Associate Software Engineer (2021)
Accenture Interview Experience for Advanced Associate Software Engineer 2021 | [
{
"code": null,
"e": 24144,
"s": 24130,
"text": "Binary Search"
},
{
"code": null,
"e": 24159,
"s": 24144,
"text": "Insertion Sort"
},
{
"code": null,
"e": 24181,
"s": 24159,
"text": "N-th root of a number"
},
{
"code": null,
"e": 24217,
"s": 24181,
"text": "Accenture Interview Experience 2021"
},
{
"code": null,
"e": 24252,
"s": 24217,
"text": "Randomized Binary Search Algorithm"
},
{
"code": null,
"e": 24333,
"s": 24252,
"text": "Accenture Interview Experience for Associate Software Engineer (Off-Campus) 2022"
},
{
"code": null,
"e": 24384,
"s": 24333,
"text": "Accenture Interview Experience | Set 1 (On-Campus)"
},
{
"code": null,
"e": 24427,
"s": 24384,
"text": "Program for replacing one digit with other"
},
{
"code": null,
"e": 24497,
"s": 24427,
"text": "Accenture Interview Experience for Associate Software Engineer (2021)"
}
]
|
PyQt5 – Create Paint Application | 08 Oct, 2021
There are so many options provided by Python to develop GUI application and PyQt5 is one of them. PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library.
In this article we will see how we can create a Paint application using PyQt5. Our Paint application will consist of following
Features :
User can select different brush sizes User can select different brush color Saving of the canvas Clearing the whole canvas at once
User can select different brush sizes
User can select different brush color
Saving of the canvas
Clearing the whole canvas at once
Steps for designing the widgets –1. Create a window sets its geometry and title 2. Create menu bar 3. Inside menu bar add different menus, that are file menu, size menu and color menu 4. Add save and clear action to the file menu
5. Add different brush sizes action to the brush size menu
6. Add different brush color action to the brush color menu
7. Create a white canvas and add it to the window
Back-end steps :1. Create different variable : Drawing flag to check if currently drawing or not and set it to False, brush size variable to set current brush size, brush color to set current brush color and current position variable to know position of cursor 2. Add action to the clear and save widget 3. Inside clear action fill the canvas with white color 4. Inside the save action save the canvas 5. Add actions(methods) to various brush sizes and color to set size and color 6. Create paint event to draw white canvas on the screen 7. Create method to know when mouse left button is pressed inside that method make drawing flag true and change the current position 8. Create method for mouse movement, inside this method check if drawing flag is true and button is still pressed then draw using painter object and change the position according. 9. Create a method to know mouse button is released inside this method make drawing flag to false.
Below is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5.QtGui import *from PyQt5.QtCore import *import sys # window classclass Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Paint with PyQt5") # setting geometry to main window self.setGeometry(100, 100, 800, 600) # creating image object self.image = QImage(self.size(), QImage.Format_RGB32) # making image color to white self.image.fill(Qt.white) # variables # drawing flag self.drawing = False # default brush size self.brushSize = 2 # default color self.brushColor = Qt.black # QPoint object to tract the point self.lastPoint = QPoint() # creating menu bar mainMenu = self.menuBar() # creating file menu for save and clear action fileMenu = mainMenu.addMenu("File") # adding brush size to main menu b_size = mainMenu.addMenu("Brush Size") # adding brush color to ain menu b_color = mainMenu.addMenu("Brush Color") # creating save action saveAction = QAction("Save", self) # adding short cut for save action saveAction.setShortcut("Ctrl + S") # adding save to the file menu fileMenu.addAction(saveAction) # adding action to the save saveAction.triggered.connect(self.save) # creating clear action clearAction = QAction("Clear", self) # adding short cut to the clear action clearAction.setShortcut("Ctrl + C") # adding clear to the file menu fileMenu.addAction(clearAction) # adding action to the clear clearAction.triggered.connect(self.clear) # creating options for brush sizes # creating action for selecting pixel of 4px pix_4 = QAction("4px", self) # adding this action to the brush size b_size.addAction(pix_4) # adding method to this pix_4.triggered.connect(self.Pixel_4) # similarly repeating above steps for different sizes pix_7 = QAction("7px", self) b_size.addAction(pix_7) pix_7.triggered.connect(self.Pixel_7) pix_9 = QAction("9px", self) b_size.addAction(pix_9) pix_9.triggered.connect(self.Pixel_9) pix_12 = QAction("12px", self) b_size.addAction(pix_12) pix_12.triggered.connect(self.Pixel_12) # creating options for brush color # creating action for black color black = QAction("Black", self) # adding this action to the brush colors b_color.addAction(black) # adding methods to the black black.triggered.connect(self.blackColor) # similarly repeating above steps for different color white = QAction("White", self) b_color.addAction(white) white.triggered.connect(self.whiteColor) green = QAction("Green", self) b_color.addAction(green) green.triggered.connect(self.greenColor) yellow = QAction("Yellow", self) b_color.addAction(yellow) yellow.triggered.connect(self.yellowColor) red = QAction("Red", self) b_color.addAction(red) red.triggered.connect(self.redColor) # method for checking mouse cicks def mousePressEvent(self, event): # if left mouse button is pressed if event.button() == Qt.LeftButton: # make drawing flag true self.drawing = True # make last point to the point of cursor self.lastPoint = event.pos() # method for tracking mouse activity def mouseMoveEvent(self, event): # checking if left button is pressed and drawing flag is true if (event.buttons() & Qt.LeftButton) & self.drawing: # creating painter object painter = QPainter(self.image) # set the pen of the painter painter.setPen(QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) # draw line from the last point of cursor to the current point # this will draw only one step painter.drawLine(self.lastPoint, event.pos()) # change the last point self.lastPoint = event.pos() # update self.update() # method for mouse left button release def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: # make drawing flag false self.drawing = False # paint event def paintEvent(self, event): # create a canvas canvasPainter = QPainter(self) # draw rectangle on the canvas canvasPainter.drawImage(self.rect(), self.image, self.image.rect()) # method for saving canvas def save(self): filePath, _ = QFileDialog.getSaveFileName(self, "Save Image", "", "PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*) ") if filePath == "": return self.image.save(filePath) # method for clearing every thing on canvas def clear(self): # make the whole canvas white self.image.fill(Qt.white) # update self.update() # methods for changing pixel sizes def Pixel_4(self): self.brushSize = 4 def Pixel_7(self): self.brushSize = 7 def Pixel_9(self): self.brushSize = 9 def Pixel_12(self): self.brushSize = 12 # methods for changing brush color def blackColor(self): self.brushColor = Qt.black def whiteColor(self): self.brushColor = Qt.white def greenColor(self): self.brushColor = Qt.green def yellowColor(self): self.brushColor = Qt.yellow def redColor(self): self.brushColor = Qt.red # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # showing the windowwindow.show() # start the appsys.exit(App.exec())
Output :
simmytarika5
PyQt-exercise
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 330,
"s": 28,
"text": "There are so many options provided by Python to develop GUI application and PyQt5 is one of them. PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library."
},
{
"code": null,
"e": 457,
"s": 330,
"text": "In this article we will see how we can create a Paint application using PyQt5. Our Paint application will consist of following"
},
{
"code": null,
"e": 469,
"s": 457,
"text": " Features :"
},
{
"code": null,
"e": 602,
"s": 469,
"text": "User can select different brush sizes User can select different brush color Saving of the canvas Clearing the whole canvas at once "
},
{
"code": null,
"e": 641,
"s": 602,
"text": "User can select different brush sizes "
},
{
"code": null,
"e": 680,
"s": 641,
"text": "User can select different brush color "
},
{
"code": null,
"e": 702,
"s": 680,
"text": "Saving of the canvas "
},
{
"code": null,
"e": 738,
"s": 702,
"text": "Clearing the whole canvas at once "
},
{
"code": null,
"e": 970,
"s": 738,
"text": "Steps for designing the widgets –1. Create a window sets its geometry and title 2. Create menu bar 3. Inside menu bar add different menus, that are file menu, size menu and color menu 4. Add save and clear action to the file menu "
},
{
"code": null,
"e": 1031,
"s": 970,
"text": "5. Add different brush sizes action to the brush size menu "
},
{
"code": null,
"e": 1093,
"s": 1031,
"text": "6. Add different brush color action to the brush color menu "
},
{
"code": null,
"e": 1143,
"s": 1093,
"text": "7. Create a white canvas and add it to the window"
},
{
"code": null,
"e": 2101,
"s": 1143,
"text": "Back-end steps :1. Create different variable : Drawing flag to check if currently drawing or not and set it to False, brush size variable to set current brush size, brush color to set current brush color and current position variable to know position of cursor 2. Add action to the clear and save widget 3. Inside clear action fill the canvas with white color 4. Inside the save action save the canvas 5. Add actions(methods) to various brush sizes and color to set size and color 6. Create paint event to draw white canvas on the screen 7. Create method to know when mouse left button is pressed inside that method make drawing flag true and change the current position 8. Create method for mouse movement, inside this method check if drawing flag is true and button is still pressed then draw using painter object and change the position according. 9. Create a method to know mouse button is released inside this method make drawing flag to false."
},
{
"code": null,
"e": 2130,
"s": 2101,
"text": "Below is the implementation "
},
{
"code": null,
"e": 2138,
"s": 2130,
"text": "Python3"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5.QtGui import *from PyQt5.QtCore import *import sys # window classclass Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Paint with PyQt5\") # setting geometry to main window self.setGeometry(100, 100, 800, 600) # creating image object self.image = QImage(self.size(), QImage.Format_RGB32) # making image color to white self.image.fill(Qt.white) # variables # drawing flag self.drawing = False # default brush size self.brushSize = 2 # default color self.brushColor = Qt.black # QPoint object to tract the point self.lastPoint = QPoint() # creating menu bar mainMenu = self.menuBar() # creating file menu for save and clear action fileMenu = mainMenu.addMenu(\"File\") # adding brush size to main menu b_size = mainMenu.addMenu(\"Brush Size\") # adding brush color to ain menu b_color = mainMenu.addMenu(\"Brush Color\") # creating save action saveAction = QAction(\"Save\", self) # adding short cut for save action saveAction.setShortcut(\"Ctrl + S\") # adding save to the file menu fileMenu.addAction(saveAction) # adding action to the save saveAction.triggered.connect(self.save) # creating clear action clearAction = QAction(\"Clear\", self) # adding short cut to the clear action clearAction.setShortcut(\"Ctrl + C\") # adding clear to the file menu fileMenu.addAction(clearAction) # adding action to the clear clearAction.triggered.connect(self.clear) # creating options for brush sizes # creating action for selecting pixel of 4px pix_4 = QAction(\"4px\", self) # adding this action to the brush size b_size.addAction(pix_4) # adding method to this pix_4.triggered.connect(self.Pixel_4) # similarly repeating above steps for different sizes pix_7 = QAction(\"7px\", self) b_size.addAction(pix_7) pix_7.triggered.connect(self.Pixel_7) pix_9 = QAction(\"9px\", self) b_size.addAction(pix_9) pix_9.triggered.connect(self.Pixel_9) pix_12 = QAction(\"12px\", self) b_size.addAction(pix_12) pix_12.triggered.connect(self.Pixel_12) # creating options for brush color # creating action for black color black = QAction(\"Black\", self) # adding this action to the brush colors b_color.addAction(black) # adding methods to the black black.triggered.connect(self.blackColor) # similarly repeating above steps for different color white = QAction(\"White\", self) b_color.addAction(white) white.triggered.connect(self.whiteColor) green = QAction(\"Green\", self) b_color.addAction(green) green.triggered.connect(self.greenColor) yellow = QAction(\"Yellow\", self) b_color.addAction(yellow) yellow.triggered.connect(self.yellowColor) red = QAction(\"Red\", self) b_color.addAction(red) red.triggered.connect(self.redColor) # method for checking mouse cicks def mousePressEvent(self, event): # if left mouse button is pressed if event.button() == Qt.LeftButton: # make drawing flag true self.drawing = True # make last point to the point of cursor self.lastPoint = event.pos() # method for tracking mouse activity def mouseMoveEvent(self, event): # checking if left button is pressed and drawing flag is true if (event.buttons() & Qt.LeftButton) & self.drawing: # creating painter object painter = QPainter(self.image) # set the pen of the painter painter.setPen(QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) # draw line from the last point of cursor to the current point # this will draw only one step painter.drawLine(self.lastPoint, event.pos()) # change the last point self.lastPoint = event.pos() # update self.update() # method for mouse left button release def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: # make drawing flag false self.drawing = False # paint event def paintEvent(self, event): # create a canvas canvasPainter = QPainter(self) # draw rectangle on the canvas canvasPainter.drawImage(self.rect(), self.image, self.image.rect()) # method for saving canvas def save(self): filePath, _ = QFileDialog.getSaveFileName(self, \"Save Image\", \"\", \"PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*) \") if filePath == \"\": return self.image.save(filePath) # method for clearing every thing on canvas def clear(self): # make the whole canvas white self.image.fill(Qt.white) # update self.update() # methods for changing pixel sizes def Pixel_4(self): self.brushSize = 4 def Pixel_7(self): self.brushSize = 7 def Pixel_9(self): self.brushSize = 9 def Pixel_12(self): self.brushSize = 12 # methods for changing brush color def blackColor(self): self.brushColor = Qt.black def whiteColor(self): self.brushColor = Qt.white def greenColor(self): self.brushColor = Qt.green def yellowColor(self): self.brushColor = Qt.yellow def redColor(self): self.brushColor = Qt.red # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # showing the windowwindow.show() # start the appsys.exit(App.exec())",
"e": 8165,
"s": 2138,
"text": null
},
{
"code": null,
"e": 8175,
"s": 8165,
"text": "Output : "
},
{
"code": null,
"e": 8190,
"s": 8177,
"text": "simmytarika5"
},
{
"code": null,
"e": 8204,
"s": 8190,
"text": "PyQt-exercise"
},
{
"code": null,
"e": 8215,
"s": 8204,
"text": "Python-gui"
},
{
"code": null,
"e": 8227,
"s": 8215,
"text": "Python-PyQt"
},
{
"code": null,
"e": 8234,
"s": 8227,
"text": "Python"
}
]
|
move() method in PyQt5 | 26 Mar, 2020
In order to move (changing the position) any widget like buttons or label move() method is used in PyQt5 application. By default, all the widgets are on top left corner therefore, there is a need of changing the position of the widgets.
Syntax : move( x, y )
Arguments : It takes two arguments :1. X co-ordinate2. Y co-ordinate
Below is the implementation of this method.
# importing the required librariesfrom PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Move") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.widget = QLabel('Moved', self) # moving the widget # move(left, top) self.widget.move(50, 50) # 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. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 265,
"s": 28,
"text": "In order to move (changing the position) any widget like buttons or label move() method is used in PyQt5 application. By default, all the widgets are on top left corner therefore, there is a need of changing the position of the widgets."
},
{
"code": null,
"e": 287,
"s": 265,
"text": "Syntax : move( x, y )"
},
{
"code": null,
"e": 356,
"s": 287,
"text": "Arguments : It takes two arguments :1. X co-ordinate2. Y co-ordinate"
},
{
"code": null,
"e": 400,
"s": 356,
"text": "Below is the implementation of this method."
},
{
"code": "# importing the required librariesfrom PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Move\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.widget = QLabel('Moved', self) # moving the widget # move(left, top) self.widget.move(50, 50) # 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())",
"e": 1079,
"s": 400,
"text": null
},
{
"code": null,
"e": 1088,
"s": 1079,
"text": "Output :"
},
{
"code": null,
"e": 1099,
"s": 1088,
"text": "Python-gui"
},
{
"code": null,
"e": 1111,
"s": 1099,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1118,
"s": 1111,
"text": "Python"
}
]
|
Python | Fetch Nearest Hospital locations using GoogleMaps API | 17 May, 2022
If you are ever curious about how you can fetch nearest places (restaurant, hospital, labs, cafe’s, etc) location using your current location, this could be achieved using Python and Google Maps API. In this article, we will use Google Maps API to find the nearest hospital’s locations using Python. The API Key can be generated using the google developers console. Then you should follow the steps there to make an API Key.
Implementation:
Install the required python libraries before running the code: googleplaces, requests
Create an google Maps API Key going to this link.
Initialize Google Places constructor as: google_places = GooglePlaces(API_KEY)
Call this function google_places.nearby_search with parameters as latitude, longitude, radius and type:{hospital, casino, bar, cafe, etc} and store the output in a variable. User can give his own latitude and longitude in the parameters.
The search results will be of class type: ‘googleplaces.Place’.
The attribute’s value can be printed like longitude, latitude, name
Below is the implementation code :
Python3
# Importing required librariesfrom googleplaces import GooglePlaces, types, langimport requestsimport json # This is the way to make api requests# using python requests library # send_url = 'http://freegeoip.net/json'# r = requests.get(send_url)# j = json.loads(r.text)# print(j)# lat = j['latitude']# lon = j['longitude'] # Generate an API key by going to this location# https://cloud.google.com /maps-platform/places/?apis =# places in the google developers # Use your own API key for making api request callsAPI_KEY = 'Your_API_Key' # Initialising the GooglePlaces constructorgoogle_places = GooglePlaces(API_KEY) # call the function nearby search with# the parameters as longitude, latitude,# radius and type of place which needs to be searched of # type can be HOSPITAL, CAFE, BAR, CASINO, etcquery_result = google_places.nearby_search( # lat_lng ={'lat': 46.1667, 'lng': -1.15}, lat_lng ={'lat': 28.4089, 'lng': 77.3178}, radius = 5000, # types =[types.TYPE_HOSPITAL] or # [types.TYPE_CAFE] or [type.TYPE_BAR] # or [type.TYPE_CASINO]) types =[types.TYPE_HOSPITAL]) # If any attributions related # with search results print themif query_result.has_attributions: print (query_result.html_attributions) # Iterate over the search resultsfor place in query_result.places: print(place) # place.get_details() print (place.name) print("Latitude", place.geo_location['lat']) print("Longitude", place.geo_location['lng']) print()
Output:
Sarvodaya Hospital
Latitude 28.4222361
Longitude 77.3167904
Metro Heart Institute with Multispeciality
Latitude 28.4060327
Longitude 77.31803429999999
Asian Institute of Medical Sciences
Latitude 28.4260095
Longitude 77.29998359999999
Rawat Medical Store
Latitude 28.3928114
Longitude 77.30199
Sparsh Hospital
Latitude 28.4449953
Longitude 77.31859759999999
..more results
varshagumber28
sumitgumber28
siva100100100
python-utility
Web-API
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
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 May, 2022"
},
{
"code": null,
"e": 478,
"s": 53,
"text": "If you are ever curious about how you can fetch nearest places (restaurant, hospital, labs, cafe’s, etc) location using your current location, this could be achieved using Python and Google Maps API. In this article, we will use Google Maps API to find the nearest hospital’s locations using Python. The API Key can be generated using the google developers console. Then you should follow the steps there to make an API Key."
},
{
"code": null,
"e": 495,
"s": 478,
"text": "Implementation: "
},
{
"code": null,
"e": 581,
"s": 495,
"text": "Install the required python libraries before running the code: googleplaces, requests"
},
{
"code": null,
"e": 631,
"s": 581,
"text": "Create an google Maps API Key going to this link."
},
{
"code": null,
"e": 711,
"s": 631,
"text": "Initialize Google Places constructor as: google_places = GooglePlaces(API_KEY) "
},
{
"code": null,
"e": 949,
"s": 711,
"text": "Call this function google_places.nearby_search with parameters as latitude, longitude, radius and type:{hospital, casino, bar, cafe, etc} and store the output in a variable. User can give his own latitude and longitude in the parameters."
},
{
"code": null,
"e": 1013,
"s": 949,
"text": "The search results will be of class type: ‘googleplaces.Place’."
},
{
"code": null,
"e": 1081,
"s": 1013,
"text": "The attribute’s value can be printed like longitude, latitude, name"
},
{
"code": null,
"e": 1117,
"s": 1081,
"text": "Below is the implementation code : "
},
{
"code": null,
"e": 1125,
"s": 1117,
"text": "Python3"
},
{
"code": "# Importing required librariesfrom googleplaces import GooglePlaces, types, langimport requestsimport json # This is the way to make api requests# using python requests library # send_url = 'http://freegeoip.net/json'# r = requests.get(send_url)# j = json.loads(r.text)# print(j)# lat = j['latitude']# lon = j['longitude'] # Generate an API key by going to this location# https://cloud.google.com /maps-platform/places/?apis =# places in the google developers # Use your own API key for making api request callsAPI_KEY = 'Your_API_Key' # Initialising the GooglePlaces constructorgoogle_places = GooglePlaces(API_KEY) # call the function nearby search with# the parameters as longitude, latitude,# radius and type of place which needs to be searched of # type can be HOSPITAL, CAFE, BAR, CASINO, etcquery_result = google_places.nearby_search( # lat_lng ={'lat': 46.1667, 'lng': -1.15}, lat_lng ={'lat': 28.4089, 'lng': 77.3178}, radius = 5000, # types =[types.TYPE_HOSPITAL] or # [types.TYPE_CAFE] or [type.TYPE_BAR] # or [type.TYPE_CASINO]) types =[types.TYPE_HOSPITAL]) # If any attributions related # with search results print themif query_result.has_attributions: print (query_result.html_attributions) # Iterate over the search resultsfor place in query_result.places: print(place) # place.get_details() print (place.name) print(\"Latitude\", place.geo_location['lat']) print(\"Longitude\", place.geo_location['lng']) print()",
"e": 2631,
"s": 1125,
"text": null
},
{
"code": null,
"e": 2640,
"s": 2631,
"text": "Output: "
},
{
"code": null,
"e": 3019,
"s": 2640,
"text": "Sarvodaya Hospital\nLatitude 28.4222361\nLongitude 77.3167904\n\nMetro Heart Institute with Multispeciality\nLatitude 28.4060327\nLongitude 77.31803429999999\n\nAsian Institute of Medical Sciences\nLatitude 28.4260095\nLongitude 77.29998359999999\n\nRawat Medical Store\nLatitude 28.3928114\nLongitude 77.30199\n\nSparsh Hospital\nLatitude 28.4449953\nLongitude 77.31859759999999\n\n..more results "
},
{
"code": null,
"e": 3036,
"s": 3021,
"text": "varshagumber28"
},
{
"code": null,
"e": 3050,
"s": 3036,
"text": "sumitgumber28"
},
{
"code": null,
"e": 3064,
"s": 3050,
"text": "siva100100100"
},
{
"code": null,
"e": 3079,
"s": 3064,
"text": "python-utility"
},
{
"code": null,
"e": 3087,
"s": 3079,
"text": "Web-API"
},
{
"code": null,
"e": 3094,
"s": 3087,
"text": "Python"
},
{
"code": null,
"e": 3192,
"s": 3094,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3210,
"s": 3192,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3252,
"s": 3210,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3274,
"s": 3252,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3300,
"s": 3274,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3332,
"s": 3300,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3361,
"s": 3332,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3388,
"s": 3361,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3409,
"s": 3388,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3445,
"s": 3409,
"text": "Convert integer to string in Python"
}
]
|
Stopwatch using C language | 20 May, 2022
Create a digital stopwatch program in C which runs on linux base system. keyboardhit() function simply stands for keyboard hit. After pressing a key it generates a signal and returns a non zero integer. In this, there are 4 loops, 1st loop for hours, 2nd for minutes, 3rd for seconds and 4th loop for maintaining the speed of seconds(3 loop). After running this program it wait for a keyboard start(s) key to be pressed and when key is pressed, it generates a signal. For storing a keyboard key there is a variable(c), if c is equal to p key then it calls the wait function. The thread is running in the background and we are waiting for the start key to be pressed. After pressing s key, the thread again jumps to thread_join function, if r key is pressed, then it jumps into reset label and all the loops are again starts with zeros, if s key is pressed it jumps into start label and if e key is pressed it calls the exit() function and program gets terminated. Prerequisite : Threads in c, Wait system call
To execute the program we use following command :
Input:
Press a key :
s -> start
e -> exit
r -> reset
p -> pause
Output :
C
// C code to create stop watch // Header file for necessary system library#include <fcntl.h>#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <termios.h>#include <unistd.h> // starting from zero#define MIN 0 // 1 hr= 60 min ; 1 min= 60 sec#define MAX 60 #define MILLI 200000 int i, j, k, n, s;char c;pthread_t t1; // Function to perform operations// according keyboard hit.int keyboardhit(void){ struct termios oldt, newt; int ch; int oldf; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); if (ch != EOF) { ungetc(ch, stdin); return 1; } return 0;} // display stopwatch on screenvoid print(){ // clear screen escape sequence printf("\033[2J\033[1;1H"); // Display Hour Min Sec in screen printf("TIME\t\t\t\tHr: %d Min: %d Sec: %d", n, i, j);} // function to pause stopwatchvoid* wait(void* arg){ while (1) { // wait for keyboard signal if keyboard // hit it return non integer number if (keyboardhit()) { // take input from user and do // operation accordingly c = getchar(); if (c == 'S' || c == 's') { break; } else if (c == 'r' || c == 'R') { s = 1; break; } else if (c == 'e' || c == 'E') exit(0); } }} // driver codeint main(){ // label to reset the valuereset: n = MIN; i = MIN; j = MIN; k = MIN, s = MIN; print(); while (1) { /* s for start e for exit p for pause r for reset */ if (keyboardhit()) { c = getchar(); if (c != 's') continue; for (n = MIN; n < MAX; n++) { for (i = MIN; i < MAX; i++) { for (j = MIN; j < MAX; j++) { for (k = MIN; k < MILLI; k++) { start: print(); if (keyboardhit()) { c = getchar(); if (c == 'r' || c == 'R') goto reset; else if (c == 'e' || c == 'E') exit(0); else if (c == 's' || c == 'S') goto start; else if (c == 'P' || c == 'p') { pthread_create(&t1, NULL, &wait, NULL); // waiting for join a thread pthread_join(t1, NULL); if (s == 1) goto reset; } } } } } } } } return 0;}
Output:
pixahosod
simmytarika5
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
'this' pointer in C++
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
Header files in C/C++ and its uses
UDP Server-Client implementation in C | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 May, 2022"
},
{
"code": null,
"e": 1062,
"s": 52,
"text": "Create a digital stopwatch program in C which runs on linux base system. keyboardhit() function simply stands for keyboard hit. After pressing a key it generates a signal and returns a non zero integer. In this, there are 4 loops, 1st loop for hours, 2nd for minutes, 3rd for seconds and 4th loop for maintaining the speed of seconds(3 loop). After running this program it wait for a keyboard start(s) key to be pressed and when key is pressed, it generates a signal. For storing a keyboard key there is a variable(c), if c is equal to p key then it calls the wait function. The thread is running in the background and we are waiting for the start key to be pressed. After pressing s key, the thread again jumps to thread_join function, if r key is pressed, then it jumps into reset label and all the loops are again starts with zeros, if s key is pressed it jumps into start label and if e key is pressed it calls the exit() function and program gets terminated. Prerequisite : Threads in c, Wait system call"
},
{
"code": null,
"e": 1112,
"s": 1062,
"text": "To execute the program we use following command :"
},
{
"code": null,
"e": 1188,
"s": 1114,
"text": "Input:\nPress a key :\ns -> start\ne -> exit\nr -> reset\np -> pause\n\nOutput :"
},
{
"code": null,
"e": 1192,
"s": 1190,
"text": "C"
},
{
"code": "// C code to create stop watch // Header file for necessary system library#include <fcntl.h>#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <termios.h>#include <unistd.h> // starting from zero#define MIN 0 // 1 hr= 60 min ; 1 min= 60 sec#define MAX 60 #define MILLI 200000 int i, j, k, n, s;char c;pthread_t t1; // Function to perform operations// according keyboard hit.int keyboardhit(void){ struct termios oldt, newt; int ch; int oldf; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); if (ch != EOF) { ungetc(ch, stdin); return 1; } return 0;} // display stopwatch on screenvoid print(){ // clear screen escape sequence printf(\"\033[2J\033[1;1H\"); // Display Hour Min Sec in screen printf(\"TIME\\t\\t\\t\\tHr: %d Min: %d Sec: %d\", n, i, j);} // function to pause stopwatchvoid* wait(void* arg){ while (1) { // wait for keyboard signal if keyboard // hit it return non integer number if (keyboardhit()) { // take input from user and do // operation accordingly c = getchar(); if (c == 'S' || c == 's') { break; } else if (c == 'r' || c == 'R') { s = 1; break; } else if (c == 'e' || c == 'E') exit(0); } }} // driver codeint main(){ // label to reset the valuereset: n = MIN; i = MIN; j = MIN; k = MIN, s = MIN; print(); while (1) { /* s for start e for exit p for pause r for reset */ if (keyboardhit()) { c = getchar(); if (c != 's') continue; for (n = MIN; n < MAX; n++) { for (i = MIN; i < MAX; i++) { for (j = MIN; j < MAX; j++) { for (k = MIN; k < MILLI; k++) { start: print(); if (keyboardhit()) { c = getchar(); if (c == 'r' || c == 'R') goto reset; else if (c == 'e' || c == 'E') exit(0); else if (c == 's' || c == 'S') goto start; else if (c == 'P' || c == 'p') { pthread_create(&t1, NULL, &wait, NULL); // waiting for join a thread pthread_join(t1, NULL); if (s == 1) goto reset; } } } } } } } } return 0;}",
"e": 4394,
"s": 1192,
"text": null
},
{
"code": null,
"e": 4402,
"s": 4394,
"text": "Output:"
},
{
"code": null,
"e": 4416,
"s": 4406,
"text": "pixahosod"
},
{
"code": null,
"e": 4429,
"s": 4416,
"text": "simmytarika5"
},
{
"code": null,
"e": 4440,
"s": 4429,
"text": "C Language"
},
{
"code": null,
"e": 4451,
"s": 4440,
"text": "C Programs"
},
{
"code": null,
"e": 4549,
"s": 4451,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4597,
"s": 4549,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 4618,
"s": 4597,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4644,
"s": 4618,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 4689,
"s": 4644,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 4711,
"s": 4689,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 4724,
"s": 4711,
"text": "Strings in C"
},
{
"code": null,
"e": 4765,
"s": 4724,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 4794,
"s": 4765,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 4829,
"s": 4794,
"text": "Header files in C/C++ and its uses"
}
]
|
Write the syntax to declare a scrollable cursor on the ORDERS DB2 table. | A SCROLLABLE CURSOR can move in both forward and backward direction. In other words, it can fetch next as well as previous rows. A SCROLLABLE CURSOR is declared
using the “SCROLL” clause in the DECLARE CURSOR.
For example, if we want to declare a SCROLLABLE CURSOR on the ORDERS table then we have to declare the cursor like below.
EXEC SQL
DECLARE ORDER_CURR SCROLL CURSOR FOR
SELECT ORDER_ID, ORDER_DATE FROM ORDERS
WHERE ORDER_DATE = ‘2020-07-29’
END-SQL | [
{
"code": null,
"e": 1272,
"s": 1062,
"text": "A SCROLLABLE CURSOR can move in both forward and backward direction. In other words, it can fetch next as well as previous rows. A SCROLLABLE CURSOR is declared\nusing the “SCROLL” clause in the DECLARE CURSOR."
},
{
"code": null,
"e": 1394,
"s": 1272,
"text": "For example, if we want to declare a SCROLLABLE CURSOR on the ORDERS table then we have to declare the cursor like below."
},
{
"code": null,
"e": 1547,
"s": 1394,
"text": "EXEC SQL\n DECLARE ORDER_CURR SCROLL CURSOR FOR\n SELECT ORDER_ID, ORDER_DATE FROM ORDERS\n WHERE ORDER_DATE = ‘2020-07-29’\nEND-SQL"
}
]
|
How to read a single character using Scanner class in Java? | From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. By default, whitespace is considered as the delimiter (to break the data into tokens).
Scanner class provides nextXXX() (where xxx is int, float, boolean etc) methods which are used to read various primitive datatypes. But it never provides a method to read a single character.
But, you still can read a single character using this class.
The next() method of the Scanner class returns the next token of the source in String format. This reads single characters (separated by delimiter) as a String.
String str = sc.next();
The toCharArray() method of the String class converts the current String to a character array.
char ch[] = str.toCharArray()
From the array you can get the character stored at the 0th position.
char myChar = ch[0];
Following example reads a single character from the user using the Scanner class.
import java.util.Scanner;
public class ContentsOfFile {
public static void main(String args[]) throws Exception {
//Creating a Scanner object
Scanner sc = new Scanner(System.in);
//Creating a StringBuffer object
System.out.println("Enter your grade: (A, B, C, D)");
char grade = sc.next().toCharArray()[0];
if(grade == 'A'){
System.out.println("You are very good, you have been promoted");
}else if(grade=='B'){
System.out.println("You are good, you have been promoted");
}else if(grade=='C'){
System.out.println("You are average, you have been " + "promoted, you need to work hard");
}else if(grade=='D'){
System.out.println("You are not promoted, try again");
}else {
System.out.println("Improper input");
}
}
}
Enter your grade: (A, B, C, D)
C
You are average, you have been promoted, you need to work hard | [
{
"code": null,
"e": 1372,
"s": 1062,
"text": "From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. By default, whitespace is considered as the delimiter (to break the data into tokens)."
},
{
"code": null,
"e": 1563,
"s": 1372,
"text": "Scanner class provides nextXXX() (where xxx is int, float, boolean etc) methods which are used to read various primitive datatypes. But it never provides a method to read a single character."
},
{
"code": null,
"e": 1624,
"s": 1563,
"text": "But, you still can read a single character using this class."
},
{
"code": null,
"e": 1785,
"s": 1624,
"text": "The next() method of the Scanner class returns the next token of the source in String format. This reads single characters (separated by delimiter) as a String."
},
{
"code": null,
"e": 1809,
"s": 1785,
"text": "String str = sc.next();"
},
{
"code": null,
"e": 1904,
"s": 1809,
"text": "The toCharArray() method of the String class converts the current String to a character array."
},
{
"code": null,
"e": 1934,
"s": 1904,
"text": "char ch[] = str.toCharArray()"
},
{
"code": null,
"e": 2003,
"s": 1934,
"text": "From the array you can get the character stored at the 0th position."
},
{
"code": null,
"e": 2024,
"s": 2003,
"text": "char myChar = ch[0];"
},
{
"code": null,
"e": 2106,
"s": 2024,
"text": "Following example reads a single character from the user using the Scanner class."
},
{
"code": null,
"e": 2937,
"s": 2106,
"text": "import java.util.Scanner;\npublic class ContentsOfFile {\n public static void main(String args[]) throws Exception {\n //Creating a Scanner object\n Scanner sc = new Scanner(System.in);\n //Creating a StringBuffer object\n System.out.println(\"Enter your grade: (A, B, C, D)\");\n char grade = sc.next().toCharArray()[0];\n if(grade == 'A'){\n System.out.println(\"You are very good, you have been promoted\");\n }else if(grade=='B'){\n System.out.println(\"You are good, you have been promoted\");\n }else if(grade=='C'){\n System.out.println(\"You are average, you have been \" + \"promoted, you need to work hard\");\n }else if(grade=='D'){\n System.out.println(\"You are not promoted, try again\");\n }else {\n System.out.println(\"Improper input\");\n }\n }\n}"
},
{
"code": null,
"e": 3033,
"s": 2937,
"text": "Enter your grade: (A, B, C, D)\nC\nYou are average, you have been promoted, you need to work hard"
}
]
|
How to implement search and filtering in a REST API with Node.js and Express.js ? - GeeksforGeeks | 06 Apr, 2021
Search and filtering are very basic features that an API must possess to serve data to the client application efficiently. By handling these operations on the server-side, we can reduce the amount of processing that has to be done on the client application, thereby increasing its performance.
An extremely popular way of implementing this is with the help of query strings. A query string is a part of the URL which allows us to pass data from client to server and vice-versa in the form of parameters and their values.
Syntax:
http://test.com?name=John&age=21
Here, the portion following the question mark (?) is the query string. These are basically key-value pairs that we can use for various purposes. In this article, we’ll see how we can build a Node.js REST API that can accept these query strings, filter a list of users on basis of these provided parameters, and then return the matching results.
Setting up the Project:
First, we’ve to initialize a new project using Node Package Manager. We can complete the setup by selecting all the default options. npm init
First, we’ve to initialize a new project using Node Package Manager. We can complete the setup by selecting all the default options.
npm init
Next, we’ve to install the express package.npm install express --save
Next, we’ve to install the express package.
npm install express --save
The entry point of this application is going to be the app.js file. All of our business logic will go here. The REST API will contain only a single route which will return a list of users, with support for searching and filtering using query strings.
Example: Initially, the app.js file will look something like this, with the route returning only a basic message.
app.js
const express = require('express');const data = require('./data'); // Initialize Appconst app = express(); // Assign routeapp.use('/', (req, res, next) => { res.send('Node.js Search and Filter');}); // Start server on PORT 5000app.listen(5000, () => { console.log('Server started!');});
Adding Mock Data: For carrying out searching and filtering, we need some mock data i.e. a list of users upon which we can carry out these operations. For this, we can create a separate file data.js
data.js
const data = [ { id: 1, name: 'Alan Wake', age: 21, city: 'New York' }, { id: 2, name: 'Steve Rogers', age: 106, city: 'Chicago' }, { id: 3, name: 'Tom Hanks', age: 47, city: 'Detroit' }, { id: 4, name: 'Ryan Burns', age: 16, city: 'New York' }, { id: 5, name: 'Jack Ryan', age: 31, city: 'New York' }, { id: 6, name: 'Clark Kent', age: 34, city: 'Metropolis' }, { id: 7, name: 'Bruce Wayne', age: 21, city: 'Gotham' }, { id: 8, name: 'Tim Drake', age: 21, city: 'Gotham' }, { id: 9, name: 'Jimmy Olsen', age: 21, city: 'Metropolis' }, { id: 10, name: 'Ryan Burns', age: 21, city: 'New York' },]; module.exports = data;
Working with the Query String:
Let’s consider this URL. Here, we want to fetch all the users who live in Metropolis and are 21 years old.http://localhost:5000?city=Metropolis&age=21
Let’s consider this URL. Here, we want to fetch all the users who live in Metropolis and are 21 years old.
http://localhost:5000?city=Metropolis&age=21
We can access the query string by using the query attribute of res objectconsole.log(res.query)
>> { city: 'Metropolis', age: '21' }
We can access the query string by using the query attribute of res object
console.log(res.query)
>> { city: 'Metropolis', age: '21' }
We can see that it contains all the parameters passed through the URL in form of key-value pairs. To apply these parameters on our list of users, we can use the Array.filter() method and check for each user, if it satisfies all the provided parameters, and if it does, then add it to the filteredUsers list.
The filteredUsers list is our final result and can be returned as the response. The final code is provided below
app.js
const express = require('express');const data = require('./data'); // Initialize Appconst app = express(); // Assign routeapp.use('/', (req, res, next) => { const filters = req.query; const filteredUsers = data.filter(user => { let isValid = true; for (key in filters) { console.log(key, user[key], filters[key]); isValid = isValid && user[key] == filters[key]; } return isValid; }); res.send(filteredUsers);}); // Start server on PORT 5000app.listen(5000, () => { console.log('Server started!');});
Examples
URL: Fetch the user whose id is 2http://localhost:5000?id=2Output:[
{
"id": 2,
"name": "Steve Rogers",
"age": 106,
"city": "Chicago"
}
]URL: Fetch all users who live in Metropolishttp://localhost:5000?city=MetropolisOutput:[
{
"id": 6,
"name": "Clark Kent",
"age": 34,
"city": "Metropolis"
},
{
"id": 9,
"name": "Jimmy Olsen",
"age": 21,
"city": "Metropolis"
}
]URL: Fetch all users who live in Metropolis and are 21 years oldhttp://localhost:5000?city=Metropolis&age=21Output[
{
"id": 9,
"name": "Jimmy Olsen",
"age": 21,
"city": "Metropolis"
}
]
URL: Fetch the user whose id is 2http://localhost:5000?id=2Output:[
{
"id": 2,
"name": "Steve Rogers",
"age": 106,
"city": "Chicago"
}
]
URL: Fetch the user whose id is 2
http://localhost:5000?id=2
Output:
[
{
"id": 2,
"name": "Steve Rogers",
"age": 106,
"city": "Chicago"
}
]
URL: Fetch all users who live in Metropolishttp://localhost:5000?city=MetropolisOutput:[
{
"id": 6,
"name": "Clark Kent",
"age": 34,
"city": "Metropolis"
},
{
"id": 9,
"name": "Jimmy Olsen",
"age": 21,
"city": "Metropolis"
}
]
URL: Fetch all users who live in Metropolis
http://localhost:5000?city=Metropolis
Output:
[
{
"id": 6,
"name": "Clark Kent",
"age": 34,
"city": "Metropolis"
},
{
"id": 9,
"name": "Jimmy Olsen",
"age": 21,
"city": "Metropolis"
}
]
URL: Fetch all users who live in Metropolis and are 21 years oldhttp://localhost:5000?city=Metropolis&age=21Output[
{
"id": 9,
"name": "Jimmy Olsen",
"age": 21,
"city": "Metropolis"
}
]
URL: Fetch all users who live in Metropolis and are 21 years old
http://localhost:5000?city=Metropolis&age=21
Output
[
{
"id": 9,
"name": "Jimmy Olsen",
"age": 21,
"city": "Metropolis"
}
]
Express.js
javascript-array
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
Express.js req.params Property
Mongoose Populate() Method
JWT Authentication with Node.js
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 25028,
"s": 25000,
"text": "\n06 Apr, 2021"
},
{
"code": null,
"e": 25322,
"s": 25028,
"text": "Search and filtering are very basic features that an API must possess to serve data to the client application efficiently. By handling these operations on the server-side, we can reduce the amount of processing that has to be done on the client application, thereby increasing its performance."
},
{
"code": null,
"e": 25549,
"s": 25322,
"text": "An extremely popular way of implementing this is with the help of query strings. A query string is a part of the URL which allows us to pass data from client to server and vice-versa in the form of parameters and their values."
},
{
"code": null,
"e": 25557,
"s": 25549,
"text": "Syntax:"
},
{
"code": null,
"e": 25590,
"s": 25557,
"text": "http://test.com?name=John&age=21"
},
{
"code": null,
"e": 25935,
"s": 25590,
"text": "Here, the portion following the question mark (?) is the query string. These are basically key-value pairs that we can use for various purposes. In this article, we’ll see how we can build a Node.js REST API that can accept these query strings, filter a list of users on basis of these provided parameters, and then return the matching results."
},
{
"code": null,
"e": 25959,
"s": 25935,
"text": "Setting up the Project:"
},
{
"code": null,
"e": 26101,
"s": 25959,
"text": "First, we’ve to initialize a new project using Node Package Manager. We can complete the setup by selecting all the default options. npm init"
},
{
"code": null,
"e": 26235,
"s": 26101,
"text": "First, we’ve to initialize a new project using Node Package Manager. We can complete the setup by selecting all the default options. "
},
{
"code": null,
"e": 26244,
"s": 26235,
"text": "npm init"
},
{
"code": null,
"e": 26314,
"s": 26244,
"text": "Next, we’ve to install the express package.npm install express --save"
},
{
"code": null,
"e": 26358,
"s": 26314,
"text": "Next, we’ve to install the express package."
},
{
"code": null,
"e": 26385,
"s": 26358,
"text": "npm install express --save"
},
{
"code": null,
"e": 26636,
"s": 26385,
"text": "The entry point of this application is going to be the app.js file. All of our business logic will go here. The REST API will contain only a single route which will return a list of users, with support for searching and filtering using query strings."
},
{
"code": null,
"e": 26750,
"s": 26636,
"text": "Example: Initially, the app.js file will look something like this, with the route returning only a basic message."
},
{
"code": null,
"e": 26757,
"s": 26750,
"text": "app.js"
},
{
"code": "const express = require('express');const data = require('./data'); // Initialize Appconst app = express(); // Assign routeapp.use('/', (req, res, next) => { res.send('Node.js Search and Filter');}); // Start server on PORT 5000app.listen(5000, () => { console.log('Server started!');});",
"e": 27049,
"s": 26757,
"text": null
},
{
"code": null,
"e": 27247,
"s": 27049,
"text": "Adding Mock Data: For carrying out searching and filtering, we need some mock data i.e. a list of users upon which we can carry out these operations. For this, we can create a separate file data.js"
},
{
"code": null,
"e": 27255,
"s": 27247,
"text": "data.js"
},
{
"code": "const data = [ { id: 1, name: 'Alan Wake', age: 21, city: 'New York' }, { id: 2, name: 'Steve Rogers', age: 106, city: 'Chicago' }, { id: 3, name: 'Tom Hanks', age: 47, city: 'Detroit' }, { id: 4, name: 'Ryan Burns', age: 16, city: 'New York' }, { id: 5, name: 'Jack Ryan', age: 31, city: 'New York' }, { id: 6, name: 'Clark Kent', age: 34, city: 'Metropolis' }, { id: 7, name: 'Bruce Wayne', age: 21, city: 'Gotham' }, { id: 8, name: 'Tim Drake', age: 21, city: 'Gotham' }, { id: 9, name: 'Jimmy Olsen', age: 21, city: 'Metropolis' }, { id: 10, name: 'Ryan Burns', age: 21, city: 'New York' },]; module.exports = data;",
"e": 27886,
"s": 27255,
"text": null
},
{
"code": null,
"e": 27917,
"s": 27886,
"text": "Working with the Query String:"
},
{
"code": null,
"e": 28068,
"s": 27917,
"text": "Let’s consider this URL. Here, we want to fetch all the users who live in Metropolis and are 21 years old.http://localhost:5000?city=Metropolis&age=21"
},
{
"code": null,
"e": 28175,
"s": 28068,
"text": "Let’s consider this URL. Here, we want to fetch all the users who live in Metropolis and are 21 years old."
},
{
"code": null,
"e": 28220,
"s": 28175,
"text": "http://localhost:5000?city=Metropolis&age=21"
},
{
"code": null,
"e": 28353,
"s": 28220,
"text": "We can access the query string by using the query attribute of res objectconsole.log(res.query)\n>> { city: 'Metropolis', age: '21' }"
},
{
"code": null,
"e": 28427,
"s": 28353,
"text": "We can access the query string by using the query attribute of res object"
},
{
"code": null,
"e": 28487,
"s": 28427,
"text": "console.log(res.query)\n>> { city: 'Metropolis', age: '21' }"
},
{
"code": null,
"e": 28796,
"s": 28487,
"text": "We can see that it contains all the parameters passed through the URL in form of key-value pairs. To apply these parameters on our list of users, we can use the Array.filter() method and check for each user, if it satisfies all the provided parameters, and if it does, then add it to the filteredUsers list. "
},
{
"code": null,
"e": 28909,
"s": 28796,
"text": "The filteredUsers list is our final result and can be returned as the response. The final code is provided below"
},
{
"code": null,
"e": 28916,
"s": 28909,
"text": "app.js"
},
{
"code": "const express = require('express');const data = require('./data'); // Initialize Appconst app = express(); // Assign routeapp.use('/', (req, res, next) => { const filters = req.query; const filteredUsers = data.filter(user => { let isValid = true; for (key in filters) { console.log(key, user[key], filters[key]); isValid = isValid && user[key] == filters[key]; } return isValid; }); res.send(filteredUsers);}); // Start server on PORT 5000app.listen(5000, () => { console.log('Server started!');});",
"e": 29446,
"s": 28916,
"text": null
},
{
"code": null,
"e": 29455,
"s": 29446,
"text": "Examples"
},
{
"code": null,
"e": 30151,
"s": 29455,
"text": "URL: Fetch the user whose id is 2http://localhost:5000?id=2Output:[\n {\n \"id\": 2,\n \"name\": \"Steve Rogers\",\n \"age\": 106,\n \"city\": \"Chicago\"\n }\n]URL: Fetch all users who live in Metropolishttp://localhost:5000?city=MetropolisOutput:[\n {\n \"id\": 6,\n \"name\": \"Clark Kent\",\n \"age\": 34,\n \"city\": \"Metropolis\"\n },\n {\n \"id\": 9,\n \"name\": \"Jimmy Olsen\",\n \"age\": 21,\n \"city\": \"Metropolis\"\n }\n]URL: Fetch all users who live in Metropolis and are 21 years oldhttp://localhost:5000?city=Metropolis&age=21Output[\n {\n \"id\": 9,\n \"name\": \"Jimmy Olsen\",\n \"age\": 21,\n \"city\": \"Metropolis\"\n }\n]"
},
{
"code": null,
"e": 30322,
"s": 30151,
"text": "URL: Fetch the user whose id is 2http://localhost:5000?id=2Output:[\n {\n \"id\": 2,\n \"name\": \"Steve Rogers\",\n \"age\": 106,\n \"city\": \"Chicago\"\n }\n]"
},
{
"code": null,
"e": 30356,
"s": 30322,
"text": "URL: Fetch the user whose id is 2"
},
{
"code": null,
"e": 30383,
"s": 30356,
"text": "http://localhost:5000?id=2"
},
{
"code": null,
"e": 30391,
"s": 30383,
"text": "Output:"
},
{
"code": null,
"e": 30496,
"s": 30391,
"text": "[\n {\n \"id\": 2,\n \"name\": \"Steve Rogers\",\n \"age\": 106,\n \"city\": \"Chicago\"\n }\n]"
},
{
"code": null,
"e": 30803,
"s": 30496,
"text": "URL: Fetch all users who live in Metropolishttp://localhost:5000?city=MetropolisOutput:[\n {\n \"id\": 6,\n \"name\": \"Clark Kent\",\n \"age\": 34,\n \"city\": \"Metropolis\"\n },\n {\n \"id\": 9,\n \"name\": \"Jimmy Olsen\",\n \"age\": 21,\n \"city\": \"Metropolis\"\n }\n]"
},
{
"code": null,
"e": 30847,
"s": 30803,
"text": "URL: Fetch all users who live in Metropolis"
},
{
"code": null,
"e": 30885,
"s": 30847,
"text": "http://localhost:5000?city=Metropolis"
},
{
"code": null,
"e": 30893,
"s": 30885,
"text": "Output:"
},
{
"code": null,
"e": 31113,
"s": 30893,
"text": "[\n {\n \"id\": 6,\n \"name\": \"Clark Kent\",\n \"age\": 34,\n \"city\": \"Metropolis\"\n },\n {\n \"id\": 9,\n \"name\": \"Jimmy Olsen\",\n \"age\": 21,\n \"city\": \"Metropolis\"\n }\n]"
},
{
"code": null,
"e": 31333,
"s": 31113,
"text": "URL: Fetch all users who live in Metropolis and are 21 years oldhttp://localhost:5000?city=Metropolis&age=21Output[\n {\n \"id\": 9,\n \"name\": \"Jimmy Olsen\",\n \"age\": 21,\n \"city\": \"Metropolis\"\n }\n]"
},
{
"code": null,
"e": 31398,
"s": 31333,
"text": "URL: Fetch all users who live in Metropolis and are 21 years old"
},
{
"code": null,
"e": 31443,
"s": 31398,
"text": "http://localhost:5000?city=Metropolis&age=21"
},
{
"code": null,
"e": 31450,
"s": 31443,
"text": "Output"
},
{
"code": null,
"e": 31556,
"s": 31450,
"text": "[\n {\n \"id\": 9,\n \"name\": \"Jimmy Olsen\",\n \"age\": 21,\n \"city\": \"Metropolis\"\n }\n]"
},
{
"code": null,
"e": 31567,
"s": 31556,
"text": "Express.js"
},
{
"code": null,
"e": 31584,
"s": 31567,
"text": "javascript-array"
},
{
"code": null,
"e": 31591,
"s": 31584,
"text": "Picked"
},
{
"code": null,
"e": 31599,
"s": 31591,
"text": "Node.js"
},
{
"code": null,
"e": 31616,
"s": 31599,
"text": "Web Technologies"
},
{
"code": null,
"e": 31714,
"s": 31616,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31751,
"s": 31714,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 31782,
"s": 31751,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 31809,
"s": 31782,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 31841,
"s": 31809,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 31888,
"s": 31841,
"text": "Difference between npm i and npm ci in Node.js"
},
{
"code": null,
"e": 31930,
"s": 31888,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 31973,
"s": 31930,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32023,
"s": 31973,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 32085,
"s": 32023,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
Rank variable by group using Dplyr package in R - GeeksforGeeks | 17 Oct, 2021
In this article, we are going to see how to rank the variable by group using dplyr in R Programming Language.
The dplyr package in R is used to perform mutations and data manipulations in R. It is particularly useful for working with data frames and data tables. The package can be downloaded and installed into the working directory using the following command :
install.packages("dplyr")
The arrange() method is invoked to arrange the data of the data frame in the ascending order or descending order. It is used to reorder the rows of the data frame based on the variable names.
arrange(col-name)
This is followed by the application of the group_by method which takes as arguments the set of column names that are used for grouping the data. It may comprise one or more columns.
group_by(col-name1, col-name2..)
The mutate() method can then be applied to the data frame to perform manipulations or modifications by changing the orientation of the data stored in the data frame. The rank() method is used to assign numerical rankings to the data values mapped to the groups assigned. By default, the rank is displayed in ascending order.
rank(col-name)
Code:
R
library("dplyr") # creating a data framedata_frame <- data.frame(col1 = rep(letters[1:3],each = 4), col2 = 1:12) print ("Original Dataframe")print (data_frame)data_frame %>% arrange(col1, col2) %>% group_by(col1) %>% mutate(rank = rank(col2))
Output:
In order to display the ranks in descending order, the col name is prepended with a minus sign. This displays the numerical ranks of the vector in decreasing order. The new column name can be assigned to the output of this method. The output data frame contains an additional column with the same name as that of the assigned name.
R
library("dplyr") # creating a data framedata_frame <- data.frame(col1 = rep(letters[1:3],each = 4), col2 = 1:12) print ("Original Dataframe")print (data_frame) # ranking by col1 variableprint ("Modified Dataframe") # ranking in descending orderdata_frame %>% arrange(col1, col2) %>% group_by(col1) %>% mutate(rank = rank(-col2))
Output:
Picked
R Dplyr
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R | [
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n17 Oct, 2021"
},
{
"code": null,
"e": 24962,
"s": 24851,
"text": "In this article, we are going to see how to rank the variable by group using dplyr in R Programming Language. "
},
{
"code": null,
"e": 25216,
"s": 24962,
"text": "The dplyr package in R is used to perform mutations and data manipulations in R. It is particularly useful for working with data frames and data tables. The package can be downloaded and installed into the working directory using the following command :"
},
{
"code": null,
"e": 25242,
"s": 25216,
"text": "install.packages(\"dplyr\")"
},
{
"code": null,
"e": 25434,
"s": 25242,
"text": "The arrange() method is invoked to arrange the data of the data frame in the ascending order or descending order. It is used to reorder the rows of the data frame based on the variable names."
},
{
"code": null,
"e": 25452,
"s": 25434,
"text": "arrange(col-name)"
},
{
"code": null,
"e": 25634,
"s": 25452,
"text": "This is followed by the application of the group_by method which takes as arguments the set of column names that are used for grouping the data. It may comprise one or more columns."
},
{
"code": null,
"e": 25667,
"s": 25634,
"text": "group_by(col-name1, col-name2..)"
},
{
"code": null,
"e": 25992,
"s": 25667,
"text": "The mutate() method can then be applied to the data frame to perform manipulations or modifications by changing the orientation of the data stored in the data frame. The rank() method is used to assign numerical rankings to the data values mapped to the groups assigned. By default, the rank is displayed in ascending order."
},
{
"code": null,
"e": 26007,
"s": 25992,
"text": "rank(col-name)"
},
{
"code": null,
"e": 26013,
"s": 26007,
"text": "Code:"
},
{
"code": null,
"e": 26015,
"s": 26013,
"text": "R"
},
{
"code": "library(\"dplyr\") # creating a data framedata_frame <- data.frame(col1 = rep(letters[1:3],each = 4), col2 = 1:12) print (\"Original Dataframe\")print (data_frame)data_frame %>% arrange(col1, col2) %>% group_by(col1) %>% mutate(rank = rank(col2))",
"e": 26288,
"s": 26015,
"text": null
},
{
"code": null,
"e": 26296,
"s": 26288,
"text": "Output:"
},
{
"code": null,
"e": 26628,
"s": 26296,
"text": "In order to display the ranks in descending order, the col name is prepended with a minus sign. This displays the numerical ranks of the vector in decreasing order. The new column name can be assigned to the output of this method. The output data frame contains an additional column with the same name as that of the assigned name."
},
{
"code": null,
"e": 26630,
"s": 26628,
"text": "R"
},
{
"code": "library(\"dplyr\") # creating a data framedata_frame <- data.frame(col1 = rep(letters[1:3],each = 4), col2 = 1:12) print (\"Original Dataframe\")print (data_frame) # ranking by col1 variableprint (\"Modified Dataframe\") # ranking in descending orderdata_frame %>% arrange(col1, col2) %>% group_by(col1) %>% mutate(rank = rank(-col2))",
"e": 26991,
"s": 26630,
"text": null
},
{
"code": null,
"e": 26999,
"s": 26991,
"text": "Output:"
},
{
"code": null,
"e": 27006,
"s": 26999,
"text": "Picked"
},
{
"code": null,
"e": 27014,
"s": 27006,
"text": "R Dplyr"
},
{
"code": null,
"e": 27025,
"s": 27014,
"text": "R Language"
},
{
"code": null,
"e": 27123,
"s": 27025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27132,
"s": 27123,
"text": "Comments"
},
{
"code": null,
"e": 27145,
"s": 27132,
"text": "Old Comments"
},
{
"code": null,
"e": 27197,
"s": 27145,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27235,
"s": 27197,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27270,
"s": 27235,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27328,
"s": 27270,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27377,
"s": 27328,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27420,
"s": 27377,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27470,
"s": 27420,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27487,
"s": 27470,
"text": "R - if statement"
},
{
"code": null,
"e": 27524,
"s": 27487,
"text": "How to import an Excel File into R ?"
}
]
|
How to monitor Python files for changes? | Monitoring files for changes in any language is hard because of cross platform issues. On python, there is a widely used cross platform library called watchdog that allows watching for changes. You can install it using:
$ pip install watchdog
To watch a file called 'my_file.txt' using watchdog, you can use the simple program:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
print("Got it!")
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path='.', recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
When you run this program and make any changes to any file in current directory, the on_modified function from MyHandler class gets called with the event. In the MyHandler class you can define your own functions to handle the events. In the path, you can specify the files/directories you want to monitor. To stop this program, use Ctrl + C | [
{
"code": null,
"e": 1282,
"s": 1062,
"text": "Monitoring files for changes in any language is hard because of cross platform issues. On python, there is a widely used cross platform library called watchdog that allows watching for changes. You can install it using:"
},
{
"code": null,
"e": 1305,
"s": 1282,
"text": "$ pip install watchdog"
},
{
"code": null,
"e": 1390,
"s": 1305,
"text": "To watch a file called 'my_file.txt' using watchdog, you can use the simple program:"
},
{
"code": null,
"e": 1825,
"s": 1390,
"text": "import time\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\nclass MyHandler(FileSystemEventHandler):\n def on_modified(self, event):\n print(\"Got it!\")\nevent_handler = MyHandler()\nobserver = Observer()\nobserver.schedule(event_handler, path='.', recursive=False)\nobserver.start()\ntry:\n while True:\n time.sleep(1)\nexcept KeyboardInterrupt:\n observer.stop()\nobserver.join()"
},
{
"code": null,
"e": 2167,
"s": 1825,
"text": " When you run this program and make any changes to any file in current directory, the on_modified function from MyHandler class gets called with the event. In the MyHandler class you can define your own functions to handle the events. In the path, you can specify the files/directories you want to monitor. To stop this program, use Ctrl + C"
}
]
|
How do I declare a global variable in Python class? | A global variable is a variable with global scope, meaning that it is visible and accessible throughout the program, unless shadowed. The set of all global variables is known as the global environment or global scope of the program.
We declare a variable global by using the keyword global before a variable. All variables have the scope of the block, where they are declared and defined in. They can only be used after the point of their declaration.
Example of global variable declaration
def f():
global s
print(s)
s = "Only in spring, but Miami is great as well!"
print(s)
s = "I am looking for a course in New York!"
f()
print(s)
I am looking for a course in New York!
Only in spring, but Miami is great as well!
Only in spring, but Miami is great as well! | [
{
"code": null,
"e": 1295,
"s": 1062,
"text": "A global variable is a variable with global scope, meaning that it is visible and accessible throughout the program, unless shadowed. The set of all global variables is known as the global environment or global scope of the program."
},
{
"code": null,
"e": 1515,
"s": 1295,
"text": " We declare a variable global by using the keyword global before a variable. All variables have the scope of the block, where they are declared and defined in. They can only be used after the point of their declaration."
},
{
"code": null,
"e": 1554,
"s": 1515,
"text": "Example of global variable declaration"
},
{
"code": null,
"e": 1745,
"s": 1554,
"text": "def f(): \n global s \n print(s) \n s = \"Only in spring, but Miami is great as well!\"\n print(s)\ns = \"I am looking for a course in New York!\" \nf()\nprint(s)"
},
{
"code": null,
"e": 1874,
"s": 1745,
"text": "I am looking for a course in New York!\nOnly in spring, but Miami is great as well!\nOnly in spring, but Miami is great as well!\n\n"
}
]
|
SQLite - Quick Guide | This chapter helps you understand what is SQLite, how it differs from SQL, why it is needed and the way in which it handles the applications Database.
SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. SQLite is one of the fastest-growing database engines around, but that's growth in terms of popularity, not anything to do with its size. The source code for SQLite is in the public domain.
SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. It is a database, which is zero-configured, which means like other databases you do not need to configure it in your system.
SQLite engine is not a standalone process like other databases, you can link it statically or dynamically as per your requirement with your application. SQLite accesses its storage files directly.
SQLite does not require a separate server process or system to operate (serverless).
SQLite does not require a separate server process or system to operate (serverless).
SQLite comes with zero-configuration, which means no setup or administration needed.
SQLite comes with zero-configuration, which means no setup or administration needed.
A complete SQLite database is stored in a single cross-platform disk file.
A complete SQLite database is stored in a single cross-platform disk file.
SQLite is very small and light weight, less than 400KiB fully configured or less than 250KiB with optional features omitted.
SQLite is very small and light weight, less than 400KiB fully configured or less than 250KiB with optional features omitted.
SQLite is self-contained, which means no external dependencies.
SQLite is self-contained, which means no external dependencies.
SQLite transactions are fully ACID-compliant, allowing safe access from multiple processes or threads.
SQLite transactions are fully ACID-compliant, allowing safe access from multiple processes or threads.
SQLite supports most of the query language features found in SQL92 (SQL2) standard.
SQLite supports most of the query language features found in SQL92 (SQL2) standard.
SQLite is written in ANSI-C and provides simple and easy-to-use API.
SQLite is written in ANSI-C and provides simple and easy-to-use API.
SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32, WinCE, WinRT).
SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32, WinCE, WinRT).
2000 - D. Richard Hipp designed SQLite for the purpose of no administration required for operating a program.
2000 - D. Richard Hipp designed SQLite for the purpose of no administration required for operating a program.
2000 - In August, SQLite 1.0 released with GNU Database Manager.
2000 - In August, SQLite 1.0 released with GNU Database Manager.
2011 - Hipp announced to add UNQl interface to SQLite DB and to develop UNQLite (Document oriented database).
2011 - Hipp announced to add UNQl interface to SQLite DB and to develop UNQLite (Document oriented database).
There are few unsupported features of SQL92 in SQLite which are listed in the following table.
RIGHT OUTER JOIN
Only LEFT OUTER JOIN is implemented.
FULL OUTER JOIN
Only LEFT OUTER JOIN is implemented.
ALTER TABLE
The RENAME TABLE and ADD COLUMN variants of the ALTER TABLE command are supported. The DROP COLUMN, ALTER COLUMN, ADD CONSTRAINT are not supported.
Trigger support
FOR EACH ROW triggers are supported but not FOR EACH STATEMENT triggers.
VIEWs
VIEWs in SQLite are read-only. You may not execute a DELETE, INSERT, or UPDATE statement on a view.
GRANT and REVOKE
The only access permissions that can be applied are the normal file access permissions of the underlying operating system.
The standard SQLite commands to interact with relational databases are similar to SQL. They are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be classified into groups based on their operational nature −
CREATE
Creates a new table, a view of a table, or other object in database.
ALTER
Modifies an existing database object, such as a table.
DROP
Deletes an entire table, a view of a table or other object in the database.
INSERT
Creates a record
UPDATE
Modifies records
DELETE
Deletes records
SELECT
Retrieves certain records from one or more tables
SQLite is famous for its great feature zero-configuration, which means no complex setup or administration is needed. This chapter will take you through the process of setting up SQLite on Windows, Linux and Mac OS X.
Step 1 − Go to SQLite download page, and download precompiled binaries from Windows section.
Step 1 − Go to SQLite download page, and download precompiled binaries from Windows section.
Step 2 − Download sqlite-shell-win32-*.zip and sqlite-dll-win32-*.zip zipped files.
Step 2 − Download sqlite-shell-win32-*.zip and sqlite-dll-win32-*.zip zipped files.
Step 3 − Create a folder C:\>sqlite and unzip above two zipped files in this folder, which will give you sqlite3.def, sqlite3.dll and sqlite3.exe files.
Step 3 − Create a folder C:\>sqlite and unzip above two zipped files in this folder, which will give you sqlite3.def, sqlite3.dll and sqlite3.exe files.
Step 4 − Add C:\>sqlite in your PATH environment variable and finally go to the command prompt and issue sqlite3 command, which should display the following result.
Step 4 − Add C:\>sqlite in your PATH environment variable and finally go to the command prompt and issue sqlite3 command, which should display the following result.
C:\>sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
Today, almost all the flavours of Linux OS are being shipped with SQLite. So you just issue the following command to check if you already have SQLite installed on your machine.
$sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
If you do not see the above result, then it means you do not have SQLite installed on your Linux machine. Following are the following steps to install SQLite −
Step 1 − Go to SQLite download page and download sqlite-autoconf-*.tar.gz from source code section.
Step 1 − Go to SQLite download page and download sqlite-autoconf-*.tar.gz from source code section.
Step 2 − Run the following command −
Step 2 − Run the following command −
$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make
$make install
The above command will end with SQLite installation on your Linux machine. Which you can verify as explained above.
Though the latest version of Mac OS X comes pre-installed with SQLite but if you do not have installation available then just follow these following steps −
Step 1 − Go to SQLite download page, and download sqlite-autoconf-*.tar.gz from source code section.
Step 1 − Go to SQLite download page, and download sqlite-autoconf-*.tar.gz from source code section.
Step 2 − Run the following command −
Step 2 − Run the following command −
$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make
$make install
The above procedure will end with SQLite installation on your Mac OS X machine. Which you can verify by issuing the following command −
$sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
Finally, you have SQLite command prompt where you can issue SQLite commands for your exercises.
This chapter will take you through simple and useful commands used by SQLite programmers. These commands are called SQLite dot commands and exception with these commands is that they should not be terminated by a semi-colon (;).
Let's start with typing a simple sqlite3 command at command prompt which will provide you with SQLite command prompt where you will issue various SQLite commands.
$sqlite3
SQLite version 3.3.6
Enter ".help" for instructions
sqlite>
For a listing of the available dot commands, you can enter ".help" any time. For example −
sqlite>.help
The above command will display a list of various important SQLite dot commands, which are listed in the following table.
.backup ?DB? FILE
Backup DB (default "main") to FILE
.bail ON|OFF
Stop after hitting an error. Default OFF
.databases
List names and files of attached databases
.dump ?TABLE?
Dump the database in an SQL text format. If TABLE specified, only dump tables matching LIKE pattern TABLE
.echo ON|OFF
Turn command echo on or off
.exit
Exit SQLite prompt
.explain ON|OFF
Turn output mode suitable for EXPLAIN on or off. With no args, it turns EXPLAIN on
.header(s) ON|OFF
Turn display of headers on or off
.help
Show this message
.import FILE TABLE
Import data from FILE into TABLE
.indices ?TABLE?
Show names of all indices. If TABLE specified, only show indices for tables matching LIKE pattern TABLE
.load FILE ?ENTRY?
Load an extension library
.log FILE|off
Turn logging on or off. FILE can be stderr/stdout
.mode MODE
Set output mode where MODE is one of −
csv − Comma-separated values
csv − Comma-separated values
column − Left-aligned columns.
column − Left-aligned columns.
html − HTML <table> code
html − HTML <table> code
insert − SQL insert statements for TABLE
insert − SQL insert statements for TABLE
line − One value per line
line − One value per line
list − Values delimited by .separator string
list − Values delimited by .separator string
tabs − Tab-separated values
tabs − Tab-separated values
tcl − TCL list elements
tcl − TCL list elements
.nullvalue STRING
Print STRING in place of NULL values
.output FILENAME
Send output to FILENAME
.output stdout
Send output to the screen
.print STRING...
Print literal STRING
.prompt MAIN CONTINUE
Replace the standard prompts
.quit
Exit SQLite prompt
.read FILENAME
Execute SQL in FILENAME
.schema ?TABLE?
Show the CREATE statements. If TABLE specified, only show tables matching LIKE pattern TABLE
.separator STRING
Change separator used by output mode and .import
.show
Show the current values for various settings
.stats ON|OFF
Turn stats on or off
.tables ?PATTERN?
List names of tables matching a LIKE pattern
.timeout MS
Try opening locked tables for MS milliseconds
.width NUM NUM
Set column widths for "column" mode
.timer ON|OFF
Turn the CPU timer measurement on or off
Let's try .show command to see default setting for your SQLite command prompt.
sqlite>.show
echo: off
explain: off
headers: off
mode: column
nullvalue: ""
output: stdout
separator: "|"
width:
sqlite>
Make sure there is no space in between sqlite> prompt and dot command, otherwise it will not work.
You can use the following sequence of dot commands to format your output.
sqlite>.header on
sqlite>.mode column
sqlite>.timer on
sqlite>
The above setting will produce the output in the following format.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
CPU Time: user 0.000000 sys 0.000000
The master table holds the key information about your database tables and it is called sqlite_master. You can see its schema as follows −
sqlite>.schema sqlite_master
This will produce the following result.
CREATE TABLE sqlite_master (
type text,
name text,
tbl_name text,
rootpage integer,
sql text
);
SQLite is followed by unique set of rules and guidelines called Syntax. This chapter lists all the basic SQLite Syntax.
Important point to be noted is that SQLite is case insensitive, but there are some commands, which are case sensitive like GLOB and glob have different meaning in SQLite statements.
SQLite comments are extra notes, which you can add in your SQLite code to increase its readability and they can appear anywhere; whitespace can occur, including inside expressions and in the middle of other SQL statements but they cannot be nested.
SQL comments begin with two consecutive "-" characters (ASCII 0x2d) and extend up to and including the next newline character (ASCII 0x0a) or until the end of input, whichever comes first.
You can also use C-style comments, which begin with "/*" and extend up to and including the next "*/" character pair or until the end of input, whichever comes first. C-style comments can span multiple lines.
sqlite> .help -- This is a single line comment
All the SQLite statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, etc., and all the statements end with a semicolon (;).
ANALYZE;
or
ANALYZE database_name;
or
ANALYZE database_name.table_name;
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION-1 {AND|OR} CONDITION-2;
ALTER TABLE table_name ADD COLUMN column_def...;
ALTER TABLE table_name RENAME TO new_table_name;
ATTACH DATABASE 'DatabaseName' As 'Alias-Name';
BEGIN;
or
BEGIN EXCLUSIVE TRANSACTION;
SELECT column1, column2....columnN
FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;
COMMIT;
CREATE INDEX index_name
ON table_name ( column_name COLLATE NOCASE );
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...columnN);
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
CREATE TRIGGER database_name.trigger_name
BEFORE INSERT ON table_name FOR EACH ROW
BEGIN
stmt1;
stmt2;
....
END;
CREATE VIEW database_name.view_name AS
SELECT statement....;
CREATE VIRTUAL TABLE database_name.table_name USING weblog( access.log );
or
CREATE VIRTUAL TABLE database_name.table_name USING fts3( );
COMMIT;
SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;
DELETE FROM table_name
WHERE {CONDITION};
DETACH DATABASE 'Alias-Name';
SELECT DISTINCT column1, column2....columnN
FROM table_name;
DROP INDEX database_name.index_name;
DROP TABLE database_name.table_name;
DROP INDEX database_name.view_name;
DROP INDEX database_name.trigger_name;
SELECT column1, column2....columnN
FROM table_name
WHERE column_name EXISTS (SELECT * FROM table_name );
EXPLAIN INSERT statement...;
or
EXPLAIN QUERY PLAN SELECT statement...;
SELECT column1, column2....columnN
FROM table_name
WHERE column_name GLOB { PATTERN };
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
INSERT INTO table_name( column1, column2....columnN)
VALUES ( value1, value2....valueN);
SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
SELECT column1, column2....columnN
FROM table_name
WHERE column_name LIKE { PATTERN };
SELECT column1, column2....columnN
FROM table_name
WHERE column_name NOT IN (val-1, val-2,...val-N);
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};
PRAGMA pragma_name;
For example:
PRAGMA page_size;
PRAGMA cache_size = 1024;
PRAGMA table_info(table_name);
RELEASE savepoint_name;
REINDEX collation_name;
REINDEX database_name.index_name;
REINDEX database_name.table_name;
ROLLBACK;
or
ROLLBACK TO SAVEPOINT savepoint_name;
SAVEPOINT savepoint_name;
SELECT column1, column2....columnN
FROM table_name;
UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN
[ WHERE CONDITION ];
VACUUM;
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION;
SQLite data type is an attribute that specifies the type of data of any object. Each column, variable and expression has related data type in SQLite.
You would use these data types while creating your tables. SQLite uses a more general dynamic type system. In SQLite, the datatype of a value is associated with the value itself, not with its container.
Each value stored in an SQLite database has one of the following storage classes −
NULL
The value is a NULL value.
INTEGER
The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
REAL
The value is a floating point value, stored as an 8-byte IEEE floating point number.
TEXT
The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE)
BLOB
The value is a blob of data, stored exactly as it was input.
SQLite storage class is slightly more general than a datatype. The INTEGER storage class, for example, includes 6 different integer datatypes of different lengths.
SQLite supports the concept of type affinity on columns. Any column can still store any type of data but the preferred storage class for a column is called its affinity. Each table column in an SQLite3 database is assigned one of the following type affinities −
TEXT
This column stores all data using storage classes NULL, TEXT or BLOB.
NUMERIC
This column may contain values using all five storage classes.
INTEGER
Behaves the same as a column with NUMERIC affinity, with an exception in a CAST expression.
REAL
Behaves like a column with NUMERIC affinity except that it forces integer values into floating point representation.
NONE
A column with affinity NONE does not prefer one storage class over another and no attempt is made to coerce data from one storage class into another.
Following table lists down various data type names which can be used while creating SQLite3 tables with the corresponding applied affinity.
INT
INTEGER
TINYINT
SMALLINT
MEDIUMINT
BIGINT
UNSIGNED BIG INT
INT2
INT8
CHARACTER(20)
VARCHAR(255)
VARYING CHARACTER(255)
NCHAR(55)
NATIVE CHARACTER(70)
NVARCHAR(100)
TEXT
CLOB
BLOB
no datatype specified
REAL
DOUBLE
DOUBLE PRECISION
FLOAT
NUMERIC
DECIMAL(10,5)
BOOLEAN
DATE
DATETIME
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).
SQLite does not have a separate storage class for storing dates and/or times, but SQLite is capable of storing dates and times as TEXT, REAL or INTEGER values.
TEXT
A date in a format like "YYYY-MM-DD HH:MM:SS.SSS"
REAL
The number of days since noon in Greenwich on November 24, 4714 B.C.
INTEGER
The number of seconds since 1970-01-01 00:00:00 UTC
You can choose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
In SQLite, sqlite3 command is used to create a new SQLite database. You do not need to have any special privilege to create a database.
Following is the basic syntax of sqlite3 command to create a database: −
$sqlite3 DatabaseName.db
Always, database name should be unique within the RDBMS.
If you want to create a new database <testDB.db>, then SQLITE3 statement would be as follows −
$sqlite3 testDB.db
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
The above command will create a file testDB.db in the current directory. This file will be used as database by SQLite engine. If you have noticed while creating database, sqlite3 command will provide a sqlite> prompt after creating a database file successfully.
Once a database is created, you can verify it in the list of databases using the following SQLite .databases command.
sqlite>.databases
seq name file
--- --------------- ----------------------
0 main /home/sqlite/testDB.db
You will use SQLite .quit command to come out of the sqlite prompt as follows −
sqlite>.quit
$
You can use .dump dot command to export complete database in a text file using the following SQLite command at the command prompt.
$sqlite3 testDB.db .dump > testDB.sql
The above command will convert the entire contents of testDB.db database into SQLite statements and dump it into ASCII text file testDB.sql. You can perform restoration from the generated testDB.sql in a simple way as follows −
$sqlite3 testDB.db < testDB.sql
At this moment your database is empty, so you can try above two procedures once you have few tables and data in your database. For now, let's proceed to the next chapter.
Consider a case when you have multiple databases available and you want to use any one of them at a time. SQLite ATTACH DATABASE statement is used to select a particular database, and after this command, all SQLite statements will be executed under the attached database.
Following is the basic syntax of SQLite ATTACH DATABASE statement.
ATTACH DATABASE 'DatabaseName' As 'Alias-Name';
The above command will also create a database in case the database is already not created, otherwise it will just attach database file name with logical database 'Alias-Name'.
If you want to attach an existing database testDB.db, then ATTACH DATABASE statement would be as follows −
sqlite> ATTACH DATABASE 'testDB.db' as 'TEST';
Use SQLite .database command to display attached database.
sqlite> .database
seq name file
--- --------------- ----------------------
0 main /home/sqlite/testDB.db
2 test /home/sqlite/testDB.db
The database names main and temp are reserved for the primary database and database to hold temporary tables and other temporary data objects. Both of these database names exist for every database connection and should not be used for attachment, otherwise you will get the following warning message.
sqlite> ATTACH DATABASE 'testDB.db' as 'TEMP';
Error: database TEMP is already in use
sqlite> ATTACH DATABASE 'testDB.db' as 'main';
Error: database TEMP is already in use
SQLite DETACH DATABASE statement is used to detach and dissociate a named database from a database connection which was previously attached using ATTACH statement. If the same database file has been attached with multiple aliases, then DETACH command will disconnect only the given name and rest of the attachment will still continue. You cannot detach the main or temp databases.
If the database is an in-memory or temporary database, the database will be destroyed and the contents will be lost.
Following is the basic syntax of SQLite DETACH DATABASE 'Alias-Name' statement.
DETACH DATABASE 'Alias-Name';
Here, 'Alias-Name' is the same alias, which you had used while attaching the database using ATTACH statement.
Consider you have a database, which you created in the previous chapter and attached it with 'test' and 'currentDB' as we can see using .database command.
sqlite>.databases
seq name file
--- --------------- ----------------------
0 main /home/sqlite/testDB.db
2 test /home/sqlite/testDB.db
3 currentDB /home/sqlite/testDB.db
Let's try to detach 'currentDB' from testDB.db using the following command.
sqlite> DETACH DATABASE 'currentDB';
Now, if you will check the current attachment, you will find that testDB.db is still connected with 'test' and 'main'.
sqlite>.databases
seq name file
--- --------------- ----------------------
0 main /home/sqlite/testDB.db
2 test /home/sqlite/testDB.db
SQLite CREATE TABLE statement is used to create a new table in any of the given database. Creating a basic table involves naming the table and defining its columns and each column's data type.
Following is the basic syntax of CREATE TABLE statement.
CREATE TABLE database_name.table_name(
column1 datatype PRIMARY KEY(one or more columns),
column2 datatype,
column3 datatype,
.....
columnN datatype
);
CREATE TABLE is the keyword telling the database system to create a new table. The unique name or identifier for the table follows the CREATE TABLE statement. Optionally, you can specify database_name along with table_name.
Following is an example which creates a COMPANY table with ID as the primary key and NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this table.
sqlite> CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
Let us create one more table, which we will use in our exercises in subsequent chapters.
sqlite> CREATE TABLE DEPARTMENT(
ID INT PRIMARY KEY NOT NULL,
DEPT CHAR(50) NOT NULL,
EMP_ID INT NOT NULL
);
You can verify if your table has been created successfully using SQLite command .tables command, which will be used to list down all the tables in an attached database.
sqlite>.tables
COMPANY DEPARTMENT
Here, you can see the COMPANY table twice because its showing COMPANY table for main database and test.COMPANY table for 'test' alias created for your testDB.db. You can get complete information about a table using the following SQLite .schema command.
sqlite>.schema COMPANY
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
SQLite DROP TABLE statement is used to remove a table definition and all associated data, indexes, triggers, constraints, and permission specifications for that table.
You have to be careful while using this command because once a table is deleted then all the information available in the table would also be lost forever.
Following is the basic syntax of DROP TABLE statement. You can optionally specify the database name along with table name as follows −
DROP TABLE database_name.table_name;
Let us first verify COMPANY table and then we will delete it from the database.
sqlite>.tables
COMPANY test.COMPANY
This means COMPANY table is available in the database, so let us drop it as follows −
sqlite>DROP TABLE COMPANY;
sqlite>
Now, if you try .TABLES command, then you will not find COMPANY table anymore.
sqlite>.tables
sqlite>
It shows nothing which means the table from your database has been dropped successfully.
SQLite INSERT INTO Statement is used to add new rows of data into a table in the database.
Following are the two basic syntaxes of INSERT INTO statement.
INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
Here, column1, column2,...columnN are the names of the columns in the table into which you want to insert data.
You may not need to specify the column(s) name in the SQLite query if you are adding values for all the columns of the table. However, make sure the order of the values is in the same order as the columns in the table. The SQLite INSERT INTO syntax would be as follows −
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Consider you already have created COMPANY table in your testDB.db as follows −
sqlite> CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
Now, the following statements would create six records in COMPANY table.
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Allen', 25, 'Texas', 15000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'David', 27, 'Texas', 85000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Kim', 22, 'South-Hall', 45000.00 );
You can create a record in COMPANY table using the second syntax as follows −
INSERT INTO COMPANY VALUES (7, 'James', 24, 'Houston', 10000.00 );
All the above statements would create the following records in COMPANY table. In the next chapter, you will learn how to display all these records from a table.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
You can populate data into a table through select statement over another table provided another table has a set of fields, which are required to populate the first table. Here is the syntax −
INSERT INTO first_table_name [(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM second_table_name
[WHERE condition];
For now, you can skip the above statement. First, let's learn SELECT and WHERE clauses which will be covered in subsequent chapters.
SQLite SELECT statement is used to fetch the data from a SQLite database table which returns data in the form of a result table. These result tables are also called result sets.
Following is the basic syntax of SQLite SELECT statement.
SELECT column1, column2, columnN FROM table_name;
Here, column1, column2 ... are the fields of a table, whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax −
SELECT * FROM table_name;
Consider COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is an example to fetch and display all these records using SELECT statement. Here, the first three commands have been used to set a properly formatted output.
sqlite>.header on
sqlite>.mode column
sqlite> SELECT * FROM COMPANY;
Finally, you will get the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
If you want to fetch only selected fields of COMPANY table, then use the following query −
sqlite> SELECT ID, NAME, SALARY FROM COMPANY;
The above query will produce the following result.
ID NAME SALARY
---------- ---------- ----------
1 Paul 20000.0
2 Allen 15000.0
3 Teddy 20000.0
4 Mark 65000.0
5 David 85000.0
6 Kim 45000.0
7 James 10000.0
Sometimes, you will face a problem related to the truncated output in case of .mode column which happens because of default width of the column to be displayed. What you can do is, you can set column displayable column width using .width num, num.... command as follows −
sqlite>.width 10, 20, 10
sqlite>SELECT * FROM COMPANY;
The above .width command sets the first column width to 10, the second column width to 20 and the third column width to 10. Finally, the above SELECT statement will give the following result.
ID NAME AGE ADDRESS SALARY
---------- -------------------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
As all the dot commands are available at SQLite prompt, hence while programming with SQLite, you will use the following SELECT statement with sqlite_master table to list down all the tables created in your database.
sqlite> SELECT tbl_name FROM sqlite_master WHERE type = 'table';
Assuming you have only COMPANY table in your testDB.db, this will produce the following result.
tbl_name
----------
COMPANY
You can list down complete information about COMPANY table as follows −
sqlite> SELECT sql FROM sqlite_master WHERE type = 'table' AND tbl_name = 'COMPANY';
Assuming you have only COMPANY table in your testDB.db, this will produce the following result.
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
)
An operator is a reserved word or a character used primarily in an SQLite statement's WHERE clause to perform operation(s), such as comparisons and arithmetic operations.
Operators are used to specify conditions in an SQLite statement and to serve as conjunctions for multiple conditions in a statement.
Arithmetic operators
Comparison operators
Logical operators
Bitwise operators
Assume variable a holds 10 and variable b holds 20, then SQLite arithmetic operators will be used as follows −
Show Examples
Assume variable a holds 10 and variable b holds 20, then SQLite comparison operators will be used as follows
Show Examples
Here is a list of all the logical operators available in SQLite.
Show Examples
AND
The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.
BETWEEN
The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value.
EXISTS
The EXISTS operator is used to search for the presence of a row in a specified table that meets certain criteria.
IN
The IN operator is used to compare a value to a list of literal values that have been specified.
NOT IN
The negation of IN operator which is used to compare a value to a list of literal values that have been specified.
LIKE
The LIKE operator is used to compare a value to similar values using wildcard operators.
GLOB
The GLOB operator is used to compare a value to similar values using wildcard operators. Also, GLOB is case sensitive, unlike LIKE.
NOT
The NOT operator reverses the meaning of the logical operator with which it is used. Eg. NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is negate operator.
OR
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
IS NULL
The NULL operator is used to compare a value with a NULL value.
IS
The IS operator work like =
IS NOT
The IS operator work like !=
||
Adds two different strings and make new one.
UNIQUE
The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates).
Bitwise operator works on bits and performs bit-by-bit operation. Following is the truth table for & and |.
Assume if A = 60; and B = 13, then in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
~A = 1100 0011
The Bitwise operators supported by SQLite language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −
Show Examples
An expression is a combination of one or more values, operators, and SQL functions that evaluate to a value.
SQL expressions are like formulas and they are written in query language. You can also use to query the database for a specific set of data.
Consider the basic syntax of the SELECT statement as follows −
SELECT column1, column2, columnN
FROM table_name
WHERE [CONDITION | EXPRESSION];
Following are the different types of SQLite expressions.
SQLite Boolean Expressions fetch the data on the basis of matching single value. Following is the syntax −
SELECT column1, column2, columnN
FROM table_name
WHERE SINGLE VALUE MATCHTING EXPRESSION;
Consider COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is a simple examples showing the usage of SQLite Boolean Expressions −
sqlite> SELECT * FROM COMPANY WHERE SALARY = 10000;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
4 James 24 Houston 10000.0
These expressions are used to perform any mathematical operation in any query. Following is the syntax −
SELECT numerical_expression as OPERATION_NAME
[FROM table_name WHERE CONDITION] ;
Here, numerical_expression is used for mathematical expression or any formula. Following is a simple example showing the usage of SQLite Numeric Expressions.
sqlite> SELECT (15 + 6) AS ADDITION
ADDITION = 21
There are several built-in functions such as avg(), sum(), count(), etc., to perform what is known as aggregate data calculations against a table or a specific table column.
sqlite> SELECT COUNT(*) AS "RECORDS" FROM COMPANY;
RECORDS = 7
Date Expressions returns the current system date and time values. These expressions are used in various data manipulations.
sqlite> SELECT CURRENT_TIMESTAMP;
CURRENT_TIMESTAMP = 2013-03-17 10:43:35
SQLite WHERE clause is used to specify a condition while fetching the data from one table or multiple tables.
If the given condition is satisfied, means true, then it returns the specific value from the table. You will have to use WHERE clause to filter the records and fetching only necessary records.
The WHERE clause not only is used in SELECT statement, but it is also used in UPDATE, DELETE statement, etc., which will be covered in subsequent chapters.
Following is the basic syntax of SQLite SELECT statement with WHERE clause.
SELECT column1, column2, columnN
FROM table_name
WHERE [condition]
You can specify a condition using Comparision or Logical Operators such as >, <, =, LIKE, NOT, etc. Consider COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is a simple examples showing the usage of SQLite Logical Operators. Following SELECT statement lists down all the records where AGE is greater than or equal to 25 AND salary is greater than or equal to 65000.00.
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00.
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE is not NULL, which means all the records because none of the record has AGE equal to NULL.
sqlite> SELECT * FROM COMPANY WHERE AGE IS NOT NULL;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'.
sqlite> SELECT * FROM COMPANY WHERE NAME LIKE 'Ki%';
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
6 Kim 22 South-Hall 45000.0
Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'.
sqlite> SELECT * FROM COMPANY WHERE NAME GLOB 'Ki*';
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
6 Kim 22 South-Hall 45000.0
Following SELECT statement lists down all the records where AGE value is either 25 or 27.
sqlite> SELECT * FROM COMPANY WHERE AGE IN ( 25, 27 );
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE value is neither 25 nor 27.
sqlite> SELECT * FROM COMPANY WHERE AGE NOT IN ( 25, 27 );
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
3 Teddy 23 Norway 20000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following SELECT statement lists down all the records where AGE value is in BETWEEN 25 AND 27.
sqlite> SELECT * FROM COMPANY WHERE AGE BETWEEN 25 AND 27;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following SELECT statement makes use of SQL sub-query, where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with EXISTS operator to list down all the records where AGE from the outside query exists in the result returned by the sub-query −
sqlite> SELECT AGE FROM COMPANY
WHERE EXISTS (SELECT AGE FROM COMPANY WHERE SALARY > 65000);
AGE
----------
32
25
23
25
27
22
24
Following SELECT statement makes use of SQL sub-query where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with > operator to list down all the records where AGE from the outside query is greater than the age in the result returned by the sub-query.
sqlite> SELECT * FROM COMPANY
WHERE AGE > (SELECT AGE FROM COMPANY WHERE SALARY > 65000);
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
SQLite AND & OR operators are used to compile multiple conditions to narrow down the selected data in an SQLite statement. These two operators are called conjunctive operators.
These operators provide a means to make multiple comparisons with different operators in the same SQLite statement.
The AND operator allows the existence of multiple conditions in a SQLite statement's WHERE clause. While using AND operator, complete condition will be assumed true when all the conditions are true. For example, [condition1] AND [condition2] will be true only when both condition1 and condition2 are true.
Following is the basic syntax of AND operator with WHERE clause.
SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];
You can combine N number of conditions using AND operator. For an action to be taken by the SQLite statement, whether it be a transaction or query, all conditions separated by the AND must be TRUE.
Consider COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following SELECT statement lists down all the records where AGE is greater than or equal to 25 AND salary is greater than or equal to 65000.00.
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
The OR operator is also used to combine multiple conditions in a SQLite statement's WHERE clause. While using OR operator, complete condition will be assumed true when at least any of the conditions is true. For example, [condition1] OR [condition2] will be true if either condition1 or condition2 is true.
Following is the basic syntax of OR operator with WHERE clause.
SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]
You can combine N number of conditions using OR operator. For an action to be taken by the SQLite statement, whether it be a transaction or query, only any ONE of the conditions separated by the OR must be TRUE.
Consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00.
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
SQLite UPDATE Query is used to modify the existing records in a table. You can use WHERE clause with UPDATE query to update selected rows, otherwise all the rows would be updated.
Following is the basic syntax of UPDATE query with WHERE clause.
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
Consider COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is an example, which will update ADDRESS for a customer whose ID is 6.
sqlite> UPDATE COMPANY SET ADDRESS = 'Texas' WHERE ID = 6;
Now, COMPANY table will have the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 Texas 45000.0
7 James 24 Houston 10000.0
If you want to modify all ADDRESS and SALARY column values in COMPANY table, you do not need to use WHERE clause and UPDATE query will be as follows −
sqlite> UPDATE COMPANY SET ADDRESS = 'Texas', SALARY = 20000.00;
Now, COMPANY table will have the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 Texas 20000.0
2 Allen 25 Texas 20000.0
3 Teddy 23 Texas 20000.0
4 Mark 25 Texas 20000.0
5 David 27 Texas 20000.0
6 Kim 22 Texas 20000.0
7 James 24 Texas 20000.0
SQLite DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete the selected rows, otherwise all the records would be deleted.
Following is the basic syntax of DELETE query with WHERE clause.
DELETE FROM table_name
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
Consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is an example, which will DELETE a customer whose ID is 7.
sqlite> DELETE FROM COMPANY WHERE ID = 7;
Now COMPANY table will have the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
If you want to DELETE all the records from COMPANY table, you do not need to use WHERE clause with DELETE query, which will be as follows −
sqlite> DELETE FROM COMPANY;
Now, COMPANY table does not have any record as all the records have been deleted by DELETE statement.
SQLite LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. There are two wildcards used in conjunction with the LIKE operator −
The percent sign (%)
The underscore (_)
The percent sign represents zero, one, or multiple numbers or characters. The underscore represents a single number or character. These symbols can be used in combinations.
Following is the basic syntax of % and _.
SELECT FROM table_name
WHERE column LIKE 'XXXX%'
or
SELECT FROM table_name
WHERE column LIKE '%XXXX%'
or
SELECT FROM table_name
WHERE column LIKE 'XXXX_'
or
SELECT FROM table_name
WHERE column LIKE '_XXXX'
or
SELECT FROM table_name
WHERE column LIKE '_XXXX_'
You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value.
Following table lists a number of examples showing WHERE part having different LIKE clause with '%' and '_' operators.
WHERE SALARY LIKE '200%'
Finds any values that start with 200
WHERE SALARY LIKE '%200%'
Finds any values that have 200 in any position
WHERE SALARY LIKE '_00%'
Finds any values that have 00 in the second and third positions
WHERE SALARY LIKE '2_%_%'
Finds any values that start with 2 and are at least 3 characters in length
WHERE SALARY LIKE '%2'
Finds any values that end with 2
WHERE SALARY LIKE '_2%3'
Finds any values that has a 2 in the second position and ends with a 3
WHERE SALARY LIKE '2___3'
Finds any values in a five-digit number that starts with 2 and ends with 3
Let us take a real example, consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is an example, which will display all the records from COMPANY table where AGE starts with 2.
sqlite> SELECT * FROM COMPANY WHERE AGE LIKE '2%';
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is an example, which will display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text.
sqlite> SELECT * FROM COMPANY WHERE ADDRESS LIKE '%-%';
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
4 Mark 25 Rich-Mond 65000.0
6 Kim 22 South-Hall 45000.0
SQLite GLOB operator is used to match only text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the GLOB operator will return true, which is 1. Unlike LIKE operator, GLOB is case sensitive and it follows syntax of UNIX for specifying THE following wildcards.
The asterisk sign (*)
The question mark (?)
The asterisk sign (*) represents zero or multiple numbers or characters. The question mark (?) represents a single number or character.
Following is the basic syntax of * and ?.
SELECT FROM table_name
WHERE column GLOB 'XXXX*'
or
SELECT FROM table_name
WHERE column GLOB '*XXXX*'
or
SELECT FROM table_name
WHERE column GLOB 'XXXX?'
or
SELECT FROM table_name
WHERE column GLOB '?XXXX'
or
SELECT FROM table_name
WHERE column GLOB '?XXXX?'
or
SELECT FROM table_name
WHERE column GLOB '????'
You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value.
Following table lists a number of examples showing WHERE part having different LIKE clause with '*' and '?' operators.
WHERE SALARY GLOB '200*'
Finds any values that start with 200
WHERE SALARY GLOB '*200*'
Finds any values that have 200 in any position
WHERE SALARY GLOB '?00*'
Finds any values that have 00 in the second and third positions
WHERE SALARY GLOB '2??'
Finds any values that start with 2 and are at least 3 characters in length
WHERE SALARY GLOB '*2'
Finds any values that end with 2
WHERE SALARY GLOB '?2*3'
Finds any values that have a 2 in the second position and end with a 3
WHERE SALARY GLOB '2???3'
Finds any values in a five-digit number that start with 2 and end with 3
Let us take a real example, consider COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is an example, which will display all the records from COMPANY table, where AGE starts with 2.
sqlite> SELECT * FROM COMPANY WHERE AGE GLOB '2*';
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is an example, which will display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text −
sqlite> SELECT * FROM COMPANY WHERE ADDRESS GLOB '*-*';
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
4 Mark 25 Rich-Mond 65000.0
6 Kim 22 South-Hall 45000.0
SQLite LIMIT clause is used to limit the data amount returned by the SELECT statement.
Following is the basic syntax of SELECT statement with LIMIT clause.
SELECT column1, column2, columnN
FROM table_name
LIMIT [no of rows]
Following is the syntax of LIMIT clause when it is used along with OFFSET clause.
SELECT column1, column2, columnN
FROM table_name
LIMIT [no of rows] OFFSET [row num]
SQLite engine will return rows starting from the next row to the given OFFSET as shown below in the last example.
Consider COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is an example, which limits the row in the table according to the number of rows you want to fetch from table.
sqlite> SELECT * FROM COMPANY LIMIT 6;
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
However in certain situations, you may need to pick up a set of records from a particular offset. Here is an example, which picks up 3 records starting from the 3rd position.
sqlite> SELECT * FROM COMPANY LIMIT 3 OFFSET 2;
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
SQLite ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns.
Following is the basic syntax of ORDER BY clause.
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be available in the column-list.
Consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is an example, which will sort the result in descending order by SALARY.
sqlite> SELECT * FROM COMPANY ORDER BY SALARY ASC;
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
7 James 24 Houston 10000.0
2 Allen 25 Texas 15000.0
1 Paul 32 California 20000.0
3 Teddy 23 Norway 20000.0
6 Kim 22 South-Hall 45000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following is an example, which will sort the result in descending order by NAME and SALARY.
sqlite> SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC;
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000.0
5 David 27 Texas 85000.0
7 James 24 Houston 10000.0
6 Kim 22 South-Hall 45000.0
4 Mark 25 Rich-Mond 65000.0
1 Paul 32 California 20000.0
3 Teddy 23 Norway 20000.0
Following is an example, which will sort the result in descending order by NAME.
sqlite> SELECT * FROM COMPANY ORDER BY NAME DESC;
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
3 Teddy 23 Norway 20000.0
1 Paul 32 California 20000.0
4 Mark 25 Rich-Mond 65000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
5 David 27 Texas 85000.0
2 Allen 25 Texas 15000.0
SQLite GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.
GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.
Following is the basic syntax of GROUP BY clause. GROUP BY clause must follow the conditions in the WHERE clause and must precede ORDER BY clause if one is used.
SELECT column-list
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2....columnN
ORDER BY column1, column2....columnN
You can use more than one column in the GROUP BY clause. Make sure whatever column you are using to group, that column should be available in the column-list.
Consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
If you want to know the total amount of salary on each customer, then GROUP BY query will be as follows −
sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME;
This will produce the following result −
NAME SUM(SALARY)
---------- -----------
Allen 15000.0
David 85000.0
James 10000.0
Kim 45000.0
Mark 65000.0
Paul 20000.0
Teddy 20000.0
Now, let us create three more records in COMPANY table using the following INSERT statements.
INSERT INTO COMPANY VALUES (8, 'Paul', 24, 'Houston', 20000.00 );
INSERT INTO COMPANY VALUES (9, 'James', 44, 'Norway', 5000.00 );
INSERT INTO COMPANY VALUES (10, 'James', 45, 'Texas', 5000.00 );
Now, our table has the following records with duplicate names.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
8 Paul 24 Houston 20000.0
9 James 44 Norway 5000.0
10 James 45 Texas 5000.0
Again, let us use the same statement to group-by all the records using NAME column as follows −
sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME;
This will produce the following result.
NAME SUM(SALARY)
---------- -----------
Allen 15000
David 85000
James 20000
Kim 45000
Mark 65000
Paul 40000
Teddy 20000
Let us use ORDER BY clause along with GROUP BY clause as follows −
sqlite> SELECT NAME, SUM(SALARY)
FROM COMPANY GROUP BY NAME ORDER BY NAME DESC;
This will produce the following result.
NAME SUM(SALARY)
---------- -----------
Teddy 20000
Paul 40000
Mark 65000
Kim 45000
James 20000
David 85000
Allen 15000
HAVING clause enables you to specify conditions that filter which group results appear in the final results.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by GROUP BY clause.
Following is the position of HAVING clause in a SELECT query.
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
HAVING clause must follow GROUP BY clause in a query and must also precede ORDER BY clause if used. Following is the syntax of the SELECT statement, including HAVING clause.
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2
Consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
8 Paul 24 Houston 20000.0
9 James 44 Norway 5000.0
10 James 45 Texas 5000.0
Following is the example, which will display the record for which the name count is less than 2.
sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) < 2;
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000
5 David 27 Texas 85000
6 Kim 22 South-Hall 45000
4 Mark 25 Rich-Mond 65000
3 Teddy 23 Norway 20000
Following is the example, which will display the record for which the name count is greater than 2.
sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) > 2;
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
10 James 45 Texas 5000
SQLite DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only the unique records.
There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records.
Following is the basic syntax of DISTINCT keyword to eliminate duplicate records.
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]
Consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
8 Paul 24 Houston 20000.0
9 James 44 Norway 5000.0
10 James 45 Texas 5000.0
First, let us see how the following SELECT query returns duplicate salary records.
sqlite> SELECT name FROM COMPANY;
This will produce the following result.
NAME
----------
Paul
Allen
Teddy
Mark
David
Kim
James
Paul
James
James
Now, let us use DISTINCT keyword with the above SELECT query and see the result.
sqlite> SELECT DISTINCT name FROM COMPANY;
This will produce the following result, where there is no duplicate entry.
NAME
----------
Paul
Allen
Teddy
Mark
David
Kim
James
SQLite PRAGMA command is a special command to be used to control various environmental variables and state flags within the SQLite environment. A PRAGMA value can be read and it can also be set based on the requirements.
To query the current PRAGMA value, just provide the name of the pragma.
PRAGMA pragma_name;
To set a new value for PRAGMA, use the following syntax.
PRAGMA pragma_name = value;
The set mode can be either the name or the integer equivalent but the returned value will always be an integer.
The auto_vacuum pragma gets or sets the auto-vacuum mode. Following is the simple syntax.
PRAGMA [database.]auto_vacuum;
PRAGMA [database.]auto_vacuum = mode;
Where mode can be any of the following −
0 or NONE
Auto-vacuum is disabled. This is the default mode which means that a database file will never shrink in size unless it is manually vacuumed using the VACUUM command.
1 or FULL
Auto-vacuum is enabled and fully automatic which allows a database file to shrink as data is removed from the database.
2 or INCREMENTAL
Auto-vacuum is enabled but must be manually activated. In this mode the reference data is maintained, but free pages are simply put on the free list. These pages can be recovered using the incremental_vacuum pragma any time.
The cache_size pragma can get or temporarily set the maximum size of the in-memory page cache. Following is the simple syntax.
PRAGMA [database.]cache_size;
PRAGMA [database.]cache_size = pages;
The pages value represents the number of pages in the cache. The built-in page cache has a default size of 2,000 pages and a minimum size of 10 pages.
The case_sensitive_like pragma controls the case-sensitivity of the built-in LIKE expression. By default, this pragma is false which means that the built-in LIKE operator ignores the letter case. Following is the simple syntax.
PRAGMA case_sensitive_like = [true|false];
There is no way to query for the current state of this pragma.
count_changes pragma gets or sets the return value of data manipulation statements such as INSERT, UPDATE and DELETE. Following is the simple syntax.
PRAGMA count_changes;
PRAGMA count_changes = [true|false];
By default, this pragma is false and these statements do not return anything. If set to true, each of the mentioned statement will return a one-column, one-row table consisting of a single integer value indicating impacted rows by the operation.
The database_list pragma will be used to list down all the databases attached. Following is the simple syntax.
PRAGMA database_list;
This pragma will return a three-column table with one row per open or attached database giving database sequence number, its name and the file associated.
The encoding pragma controls how strings are encoded and stored in a database file. Following is the simple syntax.
PRAGMA encoding;
PRAGMA encoding = format;
The format value can be one of UTF-8, UTF-16le, or UTF-16be.
The freelist_count pragma returns a single integer indicating how many database pages are currently marked as free and available. Following is the simple syntax.
PRAGMA [database.]freelist_count;
The format value can be one of UTF-8, UTF-16le, or UTF-16be.
The index_info pragma returns information about a database index. Following is the simple syntax.
PRAGMA [database.]index_info( index_name );
The result set will contain one row for each column contained in the index giving column sequence, column index with-in table and column name.
index_list pragma lists all of the indexes associated with a table. Following is the simple syntax.
PRAGMA [database.]index_list( table_name );
The result set will contain one row for each index giving index sequence, index name and flag indicating whether the index is unique or not.
The journal_mode pragma gets or sets the journal mode which controls how the journal file is stored and processed. Following is the simple syntax.
PRAGMA journal_mode;
PRAGMA journal_mode = mode;
PRAGMA database.journal_mode;
PRAGMA database.journal_mode = mode;
There are five supported journal modes as listed in the following table.
DELETE
This is the default mode. Here at the conclusion of a transaction, the journal file is deleted.
TRUNCATE
The journal file is truncated to a length of zero bytes.
PERSIST
The journal file is left in place, but the header is overwritten to indicate the journal is no longer valid.
MEMORY
The journal record is held in memory, rather than on disk.
OFF
No journal record is kept.
The max_page_count pragma gets or sets the maximum allowed page count for a database. Following is the simple syntax.
PRAGMA [database.]max_page_count;
PRAGMA [database.]max_page_count = max_page;
The default value is 1,073,741,823 which is one giga-page, which means if the default 1 KB page size, this allows databases to grow up to one terabyte.
The page_count pragma returns in the current number of pages in the database. Following is the simple syntax −
PRAGMA [database.]page_count;
The size of the database file should be page_count * page_size.
The page_size pragma gets or sets the size of the database pages. Following is the simple syntax.
PRAGMA [database.]page_size;
PRAGMA [database.]page_size = bytes;
By default, the allowed sizes are 512, 1024, 2048, 4096, 8192, 16384, and 32768 bytes. The only way to alter the page size on an existing database is to set the page size and then immediately VACUUM the database.
The parser_trace pragma controls printing the debugging state as it parses SQL commands. Following is the simple syntax.
PRAGMA parser_trace = [true|false];
By default, it is set to false but when enabled by setting it to true, the SQL parser will print its state as it parses SQL commands.
The recursive_triggers pragma gets or sets the recursive trigger functionality. If recursive triggers are not enabled, a trigger action will not fire another trigger. Following is the simple syntax.
PRAGMA recursive_triggers;
PRAGMA recursive_triggers = [true|false];
The schema_version pragma gets or sets the schema version value that is stored in the database header. Following is the simple syntax.
PRAGMA [database.]schema_version;
PRAGMA [database.]schema_version = number;
This is a 32-bit signed integer value that keeps track of schema changes. Whenever a schema-altering command is executed (like, CREATE... or DROP...), this value is incremented.
The secure_delete pragma is used to control how the content is deleted from the database. Following is the simple syntax.
PRAGMA secure_delete;
PRAGMA secure_delete = [true|false];
PRAGMA database.secure_delete;
PRAGMA database.secure_delete = [true|false];
The default value for the secure delete flag is normally off, but this can be changed with the SQLITE_SECURE_DELETE build option.
The sql_trace pragma is used to dump SQL trace results to the screen. Following is the simple syntax.
PRAGMA sql_trace;
PRAGMA sql_trace = [true|false];
SQLite must be compiled with the SQLITE_DEBUG directive for this pragma to be included.
The synchronous pragma gets or sets the current disk synchronization mode, which controls how aggressively SQLite will write data all the way out to physical storage. Following is the simple syntax.
PRAGMA [database.]synchronous;
PRAGMA [database.]synchronous = mode;
SQLite supports the following synchronization modes as listed in the table.
0 or OFF
No syncs at all
1 or NORMAL
Sync after each sequence of critical disk operations
2 or FULL
Sync after each critical disk operation
The temp_store pragma gets or sets the storage mode used by temporary database files. Following is the simple syntax.
PRAGMA temp_store;
PRAGMA temp_store = mode;
SQLite supports the following storage modes.
0 or DEFAULT
Use compile-time default. Normally FILE.
1 or FILE
Use file-based storage.
2 or MEMORY
Use memory-based storage.
The temp_store_directory pragma gets or sets the location used for temporary database files. Following is the simple syntax.
PRAGMA temp_store_directory;
PRAGMA temp_store_directory = 'directory_path';
The user_version pragma gets or sets the user-defined version value that is stored in the database header. Following is the simple syntax.
PRAGMA [database.]user_version;
PRAGMA [database.]user_version = number;
This is a 32-bit signed integer value, which can be set by the developer for version tracking purpose.
The writable_schema pragma gets or sets the ability to modify system tables. Following is the simple syntax.
PRAGMA writable_schema;
PRAGMA writable_schema = [true|false];
If this pragma is set, tables that start with sqlite_ can be created and modified, including the sqlite_master table. Be careful while using pragma because it can lead to complete database corruption.
Constraints are the rules enforced on a data columns on table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database.
Constraints could be column level or table level. Column level constraints are applied only to one column, whereas table level constraints are applied to the whole table.
Following are commonly used constraints available in SQLite.
NOT NULL Constraint − Ensures that a column cannot have NULL value.
NOT NULL Constraint − Ensures that a column cannot have NULL value.
DEFAULT Constraint − Provides a default value for a column when none is specified.
DEFAULT Constraint − Provides a default value for a column when none is specified.
UNIQUE Constraint − Ensures that all values in a column are different.
UNIQUE Constraint − Ensures that all values in a column are different.
PRIMARY Key − Uniquely identifies each row/record in a database table.
PRIMARY Key − Uniquely identifies each row/record in a database table.
CHECK Constraint − Ensures that all values in a column satisfies certain conditions.
CHECK Constraint − Ensures that all values in a column satisfies certain conditions.
By default, a column can hold NULL values. If you do not want a column to have a NULL value, then you need to define such constraint on this column specifying that NULL is now not allowed for that column.
A NULL is not the same as no data, rather, it represents unknown data.
For example, the following SQLite statement creates a new table called COMPANY and adds five columns, three of which, ID and NAME and AGE, specifies not to accept NULLs.
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not provide a specific value.
For example, the following SQLite statement creates a new table called COMPANY and adds five columns. Here, SALARY column is set to 5000.00 by default, thus in case INSERT INTO statement does not provide a value for this column, then by default, this column would be set to 5000.00.
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL DEFAULT 50000.00
);
The UNIQUE Constraint prevents two records from having identical values in a particular column. In the COMPANY table, for example, you might want to prevent two or more people from having an identical age.
For example, the following SQLite statement creates a new table called COMPANY and adds five columns. Here, AGE column is set to UNIQUE, so that you cannot have two records with the same age −
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR(50),
SALARY REAL DEFAULT 50000.00
);
The PRIMARY KEY constraint uniquely identifies each record in a database table. There can be more UNIQUE columns, but only one primary key in a table. Primary keys are important when designing the database tables. Primary keys are unique IDs.
We use them to refer to table rows. Primary keys become foreign keys in other tables, when creating relations among tables. Due to a 'longstanding coding oversight', primary keys can be NULL in SQLite. This is not the case with other databases.
A primary key is a field in a table which uniquely identifies each rows/records in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s).
You already have seen various examples above where we have created COMPANY table with ID as a primary key.
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
CHECK Constraint enables a condition to check the value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn't entered into the table.
For example, the following SQLite creates a new table called COMPANY and adds five columns. Here, we add a CHECK with SALARY column, so that you cannot have any SALARY Zero.
CREATE TABLE COMPANY3(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL CHECK(SALARY > 0)
);
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.
SQLite Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each.
SQL defines three major types of joins −
The CROSS JOIN
The INNER JOIN
The OUTER JOIN
Before we proceed, let's consider two tables COMPANY and DEPARTMENT. We already have seen INSERT statements to populate COMPANY table. So just let's assume the list of records available in COMPANY table −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Another table is DEPARTMENT with the following definition −
CREATE TABLE DEPARTMENT(
ID INT PRIMARY KEY NOT NULL,
DEPT CHAR(50) NOT NULL,
EMP_ID INT NOT NULL
);
Here is the list of INSERT statements to populate DEPARTMENT table −
INSERT INTO DEPARTMENT (ID, DEPT, EMP_ID)
VALUES (1, 'IT Billing', 1 );
INSERT INTO DEPARTMENT (ID, DEPT, EMP_ID)
VALUES (2, 'Engineering', 2 );
INSERT INTO DEPARTMENT (ID, DEPT, EMP_ID)
VALUES (3, 'Finance', 7 );
Finally, we have the following list of records available in DEPARTMENT table −
ID DEPT EMP_ID
---------- ---------- ----------
1 IT Billing 1
2 Engineering 2
3 Finance 7
CROSS JOIN matches every row of the first table with every row of the second table. If the input tables have x and y row, respectively, the resulting table will have x*y row. Because CROSS JOINs have the potential to generate extremely large tables, care must be taken to only use them when appropriate.
Following is the syntax of CROSS JOIN −
SELECT ... FROM table1 CROSS JOIN table2 ...
Based on the above tables, you can write a CROSS JOIN as follows −
sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY CROSS JOIN DEPARTMENT;
The above query will produce the following result −
EMP_ID NAME DEPT
---------- ---------- ----------
1 Paul IT Billing
2 Paul Engineering
7 Paul Finance
1 Allen IT Billing
2 Allen Engineering
7 Allen Finance
1 Teddy IT Billing
2 Teddy Engineering
7 Teddy Finance
1 Mark IT Billing
2 Mark Engineering
7 Mark Finance
1 David IT Billing
2 David Engineering
7 David Finance
1 Kim IT Billing
2 Kim Engineering
7 Kim Finance
1 James IT Billing
2 James Engineering
7 James Finance
INNER JOIN creates a new result table by combining column values of two tables (table1 and table2) based upon the join-predicate. The query compares each row of table1 with each row of table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, the column values for each matched pair of rows of A and B are combined into a result row.
An INNER JOIN is the most common and default type of join. You can use INNER keyword optionally.
Following is the syntax of INNER JOIN −
SELECT ... FROM table1 [INNER] JOIN table2 ON conditional_expression ...
To avoid redundancy and keep the phrasing shorter, INNER JOIN conditions can be declared with a USING expression. This expression specifies a list of one or more columns.
SELECT ... FROM table1 JOIN table2 USING ( column1 ,... ) ...
A NATURAL JOIN is similar to a JOIN...USING, only it automatically tests for equality between the values of every column that exists in both tables −
SELECT ... FROM table1 NATURAL JOIN table2...
Based on the above tables, you can write an INNER JOIN as follows −
sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
The above query will produce the following result −
EMP_ID NAME DEPT
---------- ---------- ----------
1 Paul IT Billing
2 Allen Engineering
7 James Finance
OUTER JOIN is an extension of INNER JOIN. Though SQL standard defines three types of OUTER JOINs: LEFT, RIGHT, and FULL, SQLite only supports the LEFT OUTER JOIN.
OUTER JOINs have a condition that is identical to INNER JOINs, expressed using an ON, USING, or NATURAL keyword. The initial results table is calculated the same way. Once the primary JOIN is calculated, an OUTER JOIN will take any unjoined rows from one or both tables, pad them out with NULLs, and append them to the resulting table.
Following is the syntax of LEFT OUTER JOIN −
SELECT ... FROM table1 LEFT OUTER JOIN table2 ON conditional_expression ...
To avoid redundancy and keep the phrasing shorter, OUTER JOIN conditions can be declared with a USING expression. This expression specifies a list of one or more columns.
SELECT ... FROM table1 LEFT OUTER JOIN table2 USING ( column1 ,... ) ...
Based on the above tables, you can write an outer join as follows −
sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
The above query will produce the following result −
EMP_ID NAME DEPT
---------- ---------- ----------
1 Paul IT Billing
2 Allen Engineering
Teddy
Mark
David
Kim
7 James Finance
SQLite UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows.
To use UNION, each SELECT must have the same number of columns selected, the same number of column expressions, the same data type, and have them in the same order, but they do not have to be of the same length.
Following is the basic syntax of UNION.
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here the given condition could be any given expression based on your requirement.
Consider the following two tables, (a) COMPANY table as follows −
sqlite> select * from COMPANY;
ID NAME AGE ADDRESS SALARY
---------- -------------------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
(b) Another table is DEPARTMENT as follows −
ID DEPT EMP_ID
---------- -------------------- ----------
1 IT Billing 1
2 Engineering 2
3 Finance 7
4 Engineering 3
5 Finance 4
6 Engineering 5
7 Finance 6
Now let us join these two tables using SELECT statement along with UNION clause as follows −
sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
This will produce the following result.
EMP_ID NAME DEPT
---------- -------------------- ----------
1 Paul IT Billing
2 Allen Engineering
3 Teddy Engineering
4 Mark Finance
5 David Engineering
6 Kim Finance
7 James Finance
The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows.
The same rules that apply to UNION apply to the UNION ALL operator as well.
Following is the basic syntax of UNION ALL.
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION ALL
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here the given condition could be any given expression based on your requirement.
Now, let us join the above-mentioned two tables in our SELECT statement as follows −
sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION ALL
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
This will produce the following result.
EMP_ID NAME DEPT
---------- -------------------- ----------
1 Paul IT Billing
2 Allen Engineering
3 Teddy Engineering
4 Mark Finance
5 David Engineering
6 Kim Finance
7 James Finance
1 Paul IT Billing
2 Allen Engineering
3 Teddy Engineering
4 Mark Finance
5 David Engineering
6 Kim Finance
7 James Finance
SQLite NULL is the term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank.
A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different than a zero value or a field that contains spaces.
Following is the basic syntax of using NULL while creating a table.
SQLite> CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
Here, NOT NULL signifies that the column should always accept an explicit value of the given data type. There are two columns where we did not use NOT NULL which means these columns could be NULL.
A field with a NULL value is one that has been left blank during record creation.
The NULL value can cause problems when selecting data, because when comparing an unknown value to any other value, the result is always unknown and not included in the final results. Consider the following table, COMPANY with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Let us use UPDATE statement to set a few nullable values as NULL as follows −
sqlite> UPDATE COMPANY SET ADDRESS = NULL, SALARY = NULL where ID IN(6,7);
Now, COMPANY table will have the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22
7 James 24
Next, let us see the usage of IS NOT NULL operator to list down all the records where SALARY is not NULL.
sqlite> SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM COMPANY
WHERE SALARY IS NOT NULL;
The above SQLite statement will produce the following result −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following is the usage of IS NULL operator, which will list down all the records where SALARY is NULL.
sqlite> SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM COMPANY
WHERE SALARY IS NULL;
The above SQLite statement will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
6 Kim 22
7 James 24
You can rename a table or a column temporarily by giving another name, which is known as ALIAS. The use of table aliases means to rename a table in a particular SQLite statement. Renaming is a temporary change and the actual table name does not change in the database.
The column aliases are used to rename a table's columns for the purpose of a particular SQLite query.
Following is the basic syntax of table alias.
SELECT column1, column2....
FROM table_name AS alias_name
WHERE [condition];
Following is the basic syntax of column alias.
SELECT column_name AS alias_name
FROM table_name
WHERE [condition];
Consider the following two tables, (a) COMPANY table is as follows −
sqlite> select * from COMPANY;
ID NAME AGE ADDRESS SALARY
---------- -------------------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
(b) Another table is DEPARTMENT as follows −
ID DEPT EMP_ID
---------- -------------------- ----------
1 IT Billing 1
2 Engineering 2
3 Finance 7
4 Engineering 3
5 Finance 4
6 Engineering 5
7 Finance 6
Now, following is the usage of TABLE ALIAS where we use C and D as aliases for COMPANY and DEPARTMENT tables respectively −
sqlite> SELECT C.ID, C.NAME, C.AGE, D.DEPT
FROM COMPANY AS C, DEPARTMENT AS D
WHERE C.ID = D.EMP_ID;
The above SQLite statement will produce the following result −
ID NAME AGE DEPT
---------- ---------- ---------- ----------
1 Paul 32 IT Billing
2 Allen 25 Engineering
3 Teddy 23 Engineering
4 Mark 25 Finance
5 David 27 Engineering
6 Kim 22 Finance
7 James 24 Finance
Consider an example for the usage of COLUMN ALIAS where COMPANY_ID is an alias of ID column and COMPANY_NAME is an alias of name column.
sqlite> SELECT C.ID AS COMPANY_ID, C.NAME AS COMPANY_NAME, C.AGE, D.DEPT
FROM COMPANY AS C, DEPARTMENT AS D
WHERE C.ID = D.EMP_ID;
The above SQLite statement will produce the following result −
COMPANY_ID COMPANY_NAME AGE DEPT
---------- ------------ ---------- ----------
1 Paul 32 IT Billing
2 Allen 25 Engineering
3 Teddy 23 Engineering
4 Mark 25 Finance
5 David 27 Engineering
6 Kim 22 Finance
7 James 24 Finance
SQLite Triggers are database callback functions, which are automatically performed/invoked when a specified database event occurs. Following are the important points about SQLite triggers −
SQLite trigger may be specified to fire whenever a DELETE, INSERT or UPDATE of a particular database table occurs or whenever an UPDATE occurs on one or more specified columns of a table.
SQLite trigger may be specified to fire whenever a DELETE, INSERT or UPDATE of a particular database table occurs or whenever an UPDATE occurs on one or more specified columns of a table.
At this time, SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers. Hence, explicitly specifying FOR EACH ROW is optional.
At this time, SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers. Hence, explicitly specifying FOR EACH ROW is optional.
Both the WHEN clause and the trigger actions may access elements of the row being inserted, deleted, or updated using references of the form NEW.column-name and OLD.column-name, where column-name is the name of a column from the table that the trigger is associated with.
Both the WHEN clause and the trigger actions may access elements of the row being inserted, deleted, or updated using references of the form NEW.column-name and OLD.column-name, where column-name is the name of a column from the table that the trigger is associated with.
If a WHEN clause is supplied, the SQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the SQL statements are executed for all rows.
If a WHEN clause is supplied, the SQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the SQL statements are executed for all rows.
The BEFORE or AFTER keyword determines when the trigger actions will be executed relative to the insertion, modification, or removal of the associated row.
The BEFORE or AFTER keyword determines when the trigger actions will be executed relative to the insertion, modification, or removal of the associated row.
Triggers are automatically dropped when the table that they are associated with is dropped.
Triggers are automatically dropped when the table that they are associated with is dropped.
The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just tablename not database.tablename.
The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just tablename not database.tablename.
A special SQL function RAISE() may be used within a trigger-program to raise an exception.
A special SQL function RAISE() may be used within a trigger-program to raise an exception.
Following is the basic syntax of creating a trigger.
CREATE TRIGGER trigger_name [BEFORE|AFTER] event_name
ON table_name
BEGIN
-- Trigger logic goes here....
END;
Here, event_name could be INSERT, DELETE, and UPDATE database operation on the mentioned table table_name. You can optionally specify FOR EACH ROW after table name.
Following is the syntax for creating a trigger on an UPDATE operation on one or more specified columns of a table.
CREATE TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_name
ON table_name
BEGIN
-- Trigger logic goes here....
END;
Let us consider a case where we want to keep audit trial for every record being inserted in COMPANY table, which we create newly as follows (Drop COMPANY table if you already have it).
sqlite> CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
To keep audit trial, we will create a new table called AUDIT where the log messages will be inserted, whenever there is an entry in COMPANY table for a new record.
sqlite> CREATE TABLE AUDIT(
EMP_ID INT NOT NULL,
ENTRY_DATE TEXT NOT NULL
);
Here, ID is the AUDIT record ID, and EMP_ID is the ID which will come from COMPANY table and DATE will keep timestamp when the record will be created in COMPANY table. Now let's create a trigger on COMPANY table as follows −
sqlite> CREATE TRIGGER audit_log AFTER INSERT
ON COMPANY
BEGIN
INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, datetime('now'));
END;
Now, we will start actual work, Let's start inserting record in COMPANY table which should result in creating an audit log record in AUDIT table. Create one record in COMPANY table as follows −
sqlite> INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 );
This will create one record in COMPANY table, which is as follows −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
Same time, one record will be created in AUDIT table. This record is the result of a trigger, which we have created on INSERT operation in COMPANY table. Similarly, you can create your triggers on UPDATE and DELETE operations based on your requirements.
EMP_ID ENTRY_DATE
---------- -------------------
1 2013-04-05 06:26:00
You can list down all the triggers from sqlite_master table as follows −
sqlite> SELECT name FROM sqlite_master
WHERE type = 'trigger';
The above SQLite statement will list down only one entry as follows −
name
----------
audit_log
If you want to list down triggers on a particular table, then use AND clause with table name as follows −
sqlite> SELECT name FROM sqlite_master
WHERE type = 'trigger' AND tbl_name = 'COMPANY';
The above SQLite statement will also list down only one entry as follows −
name
----------
audit_log
Following is the DROP command, which can be used to drop an existing trigger.
sqlite> DROP TRIGGER trigger_name;
Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index in the back of a book.
For example, if you want to reference all pages in a book that discuss a certain topic, you first refer to the index, which lists all topics alphabetically and are then referred to one or more specific page numbers.
An index helps speed up SELECT queries and WHERE clauses, but it slows down data input, with UPDATE and INSERT statements. Indexes can be created or dropped with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the index, to specify the table and which column or columns to index, and to indicate whether the index is in an ascending or descending order.
Indexes can also be unique, similar to the UNIQUE constraint, in that the index prevents duplicate entries in the column or combination of columns on which there's an index.
Following is the basic syntax of CREATE INDEX.
CREATE INDEX index_name ON table_name;
A single-column index is one that is created based on only one table column. The basic syntax is as follows −
CREATE INDEX index_name
ON table_name (column_name);
Unique indexes are used not only for performance, but also for data integrity. A unique index does not allow any duplicate values to be inserted into the table. The basic syntax is as follows −
CREATE UNIQUE INDEX index_name
on table_name (column_name);
A composite index is an index on two or more columns of a table. The basic syntax is as follows −
CREATE INDEX index_name
on table_name (column1, column2);
Whether to create a single-column index or a composite index, take into consideration the column(s) that you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should there be two or more columns that are frequently used in the WHERE clause as filters, the composite index would be the best choice.
Implicit indexes are indexes that are automatically created by the database server when an object is created. Indexes are automatically created for primary key constraints and unique constraints.
Example
Following is an example where we will create an index in COMPANY table for salary column −
sqlite> CREATE INDEX salary_index ON COMPANY (salary);
Now, let's list down all the indices available in COMPANY table using .indices command as follows −
sqlite> .indices COMPANY
This will produce the following result, where sqlite_autoindex_COMPANY_1 is an implicit index which got created when the table itself was created.
salary_index
sqlite_autoindex_COMPANY_1
You can list down all the indexes database wide as follows −
sqlite> SELECT * FROM sqlite_master WHERE type = 'index';
An index can be dropped using SQLite DROP command. Care should be taken when dropping an index because performance may be slowed or improved.
Following is the basic syntax is as follows −
DROP INDEX index_name;
You can use the following statement to delete previously created index.
sqlite> DROP INDEX salary_index;
Although indexes are intended to enhance the performance of a database, there are times when they should be avoided. The following guidelines indicate when the use of an index should be reconsidered.
Indexes should not be used in −
Small tables.
Tables that have frequent, large batch update or insert operations.
Columns that contain a high number of NULL values.
Columns that are frequently manipulated.
The "INDEXED BY index-name" clause specifies that the named index must be used in order to look up values on the preceding table.
If index-name does not exist or cannot be used for the query, then the preparation of the SQLite statement fails.
The "NOT INDEXED" clause specifies that no index shall be used when accessing the preceding table, including implied indices created by UNIQUE and PRIMARY KEY constraints.
However, the INTEGER PRIMARY KEY can still be used to look up entries even when "NOT INDEXED" is specified.
Following is the syntax for INDEXED BY clause and it can be used with DELETE, UPDATE or SELECT statement.
SELECT|DELETE|UPDATE column1, column2...
INDEXED BY (index_name)
table_name
WHERE (CONDITION);
Consider table COMPANY We will create an index and use it for performing INDEXED BY operation.
sqlite> CREATE INDEX salary_index ON COMPANY(salary);
sqlite>
Now selecting the data from table COMPANY you can use INDEXED BY clause as follows −
sqlite> SELECT * FROM COMPANY INDEXED BY salary_index WHERE salary > 5000;
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
7 James 24 Houston 10000.0
2 Allen 25 Texas 15000.0
1 Paul 32 California 20000.0
3 Teddy 23 Norway 20000.0
6 Kim 22 South-Hall 45000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
SQLite ALTER TABLE command modifies an existing table without performing a full dump and reload of the data. You can rename a table using ALTER TABLE statement and additional columns can be added in an existing table using ALTER TABLE statement.
There is no other operation supported by ALTER TABLE command in SQLite except renaming a table and adding a column in an existing table.
Following is the basic syntax of ALTER TABLE to RENAME an existing table.
ALTER TABLE database_name.table_name RENAME TO new_table_name;
Following is the basic syntax of ALTER TABLE to add a new column in an existing table.
ALTER TABLE database_name.table_name ADD COLUMN column_def...;
Consider the COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Now, let's try to rename this table using ALTER TABLE statement as follows −
sqlite> ALTER TABLE COMPANY RENAME TO OLD_COMPANY;
The above SQLite statement will rename COMPANY table to OLD_COMPANY. Now, let's try to add a new column in OLD_COMPANY table as follows −
sqlite> ALTER TABLE OLD_COMPANY ADD COLUMN SEX char(1);
COMPANY table is now changed and following will be the output from SELECT statement.
ID NAME AGE ADDRESS SALARY SEX
---------- ---------- ---------- ---------- ---------- ---
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
It should be noted that newly added column is filled with NULL values.
Unfortunately, we do not have TRUNCATE TABLE command in SQLite but you can use SQLite DELETE command to delete complete data from an existing table, though it is recommended to use DROP TABLE command to drop the complete table and re-create it once again.
Following is the basic syntax of DELETE command.
sqlite> DELETE FROM table_name;
Following is the basic syntax of DROP TABLE.
sqlite> DROP TABLE table_name;
If you are using DELETE TABLE command to delete all the records, it is recommended to use VACUUM command to clear unused space.
Consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is the example to truncate the above table −
SQLite> DELETE FROM COMPANY;
SQLite> VACUUM;
Now, COMPANY table is truncated completely and nothing will be the output from SELECT statement.
A view is nothing more than a SQLite statement that is stored in the database with an associated name. It is actually a composition of a table in the form of a predefined SQLite query.
A view can contain all rows of a table or selected rows from one or more tables. A view can be created from one or many tables which depends on the written SQLite query to create a view.
Views which are kind of virtual tables, allow the users to −
Structure data in a way that users or classes of users find natural or intuitive.
Structure data in a way that users or classes of users find natural or intuitive.
Restrict access to the data such that a user can only see limited data instead of a complete table.
Restrict access to the data such that a user can only see limited data instead of a complete table.
Summarize data from various tables, which can be used to generate reports.
Summarize data from various tables, which can be used to generate reports.
SQLite views are read-only and thus you may not be able to execute a DELETE, INSERT or UPDATE statement on a view. However, you can create a trigger on a view that fires on an attempt to DELETE, INSERT, or UPDATE a view and do what you need in the body of the trigger.
SQLite views are created using the CREATE VIEW statement. SQLite views can be created from a single table, multiple tables, or another view.
Following is the basic CREATE VIEW syntax.
CREATE [TEMP | TEMPORARY] VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a similar way as you use them in a normal SQL SELECT query. If the optional TEMP or TEMPORARY keyword is present, the view will be created in the temp database.
Consider COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is an example to create a view from COMPANY table. This view will be used to have only a few columns from COMPANY table.
sqlite> CREATE VIEW COMPANY_VIEW AS
SELECT ID, NAME, AGE
FROM COMPANY;
You can now query COMPANY_VIEW in a similar way as you query an actual table. Following is an example −
sqlite> SELECT * FROM COMPANY_VIEW;
This will produce the following result.
ID NAME AGE
---------- ---------- ----------
1 Paul 32
2 Allen 25
3 Teddy 23
4 Mark 25
5 David 27
6 Kim 22
7 James 24
To drop a view, simply use the DROP VIEW statement with the view_name. The basic DROP VIEW syntax is as follows −
sqlite> DROP VIEW view_name;
The following command will delete COMPANY_VIEW view, which we created in the last section.
sqlite> DROP VIEW COMPANY_VIEW;
A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program.
A transaction is the propagation of one or more changes to the database. For example, if you are creating, updating, or deleting a record from the table, then you are performing transaction on the table. It is important to control transactions to ensure data integrity and to handle database errors.
Practically, you will club many SQLite queries into a group and you will execute all of them together as part of a transaction.
Transactions have the following four standard properties, usually referred to by the acronym ACID.
Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state.
Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state.
Consistency − Ensures that the database properly changes states upon a successfully committed transaction.
Consistency − Ensures that the database properly changes states upon a successfully committed transaction.
Isolation − Enables transactions to operate independently of and transparent to each other.
Isolation − Enables transactions to operate independently of and transparent to each other.
Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure.
Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure.
Following are the following commands used to control transactions:
BEGIN TRANSACTION − To start a transaction.
BEGIN TRANSACTION − To start a transaction.
COMMIT − To save the changes, alternatively you can use END TRANSACTION command.
COMMIT − To save the changes, alternatively you can use END TRANSACTION command.
ROLLBACK − To rollback the changes.
ROLLBACK − To rollback the changes.
Transactional control commands are only used with DML commands INSERT, UPDATE, and DELETE. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database.
Transactions can be started using BEGIN TRANSACTION or simply BEGIN command. Such transactions usually persist until the next COMMIT or ROLLBACK command is encountered. However, a transaction will also ROLLBACK if the database is closed or if an error occurs. Following is the simple syntax to start a transaction.
BEGIN;
or
BEGIN TRANSACTION;
COMMIT command is the transactional command used to save changes invoked by a transaction to the database.
COMMIT command saves all transactions to the database since the last COMMIT or ROLLBACK command.
Following is the syntax for COMMIT command.
COMMIT;
or
END TRANSACTION;
ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database.
ROLLBACK command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued.
Following is the syntax for ROLLBACK command.
ROLLBACK;
Example
Consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Now, let's start a transaction and delete records from the table having age = 25. Then, use ROLLBACK command to undo all the changes.
sqlite> BEGIN;
sqlite> DELETE FROM COMPANY WHERE AGE = 25;
sqlite> ROLLBACK;
Now, if you check COMPANY table, it still has the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Let's start another transaction and delete records from the table having age = 25 and finally we use COMMIT command to commit all the changes.
sqlite> BEGIN;
sqlite> DELETE FROM COMPANY WHERE AGE = 25;
sqlite> COMMIT;
If you now check COMPANY table is still has the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
3 Teddy 23 Norway 20000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
A Subquery or Inner query or Nested query is a query within another SQLite query and embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators such as =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow −
Subqueries must be enclosed within parentheses.
Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns.
A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns.
An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator.
Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator.
BETWEEN operator cannot be used with a subquery; however, BETWEEN can be used within the subquery.
BETWEEN operator cannot be used with a subquery; however, BETWEEN can be used within the subquery.
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Now, let us check the following sub-query with SELECT statement.
sqlite> SELECT *
FROM COMPANY
WHERE ID IN (SELECT ID
FROM COMPANY
WHERE SALARY > 45000) ;
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Subqueries can also be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date, or number functions.
Following is the basic syntax is as follows −
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]
Consider a table COMPANY_BKP with similar structure as COMPANY table and can be created using the same CREATE TABLE using COMPANY_BKP as the table name. To copy the complete COMPANY table into COMPANY_BKP, following is the syntax −
sqlite> INSERT INTO COMPANY_BKP
SELECT * FROM COMPANY
WHERE ID IN (SELECT ID
FROM COMPANY) ;
The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement.
Following is the basic syntax is as follows −
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Assuming, we have COMPANY_BKP table available which is a backup of COMPANY table.
Following example updates SALARY by 0.50 times in COMPANY table for all the customers, whose AGE is greater than or equal to 27.
sqlite> UPDATE COMPANY
SET SALARY = SALARY * 0.50
WHERE AGE IN (SELECT AGE FROM COMPANY_BKP
WHERE AGE >= 27 );
This would impact two rows and finally COMPANY table would have the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 10000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 42500.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above.
Following is the basic syntax is as follows −
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Assuming, we have COMPANY_BKP table available which is a backup of COMPANY table.
Following example deletes records from COMPANY table for all the customers whose AGE is greater than or equal to 27.
sqlite> DELETE FROM COMPANY
WHERE AGE IN (SELECT AGE FROM COMPANY_BKP
WHERE AGE > 27 );
This will impact two rows and finally COMPANY table will have the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 42500.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto increment.
The keyword AUTOINCREMENT can be used with INTEGER field only.
The basic usage of AUTOINCREMENT keyword is as follows −
CREATE TABLE table_name(
column1 INTEGER AUTOINCREMENT,
column2 datatype,
column3 datatype,
.....
columnN datatype,
);
Consider COMPANY table to be created as follows −
sqlite> CREATE TABLE COMPANY(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
Now, insert the following records into table COMPANY −
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'Paul', 32, 'California', 20000.00 );
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ('Allen', 25, 'Texas', 15000.00 );
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ('Teddy', 23, 'Norway', 20000.00 );
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 );
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'David', 27, 'Texas', 85000.00 );
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'Kim', 22, 'South-Hall', 45000.00 );
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'James', 24, 'Houston', 10000.00 );
This will insert 7 tuples into the table COMPANY and COMPANY will have the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
If you take user input through a webpage and insert it into a SQLite database there's a chance that you have left yourself wide open for a security issue known as SQL Injection. In this chapter, you will learn how to help prevent this from happening and help you secure your scripts and SQLite statements.
Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a SQLite statement that you will unknowingly run on your database.
Never trust user provided data, process this data only after validation; as a rule, this is done by pattern matching. In the following example, the username is restricted to alphanumerical chars plus underscore and to a length between 8 and 20 chars - modify these rules as needed.
if (preg_match("/^\w{8,20}$/", $_GET['username'], $matches)){
$db = new SQLiteDatabase('filename');
$result = @$db->query("SELECT * FROM users WHERE username = $matches[0]");
} else {
echo "username not accepted";
}
To demonstrate the problem, consider this excerpt −
$name = "Qadir'; DELETE FROM users;";
@$db->query("SELECT * FROM users WHERE username = '{$name}'");
The function call is supposed to retrieve a record from the users table where the name column matches the name specified by the user. Under normal circumstances, $name would only contain alphanumeric characters and perhaps spaces, such as the string ilia. However in this case, by appending an entirely new query to $name, the call to the database turns into a disaster: the injected DELETE query removes all records from users.
There are databases interfaces which do not permit query stacking or executing multiple queries in a single function call. If you try to stack queries, the call fails but SQLite and PostgreSQL, happily perform stacked queries, executing all of the queries provided in one string and creating a serious security problem.
You can handle all escape characters smartly in scripting languages like PERL and PHP. Programming language PHP provides the function string sqlite_escape_string() to escape input characters that are special to SQLite.
if (get_magic_quotes_gpc()) {
$name = sqlite_escape_string($name);
}
$result = @$db->query("SELECT * FROM users WHERE username = '{$name}'");
Although the encoding makes it safe to insert the data, it will render simple text comparisons and LIKE clauses in your queries unusable for the columns that contain the binary data.
Note − addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.
SQLite statement can be preceded by the keyword "EXPLAIN" or by the phrase "EXPLAIN QUERY PLAN" used for describing the details of a table.
Either modification causes the SQLite statement to behave as a query and to return information about how the SQLite statement would have operated if the EXPLAIN keyword or phrase had been omitted.
The output from EXPLAIN and EXPLAIN QUERY PLAN is intended for interactive analysis and troubleshooting only.
The output from EXPLAIN and EXPLAIN QUERY PLAN is intended for interactive analysis and troubleshooting only.
The details of the output format are subject to change from one release of SQLite to the next.
The details of the output format are subject to change from one release of SQLite to the next.
Applications should not use EXPLAIN or EXPLAIN QUERY PLAN since their exact behavior is variable and only partially documented.
Applications should not use EXPLAIN or EXPLAIN QUERY PLAN since their exact behavior is variable and only partially documented.
syntax for EXPLAIN is as follows −
EXPLAIN [SQLite Query]
syntax for EXPLAIN QUERY PLAN is as follows −
EXPLAIN QUERY PLAN [SQLite Query]
Consider COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Now, let us check the following sub-query with SELECT statement −
sqlite> EXPLAIN SELECT * FROM COMPANY WHERE Salary >= 20000;
This will produce the following result.
addr opcode p1 p2 p3
---------- ---------- ---------- ---------- ----------
0 Goto 0 19
1 Integer 0 0
2 OpenRead 0 8
3 SetNumColu 0 5
4 Rewind 0 17
5 Column 0 4
6 RealAffini 0 0
7 Integer 20000 0
8 Lt 357 16 collseq(BI
9 Rowid 0 0
10 Column 0 1
11 Column 0 2
12 Column 0 3
13 Column 0 4
14 RealAffini 0 0
15 Callback 5 0
16 Next 0 5
17 Close 0 0
18 Halt 0 0
19 Transactio 0 0
20 VerifyCook 0 38
21 Goto 0 1
22 Noop 0 0
Now, let us check the following Explain Query Plan with SELECT statement −
SQLite> EXPLAIN QUERY PLAN SELECT * FROM COMPANY WHERE Salary >= 20000;
order from detail
---------- ---------- -------------
0 0 TABLE COMPANY
VACUUM command cleans the main database by copying its contents to a temporary database file and reloading the original database file from the copy. This eliminates free pages, aligns table data to be contiguous, and otherwise cleans up the database file structure.
VACUUM command may change the ROWID of entries in tables that do not have an explicit INTEGER PRIMARY KEY. The VACUUM command only works on the main database. It is not possible to VACUUM an attached database file.
VACUUM command will fail if there is an active transaction. VACUUM command is a no-op for in-memory databases. As the VACUUM command rebuilds the database file from scratch, VACUUM can also be used to modify many database-specific configuration parameters.
Following is a simple syntax to issue a VACUUM command for the whole database from command prompt −
$sqlite3 database_name "VACUUM;"
You can run VACUUM from SQLite prompt as well as follows −
sqlite> VACUUM;
You can also run VACUUM on a particular table as follows −
sqlite> VACUUM table_name;
SQLite Auto-VACUUM does not do the same as VACUUM rather it only moves free pages to the end of the database thereby reducing the database size. By doing so it can significantly fragment the database while VACUUM ensures defragmentation. Hence, Auto-VACUUM just keeps the database small.
You can enable/disable SQLite auto-vacuuming by the following pragmas running at SQLite prompt −
sqlite> PRAGMA auto_vacuum = NONE; -- 0 means disable auto vacuum
sqlite> PRAGMA auto_vacuum = FULL; -- 1 means enable full auto vacuum
sqlite> PRAGMA auto_vacuum = INCREMENTAL; -- 2 means enable incremental vacuum
You can run the following command from the command prompt to check the auto-vacuum setting −
$sqlite3 database_name "PRAGMA auto_vacuum;"
SQLite supports five date and time functions as follows −
All the above five date and time functions take a time string as an argument. The time string is followed by zero or more modifiers. The strftime() function also takes a format string as its first argument. Following section will give you detail on different types of time strings and modifiers.
A time string can be in any of the following formats −
You can use the "T" as a literal character separating the date and the time.
The time string can be followed by zero or more modifiers that will alter date and/or time returned by any of the above five functions. Modifiers are applied from the left to right.
Following modifers are available in SQLite −
NNN days
NNN hours
NNN minutes
NNN.NNNN seconds
NNN months
NNN years
start of month
start of year
start of day
weekday N
unixepoch
localtime
utc
SQLite provides a very handy function strftime() to format any date and time. You can use the following substitutions to format your date and time.
Let's try various examples now using SQLite prompt. Following command computes the current date.
sqlite> SELECT date('now');
2013-05-07
Following command computes the last day of the current month.
sqlite> SELECT date('now','start of month','+1 month','-1 day');
2013-05-31
Following command computes the date and time for a given UNIX timestamp 1092941466.
sqlite> SELECT datetime(1092941466, 'unixepoch');
2004-08-19 18:51:06
Following command computes the date and time for a given UNIX timestamp 1092941466 and compensate for your local timezone.
sqlite> SELECT datetime(1092941466, 'unixepoch', 'localtime');
2004-08-19 13:51:06
Following command computes the current UNIX timestamp.
sqlite> SELECT strftime('%s','now');
1393348134
Following command computes the number of days since the signing of the US Declaration of Independence.
sqlite> SELECT julianday('now') - julianday('1776-07-04');
86798.7094695023
Following command computes the number of seconds since a particular moment in 2004.
sqlite> SELECT strftime('%s','now') - strftime('%s','2004-01-01 02:34:56');
295001572
Following command computes the date of the first Tuesday in October for the current year.
sqlite> SELECT date('now','start of year','+9 months','weekday 2');
2013-10-01
Following command computes the time since the UNIX epoch in seconds (like strftime('%s','now') except includes fractional part).
sqlite> SELECT (julianday('now') - 2440587.5)*86400.0;
1367926077.12598
To convert between UTC and local time values when formatting a date, use the utc or localtime modifiers as follows −
sqlite> SELECT time('12:00', 'localtime');
05:00:00
sqlite> SELECT time('12:00', 'utc');
19:00:00
SQLite has many built-in functions to perform processing on string or numeric data. Following is the list of few useful SQLite built-in functions and all are case in-sensitive which means you can use these functions either in lower-case form or in upper-case or in mixed form. For more details, you can check official documentation for SQLite.
SQLite COUNT Function
SQLite COUNT aggregate function is used to count the number of rows in a database table.
SQLite MAX Function
SQLite MAX aggregate function allows us to select the highest (maximum) value for a certain column.
SQLite MIN Function
SQLite MIN aggregate function allows us to select the lowest (minimum) value for a certain column.
SQLite AVG Function
SQLite AVG aggregate function selects the average value for certain table column.
SQLite SUM Function
SQLite SUM aggregate function allows selecting the total for a numeric column.
SQLite RANDOM Function
SQLite RANDOM function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807.
SQLite ABS Function
SQLite ABS function returns the absolute value of the numeric argument.
SQLite UPPER Function
SQLite UPPER function converts a string into upper-case letters.
SQLite LOWER Function
SQLite LOWER function converts a string into lower-case letters.
SQLite LENGTH Function
SQLite LENGTH function returns the length of a string.
SQLite sqlite_version Function
SQLite sqlite_version function returns the version of the SQLite library.
Before we start giving examples on the above-mentioned functions, consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
SQLite COUNT aggregate function is used to count the number of rows in a database table. Following is an example −
sqlite> SELECT count(*) FROM COMPANY;
The above SQLite SQL statement will produce the following.
count(*)
----------
7
SQLite MAX aggregate function allows us to select the highest (maximum) value for a certain column. Following is an example −
sqlite> SELECT max(salary) FROM COMPANY;
The above SQLite SQL statement will produce the following.
max(salary)
-----------
85000.0
SQLite MIN aggregate function allows us to select the lowest (minimum) value for a certain column. Following is an example −
sqlite> SELECT min(salary) FROM COMPANY;
The above SQLite SQL statement will produce the following.
min(salary)
-----------
10000.0
SQLite AVG aggregate function selects the average value for a certain table column. Following is an the example −
sqlite> SELECT avg(salary) FROM COMPANY;
The above SQLite SQL statement will produce the following.
avg(salary)
----------------
37142.8571428572
SQLite SUM aggregate function allows selecting the total for a numeric column. Following is an example −
sqlite> SELECT sum(salary) FROM COMPANY;
The above SQLite SQL statement will produce the following.
sum(salary)
-----------
260000.0
SQLite RANDOM function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807. Following is an example −
sqlite> SELECT random() AS Random;
The above SQLite SQL statement will produce the following.
Random
-------------------
5876796417670984050
SQLite ABS function returns the absolute value of the numeric argument. Following is an example −
sqlite> SELECT abs(5), abs(-15), abs(NULL), abs(0), abs("ABC");
The above SQLite SQL statement will produce the following.
abs(5) abs(-15) abs(NULL) abs(0) abs("ABC")
---------- ---------- ---------- ---------- ----------
5 15 0 0.0
SQLite UPPER function converts a string into upper-case letters. Following is an example −
sqlite> SELECT upper(name) FROM COMPANY;
The above SQLite SQL statement will produce the following.
upper(name)
-----------
PAUL
ALLEN
TEDDY
MARK
DAVID
KIM
JAMES
SQLite LOWER function converts a string into lower-case letters. Following is an example −
sqlite> SELECT lower(name) FROM COMPANY;
The above SQLite SQL statement will produce the following.
lower(name)
-----------
paul
allen
teddy
mark
david
kim
james
SQLite LENGTH function returns the length of a string. Following is an example −
sqlite> SELECT name, length(name) FROM COMPANY;
The above SQLite SQL statement will produce the following.
NAME length(name)
---------- ------------
Paul 4
Allen 5
Teddy 5
Mark 4
David 5
Kim 3
James 5
SQLite sqlite_version function returns the version of the SQLite library. Following is an example −
sqlite> SELECT sqlite_version() AS 'SQLite Version';
The above SQLite SQL statement will produce the following.
SQLite Version
--------------
3.6.20
In this chapter, you will learn how to use SQLite in C/C++ programs.
Before you start using SQLite in our C/C++ programs, you need to make sure that you have SQLite library set up on the machine. You can check SQLite Installation chapter to understand the installation process.
Following are important C/C++ SQLite interface routines, which can suffice your requirement to work with SQLite database from your C/C++ program. If you are looking for a more sophisticated application, then you can look into SQLite official documentation.
sqlite3_open(const char *filename, sqlite3 **ppDb)
This routine opens a connection to an SQLite database file and returns a database connection object to be used by other SQLite routines.
If the filename argument is NULL or ':memory:', sqlite3_open() will create an in-memory database in RAM that lasts only for the duration of the session.
If the filename is not NULL, sqlite3_open() attempts to open the database file by using its value. If no file by that name exists, sqlite3_open() will open a new database file by that name.
sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)
This routine provides a quick, easy way to execute SQL commands provided by sql argument which can consist of more than one SQL command.
Here, the first argument sqlite3 is an open database object, sqlite_callback is a call back for which data is the 1st argument and errmsg will be returned to capture any error raised by the routine.
SQLite3_exec() routine parses and executes every command given in the sql argument until it reaches the end of the string or encounters an error.
sqlite3_close(sqlite3*)
This routine closes a database connection previously opened by a call to sqlite3_open(). All prepared statements associated with the connection should be finalized prior to closing the connection.
If any queries remain that have not been finalized, sqlite3_close() will return SQLITE_BUSY with the error message Unable to close due to unfinalized statements.
Following C code segment shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned.
#include <stdio.h>
#include <sqlite3.h>
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
rc = sqlite3_open("test.db", &db);
if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
sqlite3_close(db);
}
Now, let's compile and run the above program to create our database test.db in the current directory. You can change your path as per your requirement.
$gcc test.c -l sqlite3
$./a.out
Opened database successfully
If you are going to use C++ source code, then you can compile your code as follows −
$g++ test.c -l sqlite3
Here, we are linking our program with sqlite3 library to provide required functions to C program. This will create a database file test.db in your directory and you will have the following result.
-rwxr-xr-x. 1 root root 7383 May 8 02:06 a.out
-rw-r--r--. 1 root root 323 May 8 02:05 test.c
-rw-r--r--. 1 root root 0 May 8 02:06 test.db
Following C code segment will be used to create a table in the previously created database −
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
int i;
for(i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
/* Open database */
rc = sqlite3_open("test.db", &db);
if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stdout, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "CREATE TABLE COMPANY(" \
"ID INT PRIMARY KEY NOT NULL," \
"NAME TEXT NOT NULL," \
"AGE INT NOT NULL," \
"ADDRESS CHAR(50)," \
"SALARY REAL );";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if( rc != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Table created successfully\n");
}
sqlite3_close(db);
return 0;
}
When the above program is compiled and executed, it will create COMPANY table in your test.db and the final listing of the file will be as follows −
-rwxr-xr-x. 1 root root 9567 May 8 02:31 a.out
-rw-r--r--. 1 root root 1207 May 8 02:31 test.c
-rw-r--r--. 1 root root 3072 May 8 02:31 test.db
Following C code segment shows how you can create records in COMPANY table created in the above example −
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
int i;
for(i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
/* Open database */
rc = sqlite3_open("test.db", &db);
if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \
"VALUES (1, 'Paul', 32, 'California', 20000.00 ); " \
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \
"VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); " \
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \
"VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" \
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \
"VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if( rc != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Records created successfully\n");
}
sqlite3_close(db);
return 0;
}
When the above program is compiled and executed, it will create the given records in COMPANY table and will display the following two lines −
Opened database successfully
Records created successfully
Before proceeding with actual example to fetch records, let us look at some detail about the callback function, which we are using in our examples. This callback provides a way to obtain results from SELECT statements. It has the following declaration −
typedef int (*sqlite3_callback)(
void*, /* Data provided in the 4th argument of sqlite3_exec() */
int, /* The number of columns in row */
char**, /* An array of strings representing fields in the row */
char** /* An array of strings representing column names */
);
If the above callback is provided in sqlite_exec() routine as the third argument, SQLite will call this callback function for each record processed in each SELECT statement executed within the SQL argument.
Following C code segment shows how you can fetch and display records from the COMPANY table created in the above example −
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *data, int argc, char **argv, char **azColName){
int i;
fprintf(stderr, "%s: ", (const char*)data);
for(i = 0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called";
/* Open database */
rc = sqlite3_open("test.db", &db);
if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "SELECT * from COMPANY";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
sqlite3_close(db);
return 0;
}
When the above program is compiled and executed, it will produce the following result.
Opened database successfully
Callback function called: ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 20000.0
Callback function called: ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0
Callback function called: ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
Callback function called: ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
Following C code segment shows how we can use UPDATE statement to update any record and then fetch and display updated records from the COMPANY table.
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *data, int argc, char **argv, char **azColName){
int i;
fprintf(stderr, "%s: ", (const char*)data);
for(i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called";
/* Open database */
rc = sqlite3_open("test.db", &db);
if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
/* Create merged SQL statement */
sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; " \
"SELECT * from COMPANY";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
sqlite3_close(db);
return 0;
}
When the above program is compiled and executed, it will produce the following result.
Opened database successfully
Callback function called: ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 25000.0
Callback function called: ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0
Callback function called: ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
Callback function called: ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
Following C code segment shows how you can use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table.
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *data, int argc, char **argv, char **azColName) {
int i;
fprintf(stderr, "%s: ", (const char*)data);
for(i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called";
/* Open database */
rc = sqlite3_open("test.db", &db);
if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
/* Create merged SQL statement */
sql = "DELETE from COMPANY where ID=2; " \
"SELECT * from COMPANY";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
sqlite3_close(db);
return 0;
}
When the above program is compiled and executed, it will produce the following result.
Opened database successfully
Callback function called: ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 20000.0
Callback function called: ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
Callback function called: ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
In this chapter, you will learn how to use SQLite in Java programs.
Before you start using SQLite in our Java programs, you need to make sure that you have SQLite JDBC Driver and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up SQLite JDBC driver.
Download latest version of sqlite-jdbc-(VERSION).jar from sqlite-jdbc repository.
Download latest version of sqlite-jdbc-(VERSION).jar from sqlite-jdbc repository.
Add downloaded jar file sqlite-jdbc-(VERSION).jar in your class path, or you can use it along with -classpath option as explained in the following examples.
Add downloaded jar file sqlite-jdbc-(VERSION).jar in your class path, or you can use it along with -classpath option as explained in the following examples.
Following section assumes you have little knowledge about Java JDBC concepts. If you don't, then it is suggested to spent half an hour with JDBC Tutorial to become comfortable with the concepts explained below.
Following Java programs shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned.
import java.sql.*;
public class SQLiteJDBC {
public static void main( String args[] ) {
Connection c = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Opened database successfully");
}
}
Now, let's compile and run the above program to create our database test.db in the current directory. You can change your path as per your requirement. We are assuming the current version of JDBC driver sqlite-jdbc-3.7.2.jar is available in the current path.
$javac SQLiteJDBC.java
$java -classpath ".:sqlite-jdbc-3.7.2.jar" SQLiteJDBC
Open database successfully
If you are going to use Windows machine, then you can compile and run your code as follows −
$javac SQLiteJDBC.java
$java -classpath ".;sqlite-jdbc-3.7.2.jar" SQLiteJDBC
Opened database successfully
Following Java program will be used to create a table in the previously created database.
import java.sql.*;
public class SQLiteJDBC {
public static void main( String args[] ) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE COMPANY " +
"(ID INT PRIMARY KEY NOT NULL," +
" NAME TEXT NOT NULL, " +
" AGE INT NOT NULL, " +
" ADDRESS CHAR(50), " +
" SALARY REAL)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Table created successfully");
}
}
When the above program is compiled and executed, it will create COMPANY table in your test.db and final listing of the file will be as follows −
-rw-r--r--. 1 root root 3201128 Jan 22 19:04 sqlite-jdbc-3.7.2.jar
-rw-r--r--. 1 root root 1506 May 8 05:43 SQLiteJDBC.class
-rw-r--r--. 1 root root 832 May 8 05:42 SQLiteJDBC.java
-rw-r--r--. 1 root root 3072 May 8 05:43 test.db
Following Java program shows how to create records in the COMPANY table created in above example.
import java.sql.*;
public class SQLiteJDBC {
public static void main( String args[] ) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
"VALUES (1, 'Paul', 32, 'California', 20000.00 );";
stmt.executeUpdate(sql);
sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
"VALUES (2, 'Allen', 25, 'Texas', 15000.00 );";
stmt.executeUpdate(sql);
sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
"VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );";
stmt.executeUpdate(sql);
sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
"VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );";
stmt.executeUpdate(sql);
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Records created successfully");
}
}
When above program is compiled and executed, it will create given records in COMPANY table and will display following two line −
Opened database successfully
Records created successfully
Following Java program shows how to fetch and display records from the COMPANY table created in the above example.
import java.sql.*;
public class SQLiteJDBC {
public static void main( String args[] ) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
When the above program is compiled and executed, it will produce the following result.
Opened database successfully
ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 20000.0
ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
Following Java code shows how to use UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table.
import java.sql.*;
public class SQLiteJDBC {
public static void main( String args[] ) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";
stmt.executeUpdate(sql);
c.commit();
ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
When the above program is compiled and executed, it will produce the following result.
Opened database successfully
ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 25000.0
ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
Following Java code shows how to use use DELETE statement to delete any record and then fetch and display the remaining records from the our COMPANY table.
import java.sql.*;
public class SQLiteJDBC {
public static void main( String args[] ) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "DELETE from COMPANY where ID=2;";
stmt.executeUpdate(sql);
c.commit();
ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
When the above program is compiled and executed, it will produce the following result.
Opened database successfully
ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 25000.0
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
In this chapter, you will learn how to use SQLite in PHP programs.
SQLite3 extension is enabled by default as of PHP 5.3.0. It's possible to disable it by using --without-sqlite3 at compile time.
Windows users must enable php_sqlite3.dll in order to use this extension. This DLL is included with Windows distributions of PHP as of PHP 5.3.0.
For detailed installation instructions, kindly check our PHP tutorial and its official website.
Following are important PHP routines which can suffice your requirement to work with SQLite database from your PHP program. If you are looking for a more sophisticated application, then you can look into PHP official documentation.
public void SQLite3::open ( filename, flags, encryption_key )
Opens SQLite 3 Database. If the build includes encryption, then it will attempt to use the key.
If the filename is given as ':memory:', SQLite3::open() will create an in-memory database in RAM that lasts only for the duration of the session.
If the filename is actual device file name, SQLite3::open() attempts to open the database file by using its value. If no file by that name exists, then a new database file by that name gets created.
Optional flags used to determine how to open the SQLite database. By default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.
public bool SQLite3::exec ( string $query )
This routine provides a quick, easy way to execute SQL commands provided by sql argument, which can consist of more than one SQL command. This routine is used to execute a result-less query against a given database.
public SQLite3Result SQLite3::query ( string $query )
This routine executes an SQL query, returning an SQLite3Result object if the query returns results.
public int SQLite3::lastErrorCode ( void )
This routine returns the numeric result code of the most recent failed SQLite request.
public string SQLite3::lastErrorMsg ( void )
This routine returns English text describing the most recent failed SQLite request.
public int SQLite3::changes ( void )
This routine returns the number of database rows that were updated, inserted, or deleted by the most recent SQL statement.
public bool SQLite3::close ( void )
This routine closes a database connection previously opened by a call to SQLite3::open().
public string SQLite3::escapeString ( string $value )
This routine returns a string that has been properly escaped for safe inclusion in an SQL statement.
Following PHP code shows how to connect to an existing database. If database does not exist, then it will be created and finally a database object will be returned.
<?php
class MyDB extends SQLite3 {
function __construct() {
$this->open('test.db');
}
}
$db = new MyDB();
if(!$db) {
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
?>
Now, let's run the above program to create our database test.db in the current directory. You can change your path as per your requirement. If the database is successfully created, then it will display the following message −
Open database successfully
Following PHP program will be used to create a table in the previously created database.
<?php
class MyDB extends SQLite3 {
function __construct() {
$this->open('test.db');
}
}
$db = new MyDB();
if(!$db) {
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
CREATE TABLE COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);
EOF;
$ret = $db->exec($sql);
if(!$ret){
echo $db->lastErrorMsg();
} else {
echo "Table created successfully\n";
}
$db->close();
?>
When the above program is executed, it will create the COMPANY table in your test.db and it will display the following messages −
Opened database successfully
Table created successfully
Following PHP program shows how to create records in the COMPANY table created in the above example.
<?php
class MyDB extends SQLite3 {
function __construct() {
$this->open('test.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Allen', 25, 'Texas', 15000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );
EOF;
$ret = $db->exec($sql);
if(!$ret) {
echo $db->lastErrorMsg();
} else {
echo "Records created successfully\n";
}
$db->close();
?>
When the above program is executed, it will create the given records in the COMPANY table and will display the following two lines.
Opened database successfully
Records created successfully
Following PHP program shows how to fetch and display records from the COMPANY table created in the above example −
<?php
class MyDB extends SQLite3 {
function __construct() {
$this->open('test.db');
}
}
$db = new MyDB();
if(!$db) {
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
SELECT * from COMPANY;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ) {
echo "ID = ". $row['ID'] . "\n";
echo "NAME = ". $row['NAME'] ."\n";
echo "ADDRESS = ". $row['ADDRESS'] ."\n";
echo "SALARY = ".$row['SALARY'] ."\n\n";
}
echo "Operation done successfully\n";
$db->close();
?>
When the above program is executed, it will produce the following result.
Opened database successfully
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
Operation done successfully
Following PHP code shows how to use UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table.
<?php
class MyDB extends SQLite3 {
function __construct() {
$this->open('test.db');
}
}
$db = new MyDB();
if(!$db) {
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
UPDATE COMPANY set SALARY = 25000.00 where ID=1;
EOF;
$ret = $db->exec($sql);
if(!$ret) {
echo $db->lastErrorMsg();
} else {
echo $db->changes(), " Record updated successfully\n";
}
$sql =<<<EOF
SELECT * from COMPANY;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ) {
echo "ID = ". $row['ID'] . "\n";
echo "NAME = ". $row['NAME'] ."\n";
echo "ADDRESS = ". $row['ADDRESS'] ."\n";
echo "SALARY = ".$row['SALARY'] ."\n\n";
}
echo "Operation done successfully\n";
$db->close();
?>
When the above program is executed, it will produce the following result.
Opened database successfully
1 Record updated successfully
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
Operation done successfully
Following PHP code shows how to use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table.
<?php
class MyDB extends SQLite3 {
function __construct() {
$this->open('test.db');
}
}
$db = new MyDB();
if(!$db) {
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
DELETE from COMPANY where ID = 2;
EOF;
$ret = $db->exec($sql);
if(!$ret){
echo $db->lastErrorMsg();
} else {
echo $db->changes(), " Record deleted successfully\n";
}
$sql =<<<EOF
SELECT * from COMPANY;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ) {
echo "ID = ". $row['ID'] . "\n";
echo "NAME = ". $row['NAME'] ."\n";
echo "ADDRESS = ". $row['ADDRESS'] ."\n";
echo "SALARY = ".$row['SALARY'] ."\n\n";
}
echo "Operation done successfully\n";
$db->close();
?>
When the above program is executed, it will produce the following result.
Opened database successfully
1 Record deleted successfully
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
Operation done successfully
In this chapter, you will learn how to use SQLite in Perl programs.
SQLite3 can be integrated with Perl using Perl DBI module, which is a database access module for the Perl programming language. It defines a set of methods, variables, and conventions that provide a standard database interface.
Following are simple steps to install DBI module on your Linux/UNIX machine −
$ wget http://search.cpan.org/CPAN/authors/id/T/TI/TIMB/DBI-1.625.tar.gz
$ tar xvfz DBI-1.625.tar.gz
$ cd DBI-1.625
$ perl Makefile.PL
$ make
$ make install
If you need to install SQLite driver for DBI, then it can be installed as follows −
$ wget http://search.cpan.org/CPAN/authors/id/M/MS/MSERGEANT/DBD-SQLite-1.11.tar.gz
$ tar xvfz DBD-SQLite-1.11.tar.gz
$ cd DBD-SQLite-1.11
$ perl Makefile.PL
$ make
$ make install
Following are important DBI routines, which can suffice your requirement to work with SQLite database from your Perl program. If you are looking for a more sophisticated application, then you can look into Perl DBI official documentation.
DBI->connect($data_source, "", "", \%attr)
Establishes a database connection, or session, to the requested $data_source. Returns a database handle object if the connection succeeds.
Datasource has the form like − DBI:SQLite:dbname = 'test.db' where SQLite is SQLite driver name and test.db is the name of SQLite database file. If the filename is given as ':memory:', it will create an in-memory database in RAM that lasts only for the duration of the session.
If the filename is actual device file name, then it attempts to open the database file by using its value. If no file by that name exists, then a new database file by that name gets created.
You keep second and third parameter as blank strings and the last parameter is to pass various attributes as shown in the following example.
$dbh->do($sql)
This routine prepares and executes a single SQL statement. Returns the number of rows affected or undef on error. A return value of -1 means the number of rows is not known, not applicable, or not available. Here, $dbh is a handle returned by DBI->connect() call.
$dbh->prepare($sql)
This routine prepares a statement for later execution by the database engine and returns a reference to a statement handle object.
$sth->execute()
This routine performs whatever processing is necessary to execute the prepared statement. An undef is returned if an error occurs. A successful execute always returns true regardless of the number of rows affected. Here, $sth is a statement handle returned by $dbh->prepare($sql) call.
$sth->fetchrow_array()
This routine fetches the next row of data and returns it as a list containing the field values. Null fields are returned as undef values in the list.
$DBI::err
This is equivalent to $h->err, where $h is any of the handle types like $dbh, $sth, or $drh. This returns native database engine error code from the last driver method called.
$DBI::errstr
This is equivalent to $h->errstr, where $h is any of the handle types like $dbh, $sth, or $drh. This returns the native database engine error message from the last DBI method called.
$dbh->disconnect()
This routine closes a database connection previously opened by a call to DBI->connect().
Following Perl code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned.
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
Now, let's run the above program to create our database test.db in the current directory. You can change your path as per your requirement. Keep the above code in sqlite.pl file and execute it as shown below. If the database is successfully created, then it will display the following message −
$ chmod +x sqlite.pl
$ ./sqlite.pl
Open database successfully
Following Perl program is used to create a table in the previously created database.
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
my $stmt = qq(CREATE TABLE COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL););
my $rv = $dbh->do($stmt);
if($rv < 0) {
print $DBI::errstr;
} else {
print "Table created successfully\n";
}
$dbh->disconnect();
When the above program is executed, it will create COMPANY table in your test.db and it will display the following messages −
Opened database successfully
Table created successfully
NOTE − In case you see the following error in any of the operation −
DBD::SQLite::st execute failed: not an error(21) at dbdimp.c line 398
In such case, open dbdimp.c file available in DBD-SQLite installation and find out sqlite3_prepare() function and change its third argument to -1 instead of 0. Finally, install DBD::SQLite using make and do make install to resolve the problem.
Following Perl program shows how to create records in the COMPANY table created in the above example.
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
my $stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 ));
my $rv = $dbh->do($stmt) or die $DBI::errstr;
$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Allen', 25, 'Texas', 15000.00 ));
$rv = $dbh->do($stmt) or die $DBI::errstr;
$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'Teddy', 23, 'Norway', 20000.00 ));
$rv = $dbh->do($stmt) or die $DBI::errstr;
$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 ););
$rv = $dbh->do($stmt) or die $DBI::errstr;
print "Records created successfully\n";
$dbh->disconnect();
When the above program is executed, it will create the given records in the COMPANY table and it will display the following two lines −
Opened database successfully
Records created successfully
Following Perl program shows how to fetch and display records from the COMPANY table created in the above example.
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
my $stmt = qq(SELECT id, name, address, salary from COMPANY;);
my $sth = $dbh->prepare( $stmt );
my $rv = $sth->execute() or die $DBI::errstr;
if($rv < 0) {
print $DBI::errstr;
}
while(my @row = $sth->fetchrow_array()) {
print "ID = ". $row[0] . "\n";
print "NAME = ". $row[1] ."\n";
print "ADDRESS = ". $row[2] ."\n";
print "SALARY = ". $row[3] ."\n\n";
}
print "Operation done successfully\n";
$dbh->disconnect();
When the above program is executed, it will produce the following result.
Opened database successfully
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
Operation done successfully
Following Perl code shows how to UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table.
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
my $stmt = qq(UPDATE COMPANY set SALARY = 25000.00 where ID=1;);
my $rv = $dbh->do($stmt) or die $DBI::errstr;
if( $rv < 0 ) {
print $DBI::errstr;
} else {
print "Total number of rows updated : $rv\n";
}
$stmt = qq(SELECT id, name, address, salary from COMPANY;);
my $sth = $dbh->prepare( $stmt );
$rv = $sth->execute() or die $DBI::errstr;
if($rv < 0) {
print $DBI::errstr;
}
while(my @row = $sth->fetchrow_array()) {
print "ID = ". $row[0] . "\n";
print "NAME = ". $row[1] ."\n";
print "ADDRESS = ". $row[2] ."\n";
print "SALARY = ". $row[3] ."\n\n";
}
print "Operation done successfully\n";
$dbh->disconnect();
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows updated : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
Operation done successfully
Following Perl code shows how to use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table −
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
my $stmt = qq(DELETE from COMPANY where ID = 2;);
my $rv = $dbh->do($stmt) or die $DBI::errstr;
if( $rv < 0 ) {
print $DBI::errstr;
} else {
print "Total number of rows deleted : $rv\n";
}
$stmt = qq(SELECT id, name, address, salary from COMPANY;);
my $sth = $dbh->prepare( $stmt );
$rv = $sth->execute() or die $DBI::errstr;
if($rv < 0) {
print $DBI::errstr;
}
while(my @row = $sth->fetchrow_array()) {
print "ID = ". $row[0] . "\n";
print "NAME = ". $row[1] ."\n";
print "ADDRESS = ". $row[2] ."\n";
print "SALARY = ". $row[3] ."\n\n";
}
print "Operation done successfully\n";
$dbh->disconnect();
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows deleted : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
Operation done successfully
In this chapter, you will learn how to use SQLite in Python programs.
SQLite3 can be integrated with Python using sqlite3 module, which was written by Gerhard Haring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. You do not need to install this module separately because it is shipped by default along with Python version 2.5.x onwards.
To use sqlite3 module, you must first create a connection object that represents the database and then optionally you can create a cursor object, which will help you in executing all the SQL statements.
Following are important sqlite3 module routines, which can suffice your requirement to work with SQLite database from your Python program. If you are looking for a more sophisticated application, then you can look into Python sqlite3 module's official documentation.
sqlite3.connect(database [,timeout ,other optional arguments])
This API opens a connection to the SQLite database file. You can use ":memory:" to open a database connection to a database that resides in RAM instead of on disk. If database is opened successfully, it returns a connection object.
When a database is accessed by multiple connections, and one of the processes modifies the database, the SQLite database is locked until that transaction is committed. The timeout parameter specifies how long the connection should wait for the lock to go away until raising an exception. The default for the timeout parameter is 5.0 (five seconds).
If the given database name does not exist then this call will create the database. You can specify filename with the required path as well if you want to create a database anywhere else except in the current directory.
connection.cursor([cursorClass])
This routine creates a cursor which will be used throughout of your database programming with Python. This method accepts a single optional parameter cursorClass. If supplied, this must be a custom cursor class that extends sqlite3.Cursor.
cursor.execute(sql [, optional parameters])
This routine executes an SQL statement. The SQL statement may be parameterized (i. e. placeholders instead of SQL literals). The sqlite3 module supports two kinds of placeholders: question marks and named placeholders (named style).
For example − cursor.execute("insert into people values (?, ?)", (who, age))
connection.execute(sql [, optional parameters])
This routine is a shortcut of the above execute method provided by the cursor object and it creates an intermediate cursor object by calling the cursor method, then calls the cursor's execute method with the parameters given.
cursor.executemany(sql, seq_of_parameters)
This routine executes an SQL command against all parameter sequences or mappings found in the sequence sql.
connection.executemany(sql[, parameters])
This routine is a shortcut that creates an intermediate cursor object by calling the cursor method, then calls the cursor.s executemany method with the parameters given.
cursor.executescript(sql_script)
This routine executes multiple SQL statements at once provided in the form of script. It issues a COMMIT statement first, then executes the SQL script it gets as a parameter. All the SQL statements should be separated by a semi colon (;).
connection.executescript(sql_script)
This routine is a shortcut that creates an intermediate cursor object by calling the cursor method, then calls the cursor's executescript method with the parameters given.
connection.total_changes()
This routine returns the total number of database rows that have been modified, inserted, or deleted since the database connection was opened.
connection.commit()
This method commits the current transaction. If you don't call this method, anything you did since the last call to commit() is not visible from other database connections.
connection.rollback()
This method rolls back any changes to the database since the last call to commit().
connection.close()
This method closes the database connection. Note that this does not automatically call commit(). If you just close your database connection without calling commit() first, your changes will be lost!
cursor.fetchone()
This method fetches the next row of a query result set, returning a single sequence, or None when no more data is available.
cursor.fetchmany([size = cursor.arraysize])
This routine fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available. The method tries to fetch as many rows as indicated by the size parameter.
cursor.fetchall()
This routine fetches all (remaining) rows of a query result, returning a list. An empty list is returned when no rows are available.
Following Python code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned.
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
Here, you can also supply database name as the special name :memory: to create a database in RAM. Now, let's run the above program to create our database test.db in the current directory. You can change your path as per your requirement. Keep the above code in sqlite.py file and execute it as shown below. If the database is successfully created, then it will display the following message.
$chmod +x sqlite.py
$./sqlite.py
Open database successfully
Following Python program will be used to create a table in the previously created database.
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute('''CREATE TABLE COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
print "Table created successfully";
conn.close()
When the above program is executed, it will create the COMPANY table in your test.db and it will display the following messages −
Opened database successfully
Table created successfully
Following Python program shows how to create records in the COMPANY table created in the above example.
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (1, 'Paul', 32, 'California', 20000.00 )");
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (2, 'Allen', 25, 'Texas', 15000.00 )");
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )");
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )");
conn.commit()
print "Records created successfully";
conn.close()
When the above program is executed, it will create the given records in the COMPANY table and it will display the following two lines −
Opened database successfully
Records created successfully
Following Python program shows how to fetch and display records from the COMPANY table created in the above example.
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
print "Operation done successfully";
conn.close()
When the above program is executed, it will produce the following result.
Opened database successfully
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
Following Python code shows how to use UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table.
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("UPDATE COMPANY set SALARY = 25000.00 where ID = 1")
conn.commit()
print "Total number of rows updated :", conn.total_changes
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
print "Operation done successfully";
conn.close()
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows updated : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000.0
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
Following Python code shows how to use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table.
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("DELETE from COMPANY where ID = 2;")
conn.commit()
print "Total number of rows deleted :", conn.total_changes
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
print "Operation done successfully";
conn.close()
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows deleted : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
25 Lectures
4.5 hours
Sandip Bhattacharya
17 Lectures
1 hours
Laurence Svekis
5 Lectures
51 mins
Vinay Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2789,
"s": 2638,
"text": "This chapter helps you understand what is SQLite, how it differs from SQL, why it is needed and the way in which it handles the applications Database."
},
{
"code": null,
"e": 3109,
"s": 2789,
"text": "SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. SQLite is one of the fastest-growing database engines around, but that's growth in terms of popularity, not anything to do with its size. The source code for SQLite is in the public domain."
},
{
"code": null,
"e": 3367,
"s": 3109,
"text": "SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. It is a database, which is zero-configured, which means like other databases you do not need to configure it in your system."
},
{
"code": null,
"e": 3564,
"s": 3367,
"text": "SQLite engine is not a standalone process like other databases, you can link it statically or dynamically as per your requirement with your application. SQLite accesses its storage files directly."
},
{
"code": null,
"e": 3649,
"s": 3564,
"text": "SQLite does not require a separate server process or system to operate (serverless)."
},
{
"code": null,
"e": 3734,
"s": 3649,
"text": "SQLite does not require a separate server process or system to operate (serverless)."
},
{
"code": null,
"e": 3819,
"s": 3734,
"text": "SQLite comes with zero-configuration, which means no setup or administration needed."
},
{
"code": null,
"e": 3904,
"s": 3819,
"text": "SQLite comes with zero-configuration, which means no setup or administration needed."
},
{
"code": null,
"e": 3979,
"s": 3904,
"text": "A complete SQLite database is stored in a single cross-platform disk file."
},
{
"code": null,
"e": 4054,
"s": 3979,
"text": "A complete SQLite database is stored in a single cross-platform disk file."
},
{
"code": null,
"e": 4179,
"s": 4054,
"text": "SQLite is very small and light weight, less than 400KiB fully configured or less than 250KiB with optional features omitted."
},
{
"code": null,
"e": 4304,
"s": 4179,
"text": "SQLite is very small and light weight, less than 400KiB fully configured or less than 250KiB with optional features omitted."
},
{
"code": null,
"e": 4368,
"s": 4304,
"text": "SQLite is self-contained, which means no external dependencies."
},
{
"code": null,
"e": 4432,
"s": 4368,
"text": "SQLite is self-contained, which means no external dependencies."
},
{
"code": null,
"e": 4535,
"s": 4432,
"text": "SQLite transactions are fully ACID-compliant, allowing safe access from multiple processes or threads."
},
{
"code": null,
"e": 4638,
"s": 4535,
"text": "SQLite transactions are fully ACID-compliant, allowing safe access from multiple processes or threads."
},
{
"code": null,
"e": 4722,
"s": 4638,
"text": "SQLite supports most of the query language features found in SQL92 (SQL2) standard."
},
{
"code": null,
"e": 4806,
"s": 4722,
"text": "SQLite supports most of the query language features found in SQL92 (SQL2) standard."
},
{
"code": null,
"e": 4875,
"s": 4806,
"text": "SQLite is written in ANSI-C and provides simple and easy-to-use API."
},
{
"code": null,
"e": 4944,
"s": 4875,
"text": "SQLite is written in ANSI-C and provides simple and easy-to-use API."
},
{
"code": null,
"e": 5039,
"s": 4944,
"text": "SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32, WinCE, WinRT)."
},
{
"code": null,
"e": 5134,
"s": 5039,
"text": "SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32, WinCE, WinRT)."
},
{
"code": null,
"e": 5244,
"s": 5134,
"text": "2000 - D. Richard Hipp designed SQLite for the purpose of no administration required for operating a program."
},
{
"code": null,
"e": 5354,
"s": 5244,
"text": "2000 - D. Richard Hipp designed SQLite for the purpose of no administration required for operating a program."
},
{
"code": null,
"e": 5419,
"s": 5354,
"text": "2000 - In August, SQLite 1.0 released with GNU Database Manager."
},
{
"code": null,
"e": 5484,
"s": 5419,
"text": "2000 - In August, SQLite 1.0 released with GNU Database Manager."
},
{
"code": null,
"e": 5594,
"s": 5484,
"text": "2011 - Hipp announced to add UNQl interface to SQLite DB and to develop UNQLite (Document oriented database)."
},
{
"code": null,
"e": 5704,
"s": 5594,
"text": "2011 - Hipp announced to add UNQl interface to SQLite DB and to develop UNQLite (Document oriented database)."
},
{
"code": null,
"e": 5799,
"s": 5704,
"text": "There are few unsupported features of SQL92 in SQLite which are listed in the following table."
},
{
"code": null,
"e": 5816,
"s": 5799,
"text": "RIGHT OUTER JOIN"
},
{
"code": null,
"e": 5853,
"s": 5816,
"text": "Only LEFT OUTER JOIN is implemented."
},
{
"code": null,
"e": 5869,
"s": 5853,
"text": "FULL OUTER JOIN"
},
{
"code": null,
"e": 5906,
"s": 5869,
"text": "Only LEFT OUTER JOIN is implemented."
},
{
"code": null,
"e": 5918,
"s": 5906,
"text": "ALTER TABLE"
},
{
"code": null,
"e": 6066,
"s": 5918,
"text": "The RENAME TABLE and ADD COLUMN variants of the ALTER TABLE command are supported. The DROP COLUMN, ALTER COLUMN, ADD CONSTRAINT are not supported."
},
{
"code": null,
"e": 6082,
"s": 6066,
"text": "Trigger support"
},
{
"code": null,
"e": 6155,
"s": 6082,
"text": "FOR EACH ROW triggers are supported but not FOR EACH STATEMENT triggers."
},
{
"code": null,
"e": 6161,
"s": 6155,
"text": "VIEWs"
},
{
"code": null,
"e": 6261,
"s": 6161,
"text": "VIEWs in SQLite are read-only. You may not execute a DELETE, INSERT, or UPDATE statement on a view."
},
{
"code": null,
"e": 6278,
"s": 6261,
"text": "GRANT and REVOKE"
},
{
"code": null,
"e": 6401,
"s": 6278,
"text": "The only access permissions that can be applied are the normal file access permissions of the underlying operating system."
},
{
"code": null,
"e": 6627,
"s": 6401,
"text": "The standard SQLite commands to interact with relational databases are similar to SQL. They are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be classified into groups based on their operational nature −"
},
{
"code": null,
"e": 6634,
"s": 6627,
"text": "CREATE"
},
{
"code": null,
"e": 6703,
"s": 6634,
"text": "Creates a new table, a view of a table, or other object in database."
},
{
"code": null,
"e": 6709,
"s": 6703,
"text": "ALTER"
},
{
"code": null,
"e": 6764,
"s": 6709,
"text": "Modifies an existing database object, such as a table."
},
{
"code": null,
"e": 6769,
"s": 6764,
"text": "DROP"
},
{
"code": null,
"e": 6845,
"s": 6769,
"text": "Deletes an entire table, a view of a table or other object in the database."
},
{
"code": null,
"e": 6852,
"s": 6845,
"text": "INSERT"
},
{
"code": null,
"e": 6869,
"s": 6852,
"text": "Creates a record"
},
{
"code": null,
"e": 6876,
"s": 6869,
"text": "UPDATE"
},
{
"code": null,
"e": 6893,
"s": 6876,
"text": "Modifies records"
},
{
"code": null,
"e": 6900,
"s": 6893,
"text": "DELETE"
},
{
"code": null,
"e": 6916,
"s": 6900,
"text": "Deletes records"
},
{
"code": null,
"e": 6923,
"s": 6916,
"text": "SELECT"
},
{
"code": null,
"e": 6973,
"s": 6923,
"text": "Retrieves certain records from one or more tables"
},
{
"code": null,
"e": 7190,
"s": 6973,
"text": "SQLite is famous for its great feature zero-configuration, which means no complex setup or administration is needed. This chapter will take you through the process of setting up SQLite on Windows, Linux and Mac OS X."
},
{
"code": null,
"e": 7283,
"s": 7190,
"text": "Step 1 − Go to SQLite download page, and download precompiled binaries from Windows section."
},
{
"code": null,
"e": 7376,
"s": 7283,
"text": "Step 1 − Go to SQLite download page, and download precompiled binaries from Windows section."
},
{
"code": null,
"e": 7460,
"s": 7376,
"text": "Step 2 − Download sqlite-shell-win32-*.zip and sqlite-dll-win32-*.zip zipped files."
},
{
"code": null,
"e": 7544,
"s": 7460,
"text": "Step 2 − Download sqlite-shell-win32-*.zip and sqlite-dll-win32-*.zip zipped files."
},
{
"code": null,
"e": 7698,
"s": 7544,
"text": "Step 3 − Create a folder C:\\>sqlite and unzip above two zipped files in this folder, which will give you sqlite3.def, sqlite3.dll and sqlite3.exe files.\n"
},
{
"code": null,
"e": 7851,
"s": 7698,
"text": "Step 3 − Create a folder C:\\>sqlite and unzip above two zipped files in this folder, which will give you sqlite3.def, sqlite3.dll and sqlite3.exe files."
},
{
"code": null,
"e": 8016,
"s": 7851,
"text": "Step 4 − Add C:\\>sqlite in your PATH environment variable and finally go to the command prompt and issue sqlite3 command, which should display the following result."
},
{
"code": null,
"e": 8181,
"s": 8016,
"text": "Step 4 − Add C:\\>sqlite in your PATH environment variable and finally go to the command prompt and issue sqlite3 command, which should display the following result."
},
{
"code": null,
"e": 8320,
"s": 8181,
"text": "C:\\>sqlite3\nSQLite version 3.7.15.2 2013-01-09 11:53:05\nEnter \".help\" for instructions\nEnter SQL statements terminated with a \";\"\nsqlite>\n"
},
{
"code": null,
"e": 8497,
"s": 8320,
"text": "Today, almost all the flavours of Linux OS are being shipped with SQLite. So you just issue the following command to check if you already have SQLite installed on your machine."
},
{
"code": null,
"e": 8633,
"s": 8497,
"text": "$sqlite3\nSQLite version 3.7.15.2 2013-01-09 11:53:05\nEnter \".help\" for instructions\nEnter SQL statements terminated with a \";\"\nsqlite>\n"
},
{
"code": null,
"e": 8793,
"s": 8633,
"text": "If you do not see the above result, then it means you do not have SQLite installed on your Linux machine. Following are the following steps to install SQLite −"
},
{
"code": null,
"e": 8893,
"s": 8793,
"text": "Step 1 − Go to SQLite download page and download sqlite-autoconf-*.tar.gz from source code section."
},
{
"code": null,
"e": 8993,
"s": 8893,
"text": "Step 1 − Go to SQLite download page and download sqlite-autoconf-*.tar.gz from source code section."
},
{
"code": null,
"e": 9030,
"s": 8993,
"text": "Step 2 − Run the following command −"
},
{
"code": null,
"e": 9067,
"s": 9030,
"text": "Step 2 − Run the following command −"
},
{
"code": null,
"e": 9190,
"s": 9067,
"text": "$tar xvfz sqlite-autoconf-3071502.tar.gz\n$cd sqlite-autoconf-3071502\n$./configure --prefix=/usr/local\n$make\n$make install\n"
},
{
"code": null,
"e": 9306,
"s": 9190,
"text": "The above command will end with SQLite installation on your Linux machine. Which you can verify as explained above."
},
{
"code": null,
"e": 9463,
"s": 9306,
"text": "Though the latest version of Mac OS X comes pre-installed with SQLite but if you do not have installation available then just follow these following steps −"
},
{
"code": null,
"e": 9564,
"s": 9463,
"text": "Step 1 − Go to SQLite download page, and download sqlite-autoconf-*.tar.gz from source code section."
},
{
"code": null,
"e": 9665,
"s": 9564,
"text": "Step 1 − Go to SQLite download page, and download sqlite-autoconf-*.tar.gz from source code section."
},
{
"code": null,
"e": 9702,
"s": 9665,
"text": "Step 2 − Run the following command −"
},
{
"code": null,
"e": 9739,
"s": 9702,
"text": "Step 2 − Run the following command −"
},
{
"code": null,
"e": 9862,
"s": 9739,
"text": "$tar xvfz sqlite-autoconf-3071502.tar.gz\n$cd sqlite-autoconf-3071502\n$./configure --prefix=/usr/local\n$make\n$make install\n"
},
{
"code": null,
"e": 9998,
"s": 9862,
"text": "The above procedure will end with SQLite installation on your Mac OS X machine. Which you can verify by issuing the following command −"
},
{
"code": null,
"e": 10134,
"s": 9998,
"text": "$sqlite3\nSQLite version 3.7.15.2 2013-01-09 11:53:05\nEnter \".help\" for instructions\nEnter SQL statements terminated with a \";\"\nsqlite>\n"
},
{
"code": null,
"e": 10230,
"s": 10134,
"text": "Finally, you have SQLite command prompt where you can issue SQLite commands for your exercises."
},
{
"code": null,
"e": 10459,
"s": 10230,
"text": "This chapter will take you through simple and useful commands used by SQLite programmers. These commands are called SQLite dot commands and exception with these commands is that they should not be terminated by a semi-colon (;)."
},
{
"code": null,
"e": 10622,
"s": 10459,
"text": "Let's start with typing a simple sqlite3 command at command prompt which will provide you with SQLite command prompt where you will issue various SQLite commands."
},
{
"code": null,
"e": 10692,
"s": 10622,
"text": "$sqlite3\nSQLite version 3.3.6\nEnter \".help\" for instructions\nsqlite>\n"
},
{
"code": null,
"e": 10783,
"s": 10692,
"text": "For a listing of the available dot commands, you can enter \".help\" any time. For example −"
},
{
"code": null,
"e": 10796,
"s": 10783,
"text": "sqlite>.help"
},
{
"code": null,
"e": 10917,
"s": 10796,
"text": "The above command will display a list of various important SQLite dot commands, which are listed in the following table."
},
{
"code": null,
"e": 10935,
"s": 10917,
"text": ".backup ?DB? FILE"
},
{
"code": null,
"e": 10970,
"s": 10935,
"text": "Backup DB (default \"main\") to FILE"
},
{
"code": null,
"e": 10983,
"s": 10970,
"text": ".bail ON|OFF"
},
{
"code": null,
"e": 11024,
"s": 10983,
"text": "Stop after hitting an error. Default OFF"
},
{
"code": null,
"e": 11035,
"s": 11024,
"text": ".databases"
},
{
"code": null,
"e": 11078,
"s": 11035,
"text": "List names and files of attached databases"
},
{
"code": null,
"e": 11092,
"s": 11078,
"text": ".dump ?TABLE?"
},
{
"code": null,
"e": 11198,
"s": 11092,
"text": "Dump the database in an SQL text format. If TABLE specified, only dump tables matching LIKE pattern TABLE"
},
{
"code": null,
"e": 11211,
"s": 11198,
"text": ".echo ON|OFF"
},
{
"code": null,
"e": 11239,
"s": 11211,
"text": "Turn command echo on or off"
},
{
"code": null,
"e": 11245,
"s": 11239,
"text": ".exit"
},
{
"code": null,
"e": 11264,
"s": 11245,
"text": "Exit SQLite prompt"
},
{
"code": null,
"e": 11280,
"s": 11264,
"text": ".explain ON|OFF"
},
{
"code": null,
"e": 11363,
"s": 11280,
"text": "Turn output mode suitable for EXPLAIN on or off. With no args, it turns EXPLAIN on"
},
{
"code": null,
"e": 11381,
"s": 11363,
"text": ".header(s) ON|OFF"
},
{
"code": null,
"e": 11415,
"s": 11381,
"text": "Turn display of headers on or off"
},
{
"code": null,
"e": 11421,
"s": 11415,
"text": ".help"
},
{
"code": null,
"e": 11439,
"s": 11421,
"text": "Show this message"
},
{
"code": null,
"e": 11458,
"s": 11439,
"text": ".import FILE TABLE"
},
{
"code": null,
"e": 11491,
"s": 11458,
"text": "Import data from FILE into TABLE"
},
{
"code": null,
"e": 11508,
"s": 11491,
"text": ".indices ?TABLE?"
},
{
"code": null,
"e": 11612,
"s": 11508,
"text": "Show names of all indices. If TABLE specified, only show indices for tables matching LIKE pattern TABLE"
},
{
"code": null,
"e": 11631,
"s": 11612,
"text": ".load FILE ?ENTRY?"
},
{
"code": null,
"e": 11657,
"s": 11631,
"text": "Load an extension library"
},
{
"code": null,
"e": 11671,
"s": 11657,
"text": ".log FILE|off"
},
{
"code": null,
"e": 11721,
"s": 11671,
"text": "Turn logging on or off. FILE can be stderr/stdout"
},
{
"code": null,
"e": 11732,
"s": 11721,
"text": ".mode MODE"
},
{
"code": null,
"e": 11771,
"s": 11732,
"text": "Set output mode where MODE is one of −"
},
{
"code": null,
"e": 11800,
"s": 11771,
"text": "csv − Comma-separated values"
},
{
"code": null,
"e": 11829,
"s": 11800,
"text": "csv − Comma-separated values"
},
{
"code": null,
"e": 11860,
"s": 11829,
"text": "column − Left-aligned columns."
},
{
"code": null,
"e": 11891,
"s": 11860,
"text": "column − Left-aligned columns."
},
{
"code": null,
"e": 11916,
"s": 11891,
"text": "html − HTML <table> code"
},
{
"code": null,
"e": 11941,
"s": 11916,
"text": "html − HTML <table> code"
},
{
"code": null,
"e": 11982,
"s": 11941,
"text": "insert − SQL insert statements for TABLE"
},
{
"code": null,
"e": 12023,
"s": 11982,
"text": "insert − SQL insert statements for TABLE"
},
{
"code": null,
"e": 12049,
"s": 12023,
"text": "line − One value per line"
},
{
"code": null,
"e": 12075,
"s": 12049,
"text": "line − One value per line"
},
{
"code": null,
"e": 12120,
"s": 12075,
"text": "list − Values delimited by .separator string"
},
{
"code": null,
"e": 12165,
"s": 12120,
"text": "list − Values delimited by .separator string"
},
{
"code": null,
"e": 12193,
"s": 12165,
"text": "tabs − Tab-separated values"
},
{
"code": null,
"e": 12221,
"s": 12193,
"text": "tabs − Tab-separated values"
},
{
"code": null,
"e": 12245,
"s": 12221,
"text": "tcl − TCL list elements"
},
{
"code": null,
"e": 12269,
"s": 12245,
"text": "tcl − TCL list elements"
},
{
"code": null,
"e": 12287,
"s": 12269,
"text": ".nullvalue STRING"
},
{
"code": null,
"e": 12324,
"s": 12287,
"text": "Print STRING in place of NULL values"
},
{
"code": null,
"e": 12341,
"s": 12324,
"text": ".output FILENAME"
},
{
"code": null,
"e": 12365,
"s": 12341,
"text": "Send output to FILENAME"
},
{
"code": null,
"e": 12380,
"s": 12365,
"text": ".output stdout"
},
{
"code": null,
"e": 12407,
"s": 12380,
"text": " Send output to the screen"
},
{
"code": null,
"e": 12424,
"s": 12407,
"text": ".print STRING..."
},
{
"code": null,
"e": 12445,
"s": 12424,
"text": "Print literal STRING"
},
{
"code": null,
"e": 12467,
"s": 12445,
"text": ".prompt MAIN CONTINUE"
},
{
"code": null,
"e": 12496,
"s": 12467,
"text": "Replace the standard prompts"
},
{
"code": null,
"e": 12502,
"s": 12496,
"text": ".quit"
},
{
"code": null,
"e": 12521,
"s": 12502,
"text": "Exit SQLite prompt"
},
{
"code": null,
"e": 12536,
"s": 12521,
"text": ".read FILENAME"
},
{
"code": null,
"e": 12560,
"s": 12536,
"text": "Execute SQL in FILENAME"
},
{
"code": null,
"e": 12576,
"s": 12560,
"text": ".schema ?TABLE?"
},
{
"code": null,
"e": 12669,
"s": 12576,
"text": "Show the CREATE statements. If TABLE specified, only show tables matching LIKE pattern TABLE"
},
{
"code": null,
"e": 12687,
"s": 12669,
"text": ".separator STRING"
},
{
"code": null,
"e": 12736,
"s": 12687,
"text": "Change separator used by output mode and .import"
},
{
"code": null,
"e": 12742,
"s": 12736,
"text": ".show"
},
{
"code": null,
"e": 12787,
"s": 12742,
"text": "Show the current values for various settings"
},
{
"code": null,
"e": 12801,
"s": 12787,
"text": ".stats ON|OFF"
},
{
"code": null,
"e": 12822,
"s": 12801,
"text": "Turn stats on or off"
},
{
"code": null,
"e": 12840,
"s": 12822,
"text": ".tables ?PATTERN?"
},
{
"code": null,
"e": 12885,
"s": 12840,
"text": "List names of tables matching a LIKE pattern"
},
{
"code": null,
"e": 12897,
"s": 12885,
"text": ".timeout MS"
},
{
"code": null,
"e": 12943,
"s": 12897,
"text": "Try opening locked tables for MS milliseconds"
},
{
"code": null,
"e": 12958,
"s": 12943,
"text": ".width NUM NUM"
},
{
"code": null,
"e": 12994,
"s": 12958,
"text": "Set column widths for \"column\" mode"
},
{
"code": null,
"e": 13009,
"s": 12994,
"text": ".timer ON|OFF "
},
{
"code": null,
"e": 13050,
"s": 13009,
"text": "Turn the CPU timer measurement on or off"
},
{
"code": null,
"e": 13129,
"s": 13050,
"text": "Let's try .show command to see default setting for your SQLite command prompt."
},
{
"code": null,
"e": 13271,
"s": 13129,
"text": "sqlite>.show\n echo: off\n explain: off\n headers: off\n mode: column\nnullvalue: \"\"\n output: stdout\nseparator: \"|\"\n width:\nsqlite>"
},
{
"code": null,
"e": 13370,
"s": 13271,
"text": "Make sure there is no space in between sqlite> prompt and dot command, otherwise it will not work."
},
{
"code": null,
"e": 13444,
"s": 13370,
"text": "You can use the following sequence of dot commands to format your output."
},
{
"code": null,
"e": 13507,
"s": 13444,
"text": "sqlite>.header on\nsqlite>.mode column\nsqlite>.timer on\nsqlite>"
},
{
"code": null,
"e": 13574,
"s": 13507,
"text": "The above setting will produce the output in the following format."
},
{
"code": null,
"e": 14118,
"s": 13574,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\nCPU Time: user 0.000000 sys 0.000000\n"
},
{
"code": null,
"e": 14256,
"s": 14118,
"text": "The master table holds the key information about your database tables and it is called sqlite_master. You can see its schema as follows −"
},
{
"code": null,
"e": 14285,
"s": 14256,
"text": "sqlite>.schema sqlite_master"
},
{
"code": null,
"e": 14325,
"s": 14285,
"text": "This will produce the following result."
},
{
"code": null,
"e": 14437,
"s": 14325,
"text": "CREATE TABLE sqlite_master (\n type text,\n name text,\n tbl_name text,\n rootpage integer,\n sql text\n);\n"
},
{
"code": null,
"e": 14557,
"s": 14437,
"text": "SQLite is followed by unique set of rules and guidelines called Syntax. This chapter lists all the basic SQLite Syntax."
},
{
"code": null,
"e": 14739,
"s": 14557,
"text": "Important point to be noted is that SQLite is case insensitive, but there are some commands, which are case sensitive like GLOB and glob have different meaning in SQLite statements."
},
{
"code": null,
"e": 14988,
"s": 14739,
"text": "SQLite comments are extra notes, which you can add in your SQLite code to increase its readability and they can appear anywhere; whitespace can occur, including inside expressions and in the middle of other SQL statements but they cannot be nested."
},
{
"code": null,
"e": 15177,
"s": 14988,
"text": "SQL comments begin with two consecutive \"-\" characters (ASCII 0x2d) and extend up to and including the next newline character (ASCII 0x0a) or until the end of input, whichever comes first."
},
{
"code": null,
"e": 15386,
"s": 15177,
"text": "You can also use C-style comments, which begin with \"/*\" and extend up to and including the next \"*/\" character pair or until the end of input, whichever comes first. C-style comments can span multiple lines."
},
{
"code": null,
"e": 15433,
"s": 15386,
"text": "sqlite> .help -- This is a single line comment"
},
{
"code": null,
"e": 15595,
"s": 15433,
"text": "All the SQLite statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, etc., and all the statements end with a semicolon (;)."
},
{
"code": null,
"e": 15667,
"s": 15595,
"text": "ANALYZE;\nor\nANALYZE database_name;\nor\nANALYZE database_name.table_name;"
},
{
"code": null,
"e": 15758,
"s": 15667,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE CONDITION-1 {AND|OR} CONDITION-2;"
},
{
"code": null,
"e": 15807,
"s": 15758,
"text": "ALTER TABLE table_name ADD COLUMN column_def...;"
},
{
"code": null,
"e": 15856,
"s": 15807,
"text": "ALTER TABLE table_name RENAME TO new_table_name;"
},
{
"code": null,
"e": 15904,
"s": 15856,
"text": "ATTACH DATABASE 'DatabaseName' As 'Alias-Name';"
},
{
"code": null,
"e": 15943,
"s": 15904,
"text": "BEGIN;\nor\nBEGIN EXCLUSIVE TRANSACTION;"
},
{
"code": null,
"e": 16037,
"s": 15943,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name BETWEEN val-1 AND val-2;"
},
{
"code": null,
"e": 16045,
"s": 16037,
"text": "COMMIT;"
},
{
"code": null,
"e": 16115,
"s": 16045,
"text": "CREATE INDEX index_name\nON table_name ( column_name COLLATE NOCASE );"
},
{
"code": null,
"e": 16192,
"s": 16115,
"text": "CREATE UNIQUE INDEX index_name\nON table_name ( column1, column2,...columnN);"
},
{
"code": null,
"e": 16351,
"s": 16192,
"text": "CREATE TABLE table_name(\n column1 datatype,\n column2 datatype,\n column3 datatype,\n .....\n columnN datatype,\n PRIMARY KEY( one or more columns )\n);"
},
{
"code": null,
"e": 16476,
"s": 16351,
"text": "CREATE TRIGGER database_name.trigger_name \nBEFORE INSERT ON table_name FOR EACH ROW\nBEGIN \n stmt1; \n stmt2;\n ....\nEND;"
},
{
"code": null,
"e": 16537,
"s": 16476,
"text": "CREATE VIEW database_name.view_name AS\nSELECT statement....;"
},
{
"code": null,
"e": 16675,
"s": 16537,
"text": "CREATE VIRTUAL TABLE database_name.table_name USING weblog( access.log );\nor\nCREATE VIRTUAL TABLE database_name.table_name USING fts3( );"
},
{
"code": null,
"e": 16683,
"s": 16675,
"text": "COMMIT;"
},
{
"code": null,
"e": 16742,
"s": 16683,
"text": "SELECT COUNT(column_name)\nFROM table_name\nWHERE CONDITION;"
},
{
"code": null,
"e": 16784,
"s": 16742,
"text": "DELETE FROM table_name\nWHERE {CONDITION};"
},
{
"code": null,
"e": 16814,
"s": 16784,
"text": "DETACH DATABASE 'Alias-Name';"
},
{
"code": null,
"e": 16875,
"s": 16814,
"text": "SELECT DISTINCT column1, column2....columnN\nFROM table_name;"
},
{
"code": null,
"e": 16912,
"s": 16875,
"text": "DROP INDEX database_name.index_name;"
},
{
"code": null,
"e": 16949,
"s": 16912,
"text": "DROP TABLE database_name.table_name;"
},
{
"code": null,
"e": 16985,
"s": 16949,
"text": "DROP INDEX database_name.view_name;"
},
{
"code": null,
"e": 17024,
"s": 16985,
"text": "DROP INDEX database_name.trigger_name;"
},
{
"code": null,
"e": 17131,
"s": 17024,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name EXISTS (SELECT * FROM table_name );"
},
{
"code": null,
"e": 17204,
"s": 17131,
"text": "EXPLAIN INSERT statement...;\nor \nEXPLAIN QUERY PLAN SELECT statement...;"
},
{
"code": null,
"e": 17291,
"s": 17204,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name GLOB { PATTERN };"
},
{
"code": null,
"e": 17369,
"s": 17291,
"text": "SELECT SUM(column_name)\nFROM table_name\nWHERE CONDITION\nGROUP BY column_name;"
},
{
"code": null,
"e": 17487,
"s": 17369,
"text": "SELECT SUM(column_name)\nFROM table_name\nWHERE CONDITION\nGROUP BY column_name\nHAVING (arithematic function condition);"
},
{
"code": null,
"e": 17576,
"s": 17487,
"text": "INSERT INTO table_name( column1, column2....columnN)\nVALUES ( value1, value2....valueN);"
},
{
"code": null,
"e": 17673,
"s": 17576,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name IN (val-1, val-2,...val-N);"
},
{
"code": null,
"e": 17760,
"s": 17673,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name LIKE { PATTERN };"
},
{
"code": null,
"e": 17861,
"s": 17760,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name NOT IN (val-1, val-2,...val-N);"
},
{
"code": null,
"e": 17961,
"s": 17861,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE CONDITION\nORDER BY column_name {ASC|DESC};"
},
{
"code": null,
"e": 18071,
"s": 17961,
"text": "PRAGMA pragma_name;\n\nFor example:\n\nPRAGMA page_size;\nPRAGMA cache_size = 1024;\nPRAGMA table_info(table_name);"
},
{
"code": null,
"e": 18095,
"s": 18071,
"text": "RELEASE savepoint_name;"
},
{
"code": null,
"e": 18187,
"s": 18095,
"text": "REINDEX collation_name;\nREINDEX database_name.index_name;\nREINDEX database_name.table_name;"
},
{
"code": null,
"e": 18238,
"s": 18187,
"text": "ROLLBACK;\nor\nROLLBACK TO SAVEPOINT savepoint_name;"
},
{
"code": null,
"e": 18264,
"s": 18238,
"text": "SAVEPOINT savepoint_name;"
},
{
"code": null,
"e": 18316,
"s": 18264,
"text": "SELECT column1, column2....columnN\nFROM table_name;"
},
{
"code": null,
"e": 18413,
"s": 18316,
"text": "UPDATE table_name\nSET column1 = value1, column2 = value2....columnN=valueN\n[ WHERE CONDITION ];"
},
{
"code": null,
"e": 18421,
"s": 18413,
"text": "VACUUM;"
},
{
"code": null,
"e": 18489,
"s": 18421,
"text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE CONDITION;"
},
{
"code": null,
"e": 18639,
"s": 18489,
"text": "SQLite data type is an attribute that specifies the type of data of any object. Each column, variable and expression has related data type in SQLite."
},
{
"code": null,
"e": 18842,
"s": 18639,
"text": "You would use these data types while creating your tables. SQLite uses a more general dynamic type system. In SQLite, the datatype of a value is associated with the value itself, not with its container."
},
{
"code": null,
"e": 18925,
"s": 18842,
"text": "Each value stored in an SQLite database has one of the following storage classes −"
},
{
"code": null,
"e": 18930,
"s": 18925,
"text": "NULL"
},
{
"code": null,
"e": 18957,
"s": 18930,
"text": "The value is a NULL value."
},
{
"code": null,
"e": 18965,
"s": 18957,
"text": "INTEGER"
},
{
"code": null,
"e": 19073,
"s": 18965,
"text": "The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value."
},
{
"code": null,
"e": 19078,
"s": 19073,
"text": "REAL"
},
{
"code": null,
"e": 19163,
"s": 19078,
"text": "The value is a floating point value, stored as an 8-byte IEEE floating point number."
},
{
"code": null,
"e": 19168,
"s": 19163,
"text": "TEXT"
},
{
"code": null,
"e": 19261,
"s": 19168,
"text": "The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE)"
},
{
"code": null,
"e": 19266,
"s": 19261,
"text": "BLOB"
},
{
"code": null,
"e": 19327,
"s": 19266,
"text": "The value is a blob of data, stored exactly as it was input."
},
{
"code": null,
"e": 19491,
"s": 19327,
"text": "SQLite storage class is slightly more general than a datatype. The INTEGER storage class, for example, includes 6 different integer datatypes of different lengths."
},
{
"code": null,
"e": 19753,
"s": 19491,
"text": "SQLite supports the concept of type affinity on columns. Any column can still store any type of data but the preferred storage class for a column is called its affinity. Each table column in an SQLite3 database is assigned one of the following type affinities −"
},
{
"code": null,
"e": 19758,
"s": 19753,
"text": "TEXT"
},
{
"code": null,
"e": 19828,
"s": 19758,
"text": "This column stores all data using storage classes NULL, TEXT or BLOB."
},
{
"code": null,
"e": 19836,
"s": 19828,
"text": "NUMERIC"
},
{
"code": null,
"e": 19899,
"s": 19836,
"text": "This column may contain values using all five storage classes."
},
{
"code": null,
"e": 19907,
"s": 19899,
"text": "INTEGER"
},
{
"code": null,
"e": 19999,
"s": 19907,
"text": "Behaves the same as a column with NUMERIC affinity, with an exception in a CAST expression."
},
{
"code": null,
"e": 20004,
"s": 19999,
"text": "REAL"
},
{
"code": null,
"e": 20121,
"s": 20004,
"text": "Behaves like a column with NUMERIC affinity except that it forces integer values into floating point representation."
},
{
"code": null,
"e": 20126,
"s": 20121,
"text": "NONE"
},
{
"code": null,
"e": 20276,
"s": 20126,
"text": "A column with affinity NONE does not prefer one storage class over another and no attempt is made to coerce data from one storage class into another."
},
{
"code": null,
"e": 20416,
"s": 20276,
"text": "Following table lists down various data type names which can be used while creating SQLite3 tables with the corresponding applied affinity."
},
{
"code": null,
"e": 20420,
"s": 20416,
"text": "INT"
},
{
"code": null,
"e": 20428,
"s": 20420,
"text": "INTEGER"
},
{
"code": null,
"e": 20436,
"s": 20428,
"text": "TINYINT"
},
{
"code": null,
"e": 20445,
"s": 20436,
"text": "SMALLINT"
},
{
"code": null,
"e": 20455,
"s": 20445,
"text": "MEDIUMINT"
},
{
"code": null,
"e": 20462,
"s": 20455,
"text": "BIGINT"
},
{
"code": null,
"e": 20479,
"s": 20462,
"text": "UNSIGNED BIG INT"
},
{
"code": null,
"e": 20484,
"s": 20479,
"text": "INT2"
},
{
"code": null,
"e": 20489,
"s": 20484,
"text": "INT8"
},
{
"code": null,
"e": 20503,
"s": 20489,
"text": "CHARACTER(20)"
},
{
"code": null,
"e": 20516,
"s": 20503,
"text": "VARCHAR(255)"
},
{
"code": null,
"e": 20539,
"s": 20516,
"text": "VARYING CHARACTER(255)"
},
{
"code": null,
"e": 20549,
"s": 20539,
"text": "NCHAR(55)"
},
{
"code": null,
"e": 20570,
"s": 20549,
"text": "NATIVE CHARACTER(70)"
},
{
"code": null,
"e": 20584,
"s": 20570,
"text": "NVARCHAR(100)"
},
{
"code": null,
"e": 20589,
"s": 20584,
"text": "TEXT"
},
{
"code": null,
"e": 20594,
"s": 20589,
"text": "CLOB"
},
{
"code": null,
"e": 20599,
"s": 20594,
"text": "BLOB"
},
{
"code": null,
"e": 20621,
"s": 20599,
"text": "no datatype specified"
},
{
"code": null,
"e": 20626,
"s": 20621,
"text": "REAL"
},
{
"code": null,
"e": 20633,
"s": 20626,
"text": "DOUBLE"
},
{
"code": null,
"e": 20650,
"s": 20633,
"text": "DOUBLE PRECISION"
},
{
"code": null,
"e": 20656,
"s": 20650,
"text": "FLOAT"
},
{
"code": null,
"e": 20664,
"s": 20656,
"text": "NUMERIC"
},
{
"code": null,
"e": 20678,
"s": 20664,
"text": "DECIMAL(10,5)"
},
{
"code": null,
"e": 20686,
"s": 20678,
"text": "BOOLEAN"
},
{
"code": null,
"e": 20691,
"s": 20686,
"text": "DATE"
},
{
"code": null,
"e": 20700,
"s": 20691,
"text": "DATETIME"
},
{
"code": null,
"e": 20826,
"s": 20700,
"text": "SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true)."
},
{
"code": null,
"e": 20986,
"s": 20826,
"text": "SQLite does not have a separate storage class for storing dates and/or times, but SQLite is capable of storing dates and times as TEXT, REAL or INTEGER values."
},
{
"code": null,
"e": 20991,
"s": 20986,
"text": "TEXT"
},
{
"code": null,
"e": 21041,
"s": 20991,
"text": "A date in a format like \"YYYY-MM-DD HH:MM:SS.SSS\""
},
{
"code": null,
"e": 21046,
"s": 21041,
"text": "REAL"
},
{
"code": null,
"e": 21115,
"s": 21046,
"text": "The number of days since noon in Greenwich on November 24, 4714 B.C."
},
{
"code": null,
"e": 21123,
"s": 21115,
"text": "INTEGER"
},
{
"code": null,
"e": 21175,
"s": 21123,
"text": "The number of seconds since 1970-01-01 00:00:00 UTC"
},
{
"code": null,
"e": 21318,
"s": 21175,
"text": "You can choose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions."
},
{
"code": null,
"e": 21454,
"s": 21318,
"text": "In SQLite, sqlite3 command is used to create a new SQLite database. You do not need to have any special privilege to create a database."
},
{
"code": null,
"e": 21527,
"s": 21454,
"text": "Following is the basic syntax of sqlite3 command to create a database: −"
},
{
"code": null,
"e": 21553,
"s": 21527,
"text": "$sqlite3 DatabaseName.db\n"
},
{
"code": null,
"e": 21610,
"s": 21553,
"text": "Always, database name should be unique within the RDBMS."
},
{
"code": null,
"e": 21705,
"s": 21610,
"text": "If you want to create a new database <testDB.db>, then SQLITE3 statement would be as follows −"
},
{
"code": null,
"e": 21850,
"s": 21705,
"text": "$sqlite3 testDB.db\nSQLite version 3.7.15.2 2013-01-09 11:53:05\nEnter \".help\" for instructions\nEnter SQL statements terminated with a \";\"\nsqlite>"
},
{
"code": null,
"e": 22112,
"s": 21850,
"text": "The above command will create a file testDB.db in the current directory. This file will be used as database by SQLite engine. If you have noticed while creating database, sqlite3 command will provide a sqlite> prompt after creating a database file successfully."
},
{
"code": null,
"e": 22231,
"s": 22112,
"text": "Once a database is created, you can verify it in the list of databases using the following SQLite .databases command."
},
{
"code": null,
"e": 22367,
"s": 22231,
"text": "sqlite>.databases\nseq name file\n--- --------------- ----------------------\n0 main /home/sqlite/testDB.db\n"
},
{
"code": null,
"e": 22447,
"s": 22367,
"text": "You will use SQLite .quit command to come out of the sqlite prompt as follows −"
},
{
"code": null,
"e": 22463,
"s": 22447,
"text": "sqlite>.quit\n$\n"
},
{
"code": null,
"e": 22594,
"s": 22463,
"text": "You can use .dump dot command to export complete database in a text file using the following SQLite command at the command prompt."
},
{
"code": null,
"e": 22632,
"s": 22594,
"text": "$sqlite3 testDB.db .dump > testDB.sql"
},
{
"code": null,
"e": 22860,
"s": 22632,
"text": "The above command will convert the entire contents of testDB.db database into SQLite statements and dump it into ASCII text file testDB.sql. You can perform restoration from the generated testDB.sql in a simple way as follows −"
},
{
"code": null,
"e": 22892,
"s": 22860,
"text": "$sqlite3 testDB.db < testDB.sql"
},
{
"code": null,
"e": 23063,
"s": 22892,
"text": "At this moment your database is empty, so you can try above two procedures once you have few tables and data in your database. For now, let's proceed to the next chapter."
},
{
"code": null,
"e": 23335,
"s": 23063,
"text": "Consider a case when you have multiple databases available and you want to use any one of them at a time. SQLite ATTACH DATABASE statement is used to select a particular database, and after this command, all SQLite statements will be executed under the attached database."
},
{
"code": null,
"e": 23402,
"s": 23335,
"text": "Following is the basic syntax of SQLite ATTACH DATABASE statement."
},
{
"code": null,
"e": 23451,
"s": 23402,
"text": "ATTACH DATABASE 'DatabaseName' As 'Alias-Name';\n"
},
{
"code": null,
"e": 23627,
"s": 23451,
"text": "The above command will also create a database in case the database is already not created, otherwise it will just attach database file name with logical database 'Alias-Name'."
},
{
"code": null,
"e": 23734,
"s": 23627,
"text": "If you want to attach an existing database testDB.db, then ATTACH DATABASE statement would be as follows −"
},
{
"code": null,
"e": 23781,
"s": 23734,
"text": "sqlite> ATTACH DATABASE 'testDB.db' as 'TEST';"
},
{
"code": null,
"e": 23840,
"s": 23781,
"text": "Use SQLite .database command to display attached database."
},
{
"code": null,
"e": 24020,
"s": 23840,
"text": "sqlite> .database\nseq name file\n--- --------------- ----------------------\n0 main /home/sqlite/testDB.db\n2 test /home/sqlite/testDB.db"
},
{
"code": null,
"e": 24321,
"s": 24020,
"text": "The database names main and temp are reserved for the primary database and database to hold temporary tables and other temporary data objects. Both of these database names exist for every database connection and should not be used for attachment, otherwise you will get the following warning message."
},
{
"code": null,
"e": 24493,
"s": 24321,
"text": "sqlite> ATTACH DATABASE 'testDB.db' as 'TEMP';\nError: database TEMP is already in use\nsqlite> ATTACH DATABASE 'testDB.db' as 'main';\nError: database TEMP is already in use"
},
{
"code": null,
"e": 24874,
"s": 24493,
"text": "SQLite DETACH DATABASE statement is used to detach and dissociate a named database from a database connection which was previously attached using ATTACH statement. If the same database file has been attached with multiple aliases, then DETACH command will disconnect only the given name and rest of the attachment will still continue. You cannot detach the main or temp databases."
},
{
"code": null,
"e": 24991,
"s": 24874,
"text": "If the database is an in-memory or temporary database, the database will be destroyed and the contents will be lost."
},
{
"code": null,
"e": 25071,
"s": 24991,
"text": "Following is the basic syntax of SQLite DETACH DATABASE 'Alias-Name' statement."
},
{
"code": null,
"e": 25102,
"s": 25071,
"text": "DETACH DATABASE 'Alias-Name';\n"
},
{
"code": null,
"e": 25212,
"s": 25102,
"text": "Here, 'Alias-Name' is the same alias, which you had used while attaching the database using ATTACH statement."
},
{
"code": null,
"e": 25367,
"s": 25212,
"text": "Consider you have a database, which you created in the previous chapter and attached it with 'test' and 'currentDB' as we can see using .database command."
},
{
"code": null,
"e": 25592,
"s": 25367,
"text": "sqlite>.databases\nseq name file\n--- --------------- ----------------------\n0 main /home/sqlite/testDB.db\n2 test /home/sqlite/testDB.db\n3 currentDB /home/sqlite/testDB.db"
},
{
"code": null,
"e": 25669,
"s": 25592,
"text": "Let's try to detach 'currentDB' from testDB.db using the following command."
},
{
"code": null,
"e": 25706,
"s": 25669,
"text": "sqlite> DETACH DATABASE 'currentDB';"
},
{
"code": null,
"e": 25825,
"s": 25706,
"text": "Now, if you will check the current attachment, you will find that testDB.db is still connected with 'test' and 'main'."
},
{
"code": null,
"e": 26005,
"s": 25825,
"text": "sqlite>.databases\nseq name file\n--- --------------- ----------------------\n0 main /home/sqlite/testDB.db\n2 test /home/sqlite/testDB.db"
},
{
"code": null,
"e": 26198,
"s": 26005,
"text": "SQLite CREATE TABLE statement is used to create a new table in any of the given database. Creating a basic table involves naming the table and defining its columns and each column's data type."
},
{
"code": null,
"e": 26255,
"s": 26198,
"text": "Following is the basic syntax of CREATE TABLE statement."
},
{
"code": null,
"e": 26423,
"s": 26255,
"text": "CREATE TABLE database_name.table_name(\n column1 datatype PRIMARY KEY(one or more columns),\n column2 datatype,\n column3 datatype,\n .....\n columnN datatype\n);\n"
},
{
"code": null,
"e": 26648,
"s": 26423,
"text": "CREATE TABLE is the keyword telling the database system to create a new table. The unique name or identifier for the table follows the CREATE TABLE statement. Optionally, you can specify database_name along with table_name."
},
{
"code": null,
"e": 26841,
"s": 26648,
"text": "Following is an example which creates a COMPANY table with ID as the primary key and NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this table."
},
{
"code": null,
"e": 27033,
"s": 26841,
"text": "sqlite> CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);"
},
{
"code": null,
"e": 27122,
"s": 27033,
"text": "Let us create one more table, which we will use in our exercises in subsequent chapters."
},
{
"code": null,
"e": 27268,
"s": 27122,
"text": "sqlite> CREATE TABLE DEPARTMENT(\n ID INT PRIMARY KEY NOT NULL,\n DEPT CHAR(50) NOT NULL,\n EMP_ID INT NOT NULL\n);"
},
{
"code": null,
"e": 27437,
"s": 27268,
"text": "You can verify if your table has been created successfully using SQLite command .tables command, which will be used to list down all the tables in an attached database."
},
{
"code": null,
"e": 27475,
"s": 27437,
"text": "sqlite>.tables\nCOMPANY DEPARTMENT"
},
{
"code": null,
"e": 27728,
"s": 27475,
"text": "Here, you can see the COMPANY table twice because its showing COMPANY table for main database and test.COMPANY table for 'test' alias created for your testDB.db. You can get complete information about a table using the following SQLite .schema command."
},
{
"code": null,
"e": 27935,
"s": 27728,
"text": "sqlite>.schema COMPANY\nCREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);"
},
{
"code": null,
"e": 28103,
"s": 27935,
"text": "SQLite DROP TABLE statement is used to remove a table definition and all associated data, indexes, triggers, constraints, and permission specifications for that table."
},
{
"code": null,
"e": 28259,
"s": 28103,
"text": "You have to be careful while using this command because once a table is deleted then all the information available in the table would also be lost forever."
},
{
"code": null,
"e": 28394,
"s": 28259,
"text": "Following is the basic syntax of DROP TABLE statement. You can optionally specify the database name along with table name as follows −"
},
{
"code": null,
"e": 28432,
"s": 28394,
"text": "DROP TABLE database_name.table_name;\n"
},
{
"code": null,
"e": 28512,
"s": 28432,
"text": "Let us first verify COMPANY table and then we will delete it from the database."
},
{
"code": null,
"e": 28554,
"s": 28512,
"text": "sqlite>.tables\nCOMPANY test.COMPANY"
},
{
"code": null,
"e": 28640,
"s": 28554,
"text": "This means COMPANY table is available in the database, so let us drop it as follows −"
},
{
"code": null,
"e": 28675,
"s": 28640,
"text": "sqlite>DROP TABLE COMPANY;\nsqlite>"
},
{
"code": null,
"e": 28754,
"s": 28675,
"text": "Now, if you try .TABLES command, then you will not find COMPANY table anymore."
},
{
"code": null,
"e": 28777,
"s": 28754,
"text": "sqlite>.tables\nsqlite>"
},
{
"code": null,
"e": 28866,
"s": 28777,
"text": "It shows nothing which means the table from your database has been dropped successfully."
},
{
"code": null,
"e": 28957,
"s": 28866,
"text": "SQLite INSERT INTO Statement is used to add new rows of data into a table in the database."
},
{
"code": null,
"e": 29020,
"s": 28957,
"text": "Following are the two basic syntaxes of INSERT INTO statement."
},
{
"code": null,
"e": 29130,
"s": 29020,
"text": "INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)] \nVALUES (value1, value2, value3,...valueN);\n"
},
{
"code": null,
"e": 29242,
"s": 29130,
"text": "Here, column1, column2,...columnN are the names of the columns in the table into which you want to insert data."
},
{
"code": null,
"e": 29513,
"s": 29242,
"text": "You may not need to specify the column(s) name in the SQLite query if you are adding values for all the columns of the table. However, make sure the order of the values is in the same order as the columns in the table. The SQLite INSERT INTO syntax would be as follows −"
},
{
"code": null,
"e": 29578,
"s": 29513,
"text": "INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);\n"
},
{
"code": null,
"e": 29657,
"s": 29578,
"text": "Consider you already have created COMPANY table in your testDB.db as follows −"
},
{
"code": null,
"e": 29849,
"s": 29657,
"text": "sqlite> CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);"
},
{
"code": null,
"e": 29922,
"s": 29849,
"text": "Now, the following statements would create six records in COMPANY table."
},
{
"code": null,
"e": 30503,
"s": 29922,
"text": "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (1, 'Paul', 32, 'California', 20000.00 );\n\nINSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (2, 'Allen', 25, 'Texas', 15000.00 );\n\nINSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (3, 'Teddy', 23, 'Norway', 20000.00 );\n\nINSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );\n\nINSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (5, 'David', 27, 'Texas', 85000.00 );\n\nINSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (6, 'Kim', 22, 'South-Hall', 45000.00 );"
},
{
"code": null,
"e": 30581,
"s": 30503,
"text": "You can create a record in COMPANY table using the second syntax as follows −"
},
{
"code": null,
"e": 30649,
"s": 30581,
"text": "INSERT INTO COMPANY VALUES (7, 'James', 24, 'Houston', 10000.00 );\n"
},
{
"code": null,
"e": 30810,
"s": 30649,
"text": "All the above statements would create the following records in COMPANY table. In the next chapter, you will learn how to display all these records from a table."
},
{
"code": null,
"e": 31316,
"s": 30810,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 31508,
"s": 31316,
"text": "You can populate data into a table through select statement over another table provided another table has a set of fields, which are required to populate the first table. Here is the syntax −"
},
{
"code": null,
"e": 31661,
"s": 31508,
"text": "INSERT INTO first_table_name [(column1, column2, ... columnN)] \n SELECT column1, column2, ...columnN \n FROM second_table_name\n [WHERE condition];\n"
},
{
"code": null,
"e": 31794,
"s": 31661,
"text": "For now, you can skip the above statement. First, let's learn SELECT and WHERE clauses which will be covered in subsequent chapters."
},
{
"code": null,
"e": 31972,
"s": 31794,
"text": "SQLite SELECT statement is used to fetch the data from a SQLite database table which returns data in the form of a result table. These result tables are also called result sets."
},
{
"code": null,
"e": 32030,
"s": 31972,
"text": "Following is the basic syntax of SQLite SELECT statement."
},
{
"code": null,
"e": 32081,
"s": 32030,
"text": "SELECT column1, column2, columnN FROM table_name;\n"
},
{
"code": null,
"e": 32267,
"s": 32081,
"text": "Here, column1, column2 ... are the fields of a table, whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax −"
},
{
"code": null,
"e": 32294,
"s": 32267,
"text": "SELECT * FROM table_name;\n"
},
{
"code": null,
"e": 32346,
"s": 32294,
"text": "Consider COMPANY table with the following records −"
},
{
"code": null,
"e": 32852,
"s": 32346,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 33021,
"s": 32852,
"text": "Following is an example to fetch and display all these records using SELECT statement. Here, the first three commands have been used to set a properly formatted output."
},
{
"code": null,
"e": 33090,
"s": 33021,
"text": "sqlite>.header on\nsqlite>.mode column\nsqlite> SELECT * FROM COMPANY;"
},
{
"code": null,
"e": 33134,
"s": 33090,
"text": "Finally, you will get the following result."
},
{
"code": null,
"e": 33641,
"s": 33134,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n"
},
{
"code": null,
"e": 33732,
"s": 33641,
"text": "If you want to fetch only selected fields of COMPANY table, then use the following query −"
},
{
"code": null,
"e": 33778,
"s": 33732,
"text": "sqlite> SELECT ID, NAME, SALARY FROM COMPANY;"
},
{
"code": null,
"e": 33829,
"s": 33778,
"text": "The above query will produce the following result."
},
{
"code": null,
"e": 34120,
"s": 33829,
"text": "ID NAME SALARY\n---------- ---------- ----------\n1 Paul 20000.0\n2 Allen 15000.0\n3 Teddy 20000.0\n4 Mark 65000.0\n5 David 85000.0\n6 Kim 45000.0\n7 James 10000.0\n"
},
{
"code": null,
"e": 34392,
"s": 34120,
"text": "Sometimes, you will face a problem related to the truncated output in case of .mode column which happens because of default width of the column to be displayed. What you can do is, you can set column displayable column width using .width num, num.... command as follows −"
},
{
"code": null,
"e": 34447,
"s": 34392,
"text": "sqlite>.width 10, 20, 10\nsqlite>SELECT * FROM COMPANY;"
},
{
"code": null,
"e": 34639,
"s": 34447,
"text": "The above .width command sets the first column width to 10, the second column width to 20 and the third column width to 10. Finally, the above SELECT statement will give the following result."
},
{
"code": null,
"e": 35236,
"s": 34639,
"text": "ID NAME AGE ADDRESS SALARY\n---------- -------------------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n"
},
{
"code": null,
"e": 35452,
"s": 35236,
"text": "As all the dot commands are available at SQLite prompt, hence while programming with SQLite, you will use the following SELECT statement with sqlite_master table to list down all the tables created in your database."
},
{
"code": null,
"e": 35517,
"s": 35452,
"text": "sqlite> SELECT tbl_name FROM sqlite_master WHERE type = 'table';"
},
{
"code": null,
"e": 35613,
"s": 35517,
"text": "Assuming you have only COMPANY table in your testDB.db, this will produce the following result."
},
{
"code": null,
"e": 35642,
"s": 35613,
"text": "tbl_name\n----------\nCOMPANY\n"
},
{
"code": null,
"e": 35714,
"s": 35642,
"text": "You can list down complete information about COMPANY table as follows −"
},
{
"code": null,
"e": 35799,
"s": 35714,
"text": "sqlite> SELECT sql FROM sqlite_master WHERE type = 'table' AND tbl_name = 'COMPANY';"
},
{
"code": null,
"e": 35895,
"s": 35799,
"text": "Assuming you have only COMPANY table in your testDB.db, this will produce the following result."
},
{
"code": null,
"e": 36079,
"s": 35895,
"text": "CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n)\n"
},
{
"code": null,
"e": 36250,
"s": 36079,
"text": "An operator is a reserved word or a character used primarily in an SQLite statement's WHERE clause to perform operation(s), such as comparisons and arithmetic operations."
},
{
"code": null,
"e": 36383,
"s": 36250,
"text": "Operators are used to specify conditions in an SQLite statement and to serve as conjunctions for multiple conditions in a statement."
},
{
"code": null,
"e": 36404,
"s": 36383,
"text": "Arithmetic operators"
},
{
"code": null,
"e": 36425,
"s": 36404,
"text": "Comparison operators"
},
{
"code": null,
"e": 36443,
"s": 36425,
"text": "Logical operators"
},
{
"code": null,
"e": 36461,
"s": 36443,
"text": "Bitwise operators"
},
{
"code": null,
"e": 36572,
"s": 36461,
"text": "Assume variable a holds 10 and variable b holds 20, then SQLite arithmetic operators will be used as follows −"
},
{
"code": null,
"e": 36586,
"s": 36572,
"text": "Show Examples"
},
{
"code": null,
"e": 36695,
"s": 36586,
"text": "Assume variable a holds 10 and variable b holds 20, then SQLite comparison operators will be used as follows"
},
{
"code": null,
"e": 36709,
"s": 36695,
"text": "Show Examples"
},
{
"code": null,
"e": 36774,
"s": 36709,
"text": "Here is a list of all the logical operators available in SQLite."
},
{
"code": null,
"e": 36788,
"s": 36774,
"text": "Show Examples"
},
{
"code": null,
"e": 36792,
"s": 36788,
"text": "AND"
},
{
"code": null,
"e": 36889,
"s": 36792,
"text": "The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause."
},
{
"code": null,
"e": 36897,
"s": 36889,
"text": "BETWEEN"
},
{
"code": null,
"e": 37027,
"s": 36897,
"text": "The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value."
},
{
"code": null,
"e": 37034,
"s": 37027,
"text": "EXISTS"
},
{
"code": null,
"e": 37148,
"s": 37034,
"text": "The EXISTS operator is used to search for the presence of a row in a specified table that meets certain criteria."
},
{
"code": null,
"e": 37151,
"s": 37148,
"text": "IN"
},
{
"code": null,
"e": 37248,
"s": 37151,
"text": "The IN operator is used to compare a value to a list of literal values that have been specified."
},
{
"code": null,
"e": 37255,
"s": 37248,
"text": "NOT IN"
},
{
"code": null,
"e": 37370,
"s": 37255,
"text": "The negation of IN operator which is used to compare a value to a list of literal values that have been specified."
},
{
"code": null,
"e": 37375,
"s": 37370,
"text": "LIKE"
},
{
"code": null,
"e": 37464,
"s": 37375,
"text": "The LIKE operator is used to compare a value to similar values using wildcard operators."
},
{
"code": null,
"e": 37469,
"s": 37464,
"text": "GLOB"
},
{
"code": null,
"e": 37601,
"s": 37469,
"text": "The GLOB operator is used to compare a value to similar values using wildcard operators. Also, GLOB is case sensitive, unlike LIKE."
},
{
"code": null,
"e": 37605,
"s": 37601,
"text": "NOT"
},
{
"code": null,
"e": 37757,
"s": 37605,
"text": "The NOT operator reverses the meaning of the logical operator with which it is used. Eg. NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is negate operator."
},
{
"code": null,
"e": 37760,
"s": 37757,
"text": "OR"
},
{
"code": null,
"e": 37851,
"s": 37760,
"text": "The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause."
},
{
"code": null,
"e": 37859,
"s": 37851,
"text": "IS NULL"
},
{
"code": null,
"e": 37923,
"s": 37859,
"text": "The NULL operator is used to compare a value with a NULL value."
},
{
"code": null,
"e": 37926,
"s": 37923,
"text": "IS"
},
{
"code": null,
"e": 37954,
"s": 37926,
"text": "The IS operator work like ="
},
{
"code": null,
"e": 37961,
"s": 37954,
"text": "IS NOT"
},
{
"code": null,
"e": 37990,
"s": 37961,
"text": "The IS operator work like !="
},
{
"code": null,
"e": 37993,
"s": 37990,
"text": "||"
},
{
"code": null,
"e": 38039,
"s": 37993,
"text": " Adds two different strings and make new one."
},
{
"code": null,
"e": 38046,
"s": 38039,
"text": "UNIQUE"
},
{
"code": null,
"e": 38138,
"s": 38046,
"text": "The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates)."
},
{
"code": null,
"e": 38246,
"s": 38138,
"text": "Bitwise operator works on bits and performs bit-by-bit operation. Following is the truth table for & and |."
},
{
"code": null,
"e": 38325,
"s": 38246,
"text": "Assume if A = 60; and B = 13, then in binary format, they will be as follows −"
},
{
"code": null,
"e": 38339,
"s": 38325,
"text": "A = 0011 1100"
},
{
"code": null,
"e": 38353,
"s": 38339,
"text": "B = 0000 1101"
},
{
"code": null,
"e": 38371,
"s": 38353,
"text": "-----------------"
},
{
"code": null,
"e": 38387,
"s": 38371,
"text": "A&B = 0000 1100"
},
{
"code": null,
"e": 38403,
"s": 38387,
"text": "A|B = 0011 1101"
},
{
"code": null,
"e": 38419,
"s": 38403,
"text": "~A = 1100 0011"
},
{
"code": null,
"e": 38564,
"s": 38419,
"text": "The Bitwise operators supported by SQLite language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −"
},
{
"code": null,
"e": 38578,
"s": 38564,
"text": "Show Examples"
},
{
"code": null,
"e": 38687,
"s": 38578,
"text": "An expression is a combination of one or more values, operators, and SQL functions that evaluate to a value."
},
{
"code": null,
"e": 38828,
"s": 38687,
"text": "SQL expressions are like formulas and they are written in query language. You can also use to query the database for a specific set of data."
},
{
"code": null,
"e": 38891,
"s": 38828,
"text": "Consider the basic syntax of the SELECT statement as follows −"
},
{
"code": null,
"e": 38975,
"s": 38891,
"text": "SELECT column1, column2, columnN \nFROM table_name \nWHERE [CONDITION | EXPRESSION];\n"
},
{
"code": null,
"e": 39032,
"s": 38975,
"text": "Following are the different types of SQLite expressions."
},
{
"code": null,
"e": 39139,
"s": 39032,
"text": "SQLite Boolean Expressions fetch the data on the basis of matching single value. Following is the syntax −"
},
{
"code": null,
"e": 39232,
"s": 39139,
"text": "SELECT column1, column2, columnN \nFROM table_name \nWHERE SINGLE VALUE MATCHTING EXPRESSION;\n"
},
{
"code": null,
"e": 39284,
"s": 39232,
"text": "Consider COMPANY table with the following records −"
},
{
"code": null,
"e": 39790,
"s": 39284,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 39871,
"s": 39790,
"text": "Following is a simple examples showing the usage of SQLite Boolean Expressions −"
},
{
"code": null,
"e": 40093,
"s": 39871,
"text": "sqlite> SELECT * FROM COMPANY WHERE SALARY = 10000;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n4 James 24 Houston 10000.0"
},
{
"code": null,
"e": 40198,
"s": 40093,
"text": "These expressions are used to perform any mathematical operation in any query. Following is the syntax −"
},
{
"code": null,
"e": 40281,
"s": 40198,
"text": "SELECT numerical_expression as OPERATION_NAME\n[FROM table_name WHERE CONDITION] ;\n"
},
{
"code": null,
"e": 40439,
"s": 40281,
"text": "Here, numerical_expression is used for mathematical expression or any formula. Following is a simple example showing the usage of SQLite Numeric Expressions."
},
{
"code": null,
"e": 40489,
"s": 40439,
"text": "sqlite> SELECT (15 + 6) AS ADDITION\nADDITION = 21"
},
{
"code": null,
"e": 40663,
"s": 40489,
"text": "There are several built-in functions such as avg(), sum(), count(), etc., to perform what is known as aggregate data calculations against a table or a specific table column."
},
{
"code": null,
"e": 40727,
"s": 40663,
"text": "sqlite> SELECT COUNT(*) AS \"RECORDS\" FROM COMPANY; \nRECORDS = 7"
},
{
"code": null,
"e": 40851,
"s": 40727,
"text": "Date Expressions returns the current system date and time values. These expressions are used in various data manipulations."
},
{
"code": null,
"e": 40925,
"s": 40851,
"text": "sqlite> SELECT CURRENT_TIMESTAMP;\nCURRENT_TIMESTAMP = 2013-03-17 10:43:35"
},
{
"code": null,
"e": 41035,
"s": 40925,
"text": "SQLite WHERE clause is used to specify a condition while fetching the data from one table or multiple tables."
},
{
"code": null,
"e": 41228,
"s": 41035,
"text": "If the given condition is satisfied, means true, then it returns the specific value from the table. You will have to use WHERE clause to filter the records and fetching only necessary records."
},
{
"code": null,
"e": 41384,
"s": 41228,
"text": "The WHERE clause not only is used in SELECT statement, but it is also used in UPDATE, DELETE statement, etc., which will be covered in subsequent chapters."
},
{
"code": null,
"e": 41460,
"s": 41384,
"text": "Following is the basic syntax of SQLite SELECT statement with WHERE clause."
},
{
"code": null,
"e": 41529,
"s": 41460,
"text": "SELECT column1, column2, columnN \nFROM table_name\nWHERE [condition]\n"
},
{
"code": null,
"e": 41681,
"s": 41529,
"text": "You can specify a condition using Comparision or Logical Operators such as >, <, =, LIKE, NOT, etc. Consider COMPANY table with the following records −"
},
{
"code": null,
"e": 42187,
"s": 41681,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 42409,
"s": 42187,
"text": "Following is a simple examples showing the usage of SQLite Logical Operators. Following SELECT statement lists down all the records where AGE is greater than or equal to 25 AND salary is greater than or equal to 65000.00."
},
{
"code": null,
"e": 42703,
"s": 42409,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 42846,
"s": 42703,
"text": "Following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00."
},
{
"code": null,
"e": 43251,
"s": 42846,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 43406,
"s": 43251,
"text": "Following SELECT statement lists down all the records where AGE is not NULL, which means all the records because none of the record has AGE equal to NULL."
},
{
"code": null,
"e": 43967,
"s": 43406,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE IS NOT NULL;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 44089,
"s": 43967,
"text": "Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'."
},
{
"code": null,
"e": 44313,
"s": 44089,
"text": "sqlite> SELECT * FROM COMPANY WHERE NAME LIKE 'Ki%';\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n6 Kim 22 South-Hall 45000.0"
},
{
"code": null,
"e": 44435,
"s": 44313,
"text": "Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'."
},
{
"code": null,
"e": 44659,
"s": 44435,
"text": "sqlite> SELECT * FROM COMPANY WHERE NAME GLOB 'Ki*';\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n6 Kim 22 South-Hall 45000.0"
},
{
"code": null,
"e": 44749,
"s": 44659,
"text": "Following SELECT statement lists down all the records where AGE value is either 25 or 27."
},
{
"code": null,
"e": 45087,
"s": 44749,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE IN ( 25, 27 );\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 45179,
"s": 45087,
"text": "Following SELECT statement lists down all the records where AGE value is neither 25 nor 27."
},
{
"code": null,
"e": 45577,
"s": 45179,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE NOT IN ( 25, 27 );\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n3 Teddy 23 Norway 20000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 45672,
"s": 45577,
"text": "Following SELECT statement lists down all the records where AGE value is in BETWEEN 25 AND 27."
},
{
"code": null,
"e": 46014,
"s": 45672,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE BETWEEN 25 AND 27;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 46319,
"s": 46014,
"text": "Following SELECT statement makes use of SQL sub-query, where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with EXISTS operator to list down all the records where AGE from the outside query exists in the result returned by the sub-query −"
},
{
"code": null,
"e": 46453,
"s": 46319,
"text": "sqlite> SELECT AGE FROM COMPANY \n WHERE EXISTS (SELECT AGE FROM COMPANY WHERE SALARY > 65000);\n\nAGE\n----------\n32\n25\n23\n25\n27\n22\n24"
},
{
"code": null,
"e": 46768,
"s": 46453,
"text": "Following SELECT statement makes use of SQL sub-query where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with > operator to list down all the records where AGE from the outside query is greater than the age in the result returned by the sub-query."
},
{
"code": null,
"e": 47033,
"s": 46768,
"text": "sqlite> SELECT * FROM COMPANY \n WHERE AGE > (SELECT AGE FROM COMPANY WHERE SALARY > 65000);\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0"
},
{
"code": null,
"e": 47210,
"s": 47033,
"text": "SQLite AND & OR operators are used to compile multiple conditions to narrow down the selected data in an SQLite statement. These two operators are called conjunctive operators."
},
{
"code": null,
"e": 47326,
"s": 47210,
"text": "These operators provide a means to make multiple comparisons with different operators in the same SQLite statement."
},
{
"code": null,
"e": 47632,
"s": 47326,
"text": "The AND operator allows the existence of multiple conditions in a SQLite statement's WHERE clause. While using AND operator, complete condition will be assumed true when all the conditions are true. For example, [condition1] AND [condition2] will be true only when both condition1 and condition2 are true."
},
{
"code": null,
"e": 47697,
"s": 47632,
"text": "Following is the basic syntax of AND operator with WHERE clause."
},
{
"code": null,
"e": 47804,
"s": 47697,
"text": "SELECT column1, column2, columnN \nFROM table_name\nWHERE [condition1] AND [condition2]...AND [conditionN];\n"
},
{
"code": null,
"e": 48002,
"s": 47804,
"text": "You can combine N number of conditions using AND operator. For an action to be taken by the SQLite statement, whether it be a transaction or query, all conditions separated by the AND must be TRUE."
},
{
"code": null,
"e": 48054,
"s": 48002,
"text": "Consider COMPANY table with the following records −"
},
{
"code": null,
"e": 48560,
"s": 48054,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 48704,
"s": 48560,
"text": "Following SELECT statement lists down all the records where AGE is greater than or equal to 25 AND salary is greater than or equal to 65000.00."
},
{
"code": null,
"e": 48998,
"s": 48704,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 49305,
"s": 48998,
"text": "The OR operator is also used to combine multiple conditions in a SQLite statement's WHERE clause. While using OR operator, complete condition will be assumed true when at least any of the conditions is true. For example, [condition1] OR [condition2] will be true if either condition1 or condition2 is true."
},
{
"code": null,
"e": 49369,
"s": 49305,
"text": "Following is the basic syntax of OR operator with WHERE clause."
},
{
"code": null,
"e": 49473,
"s": 49369,
"text": "SELECT column1, column2, columnN \nFROM table_name\nWHERE [condition1] OR [condition2]...OR [conditionN]\n"
},
{
"code": null,
"e": 49685,
"s": 49473,
"text": "You can combine N number of conditions using OR operator. For an action to be taken by the SQLite statement, whether it be a transaction or query, only any ONE of the conditions separated by the OR must be TRUE."
},
{
"code": null,
"e": 49736,
"s": 49685,
"text": "Consider COMPANY table with the following records."
},
{
"code": null,
"e": 50242,
"s": 49736,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 50385,
"s": 50242,
"text": "Following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00."
},
{
"code": null,
"e": 50790,
"s": 50385,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 50970,
"s": 50790,
"text": "SQLite UPDATE Query is used to modify the existing records in a table. You can use WHERE clause with UPDATE query to update selected rows, otherwise all the rows would be updated."
},
{
"code": null,
"e": 51035,
"s": 50970,
"text": "Following is the basic syntax of UPDATE query with WHERE clause."
},
{
"code": null,
"e": 51134,
"s": 51035,
"text": "UPDATE table_name\nSET column1 = value1, column2 = value2...., columnN = valueN\nWHERE [condition];\n"
},
{
"code": null,
"e": 51200,
"s": 51134,
"text": "You can combine N number of conditions using AND or OR operators."
},
{
"code": null,
"e": 51252,
"s": 51200,
"text": "Consider COMPANY table with the following records −"
},
{
"code": null,
"e": 51758,
"s": 51252,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 51839,
"s": 51758,
"text": "Following is an example, which will update ADDRESS for a customer whose ID is 6."
},
{
"code": null,
"e": 51898,
"s": 51839,
"text": "sqlite> UPDATE COMPANY SET ADDRESS = 'Texas' WHERE ID = 6;"
},
{
"code": null,
"e": 51950,
"s": 51898,
"text": "Now, COMPANY table will have the following records."
},
{
"code": null,
"e": 52456,
"s": 51950,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 Texas 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 52607,
"s": 52456,
"text": "If you want to modify all ADDRESS and SALARY column values in COMPANY table, you do not need to use WHERE clause and UPDATE query will be as follows −"
},
{
"code": null,
"e": 52672,
"s": 52607,
"text": "sqlite> UPDATE COMPANY SET ADDRESS = 'Texas', SALARY = 20000.00;"
},
{
"code": null,
"e": 52725,
"s": 52672,
"text": "Now, COMPANY table will have the following records −"
},
{
"code": null,
"e": 53231,
"s": 52725,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 Texas 20000.0\n2 Allen 25 Texas 20000.0\n3 Teddy 23 Texas 20000.0\n4 Mark 25 Texas 20000.0\n5 David 27 Texas 20000.0\n6 Kim 22 Texas 20000.0\n7 James 24 Texas 20000.0"
},
{
"code": null,
"e": 53420,
"s": 53231,
"text": "SQLite DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete the selected rows, otherwise all the records would be deleted."
},
{
"code": null,
"e": 53485,
"s": 53420,
"text": "Following is the basic syntax of DELETE query with WHERE clause."
},
{
"code": null,
"e": 53528,
"s": 53485,
"text": "DELETE FROM table_name\nWHERE [condition];\n"
},
{
"code": null,
"e": 53594,
"s": 53528,
"text": "You can combine N number of conditions using AND or OR operators."
},
{
"code": null,
"e": 53645,
"s": 53594,
"text": "Consider COMPANY table with the following records."
},
{
"code": null,
"e": 54151,
"s": 53645,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 54220,
"s": 54151,
"text": "Following is an example, which will DELETE a customer whose ID is 7."
},
{
"code": null,
"e": 54262,
"s": 54220,
"text": "sqlite> DELETE FROM COMPANY WHERE ID = 7;"
},
{
"code": null,
"e": 54313,
"s": 54262,
"text": "Now COMPANY table will have the following records."
},
{
"code": null,
"e": 54763,
"s": 54313,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0"
},
{
"code": null,
"e": 54903,
"s": 54763,
"text": "If you want to DELETE all the records from COMPANY table, you do not need to use WHERE clause with DELETE query, which will be as follows −"
},
{
"code": null,
"e": 54932,
"s": 54903,
"text": "sqlite> DELETE FROM COMPANY;"
},
{
"code": null,
"e": 55034,
"s": 54932,
"text": "Now, COMPANY table does not have any record as all the records have been deleted by DELETE statement."
},
{
"code": null,
"e": 55303,
"s": 55034,
"text": "SQLite LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. There are two wildcards used in conjunction with the LIKE operator −"
},
{
"code": null,
"e": 55324,
"s": 55303,
"text": "The percent sign (%)"
},
{
"code": null,
"e": 55343,
"s": 55324,
"text": "The underscore (_)"
},
{
"code": null,
"e": 55516,
"s": 55343,
"text": "The percent sign represents zero, one, or multiple numbers or characters. The underscore represents a single number or character. These symbols can be used in combinations."
},
{
"code": null,
"e": 55558,
"s": 55516,
"text": "Following is the basic syntax of % and _."
},
{
"code": null,
"e": 55819,
"s": 55558,
"text": "SELECT FROM table_name\nWHERE column LIKE 'XXXX%'\nor \nSELECT FROM table_name\nWHERE column LIKE '%XXXX%'\nor\nSELECT FROM table_name\nWHERE column LIKE 'XXXX_'\nor\nSELECT FROM table_name\nWHERE column LIKE '_XXXX'\nor\nSELECT FROM table_name\nWHERE column LIKE '_XXXX_'\n"
},
{
"code": null,
"e": 55934,
"s": 55819,
"text": "You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value."
},
{
"code": null,
"e": 56053,
"s": 55934,
"text": "Following table lists a number of examples showing WHERE part having different LIKE clause with '%' and '_' operators."
},
{
"code": null,
"e": 56078,
"s": 56053,
"text": "WHERE SALARY LIKE '200%'"
},
{
"code": null,
"e": 56115,
"s": 56078,
"text": "Finds any values that start with 200"
},
{
"code": null,
"e": 56141,
"s": 56115,
"text": "WHERE SALARY LIKE '%200%'"
},
{
"code": null,
"e": 56188,
"s": 56141,
"text": "Finds any values that have 200 in any position"
},
{
"code": null,
"e": 56213,
"s": 56188,
"text": "WHERE SALARY LIKE '_00%'"
},
{
"code": null,
"e": 56277,
"s": 56213,
"text": "Finds any values that have 00 in the second and third positions"
},
{
"code": null,
"e": 56303,
"s": 56277,
"text": "WHERE SALARY LIKE '2_%_%'"
},
{
"code": null,
"e": 56378,
"s": 56303,
"text": "Finds any values that start with 2 and are at least 3 characters in length"
},
{
"code": null,
"e": 56401,
"s": 56378,
"text": "WHERE SALARY LIKE '%2'"
},
{
"code": null,
"e": 56434,
"s": 56401,
"text": "Finds any values that end with 2"
},
{
"code": null,
"e": 56459,
"s": 56434,
"text": "WHERE SALARY LIKE '_2%3'"
},
{
"code": null,
"e": 56530,
"s": 56459,
"text": "Finds any values that has a 2 in the second position and ends with a 3"
},
{
"code": null,
"e": 56556,
"s": 56530,
"text": "WHERE SALARY LIKE '2___3'"
},
{
"code": null,
"e": 56631,
"s": 56556,
"text": "Finds any values in a five-digit number that starts with 2 and ends with 3"
},
{
"code": null,
"e": 56710,
"s": 56631,
"text": "Let us take a real example, consider COMPANY table with the following records."
},
{
"code": null,
"e": 57216,
"s": 56710,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 57320,
"s": 57216,
"text": "Following is an example, which will display all the records from COMPANY table where AGE starts with 2."
},
{
"code": null,
"e": 57371,
"s": 57320,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE LIKE '2%';"
},
{
"code": null,
"e": 57411,
"s": 57371,
"text": "This will produce the following result."
},
{
"code": null,
"e": 57862,
"s": 57411,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n"
},
{
"code": null,
"e": 57995,
"s": 57862,
"text": "Following is an example, which will display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text."
},
{
"code": null,
"e": 58052,
"s": 57995,
"text": "sqlite> SELECT * FROM COMPANY WHERE ADDRESS LIKE '%-%';"
},
{
"code": null,
"e": 58092,
"s": 58052,
"text": "This will produce the following result."
},
{
"code": null,
"e": 58319,
"s": 58092,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n4 Mark 25 Rich-Mond 65000.0\n6 Kim 22 South-Hall 45000.0\n"
},
{
"code": null,
"e": 58639,
"s": 58319,
"text": "SQLite GLOB operator is used to match only text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the GLOB operator will return true, which is 1. Unlike LIKE operator, GLOB is case sensitive and it follows syntax of UNIX for specifying THE following wildcards."
},
{
"code": null,
"e": 58661,
"s": 58639,
"text": "The asterisk sign (*)"
},
{
"code": null,
"e": 58683,
"s": 58661,
"text": "The question mark (?)"
},
{
"code": null,
"e": 58819,
"s": 58683,
"text": "The asterisk sign (*) represents zero or multiple numbers or characters. The question mark (?) represents a single number or character."
},
{
"code": null,
"e": 58861,
"s": 58819,
"text": "Following is the basic syntax of * and ?."
},
{
"code": null,
"e": 59173,
"s": 58861,
"text": "SELECT FROM table_name\nWHERE column GLOB 'XXXX*'\nor \nSELECT FROM table_name\nWHERE column GLOB '*XXXX*'\nor\nSELECT FROM table_name\nWHERE column GLOB 'XXXX?'\nor\nSELECT FROM table_name\nWHERE column GLOB '?XXXX'\nor\nSELECT FROM table_name\nWHERE column GLOB '?XXXX?'\nor\nSELECT FROM table_name\nWHERE column GLOB '????'\n"
},
{
"code": null,
"e": 59288,
"s": 59173,
"text": "You can combine N number of conditions using AND or OR operators. Here, XXXX could be any numeric or string value."
},
{
"code": null,
"e": 59407,
"s": 59288,
"text": "Following table lists a number of examples showing WHERE part having different LIKE clause with '*' and '?' operators."
},
{
"code": null,
"e": 59432,
"s": 59407,
"text": "WHERE SALARY GLOB '200*'"
},
{
"code": null,
"e": 59469,
"s": 59432,
"text": "Finds any values that start with 200"
},
{
"code": null,
"e": 59495,
"s": 59469,
"text": "WHERE SALARY GLOB '*200*'"
},
{
"code": null,
"e": 59542,
"s": 59495,
"text": "Finds any values that have 200 in any position"
},
{
"code": null,
"e": 59567,
"s": 59542,
"text": "WHERE SALARY GLOB '?00*'"
},
{
"code": null,
"e": 59631,
"s": 59567,
"text": "Finds any values that have 00 in the second and third positions"
},
{
"code": null,
"e": 59655,
"s": 59631,
"text": "WHERE SALARY GLOB '2??'"
},
{
"code": null,
"e": 59730,
"s": 59655,
"text": "Finds any values that start with 2 and are at least 3 characters in length"
},
{
"code": null,
"e": 59753,
"s": 59730,
"text": "WHERE SALARY GLOB '*2'"
},
{
"code": null,
"e": 59786,
"s": 59753,
"text": "Finds any values that end with 2"
},
{
"code": null,
"e": 59811,
"s": 59786,
"text": "WHERE SALARY GLOB '?2*3'"
},
{
"code": null,
"e": 59882,
"s": 59811,
"text": "Finds any values that have a 2 in the second position and end with a 3"
},
{
"code": null,
"e": 59908,
"s": 59882,
"text": "WHERE SALARY GLOB '2???3'"
},
{
"code": null,
"e": 59981,
"s": 59908,
"text": "Finds any values in a five-digit number that start with 2 and end with 3"
},
{
"code": null,
"e": 60061,
"s": 59981,
"text": "Let us take a real example, consider COMPANY table with the following records −"
},
{
"code": null,
"e": 60567,
"s": 60061,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 60672,
"s": 60567,
"text": "Following is an example, which will display all the records from COMPANY table, where AGE starts with 2."
},
{
"code": null,
"e": 60724,
"s": 60672,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE GLOB '2*';"
},
{
"code": null,
"e": 60764,
"s": 60724,
"text": "This will produce the following result."
},
{
"code": null,
"e": 61215,
"s": 60764,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n"
},
{
"code": null,
"e": 61349,
"s": 61215,
"text": "Following is an example, which will display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text −"
},
{
"code": null,
"e": 61406,
"s": 61349,
"text": "sqlite> SELECT * FROM COMPANY WHERE ADDRESS GLOB '*-*';"
},
{
"code": null,
"e": 61446,
"s": 61406,
"text": "This will produce the following result."
},
{
"code": null,
"e": 61673,
"s": 61446,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n4 Mark 25 Rich-Mond 65000.0\n6 Kim 22 South-Hall 45000.0\n"
},
{
"code": null,
"e": 61760,
"s": 61673,
"text": "SQLite LIMIT clause is used to limit the data amount returned by the SELECT statement."
},
{
"code": null,
"e": 61829,
"s": 61760,
"text": "Following is the basic syntax of SELECT statement with LIMIT clause."
},
{
"code": null,
"e": 61899,
"s": 61829,
"text": "SELECT column1, column2, columnN \nFROM table_name\nLIMIT [no of rows]\n"
},
{
"code": null,
"e": 61981,
"s": 61899,
"text": "Following is the syntax of LIMIT clause when it is used along with OFFSET clause."
},
{
"code": null,
"e": 62068,
"s": 61981,
"text": "SELECT column1, column2, columnN \nFROM table_name\nLIMIT [no of rows] OFFSET [row num]\n"
},
{
"code": null,
"e": 62182,
"s": 62068,
"text": "SQLite engine will return rows starting from the next row to the given OFFSET as shown below in the last example."
},
{
"code": null,
"e": 62234,
"s": 62182,
"text": "Consider COMPANY table with the following records −"
},
{
"code": null,
"e": 62740,
"s": 62234,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 62861,
"s": 62740,
"text": "Following is an example, which limits the row in the table according to the number of rows you want to fetch from table."
},
{
"code": null,
"e": 62900,
"s": 62861,
"text": "sqlite> SELECT * FROM COMPANY LIMIT 6;"
},
{
"code": null,
"e": 62940,
"s": 62900,
"text": "This will produce the following result."
},
{
"code": null,
"e": 63391,
"s": 62940,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n"
},
{
"code": null,
"e": 63566,
"s": 63391,
"text": "However in certain situations, you may need to pick up a set of records from a particular offset. Here is an example, which picks up 3 records starting from the 3rd position."
},
{
"code": null,
"e": 63614,
"s": 63566,
"text": "sqlite> SELECT * FROM COMPANY LIMIT 3 OFFSET 2;"
},
{
"code": null,
"e": 63654,
"s": 63614,
"text": "This will produce the following result."
},
{
"code": null,
"e": 63937,
"s": 63654,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n"
},
{
"code": null,
"e": 64052,
"s": 63937,
"text": "SQLite ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns."
},
{
"code": null,
"e": 64102,
"s": 64052,
"text": "Following is the basic syntax of ORDER BY clause."
},
{
"code": null,
"e": 64213,
"s": 64102,
"text": "SELECT column-list \nFROM table_name \n[WHERE condition] \n[ORDER BY column1, column2, .. columnN] [ASC | DESC];\n"
},
{
"code": null,
"e": 64371,
"s": 64213,
"text": "You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be available in the column-list."
},
{
"code": null,
"e": 64422,
"s": 64371,
"text": "Consider COMPANY table with the following records."
},
{
"code": null,
"e": 64928,
"s": 64422,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 65011,
"s": 64928,
"text": "Following is an example, which will sort the result in descending order by SALARY."
},
{
"code": null,
"e": 65062,
"s": 65011,
"text": "sqlite> SELECT * FROM COMPANY ORDER BY SALARY ASC;"
},
{
"code": null,
"e": 65102,
"s": 65062,
"text": "This will produce the following result."
},
{
"code": null,
"e": 65609,
"s": 65102,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n7 James 24 Houston 10000.0\n2 Allen 25 Texas 15000.0\n1 Paul 32 California 20000.0\n3 Teddy 23 Norway 20000.0\n6 Kim 22 South-Hall 45000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n"
},
{
"code": null,
"e": 65701,
"s": 65609,
"text": "Following is an example, which will sort the result in descending order by NAME and SALARY."
},
{
"code": null,
"e": 65758,
"s": 65701,
"text": "sqlite> SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC;"
},
{
"code": null,
"e": 65798,
"s": 65758,
"text": "This will produce the following result."
},
{
"code": null,
"e": 66305,
"s": 65798,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000.0\n5 David 27 Texas 85000.0\n7 James 24 Houston 10000.0\n6 Kim 22 South-Hall 45000.0\n4 Mark 25 Rich-Mond 65000.0\n1 Paul 32 California 20000.0\n3 Teddy 23 Norway 20000.0\n"
},
{
"code": null,
"e": 66386,
"s": 66305,
"text": "Following is an example, which will sort the result in descending order by NAME."
},
{
"code": null,
"e": 66436,
"s": 66386,
"text": "sqlite> SELECT * FROM COMPANY ORDER BY NAME DESC;"
},
{
"code": null,
"e": 66476,
"s": 66436,
"text": "This will produce the following result."
},
{
"code": null,
"e": 66983,
"s": 66476,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n3 Teddy 23 Norway 20000.0\n1 Paul 32 California 20000.0\n4 Mark 25 Rich-Mond 65000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n5 David 27 Texas 85000.0\n2 Allen 25 Texas 15000.0\n"
},
{
"code": null,
"e": 67097,
"s": 66983,
"text": "SQLite GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups."
},
{
"code": null,
"e": 67194,
"s": 67097,
"text": "GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause."
},
{
"code": null,
"e": 67356,
"s": 67194,
"text": "Following is the basic syntax of GROUP BY clause. GROUP BY clause must follow the conditions in the WHERE clause and must precede ORDER BY clause if one is used."
},
{
"code": null,
"e": 67487,
"s": 67356,
"text": "SELECT column-list\nFROM table_name\nWHERE [ conditions ]\nGROUP BY column1, column2....columnN\nORDER BY column1, column2....columnN\n"
},
{
"code": null,
"e": 67646,
"s": 67487,
"text": "You can use more than one column in the GROUP BY clause. Make sure whatever column you are using to group, that column should be available in the column-list."
},
{
"code": null,
"e": 67697,
"s": 67646,
"text": "Consider COMPANY table with the following records."
},
{
"code": null,
"e": 68203,
"s": 67697,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 68309,
"s": 68203,
"text": "If you want to know the total amount of salary on each customer, then GROUP BY query will be as follows −"
},
{
"code": null,
"e": 68370,
"s": 68309,
"text": "sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME;"
},
{
"code": null,
"e": 68411,
"s": 68370,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 68600,
"s": 68411,
"text": "NAME SUM(SALARY)\n---------- -----------\nAllen 15000.0\nDavid 85000.0\nJames 10000.0\nKim 45000.0\nMark 65000.0\nPaul 20000.0\nTeddy 20000.0\n"
},
{
"code": null,
"e": 68694,
"s": 68600,
"text": "Now, let us create three more records in COMPANY table using the following INSERT statements."
},
{
"code": null,
"e": 68890,
"s": 68694,
"text": "INSERT INTO COMPANY VALUES (8, 'Paul', 24, 'Houston', 20000.00 );\nINSERT INTO COMPANY VALUES (9, 'James', 44, 'Norway', 5000.00 );\nINSERT INTO COMPANY VALUES (10, 'James', 45, 'Texas', 5000.00 );"
},
{
"code": null,
"e": 68953,
"s": 68890,
"text": "Now, our table has the following records with duplicate names."
},
{
"code": null,
"e": 69625,
"s": 68953,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n8 Paul 24 Houston 20000.0\n9 James 44 Norway 5000.0\n10 James 45 Texas 5000.0"
},
{
"code": null,
"e": 69721,
"s": 69625,
"text": "Again, let us use the same statement to group-by all the records using NAME column as follows −"
},
{
"code": null,
"e": 69796,
"s": 69721,
"text": "sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME;"
},
{
"code": null,
"e": 69836,
"s": 69796,
"text": "This will produce the following result."
},
{
"code": null,
"e": 70011,
"s": 69836,
"text": "NAME SUM(SALARY)\n---------- -----------\nAllen 15000\nDavid 85000\nJames 20000\nKim 45000\nMark 65000\nPaul 40000\nTeddy 20000\n"
},
{
"code": null,
"e": 70078,
"s": 70011,
"text": "Let us use ORDER BY clause along with GROUP BY clause as follows −"
},
{
"code": null,
"e": 70163,
"s": 70078,
"text": "sqlite> SELECT NAME, SUM(SALARY) \n FROM COMPANY GROUP BY NAME ORDER BY NAME DESC;"
},
{
"code": null,
"e": 70203,
"s": 70163,
"text": "This will produce the following result."
},
{
"code": null,
"e": 70378,
"s": 70203,
"text": "NAME SUM(SALARY)\n---------- -----------\nTeddy 20000\nPaul 40000\nMark 65000\nKim 45000\nJames 20000\nDavid 85000\nAllen 15000\n"
},
{
"code": null,
"e": 70487,
"s": 70378,
"text": "HAVING clause enables you to specify conditions that filter which group results appear in the final results."
},
{
"code": null,
"e": 70629,
"s": 70487,
"text": "The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by GROUP BY clause."
},
{
"code": null,
"e": 70691,
"s": 70629,
"text": "Following is the position of HAVING clause in a SELECT query."
},
{
"code": null,
"e": 70734,
"s": 70691,
"text": "SELECT\nFROM\nWHERE\nGROUP BY\nHAVING\nORDER BY"
},
{
"code": null,
"e": 70908,
"s": 70734,
"text": "HAVING clause must follow GROUP BY clause in a query and must also precede ORDER BY clause if used. Following is the syntax of the SELECT statement, including HAVING clause."
},
{
"code": null,
"e": 71048,
"s": 70908,
"text": "SELECT column1, column2\nFROM table1, table2\nWHERE [ conditions ]\nGROUP BY column1, column2\nHAVING [ conditions ]\nORDER BY column1, column2\n"
},
{
"code": null,
"e": 71099,
"s": 71048,
"text": "Consider COMPANY table with the following records."
},
{
"code": null,
"e": 71771,
"s": 71099,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n8 Paul 24 Houston 20000.0\n9 James 44 Norway 5000.0\n10 James 45 Texas 5000.0"
},
{
"code": null,
"e": 71868,
"s": 71771,
"text": "Following is the example, which will display the record for which the name count is less than 2."
},
{
"code": null,
"e": 71937,
"s": 71868,
"text": "sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) < 2;"
},
{
"code": null,
"e": 71977,
"s": 71937,
"text": "This will produce the following result."
},
{
"code": null,
"e": 72362,
"s": 71977,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000\n5 David 27 Texas 85000\n6 Kim 22 South-Hall 45000\n4 Mark 25 Rich-Mond 65000\n3 Teddy 23 Norway 20000\n"
},
{
"code": null,
"e": 72462,
"s": 72362,
"text": "Following is the example, which will display the record for which the name count is greater than 2."
},
{
"code": null,
"e": 72531,
"s": 72462,
"text": "sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) > 2;"
},
{
"code": null,
"e": 72571,
"s": 72531,
"text": "This will produce the following result."
},
{
"code": null,
"e": 72739,
"s": 72571,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n10 James 45 Texas 5000\n"
},
{
"code": null,
"e": 72885,
"s": 72739,
"text": "SQLite DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only the unique records."
},
{
"code": null,
"e": 73080,
"s": 72885,
"text": "There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records."
},
{
"code": null,
"e": 73162,
"s": 73080,
"text": "Following is the basic syntax of DISTINCT keyword to eliminate duplicate records."
},
{
"code": null,
"e": 73244,
"s": 73162,
"text": "SELECT DISTINCT column1, column2,.....columnN \nFROM table_name\nWHERE [condition]\n"
},
{
"code": null,
"e": 73295,
"s": 73244,
"text": "Consider COMPANY table with the following records."
},
{
"code": null,
"e": 73967,
"s": 73295,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n8 Paul 24 Houston 20000.0\n9 James 44 Norway 5000.0\n10 James 45 Texas 5000.0"
},
{
"code": null,
"e": 74050,
"s": 73967,
"text": "First, let us see how the following SELECT query returns duplicate salary records."
},
{
"code": null,
"e": 74084,
"s": 74050,
"text": "sqlite> SELECT name FROM COMPANY;"
},
{
"code": null,
"e": 74124,
"s": 74084,
"text": "This will produce the following result."
},
{
"code": null,
"e": 74196,
"s": 74124,
"text": "NAME\n----------\nPaul\nAllen\nTeddy\nMark\nDavid\nKim\nJames\nPaul\nJames\nJames\n"
},
{
"code": null,
"e": 74277,
"s": 74196,
"text": "Now, let us use DISTINCT keyword with the above SELECT query and see the result."
},
{
"code": null,
"e": 74320,
"s": 74277,
"text": "sqlite> SELECT DISTINCT name FROM COMPANY;"
},
{
"code": null,
"e": 74395,
"s": 74320,
"text": "This will produce the following result, where there is no duplicate entry."
},
{
"code": null,
"e": 74450,
"s": 74395,
"text": "NAME\n----------\nPaul\nAllen\nTeddy\nMark\nDavid\nKim\nJames\n"
},
{
"code": null,
"e": 74671,
"s": 74450,
"text": "SQLite PRAGMA command is a special command to be used to control various environmental variables and state flags within the SQLite environment. A PRAGMA value can be read and it can also be set based on the requirements."
},
{
"code": null,
"e": 74743,
"s": 74671,
"text": "To query the current PRAGMA value, just provide the name of the pragma."
},
{
"code": null,
"e": 74764,
"s": 74743,
"text": "PRAGMA pragma_name;\n"
},
{
"code": null,
"e": 74821,
"s": 74764,
"text": "To set a new value for PRAGMA, use the following syntax."
},
{
"code": null,
"e": 74850,
"s": 74821,
"text": "PRAGMA pragma_name = value;\n"
},
{
"code": null,
"e": 74962,
"s": 74850,
"text": "The set mode can be either the name or the integer equivalent but the returned value will always be an integer."
},
{
"code": null,
"e": 75052,
"s": 74962,
"text": "The auto_vacuum pragma gets or sets the auto-vacuum mode. Following is the simple syntax."
},
{
"code": null,
"e": 75122,
"s": 75052,
"text": "PRAGMA [database.]auto_vacuum;\nPRAGMA [database.]auto_vacuum = mode;\n"
},
{
"code": null,
"e": 75163,
"s": 75122,
"text": "Where mode can be any of the following −"
},
{
"code": null,
"e": 75173,
"s": 75163,
"text": "0 or NONE"
},
{
"code": null,
"e": 75339,
"s": 75173,
"text": "Auto-vacuum is disabled. This is the default mode which means that a database file will never shrink in size unless it is manually vacuumed using the VACUUM command."
},
{
"code": null,
"e": 75349,
"s": 75339,
"text": "1 or FULL"
},
{
"code": null,
"e": 75469,
"s": 75349,
"text": "Auto-vacuum is enabled and fully automatic which allows a database file to shrink as data is removed from the database."
},
{
"code": null,
"e": 75486,
"s": 75469,
"text": "2 or INCREMENTAL"
},
{
"code": null,
"e": 75711,
"s": 75486,
"text": "Auto-vacuum is enabled but must be manually activated. In this mode the reference data is maintained, but free pages are simply put on the free list. These pages can be recovered using the incremental_vacuum pragma any time."
},
{
"code": null,
"e": 75838,
"s": 75711,
"text": "The cache_size pragma can get or temporarily set the maximum size of the in-memory page cache. Following is the simple syntax."
},
{
"code": null,
"e": 75907,
"s": 75838,
"text": "PRAGMA [database.]cache_size;\nPRAGMA [database.]cache_size = pages;\n"
},
{
"code": null,
"e": 76058,
"s": 75907,
"text": "The pages value represents the number of pages in the cache. The built-in page cache has a default size of 2,000 pages and a minimum size of 10 pages."
},
{
"code": null,
"e": 76286,
"s": 76058,
"text": "The case_sensitive_like pragma controls the case-sensitivity of the built-in LIKE expression. By default, this pragma is false which means that the built-in LIKE operator ignores the letter case. Following is the simple syntax."
},
{
"code": null,
"e": 76330,
"s": 76286,
"text": "PRAGMA case_sensitive_like = [true|false];\n"
},
{
"code": null,
"e": 76393,
"s": 76330,
"text": "There is no way to query for the current state of this pragma."
},
{
"code": null,
"e": 76543,
"s": 76393,
"text": "count_changes pragma gets or sets the return value of data manipulation statements such as INSERT, UPDATE and DELETE. Following is the simple syntax."
},
{
"code": null,
"e": 76603,
"s": 76543,
"text": "PRAGMA count_changes;\nPRAGMA count_changes = [true|false];\n"
},
{
"code": null,
"e": 76849,
"s": 76603,
"text": "By default, this pragma is false and these statements do not return anything. If set to true, each of the mentioned statement will return a one-column, one-row table consisting of a single integer value indicating impacted rows by the operation."
},
{
"code": null,
"e": 76960,
"s": 76849,
"text": "The database_list pragma will be used to list down all the databases attached. Following is the simple syntax."
},
{
"code": null,
"e": 76983,
"s": 76960,
"text": "PRAGMA database_list;\n"
},
{
"code": null,
"e": 77138,
"s": 76983,
"text": "This pragma will return a three-column table with one row per open or attached database giving database sequence number, its name and the file associated."
},
{
"code": null,
"e": 77254,
"s": 77138,
"text": "The encoding pragma controls how strings are encoded and stored in a database file. Following is the simple syntax."
},
{
"code": null,
"e": 77298,
"s": 77254,
"text": "PRAGMA encoding;\nPRAGMA encoding = format;\n"
},
{
"code": null,
"e": 77359,
"s": 77298,
"text": "The format value can be one of UTF-8, UTF-16le, or UTF-16be."
},
{
"code": null,
"e": 77521,
"s": 77359,
"text": "The freelist_count pragma returns a single integer indicating how many database pages are currently marked as free and available. Following is the simple syntax."
},
{
"code": null,
"e": 77556,
"s": 77521,
"text": "PRAGMA [database.]freelist_count;\n"
},
{
"code": null,
"e": 77617,
"s": 77556,
"text": "The format value can be one of UTF-8, UTF-16le, or UTF-16be."
},
{
"code": null,
"e": 77715,
"s": 77617,
"text": "The index_info pragma returns information about a database index. Following is the simple syntax."
},
{
"code": null,
"e": 77760,
"s": 77715,
"text": "PRAGMA [database.]index_info( index_name );\n"
},
{
"code": null,
"e": 77903,
"s": 77760,
"text": "The result set will contain one row for each column contained in the index giving column sequence, column index with-in table and column name."
},
{
"code": null,
"e": 78003,
"s": 77903,
"text": "index_list pragma lists all of the indexes associated with a table. Following is the simple syntax."
},
{
"code": null,
"e": 78048,
"s": 78003,
"text": "PRAGMA [database.]index_list( table_name );\n"
},
{
"code": null,
"e": 78189,
"s": 78048,
"text": "The result set will contain one row for each index giving index sequence, index name and flag indicating whether the index is unique or not."
},
{
"code": null,
"e": 78336,
"s": 78189,
"text": "The journal_mode pragma gets or sets the journal mode which controls how the journal file is stored and processed. Following is the simple syntax."
},
{
"code": null,
"e": 78453,
"s": 78336,
"text": "PRAGMA journal_mode;\nPRAGMA journal_mode = mode;\nPRAGMA database.journal_mode;\nPRAGMA database.journal_mode = mode;\n"
},
{
"code": null,
"e": 78526,
"s": 78453,
"text": "There are five supported journal modes as listed in the following table."
},
{
"code": null,
"e": 78533,
"s": 78526,
"text": "DELETE"
},
{
"code": null,
"e": 78629,
"s": 78533,
"text": "This is the default mode. Here at the conclusion of a transaction, the journal file is deleted."
},
{
"code": null,
"e": 78638,
"s": 78629,
"text": "TRUNCATE"
},
{
"code": null,
"e": 78695,
"s": 78638,
"text": "The journal file is truncated to a length of zero bytes."
},
{
"code": null,
"e": 78703,
"s": 78695,
"text": "PERSIST"
},
{
"code": null,
"e": 78812,
"s": 78703,
"text": "The journal file is left in place, but the header is overwritten to indicate the journal is no longer valid."
},
{
"code": null,
"e": 78819,
"s": 78812,
"text": "MEMORY"
},
{
"code": null,
"e": 78878,
"s": 78819,
"text": "The journal record is held in memory, rather than on disk."
},
{
"code": null,
"e": 78882,
"s": 78878,
"text": "OFF"
},
{
"code": null,
"e": 78909,
"s": 78882,
"text": "No journal record is kept."
},
{
"code": null,
"e": 79027,
"s": 78909,
"text": "The max_page_count pragma gets or sets the maximum allowed page count for a database. Following is the simple syntax."
},
{
"code": null,
"e": 79107,
"s": 79027,
"text": "PRAGMA [database.]max_page_count;\nPRAGMA [database.]max_page_count = max_page;\n"
},
{
"code": null,
"e": 79259,
"s": 79107,
"text": "The default value is 1,073,741,823 which is one giga-page, which means if the default 1 KB page size, this allows databases to grow up to one terabyte."
},
{
"code": null,
"e": 79370,
"s": 79259,
"text": "The page_count pragma returns in the current number of pages in the database. Following is the simple syntax −"
},
{
"code": null,
"e": 79401,
"s": 79370,
"text": "PRAGMA [database.]page_count;\n"
},
{
"code": null,
"e": 79465,
"s": 79401,
"text": "The size of the database file should be page_count * page_size."
},
{
"code": null,
"e": 79563,
"s": 79465,
"text": "The page_size pragma gets or sets the size of the database pages. Following is the simple syntax."
},
{
"code": null,
"e": 79630,
"s": 79563,
"text": "PRAGMA [database.]page_size;\nPRAGMA [database.]page_size = bytes;\n"
},
{
"code": null,
"e": 79843,
"s": 79630,
"text": "By default, the allowed sizes are 512, 1024, 2048, 4096, 8192, 16384, and 32768 bytes. The only way to alter the page size on an existing database is to set the page size and then immediately VACUUM the database."
},
{
"code": null,
"e": 79964,
"s": 79843,
"text": "The parser_trace pragma controls printing the debugging state as it parses SQL commands. Following is the simple syntax."
},
{
"code": null,
"e": 80001,
"s": 79964,
"text": "PRAGMA parser_trace = [true|false];\n"
},
{
"code": null,
"e": 80135,
"s": 80001,
"text": "By default, it is set to false but when enabled by setting it to true, the SQL parser will print its state as it parses SQL commands."
},
{
"code": null,
"e": 80334,
"s": 80135,
"text": "The recursive_triggers pragma gets or sets the recursive trigger functionality. If recursive triggers are not enabled, a trigger action will not fire another trigger. Following is the simple syntax."
},
{
"code": null,
"e": 80404,
"s": 80334,
"text": "PRAGMA recursive_triggers;\nPRAGMA recursive_triggers = [true|false];\n"
},
{
"code": null,
"e": 80539,
"s": 80404,
"text": "The schema_version pragma gets or sets the schema version value that is stored in the database header. Following is the simple syntax."
},
{
"code": null,
"e": 80617,
"s": 80539,
"text": "PRAGMA [database.]schema_version;\nPRAGMA [database.]schema_version = number;\n"
},
{
"code": null,
"e": 80795,
"s": 80617,
"text": "This is a 32-bit signed integer value that keeps track of schema changes. Whenever a schema-altering command is executed (like, CREATE... or DROP...), this value is incremented."
},
{
"code": null,
"e": 80917,
"s": 80795,
"text": "The secure_delete pragma is used to control how the content is deleted from the database. Following is the simple syntax."
},
{
"code": null,
"e": 81054,
"s": 80917,
"text": "PRAGMA secure_delete;\nPRAGMA secure_delete = [true|false];\nPRAGMA database.secure_delete;\nPRAGMA database.secure_delete = [true|false];\n"
},
{
"code": null,
"e": 81184,
"s": 81054,
"text": "The default value for the secure delete flag is normally off, but this can be changed with the SQLITE_SECURE_DELETE build option."
},
{
"code": null,
"e": 81286,
"s": 81184,
"text": "The sql_trace pragma is used to dump SQL trace results to the screen. Following is the simple syntax."
},
{
"code": null,
"e": 81338,
"s": 81286,
"text": "PRAGMA sql_trace;\nPRAGMA sql_trace = [true|false];\n"
},
{
"code": null,
"e": 81426,
"s": 81338,
"text": "SQLite must be compiled with the SQLITE_DEBUG directive for this pragma to be included."
},
{
"code": null,
"e": 81625,
"s": 81426,
"text": "The synchronous pragma gets or sets the current disk synchronization mode, which controls how aggressively SQLite will write data all the way out to physical storage. Following is the simple syntax."
},
{
"code": null,
"e": 81695,
"s": 81625,
"text": "PRAGMA [database.]synchronous;\nPRAGMA [database.]synchronous = mode;\n"
},
{
"code": null,
"e": 81771,
"s": 81695,
"text": "SQLite supports the following synchronization modes as listed in the table."
},
{
"code": null,
"e": 81780,
"s": 81771,
"text": "0 or OFF"
},
{
"code": null,
"e": 81796,
"s": 81780,
"text": "No syncs at all"
},
{
"code": null,
"e": 81808,
"s": 81796,
"text": "1 or NORMAL"
},
{
"code": null,
"e": 81861,
"s": 81808,
"text": "Sync after each sequence of critical disk operations"
},
{
"code": null,
"e": 81871,
"s": 81861,
"text": "2 or FULL"
},
{
"code": null,
"e": 81911,
"s": 81871,
"text": "Sync after each critical disk operation"
},
{
"code": null,
"e": 82029,
"s": 81911,
"text": "The temp_store pragma gets or sets the storage mode used by temporary database files. Following is the simple syntax."
},
{
"code": null,
"e": 82075,
"s": 82029,
"text": "PRAGMA temp_store;\nPRAGMA temp_store = mode;\n"
},
{
"code": null,
"e": 82120,
"s": 82075,
"text": "SQLite supports the following storage modes."
},
{
"code": null,
"e": 82133,
"s": 82120,
"text": "0 or DEFAULT"
},
{
"code": null,
"e": 82174,
"s": 82133,
"text": "Use compile-time default. Normally FILE."
},
{
"code": null,
"e": 82184,
"s": 82174,
"text": "1 or FILE"
},
{
"code": null,
"e": 82208,
"s": 82184,
"text": "Use file-based storage."
},
{
"code": null,
"e": 82220,
"s": 82208,
"text": "2 or MEMORY"
},
{
"code": null,
"e": 82246,
"s": 82220,
"text": "Use memory-based storage."
},
{
"code": null,
"e": 82371,
"s": 82246,
"text": "The temp_store_directory pragma gets or sets the location used for temporary database files. Following is the simple syntax."
},
{
"code": null,
"e": 82449,
"s": 82371,
"text": "PRAGMA temp_store_directory;\nPRAGMA temp_store_directory = 'directory_path';\n"
},
{
"code": null,
"e": 82588,
"s": 82449,
"text": "The user_version pragma gets or sets the user-defined version value that is stored in the database header. Following is the simple syntax."
},
{
"code": null,
"e": 82662,
"s": 82588,
"text": "PRAGMA [database.]user_version;\nPRAGMA [database.]user_version = number;\n"
},
{
"code": null,
"e": 82765,
"s": 82662,
"text": "This is a 32-bit signed integer value, which can be set by the developer for version tracking purpose."
},
{
"code": null,
"e": 82874,
"s": 82765,
"text": "The writable_schema pragma gets or sets the ability to modify system tables. Following is the simple syntax."
},
{
"code": null,
"e": 82938,
"s": 82874,
"text": "PRAGMA writable_schema;\nPRAGMA writable_schema = [true|false];\n"
},
{
"code": null,
"e": 83139,
"s": 82938,
"text": "If this pragma is set, tables that start with sqlite_ can be created and modified, including the sqlite_master table. Be careful while using pragma because it can lead to complete database corruption."
},
{
"code": null,
"e": 83341,
"s": 83139,
"text": "Constraints are the rules enforced on a data columns on table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database. "
},
{
"code": null,
"e": 83512,
"s": 83341,
"text": "Constraints could be column level or table level. Column level constraints are applied only to one column, whereas table level constraints are applied to the whole table."
},
{
"code": null,
"e": 83573,
"s": 83512,
"text": "Following are commonly used constraints available in SQLite."
},
{
"code": null,
"e": 83641,
"s": 83573,
"text": "NOT NULL Constraint − Ensures that a column cannot have NULL value."
},
{
"code": null,
"e": 83709,
"s": 83641,
"text": "NOT NULL Constraint − Ensures that a column cannot have NULL value."
},
{
"code": null,
"e": 83793,
"s": 83709,
"text": "DEFAULT Constraint − Provides a default value for a column when none is specified."
},
{
"code": null,
"e": 83877,
"s": 83793,
"text": "DEFAULT Constraint − Provides a default value for a column when none is specified."
},
{
"code": null,
"e": 83948,
"s": 83877,
"text": "UNIQUE Constraint − Ensures that all values in a column are different."
},
{
"code": null,
"e": 84019,
"s": 83948,
"text": "UNIQUE Constraint − Ensures that all values in a column are different."
},
{
"code": null,
"e": 84090,
"s": 84019,
"text": "PRIMARY Key − Uniquely identifies each row/record in a database table."
},
{
"code": null,
"e": 84161,
"s": 84090,
"text": "PRIMARY Key − Uniquely identifies each row/record in a database table."
},
{
"code": null,
"e": 84247,
"s": 84161,
"text": "CHECK Constraint − Ensures that all values in a column satisfies certain conditions. "
},
{
"code": null,
"e": 84333,
"s": 84247,
"text": "CHECK Constraint − Ensures that all values in a column satisfies certain conditions. "
},
{
"code": null,
"e": 84538,
"s": 84333,
"text": "By default, a column can hold NULL values. If you do not want a column to have a NULL value, then you need to define such constraint on this column specifying that NULL is now not allowed for that column."
},
{
"code": null,
"e": 84609,
"s": 84538,
"text": "A NULL is not the same as no data, rather, it represents unknown data."
},
{
"code": null,
"e": 84779,
"s": 84609,
"text": "For example, the following SQLite statement creates a new table called COMPANY and adds five columns, three of which, ID and NAME and AGE, specifies not to accept NULLs."
},
{
"code": null,
"e": 84963,
"s": 84779,
"text": "CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);"
},
{
"code": null,
"e": 85089,
"s": 84963,
"text": "The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not provide a specific value."
},
{
"code": null,
"e": 85372,
"s": 85089,
"text": "For example, the following SQLite statement creates a new table called COMPANY and adds five columns. Here, SALARY column is set to 5000.00 by default, thus in case INSERT INTO statement does not provide a value for this column, then by default, this column would be set to 5000.00."
},
{
"code": null,
"e": 85576,
"s": 85372,
"text": "CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL DEFAULT 50000.00\n);"
},
{
"code": null,
"e": 85782,
"s": 85576,
"text": "The UNIQUE Constraint prevents two records from having identical values in a particular column. In the COMPANY table, for example, you might want to prevent two or more people from having an identical age."
},
{
"code": null,
"e": 85975,
"s": 85782,
"text": "For example, the following SQLite statement creates a new table called COMPANY and adds five columns. Here, AGE column is set to UNIQUE, so that you cannot have two records with the same age −"
},
{
"code": null,
"e": 86186,
"s": 85975,
"text": "CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL UNIQUE,\n ADDRESS CHAR(50),\n SALARY REAL DEFAULT 50000.00\n);"
},
{
"code": null,
"e": 86429,
"s": 86186,
"text": "The PRIMARY KEY constraint uniquely identifies each record in a database table. There can be more UNIQUE columns, but only one primary key in a table. Primary keys are important when designing the database tables. Primary keys are unique IDs."
},
{
"code": null,
"e": 86675,
"s": 86429,
"text": " We use them to refer to table rows. Primary keys become foreign keys in other tables, when creating relations among tables. Due to a 'longstanding coding oversight', primary keys can be NULL in SQLite. This is not the case with other databases."
},
{
"code": null,
"e": 86863,
"s": 86675,
"text": "A primary key is a field in a table which uniquely identifies each rows/records in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values."
},
{
"code": null,
"e": 87031,
"s": 86863,
"text": "A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key."
},
{
"code": null,
"e": 87158,
"s": 87031,
"text": "If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s)."
},
{
"code": null,
"e": 87265,
"s": 87158,
"text": "You already have seen various examples above where we have created COMPANY table with ID as a primary key."
},
{
"code": null,
"e": 87449,
"s": 87265,
"text": "CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);"
},
{
"code": null,
"e": 87640,
"s": 87449,
"text": "CHECK Constraint enables a condition to check the value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn't entered into the table."
},
{
"code": null,
"e": 87814,
"s": 87640,
"text": "For example, the following SQLite creates a new table called COMPANY and adds five columns. Here, we add a CHECK with SALARY column, so that you cannot have any SALARY Zero."
},
{
"code": null,
"e": 88020,
"s": 87814,
"text": "CREATE TABLE COMPANY3(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL CHECK(SALARY > 0)\n);"
},
{
"code": null,
"e": 88278,
"s": 88020,
"text": "SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table."
},
{
"code": null,
"e": 88451,
"s": 88278,
"text": "SQLite Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each."
},
{
"code": null,
"e": 88492,
"s": 88451,
"text": "SQL defines three major types of joins −"
},
{
"code": null,
"e": 88507,
"s": 88492,
"text": "The CROSS JOIN"
},
{
"code": null,
"e": 88522,
"s": 88507,
"text": "The INNER JOIN"
},
{
"code": null,
"e": 88537,
"s": 88522,
"text": "The OUTER JOIN"
},
{
"code": null,
"e": 88742,
"s": 88537,
"text": "Before we proceed, let's consider two tables COMPANY and DEPARTMENT. We already have seen INSERT statements to populate COMPANY table. So just let's assume the list of records available in COMPANY table −"
},
{
"code": null,
"e": 89248,
"s": 88742,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 89308,
"s": 89248,
"text": "Another table is DEPARTMENT with the following definition −"
},
{
"code": null,
"e": 89446,
"s": 89308,
"text": "CREATE TABLE DEPARTMENT(\n ID INT PRIMARY KEY NOT NULL,\n DEPT CHAR(50) NOT NULL,\n EMP_ID INT NOT NULL\n);"
},
{
"code": null,
"e": 89515,
"s": 89446,
"text": "Here is the list of INSERT statements to populate DEPARTMENT table −"
},
{
"code": null,
"e": 89731,
"s": 89515,
"text": "INSERT INTO DEPARTMENT (ID, DEPT, EMP_ID)\nVALUES (1, 'IT Billing', 1 );\n\nINSERT INTO DEPARTMENT (ID, DEPT, EMP_ID)\nVALUES (2, 'Engineering', 2 );\n\nINSERT INTO DEPARTMENT (ID, DEPT, EMP_ID)\nVALUES (3, 'Finance', 7 );"
},
{
"code": null,
"e": 89810,
"s": 89731,
"text": "Finally, we have the following list of records available in DEPARTMENT table −"
},
{
"code": null,
"e": 89954,
"s": 89810,
"text": "ID DEPT EMP_ID\n---------- ---------- ----------\n1 IT Billing 1\n2 Engineering 2\n3 Finance 7"
},
{
"code": null,
"e": 90258,
"s": 89954,
"text": "CROSS JOIN matches every row of the first table with every row of the second table. If the input tables have x and y row, respectively, the resulting table will have x*y row. Because CROSS JOINs have the potential to generate extremely large tables, care must be taken to only use them when appropriate."
},
{
"code": null,
"e": 90298,
"s": 90258,
"text": "Following is the syntax of CROSS JOIN −"
},
{
"code": null,
"e": 90344,
"s": 90298,
"text": "SELECT ... FROM table1 CROSS JOIN table2 ...\n"
},
{
"code": null,
"e": 90411,
"s": 90344,
"text": "Based on the above tables, you can write a CROSS JOIN as follows −"
},
{
"code": null,
"e": 90481,
"s": 90411,
"text": "sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY CROSS JOIN DEPARTMENT;"
},
{
"code": null,
"e": 90533,
"s": 90481,
"text": "The above query will produce the following result −"
},
{
"code": null,
"e": 91319,
"s": 90533,
"text": "EMP_ID NAME DEPT\n---------- ---------- ----------\n1 Paul IT Billing\n2 Paul Engineering\n7 Paul Finance\n1 Allen IT Billing\n2 Allen Engineering\n7 Allen Finance\n1 Teddy IT Billing\n2 Teddy Engineering\n7 Teddy Finance\n1 Mark IT Billing\n2 Mark Engineering\n7 Mark Finance\n1 David IT Billing\n2 David Engineering\n7 David Finance\n1 Kim IT Billing\n2 Kim Engineering\n7 Kim Finance\n1 James IT Billing\n2 James Engineering\n7 James Finance\n"
},
{
"code": null,
"e": 91700,
"s": 91319,
"text": "INNER JOIN creates a new result table by combining column values of two tables (table1 and table2) based upon the join-predicate. The query compares each row of table1 with each row of table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, the column values for each matched pair of rows of A and B are combined into a result row."
},
{
"code": null,
"e": 91797,
"s": 91700,
"text": "An INNER JOIN is the most common and default type of join. You can use INNER keyword optionally."
},
{
"code": null,
"e": 91837,
"s": 91797,
"text": "Following is the syntax of INNER JOIN −"
},
{
"code": null,
"e": 91911,
"s": 91837,
"text": "SELECT ... FROM table1 [INNER] JOIN table2 ON conditional_expression ...\n"
},
{
"code": null,
"e": 92082,
"s": 91911,
"text": "To avoid redundancy and keep the phrasing shorter, INNER JOIN conditions can be declared with a USING expression. This expression specifies a list of one or more columns."
},
{
"code": null,
"e": 92144,
"s": 92082,
"text": "SELECT ... FROM table1 JOIN table2 USING ( column1 ,... ) ..."
},
{
"code": null,
"e": 92294,
"s": 92144,
"text": "A NATURAL JOIN is similar to a JOIN...USING, only it automatically tests for equality between the values of every column that exists in both tables −"
},
{
"code": null,
"e": 92340,
"s": 92294,
"text": "SELECT ... FROM table1 NATURAL JOIN table2..."
},
{
"code": null,
"e": 92408,
"s": 92340,
"text": "Based on the above tables, you can write an INNER JOIN as follows −"
},
{
"code": null,
"e": 92515,
"s": 92408,
"text": "sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID;"
},
{
"code": null,
"e": 92567,
"s": 92515,
"text": "The above query will produce the following result −"
},
{
"code": null,
"e": 92735,
"s": 92567,
"text": "EMP_ID NAME DEPT\n---------- ---------- ----------\n1 Paul IT Billing\n2 Allen Engineering\n7 James Finance\n"
},
{
"code": null,
"e": 92898,
"s": 92735,
"text": "OUTER JOIN is an extension of INNER JOIN. Though SQL standard defines three types of OUTER JOINs: LEFT, RIGHT, and FULL, SQLite only supports the LEFT OUTER JOIN."
},
{
"code": null,
"e": 93234,
"s": 92898,
"text": "OUTER JOINs have a condition that is identical to INNER JOINs, expressed using an ON, USING, or NATURAL keyword. The initial results table is calculated the same way. Once the primary JOIN is calculated, an OUTER JOIN will take any unjoined rows from one or both tables, pad them out with NULLs, and append them to the resulting table."
},
{
"code": null,
"e": 93279,
"s": 93234,
"text": "Following is the syntax of LEFT OUTER JOIN −"
},
{
"code": null,
"e": 93356,
"s": 93279,
"text": "SELECT ... FROM table1 LEFT OUTER JOIN table2 ON conditional_expression ...\n"
},
{
"code": null,
"e": 93527,
"s": 93356,
"text": "To avoid redundancy and keep the phrasing shorter, OUTER JOIN conditions can be declared with a USING expression. This expression specifies a list of one or more columns."
},
{
"code": null,
"e": 93600,
"s": 93527,
"text": "SELECT ... FROM table1 LEFT OUTER JOIN table2 USING ( column1 ,... ) ..."
},
{
"code": null,
"e": 93668,
"s": 93600,
"text": "Based on the above tables, you can write an outer join as follows −"
},
{
"code": null,
"e": 93780,
"s": 93668,
"text": "sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID;"
},
{
"code": null,
"e": 93832,
"s": 93780,
"text": "The above query will produce the following result −"
},
{
"code": null,
"e": 94069,
"s": 93832,
"text": "EMP_ID NAME DEPT\n---------- ---------- ----------\n1 Paul IT Billing\n2 Allen Engineering\n Teddy\n Mark\n David\n Kim\n7 James Finance\n"
},
{
"code": null,
"e": 94200,
"s": 94069,
"text": "SQLite UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows."
},
{
"code": null,
"e": 94412,
"s": 94200,
"text": "To use UNION, each SELECT must have the same number of columns selected, the same number of column expressions, the same data type, and have them in the same order, but they do not have to be of the same length."
},
{
"code": null,
"e": 94452,
"s": 94412,
"text": "Following is the basic syntax of UNION."
},
{
"code": null,
"e": 94601,
"s": 94452,
"text": "SELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n\nUNION\n\nSELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n"
},
{
"code": null,
"e": 94683,
"s": 94601,
"text": "Here the given condition could be any given expression based on your requirement."
},
{
"code": null,
"e": 94749,
"s": 94683,
"text": "Consider the following two tables, (a) COMPANY table as follows −"
},
{
"code": null,
"e": 95376,
"s": 94749,
"text": "sqlite> select * from COMPANY;\nID NAME AGE ADDRESS SALARY\n---------- -------------------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 95421,
"s": 95376,
"text": "(b) Another table is DEPARTMENT as follows −"
},
{
"code": null,
"e": 95759,
"s": 95421,
"text": "ID DEPT EMP_ID\n---------- -------------------- ----------\n1 IT Billing 1\n2 Engineering 2\n3 Finance 7\n4 Engineering 3\n5 Finance 4\n6 Engineering 5\n7 Finance 6"
},
{
"code": null,
"e": 95852,
"s": 95759,
"text": "Now let us join these two tables using SELECT statement along with UNION clause as follows −"
},
{
"code": null,
"e": 96119,
"s": 95852,
"text": "sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID\n \n UNION\n \n SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID;"
},
{
"code": null,
"e": 96159,
"s": 96119,
"text": "This will produce the following result."
},
{
"code": null,
"e": 96553,
"s": 96159,
"text": "EMP_ID NAME DEPT\n---------- -------------------- ----------\n1 Paul IT Billing\n2 Allen Engineering\n3 Teddy Engineering\n4 Mark Finance\n5 David Engineering\n6 Kim Finance\n7 James Finance\n"
},
{
"code": null,
"e": 96658,
"s": 96553,
"text": "The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows."
},
{
"code": null,
"e": 96734,
"s": 96658,
"text": "The same rules that apply to UNION apply to the UNION ALL operator as well."
},
{
"code": null,
"e": 96778,
"s": 96734,
"text": "Following is the basic syntax of UNION ALL."
},
{
"code": null,
"e": 96931,
"s": 96778,
"text": "SELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n\nUNION ALL\n\nSELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n"
},
{
"code": null,
"e": 97013,
"s": 96931,
"text": "Here the given condition could be any given expression based on your requirement."
},
{
"code": null,
"e": 97098,
"s": 97013,
"text": "Now, let us join the above-mentioned two tables in our SELECT statement as follows −"
},
{
"code": null,
"e": 97360,
"s": 97098,
"text": "sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID\n \n UNION ALL\n\n SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID;"
},
{
"code": null,
"e": 97400,
"s": 97360,
"text": "This will produce the following result."
},
{
"code": null,
"e": 98103,
"s": 97400,
"text": "EMP_ID NAME DEPT\n---------- -------------------- ----------\n1 Paul IT Billing\n2 Allen Engineering\n3 Teddy Engineering\n4 Mark Finance\n5 David Engineering\n6 Kim Finance\n7 James Finance\n1 Paul IT Billing\n2 Allen Engineering\n3 Teddy Engineering\n4 Mark Finance\n5 David Engineering\n6 Kim Finance\n7 James Finance\n"
},
{
"code": null,
"e": 98234,
"s": 98103,
"text": "SQLite NULL is the term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank."
},
{
"code": null,
"e": 98403,
"s": 98234,
"text": "A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different than a zero value or a field that contains spaces."
},
{
"code": null,
"e": 98471,
"s": 98403,
"text": "Following is the basic syntax of using NULL while creating a table."
},
{
"code": null,
"e": 98664,
"s": 98471,
"text": "SQLite> CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);\n"
},
{
"code": null,
"e": 98861,
"s": 98664,
"text": "Here, NOT NULL signifies that the column should always accept an explicit value of the given data type. There are two columns where we did not use NOT NULL which means these columns could be NULL."
},
{
"code": null,
"e": 98943,
"s": 98861,
"text": "A field with a NULL value is one that has been left blank during record creation."
},
{
"code": null,
"e": 99193,
"s": 98943,
"text": "The NULL value can cause problems when selecting data, because when comparing an unknown value to any other value, the result is always unknown and not included in the final results. Consider the following table, COMPANY with the following records −"
},
{
"code": null,
"e": 99699,
"s": 99193,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 99777,
"s": 99699,
"text": "Let us use UPDATE statement to set a few nullable values as NULL as follows −"
},
{
"code": null,
"e": 99852,
"s": 99777,
"text": "sqlite> UPDATE COMPANY SET ADDRESS = NULL, SALARY = NULL where ID IN(6,7);"
},
{
"code": null,
"e": 99904,
"s": 99852,
"text": "Now, COMPANY table will have the following records."
},
{
"code": null,
"e": 100352,
"s": 99904,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22\n7 James 24"
},
{
"code": null,
"e": 100458,
"s": 100352,
"text": "Next, let us see the usage of IS NOT NULL operator to list down all the records where SALARY is not NULL."
},
{
"code": null,
"e": 100560,
"s": 100458,
"text": "sqlite> SELECT ID, NAME, AGE, ADDRESS, SALARY\n FROM COMPANY\n WHERE SALARY IS NOT NULL;"
},
{
"code": null,
"e": 100623,
"s": 100560,
"text": "The above SQLite statement will produce the following result −"
},
{
"code": null,
"e": 101018,
"s": 100623,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n"
},
{
"code": null,
"e": 101121,
"s": 101018,
"text": "Following is the usage of IS NULL operator, which will list down all the records where SALARY is NULL."
},
{
"code": null,
"e": 101219,
"s": 101121,
"text": "sqlite> SELECT ID, NAME, AGE, ADDRESS, SALARY\n FROM COMPANY\n WHERE SALARY IS NULL;"
},
{
"code": null,
"e": 101281,
"s": 101219,
"text": "The above SQLite statement will produce the following result."
},
{
"code": null,
"e": 101450,
"s": 101281,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n6 Kim 22\n7 James 24\n"
},
{
"code": null,
"e": 101719,
"s": 101450,
"text": "You can rename a table or a column temporarily by giving another name, which is known as ALIAS. The use of table aliases means to rename a table in a particular SQLite statement. Renaming is a temporary change and the actual table name does not change in the database."
},
{
"code": null,
"e": 101821,
"s": 101719,
"text": "The column aliases are used to rename a table's columns for the purpose of a particular SQLite query."
},
{
"code": null,
"e": 101867,
"s": 101821,
"text": "Following is the basic syntax of table alias."
},
{
"code": null,
"e": 101945,
"s": 101867,
"text": "SELECT column1, column2....\nFROM table_name AS alias_name\nWHERE [condition];\n"
},
{
"code": null,
"e": 101992,
"s": 101945,
"text": "Following is the basic syntax of column alias."
},
{
"code": null,
"e": 102061,
"s": 101992,
"text": "SELECT column_name AS alias_name\nFROM table_name\nWHERE [condition];\n"
},
{
"code": null,
"e": 102130,
"s": 102061,
"text": "Consider the following two tables, (a) COMPANY table is as follows −"
},
{
"code": null,
"e": 102757,
"s": 102130,
"text": "sqlite> select * from COMPANY;\nID NAME AGE ADDRESS SALARY\n---------- -------------------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 102802,
"s": 102757,
"text": "(b) Another table is DEPARTMENT as follows −"
},
{
"code": null,
"e": 103140,
"s": 102802,
"text": "ID DEPT EMP_ID\n---------- -------------------- ----------\n1 IT Billing 1\n2 Engineering 2\n3 Finance 7\n4 Engineering 3\n5 Finance 4\n6 Engineering 5\n7 Finance 6"
},
{
"code": null,
"e": 103264,
"s": 103140,
"text": "Now, following is the usage of TABLE ALIAS where we use C and D as aliases for COMPANY and DEPARTMENT tables respectively −"
},
{
"code": null,
"e": 103382,
"s": 103264,
"text": "sqlite> SELECT C.ID, C.NAME, C.AGE, D.DEPT\n FROM COMPANY AS C, DEPARTMENT AS D\n WHERE C.ID = D.EMP_ID;"
},
{
"code": null,
"e": 103445,
"s": 103382,
"text": "The above SQLite statement will produce the following result −"
},
{
"code": null,
"e": 103857,
"s": 103445,
"text": "ID NAME AGE DEPT\n---------- ---------- ---------- ----------\n1 Paul 32 IT Billing\n2 Allen 25 Engineering\n3 Teddy 23 Engineering\n4 Mark 25 Finance\n5 David 27 Engineering\n6 Kim 22 Finance\n7 James 24 Finance\n"
},
{
"code": null,
"e": 103994,
"s": 103857,
"text": "Consider an example for the usage of COLUMN ALIAS where COMPANY_ID is an alias of ID column and COMPANY_NAME is an alias of name column."
},
{
"code": null,
"e": 104142,
"s": 103994,
"text": "sqlite> SELECT C.ID AS COMPANY_ID, C.NAME AS COMPANY_NAME, C.AGE, D.DEPT\n FROM COMPANY AS C, DEPARTMENT AS D\n WHERE C.ID = D.EMP_ID;"
},
{
"code": null,
"e": 104205,
"s": 104142,
"text": "The above SQLite statement will produce the following result −"
},
{
"code": null,
"e": 104635,
"s": 104205,
"text": "COMPANY_ID COMPANY_NAME AGE DEPT\n---------- ------------ ---------- ----------\n1 Paul 32 IT Billing\n2 Allen 25 Engineering\n3 Teddy 23 Engineering\n4 Mark 25 Finance\n5 David 27 Engineering\n6 Kim 22 Finance\n7 James 24 Finance\n"
},
{
"code": null,
"e": 104825,
"s": 104635,
"text": "SQLite Triggers are database callback functions, which are automatically performed/invoked when a specified database event occurs. Following are the important points about SQLite triggers −"
},
{
"code": null,
"e": 105013,
"s": 104825,
"text": "SQLite trigger may be specified to fire whenever a DELETE, INSERT or UPDATE of a particular database table occurs or whenever an UPDATE occurs on one or more specified columns of a table."
},
{
"code": null,
"e": 105201,
"s": 105013,
"text": "SQLite trigger may be specified to fire whenever a DELETE, INSERT or UPDATE of a particular database table occurs or whenever an UPDATE occurs on one or more specified columns of a table."
},
{
"code": null,
"e": 105347,
"s": 105201,
"text": "At this time, SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers. Hence, explicitly specifying FOR EACH ROW is optional."
},
{
"code": null,
"e": 105493,
"s": 105347,
"text": "At this time, SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers. Hence, explicitly specifying FOR EACH ROW is optional."
},
{
"code": null,
"e": 105765,
"s": 105493,
"text": "Both the WHEN clause and the trigger actions may access elements of the row being inserted, deleted, or updated using references of the form NEW.column-name and OLD.column-name, where column-name is the name of a column from the table that the trigger is associated with."
},
{
"code": null,
"e": 106037,
"s": 105765,
"text": "Both the WHEN clause and the trigger actions may access elements of the row being inserted, deleted, or updated using references of the form NEW.column-name and OLD.column-name, where column-name is the name of a column from the table that the trigger is associated with."
},
{
"code": null,
"e": 106235,
"s": 106037,
"text": "If a WHEN clause is supplied, the SQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the SQL statements are executed for all rows."
},
{
"code": null,
"e": 106433,
"s": 106235,
"text": "If a WHEN clause is supplied, the SQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the SQL statements are executed for all rows."
},
{
"code": null,
"e": 106589,
"s": 106433,
"text": "The BEFORE or AFTER keyword determines when the trigger actions will be executed relative to the insertion, modification, or removal of the associated row."
},
{
"code": null,
"e": 106745,
"s": 106589,
"text": "The BEFORE or AFTER keyword determines when the trigger actions will be executed relative to the insertion, modification, or removal of the associated row."
},
{
"code": null,
"e": 106837,
"s": 106745,
"text": "Triggers are automatically dropped when the table that they are associated with is dropped."
},
{
"code": null,
"e": 106929,
"s": 106837,
"text": "Triggers are automatically dropped when the table that they are associated with is dropped."
},
{
"code": null,
"e": 107096,
"s": 106929,
"text": "The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just tablename not database.tablename."
},
{
"code": null,
"e": 107263,
"s": 107096,
"text": "The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just tablename not database.tablename."
},
{
"code": null,
"e": 107354,
"s": 107263,
"text": "A special SQL function RAISE() may be used within a trigger-program to raise an exception."
},
{
"code": null,
"e": 107445,
"s": 107354,
"text": "A special SQL function RAISE() may be used within a trigger-program to raise an exception."
},
{
"code": null,
"e": 107498,
"s": 107445,
"text": "Following is the basic syntax of creating a trigger."
},
{
"code": null,
"e": 107611,
"s": 107498,
"text": "CREATE TRIGGER trigger_name [BEFORE|AFTER] event_name \nON table_name\nBEGIN\n -- Trigger logic goes here....\nEND;\n"
},
{
"code": null,
"e": 107776,
"s": 107611,
"text": "Here, event_name could be INSERT, DELETE, and UPDATE database operation on the mentioned table table_name. You can optionally specify FOR EACH ROW after table name."
},
{
"code": null,
"e": 107891,
"s": 107776,
"text": "Following is the syntax for creating a trigger on an UPDATE operation on one or more specified columns of a table."
},
{
"code": null,
"e": 108017,
"s": 107891,
"text": "CREATE TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_name \nON table_name\nBEGIN\n -- Trigger logic goes here....\nEND;\n"
},
{
"code": null,
"e": 108202,
"s": 108017,
"text": "Let us consider a case where we want to keep audit trial for every record being inserted in COMPANY table, which we create newly as follows (Drop COMPANY table if you already have it)."
},
{
"code": null,
"e": 108394,
"s": 108202,
"text": "sqlite> CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);"
},
{
"code": null,
"e": 108558,
"s": 108394,
"text": "To keep audit trial, we will create a new table called AUDIT where the log messages will be inserted, whenever there is an entry in COMPANY table for a new record."
},
{
"code": null,
"e": 108641,
"s": 108558,
"text": "sqlite> CREATE TABLE AUDIT(\n EMP_ID INT NOT NULL,\n ENTRY_DATE TEXT NOT NULL\n);"
},
{
"code": null,
"e": 108866,
"s": 108641,
"text": "Here, ID is the AUDIT record ID, and EMP_ID is the ID which will come from COMPANY table and DATE will keep timestamp when the record will be created in COMPANY table. Now let's create a trigger on COMPANY table as follows −"
},
{
"code": null,
"e": 109010,
"s": 108866,
"text": "sqlite> CREATE TRIGGER audit_log AFTER INSERT \nON COMPANY\nBEGIN\n INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, datetime('now'));\nEND;"
},
{
"code": null,
"e": 109204,
"s": 109010,
"text": "Now, we will start actual work, Let's start inserting record in COMPANY table which should result in creating an audit log record in AUDIT table. Create one record in COMPANY table as follows −"
},
{
"code": null,
"e": 109310,
"s": 109204,
"text": "sqlite> INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (1, 'Paul', 32, 'California', 20000.00 );"
},
{
"code": null,
"e": 109378,
"s": 109310,
"text": "This will create one record in COMPANY table, which is as follows −"
},
{
"code": null,
"e": 109548,
"s": 109378,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0"
},
{
"code": null,
"e": 109802,
"s": 109548,
"text": "Same time, one record will be created in AUDIT table. This record is the result of a trigger, which we have created on INSERT operation in COMPANY table. Similarly, you can create your triggers on UPDATE and DELETE operations based on your requirements."
},
{
"code": null,
"e": 109889,
"s": 109802,
"text": "EMP_ID ENTRY_DATE\n---------- -------------------\n1 2013-04-05 06:26:00"
},
{
"code": null,
"e": 109962,
"s": 109889,
"text": "You can list down all the triggers from sqlite_master table as follows −"
},
{
"code": null,
"e": 110025,
"s": 109962,
"text": "sqlite> SELECT name FROM sqlite_master\nWHERE type = 'trigger';"
},
{
"code": null,
"e": 110095,
"s": 110025,
"text": "The above SQLite statement will list down only one entry as follows −"
},
{
"code": null,
"e": 110121,
"s": 110095,
"text": "name\n----------\naudit_log"
},
{
"code": null,
"e": 110227,
"s": 110121,
"text": "If you want to list down triggers on a particular table, then use AND clause with table name as follows −"
},
{
"code": null,
"e": 110315,
"s": 110227,
"text": "sqlite> SELECT name FROM sqlite_master\nWHERE type = 'trigger' AND tbl_name = 'COMPANY';"
},
{
"code": null,
"e": 110390,
"s": 110315,
"text": "The above SQLite statement will also list down only one entry as follows −"
},
{
"code": null,
"e": 110416,
"s": 110390,
"text": "name\n----------\naudit_log"
},
{
"code": null,
"e": 110494,
"s": 110416,
"text": "Following is the DROP command, which can be used to drop an existing trigger."
},
{
"code": null,
"e": 110529,
"s": 110494,
"text": "sqlite> DROP TRIGGER trigger_name;"
},
{
"code": null,
"e": 110759,
"s": 110529,
"text": "Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index in the back of a book."
},
{
"code": null,
"e": 110975,
"s": 110759,
"text": "For example, if you want to reference all pages in a book that discuss a certain topic, you first refer to the index, which lists all topics alphabetically and are then referred to one or more specific page numbers."
},
{
"code": null,
"e": 111160,
"s": 110975,
"text": "An index helps speed up SELECT queries and WHERE clauses, but it slows down data input, with UPDATE and INSERT statements. Indexes can be created or dropped with no effect on the data."
},
{
"code": null,
"e": 111384,
"s": 111160,
"text": "Creating an index involves the CREATE INDEX statement, which allows you to name the index, to specify the table and which column or columns to index, and to indicate whether the index is in an ascending or descending order."
},
{
"code": null,
"e": 111558,
"s": 111384,
"text": "Indexes can also be unique, similar to the UNIQUE constraint, in that the index prevents duplicate entries in the column or combination of columns on which there's an index."
},
{
"code": null,
"e": 111605,
"s": 111558,
"text": "Following is the basic syntax of CREATE INDEX."
},
{
"code": null,
"e": 111645,
"s": 111605,
"text": "CREATE INDEX index_name ON table_name;\n"
},
{
"code": null,
"e": 111755,
"s": 111645,
"text": "A single-column index is one that is created based on only one table column. The basic syntax is as follows −"
},
{
"code": null,
"e": 111809,
"s": 111755,
"text": "CREATE INDEX index_name\nON table_name (column_name);\n"
},
{
"code": null,
"e": 112003,
"s": 111809,
"text": "Unique indexes are used not only for performance, but also for data integrity. A unique index does not allow any duplicate values to be inserted into the table. The basic syntax is as follows −"
},
{
"code": null,
"e": 112064,
"s": 112003,
"text": "CREATE UNIQUE INDEX index_name\non table_name (column_name);\n"
},
{
"code": null,
"e": 112162,
"s": 112064,
"text": "A composite index is an index on two or more columns of a table. The basic syntax is as follows −"
},
{
"code": null,
"e": 112221,
"s": 112162,
"text": "CREATE INDEX index_name\non table_name (column1, column2);\n"
},
{
"code": null,
"e": 112402,
"s": 112221,
"text": "Whether to create a single-column index or a composite index, take into consideration the column(s) that you may use very frequently in a query's WHERE clause as filter conditions."
},
{
"code": null,
"e": 112623,
"s": 112402,
"text": "Should there be only one column used, a single-column index should be the choice. Should there be two or more columns that are frequently used in the WHERE clause as filters, the composite index would be the best choice."
},
{
"code": null,
"e": 112819,
"s": 112623,
"text": "Implicit indexes are indexes that are automatically created by the database server when an object is created. Indexes are automatically created for primary key constraints and unique constraints."
},
{
"code": null,
"e": 112827,
"s": 112819,
"text": "Example"
},
{
"code": null,
"e": 112918,
"s": 112827,
"text": "Following is an example where we will create an index in COMPANY table for salary column −"
},
{
"code": null,
"e": 112973,
"s": 112918,
"text": "sqlite> CREATE INDEX salary_index ON COMPANY (salary);"
},
{
"code": null,
"e": 113073,
"s": 112973,
"text": "Now, let's list down all the indices available in COMPANY table using .indices command as follows −"
},
{
"code": null,
"e": 113098,
"s": 113073,
"text": "sqlite> .indices COMPANY"
},
{
"code": null,
"e": 113245,
"s": 113098,
"text": "This will produce the following result, where sqlite_autoindex_COMPANY_1 is an implicit index which got created when the table itself was created."
},
{
"code": null,
"e": 113286,
"s": 113245,
"text": "salary_index\nsqlite_autoindex_COMPANY_1\n"
},
{
"code": null,
"e": 113347,
"s": 113286,
"text": "You can list down all the indexes database wide as follows −"
},
{
"code": null,
"e": 113405,
"s": 113347,
"text": "sqlite> SELECT * FROM sqlite_master WHERE type = 'index';"
},
{
"code": null,
"e": 113547,
"s": 113405,
"text": "An index can be dropped using SQLite DROP command. Care should be taken when dropping an index because performance may be slowed or improved."
},
{
"code": null,
"e": 113593,
"s": 113547,
"text": "Following is the basic syntax is as follows −"
},
{
"code": null,
"e": 113617,
"s": 113593,
"text": "DROP INDEX index_name;\n"
},
{
"code": null,
"e": 113689,
"s": 113617,
"text": "You can use the following statement to delete previously created index."
},
{
"code": null,
"e": 113722,
"s": 113689,
"text": "sqlite> DROP INDEX salary_index;"
},
{
"code": null,
"e": 113922,
"s": 113722,
"text": "Although indexes are intended to enhance the performance of a database, there are times when they should be avoided. The following guidelines indicate when the use of an index should be reconsidered."
},
{
"code": null,
"e": 113954,
"s": 113922,
"text": "Indexes should not be used in −"
},
{
"code": null,
"e": 113968,
"s": 113954,
"text": "Small tables."
},
{
"code": null,
"e": 114036,
"s": 113968,
"text": "Tables that have frequent, large batch update or insert operations."
},
{
"code": null,
"e": 114087,
"s": 114036,
"text": "Columns that contain a high number of NULL values."
},
{
"code": null,
"e": 114128,
"s": 114087,
"text": "Columns that are frequently manipulated."
},
{
"code": null,
"e": 114258,
"s": 114128,
"text": "The \"INDEXED BY index-name\" clause specifies that the named index must be used in order to look up values on the preceding table."
},
{
"code": null,
"e": 114374,
"s": 114258,
"text": " If index-name does not exist or cannot be used for the query, then the preparation of the SQLite statement fails. "
},
{
"code": null,
"e": 114546,
"s": 114374,
"text": "The \"NOT INDEXED\" clause specifies that no index shall be used when accessing the preceding table, including implied indices created by UNIQUE and PRIMARY KEY constraints."
},
{
"code": null,
"e": 114654,
"s": 114546,
"text": "However, the INTEGER PRIMARY KEY can still be used to look up entries even when \"NOT INDEXED\" is specified."
},
{
"code": null,
"e": 114760,
"s": 114654,
"text": "Following is the syntax for INDEXED BY clause and it can be used with DELETE, UPDATE or SELECT statement."
},
{
"code": null,
"e": 114856,
"s": 114760,
"text": "SELECT|DELETE|UPDATE column1, column2...\nINDEXED BY (index_name)\ntable_name\nWHERE (CONDITION);\n"
},
{
"code": null,
"e": 114951,
"s": 114856,
"text": "Consider table COMPANY We will create an index and use it for performing INDEXED BY operation."
},
{
"code": null,
"e": 115013,
"s": 114951,
"text": "sqlite> CREATE INDEX salary_index ON COMPANY(salary);\nsqlite>"
},
{
"code": null,
"e": 115098,
"s": 115013,
"text": "Now selecting the data from table COMPANY you can use INDEXED BY clause as follows −"
},
{
"code": null,
"e": 115173,
"s": 115098,
"text": "sqlite> SELECT * FROM COMPANY INDEXED BY salary_index WHERE salary > 5000;"
},
{
"code": null,
"e": 115213,
"s": 115173,
"text": "This will produce the following result."
},
{
"code": null,
"e": 115720,
"s": 115213,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n7 James 24 Houston 10000.0\n2 Allen 25 Texas 15000.0\n1 Paul 32 California 20000.0\n3 Teddy 23 Norway 20000.0\n6 Kim 22 South-Hall 45000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n"
},
{
"code": null,
"e": 115966,
"s": 115720,
"text": "SQLite ALTER TABLE command modifies an existing table without performing a full dump and reload of the data. You can rename a table using ALTER TABLE statement and additional columns can be added in an existing table using ALTER TABLE statement."
},
{
"code": null,
"e": 116103,
"s": 115966,
"text": "There is no other operation supported by ALTER TABLE command in SQLite except renaming a table and adding a column in an existing table."
},
{
"code": null,
"e": 116177,
"s": 116103,
"text": "Following is the basic syntax of ALTER TABLE to RENAME an existing table."
},
{
"code": null,
"e": 116241,
"s": 116177,
"text": "ALTER TABLE database_name.table_name RENAME TO new_table_name;\n"
},
{
"code": null,
"e": 116328,
"s": 116241,
"text": "Following is the basic syntax of ALTER TABLE to add a new column in an existing table."
},
{
"code": null,
"e": 116392,
"s": 116328,
"text": "ALTER TABLE database_name.table_name ADD COLUMN column_def...;\n"
},
{
"code": null,
"e": 116448,
"s": 116392,
"text": "Consider the COMPANY table with the following records −"
},
{
"code": null,
"e": 116954,
"s": 116448,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 117031,
"s": 116954,
"text": "Now, let's try to rename this table using ALTER TABLE statement as follows −"
},
{
"code": null,
"e": 117082,
"s": 117031,
"text": "sqlite> ALTER TABLE COMPANY RENAME TO OLD_COMPANY;"
},
{
"code": null,
"e": 117220,
"s": 117082,
"text": "The above SQLite statement will rename COMPANY table to OLD_COMPANY. Now, let's try to add a new column in OLD_COMPANY table as follows −"
},
{
"code": null,
"e": 117276,
"s": 117220,
"text": "sqlite> ALTER TABLE OLD_COMPANY ADD COLUMN SEX char(1);"
},
{
"code": null,
"e": 117361,
"s": 117276,
"text": "COMPANY table is now changed and following will be the output from SELECT statement."
},
{
"code": null,
"e": 117881,
"s": 117361,
"text": "ID NAME AGE ADDRESS SALARY SEX\n---------- ---------- ---------- ---------- ---------- ---\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 117952,
"s": 117881,
"text": "It should be noted that newly added column is filled with NULL values."
},
{
"code": null,
"e": 118209,
"s": 117952,
"text": "Unfortunately, we do not have TRUNCATE TABLE command in SQLite but you can use SQLite DELETE command to delete complete data from an existing table, though it is recommended to use DROP TABLE command to drop the complete table and re-create it once again."
},
{
"code": null,
"e": 118258,
"s": 118209,
"text": "Following is the basic syntax of DELETE command."
},
{
"code": null,
"e": 118291,
"s": 118258,
"text": "sqlite> DELETE FROM table_name;\n"
},
{
"code": null,
"e": 118336,
"s": 118291,
"text": "Following is the basic syntax of DROP TABLE."
},
{
"code": null,
"e": 118368,
"s": 118336,
"text": "sqlite> DROP TABLE table_name;\n"
},
{
"code": null,
"e": 118496,
"s": 118368,
"text": "If you are using DELETE TABLE command to delete all the records, it is recommended to use VACUUM command to clear unused space."
},
{
"code": null,
"e": 118547,
"s": 118496,
"text": "Consider COMPANY table with the following records."
},
{
"code": null,
"e": 119053,
"s": 118547,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 119108,
"s": 119053,
"text": "Following is the example to truncate the above table −"
},
{
"code": null,
"e": 119153,
"s": 119108,
"text": "SQLite> DELETE FROM COMPANY;\nSQLite> VACUUM;"
},
{
"code": null,
"e": 119250,
"s": 119153,
"text": "Now, COMPANY table is truncated completely and nothing will be the output from SELECT statement."
},
{
"code": null,
"e": 119435,
"s": 119250,
"text": "A view is nothing more than a SQLite statement that is stored in the database with an associated name. It is actually a composition of a table in the form of a predefined SQLite query."
},
{
"code": null,
"e": 119622,
"s": 119435,
"text": "A view can contain all rows of a table or selected rows from one or more tables. A view can be created from one or many tables which depends on the written SQLite query to create a view."
},
{
"code": null,
"e": 119683,
"s": 119622,
"text": "Views which are kind of virtual tables, allow the users to −"
},
{
"code": null,
"e": 119765,
"s": 119683,
"text": "Structure data in a way that users or classes of users find natural or intuitive."
},
{
"code": null,
"e": 119847,
"s": 119765,
"text": "Structure data in a way that users or classes of users find natural or intuitive."
},
{
"code": null,
"e": 119947,
"s": 119847,
"text": "Restrict access to the data such that a user can only see limited data instead of a complete table."
},
{
"code": null,
"e": 120047,
"s": 119947,
"text": "Restrict access to the data such that a user can only see limited data instead of a complete table."
},
{
"code": null,
"e": 120122,
"s": 120047,
"text": "Summarize data from various tables, which can be used to generate reports."
},
{
"code": null,
"e": 120197,
"s": 120122,
"text": "Summarize data from various tables, which can be used to generate reports."
},
{
"code": null,
"e": 120466,
"s": 120197,
"text": "SQLite views are read-only and thus you may not be able to execute a DELETE, INSERT or UPDATE statement on a view. However, you can create a trigger on a view that fires on an attempt to DELETE, INSERT, or UPDATE a view and do what you need in the body of the trigger."
},
{
"code": null,
"e": 120607,
"s": 120466,
"text": "SQLite views are created using the CREATE VIEW statement. SQLite views can be created from a single table, multiple tables, or another view."
},
{
"code": null,
"e": 120650,
"s": 120607,
"text": "Following is the basic CREATE VIEW syntax."
},
{
"code": null,
"e": 120759,
"s": 120650,
"text": "CREATE [TEMP | TEMPORARY] VIEW view_name AS\nSELECT column1, column2.....\nFROM table_name\nWHERE [condition];\n"
},
{
"code": null,
"e": 120980,
"s": 120759,
"text": "You can include multiple tables in your SELECT statement in a similar way as you use them in a normal SQL SELECT query. If the optional TEMP or TEMPORARY keyword is present, the view will be created in the temp database."
},
{
"code": null,
"e": 121032,
"s": 120980,
"text": "Consider COMPANY table with the following records −"
},
{
"code": null,
"e": 121538,
"s": 121032,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 121669,
"s": 121538,
"text": "Following is an example to create a view from COMPANY table. This view will be used to have only a few columns from COMPANY table."
},
{
"code": null,
"e": 121741,
"s": 121669,
"text": "sqlite> CREATE VIEW COMPANY_VIEW AS\nSELECT ID, NAME, AGE\nFROM COMPANY;"
},
{
"code": null,
"e": 121845,
"s": 121741,
"text": "You can now query COMPANY_VIEW in a similar way as you query an actual table. Following is an example −"
},
{
"code": null,
"e": 121881,
"s": 121845,
"text": "sqlite> SELECT * FROM COMPANY_VIEW;"
},
{
"code": null,
"e": 121921,
"s": 121881,
"text": "This will produce the following result."
},
{
"code": null,
"e": 122174,
"s": 121921,
"text": "ID NAME AGE\n---------- ---------- ----------\n1 Paul 32\n2 Allen 25\n3 Teddy 23\n4 Mark 25\n5 David 27\n6 Kim 22\n7 James 24\n"
},
{
"code": null,
"e": 122288,
"s": 122174,
"text": "To drop a view, simply use the DROP VIEW statement with the view_name. The basic DROP VIEW syntax is as follows −"
},
{
"code": null,
"e": 122318,
"s": 122288,
"text": "sqlite> DROP VIEW view_name;\n"
},
{
"code": null,
"e": 122409,
"s": 122318,
"text": "The following command will delete COMPANY_VIEW view, which we created in the last section."
},
{
"code": null,
"e": 122441,
"s": 122409,
"text": "sqlite> DROP VIEW COMPANY_VIEW;"
},
{
"code": null,
"e": 122679,
"s": 122441,
"text": "A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program."
},
{
"code": null,
"e": 122979,
"s": 122679,
"text": "A transaction is the propagation of one or more changes to the database. For example, if you are creating, updating, or deleting a record from the table, then you are performing transaction on the table. It is important to control transactions to ensure data integrity and to handle database errors."
},
{
"code": null,
"e": 123107,
"s": 122979,
"text": "Practically, you will club many SQLite queries into a group and you will execute all of them together as part of a transaction."
},
{
"code": null,
"e": 123206,
"s": 123107,
"text": "Transactions have the following four standard properties, usually referred to by the acronym ACID."
},
{
"code": null,
"e": 123420,
"s": 123206,
"text": "Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state."
},
{
"code": null,
"e": 123634,
"s": 123420,
"text": "Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state."
},
{
"code": null,
"e": 123741,
"s": 123634,
"text": "Consistency − Ensures that the database properly changes states upon a successfully committed transaction."
},
{
"code": null,
"e": 123848,
"s": 123741,
"text": "Consistency − Ensures that the database properly changes states upon a successfully committed transaction."
},
{
"code": null,
"e": 123940,
"s": 123848,
"text": "Isolation − Enables transactions to operate independently of and transparent to each other."
},
{
"code": null,
"e": 124032,
"s": 123940,
"text": "Isolation − Enables transactions to operate independently of and transparent to each other."
},
{
"code": null,
"e": 124144,
"s": 124032,
"text": "Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure."
},
{
"code": null,
"e": 124256,
"s": 124144,
"text": "Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure."
},
{
"code": null,
"e": 124323,
"s": 124256,
"text": "Following are the following commands used to control transactions:"
},
{
"code": null,
"e": 124367,
"s": 124323,
"text": "BEGIN TRANSACTION − To start a transaction."
},
{
"code": null,
"e": 124411,
"s": 124367,
"text": "BEGIN TRANSACTION − To start a transaction."
},
{
"code": null,
"e": 124492,
"s": 124411,
"text": "COMMIT − To save the changes, alternatively you can use END TRANSACTION command."
},
{
"code": null,
"e": 124573,
"s": 124492,
"text": "COMMIT − To save the changes, alternatively you can use END TRANSACTION command."
},
{
"code": null,
"e": 124609,
"s": 124573,
"text": "ROLLBACK − To rollback the changes."
},
{
"code": null,
"e": 124645,
"s": 124609,
"text": "ROLLBACK − To rollback the changes."
},
{
"code": null,
"e": 124865,
"s": 124645,
"text": "Transactional control commands are only used with DML commands INSERT, UPDATE, and DELETE. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database."
},
{
"code": null,
"e": 125180,
"s": 124865,
"text": "Transactions can be started using BEGIN TRANSACTION or simply BEGIN command. Such transactions usually persist until the next COMMIT or ROLLBACK command is encountered. However, a transaction will also ROLLBACK if the database is closed or if an error occurs. Following is the simple syntax to start a transaction."
},
{
"code": null,
"e": 125211,
"s": 125180,
"text": "BEGIN;\nor \nBEGIN TRANSACTION;\n"
},
{
"code": null,
"e": 125318,
"s": 125211,
"text": "COMMIT command is the transactional command used to save changes invoked by a transaction to the database."
},
{
"code": null,
"e": 125415,
"s": 125318,
"text": "COMMIT command saves all transactions to the database since the last COMMIT or ROLLBACK command."
},
{
"code": null,
"e": 125459,
"s": 125415,
"text": "Following is the syntax for COMMIT command."
},
{
"code": null,
"e": 125488,
"s": 125459,
"text": "COMMIT;\nor\nEND TRANSACTION;\n"
},
{
"code": null,
"e": 125610,
"s": 125488,
"text": "ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database."
},
{
"code": null,
"e": 125719,
"s": 125610,
"text": "ROLLBACK command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued."
},
{
"code": null,
"e": 125765,
"s": 125719,
"text": "Following is the syntax for ROLLBACK command."
},
{
"code": null,
"e": 125776,
"s": 125765,
"text": "ROLLBACK;\n"
},
{
"code": null,
"e": 125784,
"s": 125776,
"text": "Example"
},
{
"code": null,
"e": 125835,
"s": 125784,
"text": "Consider COMPANY table with the following records."
},
{
"code": null,
"e": 126341,
"s": 125835,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 126475,
"s": 126341,
"text": "Now, let's start a transaction and delete records from the table having age = 25. Then, use ROLLBACK command to undo all the changes."
},
{
"code": null,
"e": 126552,
"s": 126475,
"text": "sqlite> BEGIN;\nsqlite> DELETE FROM COMPANY WHERE AGE = 25;\nsqlite> ROLLBACK;"
},
{
"code": null,
"e": 126622,
"s": 126552,
"text": "Now, if you check COMPANY table, it still has the following records −"
},
{
"code": null,
"e": 127128,
"s": 126622,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 127271,
"s": 127128,
"text": "Let's start another transaction and delete records from the table having age = 25 and finally we use COMMIT command to commit all the changes."
},
{
"code": null,
"e": 127346,
"s": 127271,
"text": "sqlite> BEGIN;\nsqlite> DELETE FROM COMPANY WHERE AGE = 25;\nsqlite> COMMIT;"
},
{
"code": null,
"e": 127414,
"s": 127346,
"text": "If you now check COMPANY table is still has the following records −"
},
{
"code": null,
"e": 127808,
"s": 127414,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n3 Teddy 23 Norway 20000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 127927,
"s": 127808,
"text": "A Subquery or Inner query or Nested query is a query within another SQLite query and embedded within the WHERE clause."
},
{
"code": null,
"e": 128058,
"s": 127927,
"text": "A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved."
},
{
"code": null,
"e": 128204,
"s": 128058,
"text": "Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators such as =, <, >, >=, <=, IN, BETWEEN, etc."
},
{
"code": null,
"e": 128256,
"s": 128204,
"text": "There are a few rules that subqueries must follow −"
},
{
"code": null,
"e": 128304,
"s": 128256,
"text": "Subqueries must be enclosed within parentheses."
},
{
"code": null,
"e": 128352,
"s": 128304,
"text": "Subqueries must be enclosed within parentheses."
},
{
"code": null,
"e": 128506,
"s": 128352,
"text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns."
},
{
"code": null,
"e": 128660,
"s": 128506,
"text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns."
},
{
"code": null,
"e": 128832,
"s": 128660,
"text": "An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery."
},
{
"code": null,
"e": 129004,
"s": 128832,
"text": "An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery."
},
{
"code": null,
"e": 129118,
"s": 129004,
"text": "Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator."
},
{
"code": null,
"e": 129232,
"s": 129118,
"text": "Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator."
},
{
"code": null,
"e": 129331,
"s": 129232,
"text": "BETWEEN operator cannot be used with a subquery; however, BETWEEN can be used within the subquery."
},
{
"code": null,
"e": 129430,
"s": 129331,
"text": "BETWEEN operator cannot be used with a subquery; however, BETWEEN can be used within the subquery."
},
{
"code": null,
"e": 129526,
"s": 129430,
"text": "Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −"
},
{
"code": null,
"e": 129699,
"s": 129526,
"text": "SELECT column_name [, column_name ]\nFROM table1 [, table2 ]\nWHERE column_name OPERATOR\n (SELECT column_name [, column_name ]\n FROM table1 [, table2 ]\n [WHERE])\n"
},
{
"code": null,
"e": 129750,
"s": 129699,
"text": "Consider COMPANY table with the following records."
},
{
"code": null,
"e": 130256,
"s": 129750,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 130321,
"s": 130256,
"text": "Now, let us check the following sub-query with SELECT statement."
},
{
"code": null,
"e": 130433,
"s": 130321,
"text": "sqlite> SELECT * \n FROM COMPANY \n WHERE ID IN (SELECT ID \n FROM COMPANY \n WHERE SALARY > 45000) ;"
},
{
"code": null,
"e": 130473,
"s": 130433,
"text": "This will produce the following result."
},
{
"code": null,
"e": 130700,
"s": 130473,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n"
},
{
"code": null,
"e": 130948,
"s": 130700,
"text": "Subqueries can also be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date, or number functions."
},
{
"code": null,
"e": 130994,
"s": 130948,
"text": "Following is the basic syntax is as follows −"
},
{
"code": null,
"e": 131135,
"s": 130994,
"text": "INSERT INTO table_name [ (column1 [, column2 ]) ]\n SELECT [ *|column1 [, column2 ]\n FROM table1 [, table2 ]\n [ WHERE VALUE OPERATOR ]\n"
},
{
"code": null,
"e": 131367,
"s": 131135,
"text": "Consider a table COMPANY_BKP with similar structure as COMPANY table and can be created using the same CREATE TABLE using COMPANY_BKP as the table name. To copy the complete COMPANY table into COMPANY_BKP, following is the syntax −"
},
{
"code": null,
"e": 131475,
"s": 131367,
"text": "sqlite> INSERT INTO COMPANY_BKP\n SELECT * FROM COMPANY \n WHERE ID IN (SELECT ID \n FROM COMPANY) ;\n"
},
{
"code": null,
"e": 131651,
"s": 131475,
"text": "The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement."
},
{
"code": null,
"e": 131697,
"s": 131651,
"text": "Following is the basic syntax is as follows −"
},
{
"code": null,
"e": 131826,
"s": 131697,
"text": "UPDATE table\nSET column_name = new_value\n[ WHERE OPERATOR [ VALUE ]\n (SELECT COLUMN_NAME\n FROM TABLE_NAME)\n [ WHERE) ]\n"
},
{
"code": null,
"e": 131908,
"s": 131826,
"text": "Assuming, we have COMPANY_BKP table available which is a backup of COMPANY table."
},
{
"code": null,
"e": 132037,
"s": 131908,
"text": "Following example updates SALARY by 0.50 times in COMPANY table for all the customers, whose AGE is greater than or equal to 27."
},
{
"code": null,
"e": 132160,
"s": 132037,
"text": "sqlite> UPDATE COMPANY\n SET SALARY = SALARY * 0.50\n WHERE AGE IN (SELECT AGE FROM COMPANY_BKP\n WHERE AGE >= 27 );"
},
{
"code": null,
"e": 132248,
"s": 132160,
"text": "This would impact two rows and finally COMPANY table would have the following records −"
},
{
"code": null,
"e": 132755,
"s": 132248,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 10000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 42500.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n"
},
{
"code": null,
"e": 132865,
"s": 132755,
"text": "Subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above."
},
{
"code": null,
"e": 132911,
"s": 132865,
"text": "Following is the basic syntax is as follows −"
},
{
"code": null,
"e": 133022,
"s": 132911,
"text": "DELETE FROM TABLE_NAME\n[ WHERE OPERATOR [ VALUE ]\n (SELECT COLUMN_NAME\n FROM TABLE_NAME)\n [ WHERE) ]\n"
},
{
"code": null,
"e": 133104,
"s": 133022,
"text": "Assuming, we have COMPANY_BKP table available which is a backup of COMPANY table."
},
{
"code": null,
"e": 133221,
"s": 133104,
"text": "Following example deletes records from COMPANY table for all the customers whose AGE is greater than or equal to 27."
},
{
"code": null,
"e": 133315,
"s": 133221,
"text": "sqlite> DELETE FROM COMPANY\n WHERE AGE IN (SELECT AGE FROM COMPANY_BKP\n WHERE AGE > 27 );"
},
{
"code": null,
"e": 133401,
"s": 133315,
"text": "This will impact two rows and finally COMPANY table will have the following records −"
},
{
"code": null,
"e": 133852,
"s": 133401,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 42500.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n"
},
{
"code": null,
"e": 134080,
"s": 133852,
"text": "SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto increment."
},
{
"code": null,
"e": 134143,
"s": 134080,
"text": "The keyword AUTOINCREMENT can be used with INTEGER field only."
},
{
"code": null,
"e": 134200,
"s": 134143,
"text": "The basic usage of AUTOINCREMENT keyword is as follows −"
},
{
"code": null,
"e": 134334,
"s": 134200,
"text": "CREATE TABLE table_name(\n column1 INTEGER AUTOINCREMENT,\n column2 datatype,\n column3 datatype,\n .....\n columnN datatype,\n);"
},
{
"code": null,
"e": 134384,
"s": 134334,
"text": "Consider COMPANY table to be created as follows −"
},
{
"code": null,
"e": 134585,
"s": 134384,
"text": "sqlite> CREATE TABLE COMPANY(\n ID INTEGER PRIMARY KEY AUTOINCREMENT,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);"
},
{
"code": null,
"e": 134640,
"s": 134585,
"text": "Now, insert the following records into table COMPANY −"
},
{
"code": null,
"e": 135282,
"s": 134640,
"text": "INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'Paul', 32, 'California', 20000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ('Allen', 25, 'Texas', 15000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ('Teddy', 23, 'Norway', 20000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'David', 27, 'Texas', 85000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'Kim', 22, 'South-Hall', 45000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'James', 24, 'Houston', 10000.00 );\n"
},
{
"code": null,
"e": 135377,
"s": 135282,
"text": "This will insert 7 tuples into the table COMPANY and COMPANY will have the following records −"
},
{
"code": null,
"e": 135883,
"s": 135377,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 136189,
"s": 135883,
"text": "If you take user input through a webpage and insert it into a SQLite database there's a chance that you have left yourself wide open for a security issue known as SQL Injection. In this chapter, you will learn how to help prevent this from happening and help you secure your scripts and SQLite statements."
},
{
"code": null,
"e": 136365,
"s": 136189,
"text": "Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a SQLite statement that you will unknowingly run on your database."
},
{
"code": null,
"e": 136647,
"s": 136365,
"text": "Never trust user provided data, process this data only after validation; as a rule, this is done by pattern matching. In the following example, the username is restricted to alphanumerical chars plus underscore and to a length between 8 and 20 chars - modify these rules as needed."
},
{
"code": null,
"e": 136873,
"s": 136647,
"text": "if (preg_match(\"/^\\w{8,20}$/\", $_GET['username'], $matches)){\n $db = new SQLiteDatabase('filename');\n $result = @$db->query(\"SELECT * FROM users WHERE username = $matches[0]\");\n} else {\n echo \"username not accepted\";\n}\n"
},
{
"code": null,
"e": 136925,
"s": 136873,
"text": "To demonstrate the problem, consider this excerpt −"
},
{
"code": null,
"e": 137027,
"s": 136925,
"text": "$name = \"Qadir'; DELETE FROM users;\";\n@$db->query(\"SELECT * FROM users WHERE username = '{$name}'\");\n"
},
{
"code": null,
"e": 137456,
"s": 137027,
"text": "The function call is supposed to retrieve a record from the users table where the name column matches the name specified by the user. Under normal circumstances, $name would only contain alphanumeric characters and perhaps spaces, such as the string ilia. However in this case, by appending an entirely new query to $name, the call to the database turns into a disaster: the injected DELETE query removes all records from users."
},
{
"code": null,
"e": 137776,
"s": 137456,
"text": "There are databases interfaces which do not permit query stacking or executing multiple queries in a single function call. If you try to stack queries, the call fails but SQLite and PostgreSQL, happily perform stacked queries, executing all of the queries provided in one string and creating a serious security problem."
},
{
"code": null,
"e": 137995,
"s": 137776,
"text": "You can handle all escape characters smartly in scripting languages like PERL and PHP. Programming language PHP provides the function string sqlite_escape_string() to escape input characters that are special to SQLite."
},
{
"code": null,
"e": 138140,
"s": 137995,
"text": "if (get_magic_quotes_gpc()) {\n $name = sqlite_escape_string($name);\n}\n$result = @$db->query(\"SELECT * FROM users WHERE username = '{$name}'\");"
},
{
"code": null,
"e": 138323,
"s": 138140,
"text": "Although the encoding makes it safe to insert the data, it will render simple text comparisons and LIKE clauses in your queries unusable for the columns that contain the binary data."
},
{
"code": null,
"e": 138463,
"s": 138323,
"text": "Note − addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data."
},
{
"code": null,
"e": 138603,
"s": 138463,
"text": "SQLite statement can be preceded by the keyword \"EXPLAIN\" or by the phrase \"EXPLAIN QUERY PLAN\" used for describing the details of a table."
},
{
"code": null,
"e": 138801,
"s": 138603,
"text": " Either modification causes the SQLite statement to behave as a query and to return information about how the SQLite statement would have operated if the EXPLAIN keyword or phrase had been omitted."
},
{
"code": null,
"e": 138911,
"s": 138801,
"text": "The output from EXPLAIN and EXPLAIN QUERY PLAN is intended for interactive analysis and troubleshooting only."
},
{
"code": null,
"e": 139021,
"s": 138911,
"text": "The output from EXPLAIN and EXPLAIN QUERY PLAN is intended for interactive analysis and troubleshooting only."
},
{
"code": null,
"e": 139117,
"s": 139021,
"text": "The details of the output format are subject to change from one release of SQLite to the next. "
},
{
"code": null,
"e": 139213,
"s": 139117,
"text": "The details of the output format are subject to change from one release of SQLite to the next. "
},
{
"code": null,
"e": 139341,
"s": 139213,
"text": "Applications should not use EXPLAIN or EXPLAIN QUERY PLAN since their exact behavior is variable and only partially documented."
},
{
"code": null,
"e": 139469,
"s": 139341,
"text": "Applications should not use EXPLAIN or EXPLAIN QUERY PLAN since their exact behavior is variable and only partially documented."
},
{
"code": null,
"e": 139504,
"s": 139469,
"text": "syntax for EXPLAIN is as follows −"
},
{
"code": null,
"e": 139528,
"s": 139504,
"text": "EXPLAIN [SQLite Query]\n"
},
{
"code": null,
"e": 139574,
"s": 139528,
"text": "syntax for EXPLAIN QUERY PLAN is as follows −"
},
{
"code": null,
"e": 139610,
"s": 139574,
"text": "EXPLAIN QUERY PLAN [SQLite Query]\n"
},
{
"code": null,
"e": 139662,
"s": 139610,
"text": "Consider COMPANY table with the following records −"
},
{
"code": null,
"e": 140168,
"s": 139662,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 140234,
"s": 140168,
"text": "Now, let us check the following sub-query with SELECT statement −"
},
{
"code": null,
"e": 140295,
"s": 140234,
"text": "sqlite> EXPLAIN SELECT * FROM COMPANY WHERE Salary >= 20000;"
},
{
"code": null,
"e": 140335,
"s": 140295,
"text": "This will produce the following result."
},
{
"code": null,
"e": 141344,
"s": 140335,
"text": "addr opcode p1 p2 p3\n---------- ---------- ---------- ---------- ----------\n0 Goto 0 19\n1 Integer 0 0\n2 OpenRead 0 8\n3 SetNumColu 0 5\n4 Rewind 0 17\n5 Column 0 4\n6 RealAffini 0 0\n7 Integer 20000 0\n8 Lt 357 16 collseq(BI\n9 Rowid 0 0\n10 Column 0 1\n11 Column 0 2\n12 Column 0 3\n13 Column 0 4\n14 RealAffini 0 0\n15 Callback 5 0\n16 Next 0 5\n17 Close 0 0\n18 Halt 0 0\n19 Transactio 0 0\n20 VerifyCook 0 38\n21 Goto 0 1\n22 Noop 0 0\n"
},
{
"code": null,
"e": 141420,
"s": 141344,
"text": "Now, let us check the following Explain Query Plan with SELECT statement −"
},
{
"code": null,
"e": 141600,
"s": 141420,
"text": "SQLite> EXPLAIN QUERY PLAN SELECT * FROM COMPANY WHERE Salary >= 20000;\n\norder from detail\n---------- ---------- -------------\n0 0 TABLE COMPANY"
},
{
"code": null,
"e": 141866,
"s": 141600,
"text": "VACUUM command cleans the main database by copying its contents to a temporary database file and reloading the original database file from the copy. This eliminates free pages, aligns table data to be contiguous, and otherwise cleans up the database file structure."
},
{
"code": null,
"e": 142081,
"s": 141866,
"text": "VACUUM command may change the ROWID of entries in tables that do not have an explicit INTEGER PRIMARY KEY. The VACUUM command only works on the main database. It is not possible to VACUUM an attached database file."
},
{
"code": null,
"e": 142338,
"s": 142081,
"text": "VACUUM command will fail if there is an active transaction. VACUUM command is a no-op for in-memory databases. As the VACUUM command rebuilds the database file from scratch, VACUUM can also be used to modify many database-specific configuration parameters."
},
{
"code": null,
"e": 142438,
"s": 142338,
"text": "Following is a simple syntax to issue a VACUUM command for the whole database from command prompt −"
},
{
"code": null,
"e": 142472,
"s": 142438,
"text": "$sqlite3 database_name \"VACUUM;\"\n"
},
{
"code": null,
"e": 142531,
"s": 142472,
"text": "You can run VACUUM from SQLite prompt as well as follows −"
},
{
"code": null,
"e": 142547,
"s": 142531,
"text": "sqlite> VACUUM;"
},
{
"code": null,
"e": 142606,
"s": 142547,
"text": "You can also run VACUUM on a particular table as follows −"
},
{
"code": null,
"e": 142633,
"s": 142606,
"text": "sqlite> VACUUM table_name;"
},
{
"code": null,
"e": 142921,
"s": 142633,
"text": "SQLite Auto-VACUUM does not do the same as VACUUM rather it only moves free pages to the end of the database thereby reducing the database size. By doing so it can significantly fragment the database while VACUUM ensures defragmentation. Hence, Auto-VACUUM just keeps the database small."
},
{
"code": null,
"e": 143018,
"s": 142921,
"text": "You can enable/disable SQLite auto-vacuuming by the following pragmas running at SQLite prompt −"
},
{
"code": null,
"e": 143233,
"s": 143018,
"text": "sqlite> PRAGMA auto_vacuum = NONE; -- 0 means disable auto vacuum\nsqlite> PRAGMA auto_vacuum = FULL; -- 1 means enable full auto vacuum\nsqlite> PRAGMA auto_vacuum = INCREMENTAL; -- 2 means enable incremental vacuum"
},
{
"code": null,
"e": 143326,
"s": 143233,
"text": "You can run the following command from the command prompt to check the auto-vacuum setting −"
},
{
"code": null,
"e": 143372,
"s": 143326,
"text": "$sqlite3 database_name \"PRAGMA auto_vacuum;\"\n"
},
{
"code": null,
"e": 143430,
"s": 143372,
"text": "SQLite supports five date and time functions as follows −"
},
{
"code": null,
"e": 143726,
"s": 143430,
"text": "All the above five date and time functions take a time string as an argument. The time string is followed by zero or more modifiers. The strftime() function also takes a format string as its first argument. Following section will give you detail on different types of time strings and modifiers."
},
{
"code": null,
"e": 143781,
"s": 143726,
"text": "A time string can be in any of the following formats −"
},
{
"code": null,
"e": 143858,
"s": 143781,
"text": "You can use the \"T\" as a literal character separating the date and the time."
},
{
"code": null,
"e": 144040,
"s": 143858,
"text": "The time string can be followed by zero or more modifiers that will alter date and/or time returned by any of the above five functions. Modifiers are applied from the left to right."
},
{
"code": null,
"e": 144085,
"s": 144040,
"text": "Following modifers are available in SQLite −"
},
{
"code": null,
"e": 144094,
"s": 144085,
"text": "NNN days"
},
{
"code": null,
"e": 144104,
"s": 144094,
"text": "NNN hours"
},
{
"code": null,
"e": 144116,
"s": 144104,
"text": "NNN minutes"
},
{
"code": null,
"e": 144133,
"s": 144116,
"text": "NNN.NNNN seconds"
},
{
"code": null,
"e": 144144,
"s": 144133,
"text": "NNN months"
},
{
"code": null,
"e": 144154,
"s": 144144,
"text": "NNN years"
},
{
"code": null,
"e": 144169,
"s": 144154,
"text": "start of month"
},
{
"code": null,
"e": 144183,
"s": 144169,
"text": "start of year"
},
{
"code": null,
"e": 144196,
"s": 144183,
"text": "start of day"
},
{
"code": null,
"e": 144206,
"s": 144196,
"text": "weekday N"
},
{
"code": null,
"e": 144216,
"s": 144206,
"text": "unixepoch"
},
{
"code": null,
"e": 144226,
"s": 144216,
"text": "localtime"
},
{
"code": null,
"e": 144230,
"s": 144226,
"text": "utc"
},
{
"code": null,
"e": 144378,
"s": 144230,
"text": "SQLite provides a very handy function strftime() to format any date and time. You can use the following substitutions to format your date and time."
},
{
"code": null,
"e": 144475,
"s": 144378,
"text": "Let's try various examples now using SQLite prompt. Following command computes the current date."
},
{
"code": null,
"e": 144514,
"s": 144475,
"text": "sqlite> SELECT date('now');\n2013-05-07"
},
{
"code": null,
"e": 144576,
"s": 144514,
"text": "Following command computes the last day of the current month."
},
{
"code": null,
"e": 144652,
"s": 144576,
"text": "sqlite> SELECT date('now','start of month','+1 month','-1 day');\n2013-05-31"
},
{
"code": null,
"e": 144736,
"s": 144652,
"text": "Following command computes the date and time for a given UNIX timestamp 1092941466."
},
{
"code": null,
"e": 144806,
"s": 144736,
"text": "sqlite> SELECT datetime(1092941466, 'unixepoch');\n2004-08-19 18:51:06"
},
{
"code": null,
"e": 144929,
"s": 144806,
"text": "Following command computes the date and time for a given UNIX timestamp 1092941466 and compensate for your local timezone."
},
{
"code": null,
"e": 145012,
"s": 144929,
"text": "sqlite> SELECT datetime(1092941466, 'unixepoch', 'localtime');\n2004-08-19 13:51:06"
},
{
"code": null,
"e": 145067,
"s": 145012,
"text": "Following command computes the current UNIX timestamp."
},
{
"code": null,
"e": 145115,
"s": 145067,
"text": "sqlite> SELECT strftime('%s','now');\n1393348134"
},
{
"code": null,
"e": 145218,
"s": 145115,
"text": "Following command computes the number of days since the signing of the US Declaration of Independence."
},
{
"code": null,
"e": 145294,
"s": 145218,
"text": "sqlite> SELECT julianday('now') - julianday('1776-07-04');\n86798.7094695023"
},
{
"code": null,
"e": 145378,
"s": 145294,
"text": "Following command computes the number of seconds since a particular moment in 2004."
},
{
"code": null,
"e": 145464,
"s": 145378,
"text": "sqlite> SELECT strftime('%s','now') - strftime('%s','2004-01-01 02:34:56');\n295001572"
},
{
"code": null,
"e": 145554,
"s": 145464,
"text": "Following command computes the date of the first Tuesday in October for the current year."
},
{
"code": null,
"e": 145633,
"s": 145554,
"text": "sqlite> SELECT date('now','start of year','+9 months','weekday 2');\n2013-10-01"
},
{
"code": null,
"e": 145762,
"s": 145633,
"text": "Following command computes the time since the UNIX epoch in seconds (like strftime('%s','now') except includes fractional part)."
},
{
"code": null,
"e": 145834,
"s": 145762,
"text": "sqlite> SELECT (julianday('now') - 2440587.5)*86400.0;\n1367926077.12598"
},
{
"code": null,
"e": 145951,
"s": 145834,
"text": "To convert between UTC and local time values when formatting a date, use the utc or localtime modifiers as follows −"
},
{
"code": null,
"e": 146003,
"s": 145951,
"text": "sqlite> SELECT time('12:00', 'localtime');\n05:00:00"
},
{
"code": null,
"e": 146049,
"s": 146003,
"text": "sqlite> SELECT time('12:00', 'utc');\n19:00:00"
},
{
"code": null,
"e": 146393,
"s": 146049,
"text": "SQLite has many built-in functions to perform processing on string or numeric data. Following is the list of few useful SQLite built-in functions and all are case in-sensitive which means you can use these functions either in lower-case form or in upper-case or in mixed form. For more details, you can check official documentation for SQLite."
},
{
"code": null,
"e": 146415,
"s": 146393,
"text": "SQLite COUNT Function"
},
{
"code": null,
"e": 146504,
"s": 146415,
"text": "SQLite COUNT aggregate function is used to count the number of rows in a database table."
},
{
"code": null,
"e": 146525,
"s": 146504,
"text": "SQLite MAX Function "
},
{
"code": null,
"e": 146625,
"s": 146525,
"text": "SQLite MAX aggregate function allows us to select the highest (maximum) value for a certain column."
},
{
"code": null,
"e": 146645,
"s": 146625,
"text": "SQLite MIN Function"
},
{
"code": null,
"e": 146744,
"s": 146645,
"text": "SQLite MIN aggregate function allows us to select the lowest (minimum) value for a certain column."
},
{
"code": null,
"e": 146765,
"s": 146744,
"text": "SQLite AVG Function "
},
{
"code": null,
"e": 146847,
"s": 146765,
"text": "SQLite AVG aggregate function selects the average value for certain table column."
},
{
"code": null,
"e": 146867,
"s": 146847,
"text": "SQLite SUM Function"
},
{
"code": null,
"e": 146946,
"s": 146867,
"text": "SQLite SUM aggregate function allows selecting the total for a numeric column."
},
{
"code": null,
"e": 146969,
"s": 146946,
"text": "SQLite RANDOM Function"
},
{
"code": null,
"e": 147079,
"s": 146969,
"text": "SQLite RANDOM function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807."
},
{
"code": null,
"e": 147099,
"s": 147079,
"text": "SQLite ABS Function"
},
{
"code": null,
"e": 147171,
"s": 147099,
"text": "SQLite ABS function returns the absolute value of the numeric argument."
},
{
"code": null,
"e": 147193,
"s": 147171,
"text": "SQLite UPPER Function"
},
{
"code": null,
"e": 147258,
"s": 147193,
"text": "SQLite UPPER function converts a string into upper-case letters."
},
{
"code": null,
"e": 147280,
"s": 147258,
"text": "SQLite LOWER Function"
},
{
"code": null,
"e": 147345,
"s": 147280,
"text": "SQLite LOWER function converts a string into lower-case letters."
},
{
"code": null,
"e": 147368,
"s": 147345,
"text": "SQLite LENGTH Function"
},
{
"code": null,
"e": 147423,
"s": 147368,
"text": "SQLite LENGTH function returns the length of a string."
},
{
"code": null,
"e": 147454,
"s": 147423,
"text": "SQLite sqlite_version Function"
},
{
"code": null,
"e": 147528,
"s": 147454,
"text": "SQLite sqlite_version function returns the version of the SQLite library."
},
{
"code": null,
"e": 147645,
"s": 147528,
"text": "Before we start giving examples on the above-mentioned functions, consider COMPANY table with the following records."
},
{
"code": null,
"e": 148151,
"s": 147645,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 148266,
"s": 148151,
"text": "SQLite COUNT aggregate function is used to count the number of rows in a database table. Following is an example −"
},
{
"code": null,
"e": 148304,
"s": 148266,
"text": "sqlite> SELECT count(*) FROM COMPANY;"
},
{
"code": null,
"e": 148363,
"s": 148304,
"text": "The above SQLite SQL statement will produce the following."
},
{
"code": null,
"e": 148386,
"s": 148363,
"text": "count(*)\n----------\n7\n"
},
{
"code": null,
"e": 148512,
"s": 148386,
"text": "SQLite MAX aggregate function allows us to select the highest (maximum) value for a certain column. Following is an example −"
},
{
"code": null,
"e": 148553,
"s": 148512,
"text": "sqlite> SELECT max(salary) FROM COMPANY;"
},
{
"code": null,
"e": 148612,
"s": 148553,
"text": "The above SQLite SQL statement will produce the following."
},
{
"code": null,
"e": 148645,
"s": 148612,
"text": "max(salary)\n-----------\n85000.0\n"
},
{
"code": null,
"e": 148770,
"s": 148645,
"text": "SQLite MIN aggregate function allows us to select the lowest (minimum) value for a certain column. Following is an example −"
},
{
"code": null,
"e": 148811,
"s": 148770,
"text": "sqlite> SELECT min(salary) FROM COMPANY;"
},
{
"code": null,
"e": 148870,
"s": 148811,
"text": "The above SQLite SQL statement will produce the following."
},
{
"code": null,
"e": 148903,
"s": 148870,
"text": "min(salary)\n-----------\n10000.0\n"
},
{
"code": null,
"e": 149017,
"s": 148903,
"text": "SQLite AVG aggregate function selects the average value for a certain table column. Following is an the example −"
},
{
"code": null,
"e": 149058,
"s": 149017,
"text": "sqlite> SELECT avg(salary) FROM COMPANY;"
},
{
"code": null,
"e": 149117,
"s": 149058,
"text": "The above SQLite SQL statement will produce the following."
},
{
"code": null,
"e": 149164,
"s": 149117,
"text": "avg(salary)\n----------------\n37142.8571428572\n"
},
{
"code": null,
"e": 149269,
"s": 149164,
"text": "SQLite SUM aggregate function allows selecting the total for a numeric column. Following is an example −"
},
{
"code": null,
"e": 149310,
"s": 149269,
"text": "sqlite> SELECT sum(salary) FROM COMPANY;"
},
{
"code": null,
"e": 149369,
"s": 149310,
"text": "The above SQLite SQL statement will produce the following."
},
{
"code": null,
"e": 149403,
"s": 149369,
"text": "sum(salary)\n-----------\n260000.0\n"
},
{
"code": null,
"e": 149539,
"s": 149403,
"text": "SQLite RANDOM function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807. Following is an example −"
},
{
"code": null,
"e": 149574,
"s": 149539,
"text": "sqlite> SELECT random() AS Random;"
},
{
"code": null,
"e": 149633,
"s": 149574,
"text": "The above SQLite SQL statement will produce the following."
},
{
"code": null,
"e": 149681,
"s": 149633,
"text": "Random\n-------------------\n5876796417670984050\n"
},
{
"code": null,
"e": 149779,
"s": 149681,
"text": "SQLite ABS function returns the absolute value of the numeric argument. Following is an example −"
},
{
"code": null,
"e": 149843,
"s": 149779,
"text": "sqlite> SELECT abs(5), abs(-15), abs(NULL), abs(0), abs(\"ABC\");"
},
{
"code": null,
"e": 149902,
"s": 149843,
"text": "The above SQLite SQL statement will produce the following."
},
{
"code": null,
"e": 150073,
"s": 149902,
"text": "abs(5) abs(-15) abs(NULL) abs(0) abs(\"ABC\")\n---------- ---------- ---------- ---------- ----------\n5 15 0 0.0\n"
},
{
"code": null,
"e": 150164,
"s": 150073,
"text": "SQLite UPPER function converts a string into upper-case letters. Following is an example −"
},
{
"code": null,
"e": 150205,
"s": 150164,
"text": "sqlite> SELECT upper(name) FROM COMPANY;"
},
{
"code": null,
"e": 150264,
"s": 150205,
"text": "The above SQLite SQL statement will produce the following."
},
{
"code": null,
"e": 150327,
"s": 150264,
"text": "upper(name)\n-----------\nPAUL\nALLEN\nTEDDY\nMARK\nDAVID\nKIM\nJAMES\n"
},
{
"code": null,
"e": 150418,
"s": 150327,
"text": "SQLite LOWER function converts a string into lower-case letters. Following is an example −"
},
{
"code": null,
"e": 150459,
"s": 150418,
"text": "sqlite> SELECT lower(name) FROM COMPANY;"
},
{
"code": null,
"e": 150518,
"s": 150459,
"text": "The above SQLite SQL statement will produce the following."
},
{
"code": null,
"e": 150581,
"s": 150518,
"text": "lower(name)\n-----------\npaul\nallen\nteddy\nmark\ndavid\nkim\njames\n"
},
{
"code": null,
"e": 150662,
"s": 150581,
"text": "SQLite LENGTH function returns the length of a string. Following is an example −"
},
{
"code": null,
"e": 150710,
"s": 150662,
"text": "sqlite> SELECT name, length(name) FROM COMPANY;"
},
{
"code": null,
"e": 150769,
"s": 150710,
"text": "The above SQLite SQL statement will produce the following."
},
{
"code": null,
"e": 150918,
"s": 150769,
"text": "NAME length(name)\n---------- ------------\nPaul 4\nAllen 5\nTeddy 5\nMark 4\nDavid 5\nKim 3\nJames 5\n"
},
{
"code": null,
"e": 151018,
"s": 150918,
"text": "SQLite sqlite_version function returns the version of the SQLite library. Following is an example −"
},
{
"code": null,
"e": 151071,
"s": 151018,
"text": "sqlite> SELECT sqlite_version() AS 'SQLite Version';"
},
{
"code": null,
"e": 151130,
"s": 151071,
"text": "The above SQLite SQL statement will produce the following."
},
{
"code": null,
"e": 151168,
"s": 151130,
"text": "SQLite Version\n--------------\n3.6.20\n"
},
{
"code": null,
"e": 151237,
"s": 151168,
"text": "In this chapter, you will learn how to use SQLite in C/C++ programs."
},
{
"code": null,
"e": 151446,
"s": 151237,
"text": "Before you start using SQLite in our C/C++ programs, you need to make sure that you have SQLite library set up on the machine. You can check SQLite Installation chapter to understand the installation process."
},
{
"code": null,
"e": 151703,
"s": 151446,
"text": "Following are important C/C++ SQLite interface routines, which can suffice your requirement to work with SQLite database from your C/C++ program. If you are looking for a more sophisticated application, then you can look into SQLite official documentation."
},
{
"code": null,
"e": 151754,
"s": 151703,
"text": "sqlite3_open(const char *filename, sqlite3 **ppDb)"
},
{
"code": null,
"e": 151891,
"s": 151754,
"text": "This routine opens a connection to an SQLite database file and returns a database connection object to be used by other SQLite routines."
},
{
"code": null,
"e": 152044,
"s": 151891,
"text": "If the filename argument is NULL or ':memory:', sqlite3_open() will create an in-memory database in RAM that lasts only for the duration of the session."
},
{
"code": null,
"e": 152234,
"s": 152044,
"text": "If the filename is not NULL, sqlite3_open() attempts to open the database file by using its value. If no file by that name exists, sqlite3_open() will open a new database file by that name."
},
{
"code": null,
"e": 152318,
"s": 152234,
"text": "sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)"
},
{
"code": null,
"e": 152455,
"s": 152318,
"text": "This routine provides a quick, easy way to execute SQL commands provided by sql argument which can consist of more than one SQL command."
},
{
"code": null,
"e": 152654,
"s": 152455,
"text": "Here, the first argument sqlite3 is an open database object, sqlite_callback is a call back for which data is the 1st argument and errmsg will be returned to capture any error raised by the routine."
},
{
"code": null,
"e": 152800,
"s": 152654,
"text": "SQLite3_exec() routine parses and executes every command given in the sql argument until it reaches the end of the string or encounters an error."
},
{
"code": null,
"e": 152824,
"s": 152800,
"text": "sqlite3_close(sqlite3*)"
},
{
"code": null,
"e": 153021,
"s": 152824,
"text": "This routine closes a database connection previously opened by a call to sqlite3_open(). All prepared statements associated with the connection should be finalized prior to closing the connection."
},
{
"code": null,
"e": 153183,
"s": 153021,
"text": "If any queries remain that have not been finalized, sqlite3_close() will return SQLITE_BUSY with the error message Unable to close due to unfinalized statements."
},
{
"code": null,
"e": 153358,
"s": 153183,
"text": "Following C code segment shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned."
},
{
"code": null,
"e": 153725,
"s": 153358,
"text": "#include <stdio.h>\n#include <sqlite3.h> \n\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n\n rc = sqlite3_open(\"test.db\", &db);\n\n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n sqlite3_close(db);\n}"
},
{
"code": null,
"e": 153877,
"s": 153725,
"text": "Now, let's compile and run the above program to create our database test.db in the current directory. You can change your path as per your requirement."
},
{
"code": null,
"e": 153938,
"s": 153877,
"text": "$gcc test.c -l sqlite3\n$./a.out\nOpened database successfully"
},
{
"code": null,
"e": 154023,
"s": 153938,
"text": "If you are going to use C++ source code, then you can compile your code as follows −"
},
{
"code": null,
"e": 154046,
"s": 154023,
"text": "$g++ test.c -l sqlite3"
},
{
"code": null,
"e": 154243,
"s": 154046,
"text": "Here, we are linking our program with sqlite3 library to provide required functions to C program. This will create a database file test.db in your directory and you will have the following result."
},
{
"code": null,
"e": 154388,
"s": 154243,
"text": "-rwxr-xr-x. 1 root root 7383 May 8 02:06 a.out\n-rw-r--r--. 1 root root 323 May 8 02:05 test.c\n-rw-r--r--. 1 root root 0 May 8 02:06 test.db\n"
},
{
"code": null,
"e": 154481,
"s": 154388,
"text": "Following C code segment will be used to create a table in the previously created database −"
},
{
"code": null,
"e": 155676,
"s": 154481,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h> \n\nstatic int callback(void *NotUsed, int argc, char **argv, char **azColName) {\n int i;\n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\n\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n \n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stdout, \"Opened database successfully\\n\");\n }\n\n /* Create SQL statement */\n sql = \"CREATE TABLE COMPANY(\" \\\n \"ID INT PRIMARY KEY NOT NULL,\" \\\n \"NAME TEXT NOT NULL,\" \\\n \"AGE INT NOT NULL,\" \\\n \"ADDRESS CHAR(50),\" \\\n \"SALARY REAL );\";\n\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);\n \n if( rc != SQLITE_OK ){\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Table created successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}"
},
{
"code": null,
"e": 155825,
"s": 155676,
"text": "When the above program is compiled and executed, it will create COMPANY table in your test.db and the final listing of the file will be as follows −"
},
{
"code": null,
"e": 155970,
"s": 155825,
"text": "-rwxr-xr-x. 1 root root 9567 May 8 02:31 a.out\n-rw-r--r--. 1 root root 1207 May 8 02:31 test.c\n-rw-r--r--. 1 root root 3072 May 8 02:31 test.db\n"
},
{
"code": null,
"e": 156076,
"s": 155970,
"text": "Following C code segment shows how you can create records in COMPANY table created in the above example −"
},
{
"code": null,
"e": 157539,
"s": 156076,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h> \n\nstatic int callback(void *NotUsed, int argc, char **argv, char **azColName) {\n int i;\n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\n\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n \n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n\n /* Create SQL statement */\n sql = \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \" \\\n \"VALUES (1, 'Paul', 32, 'California', 20000.00 ); \" \\\n \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \" \\\n \"VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); \" \\\n \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\" \\\n \"VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );\" \\\n \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\" \\\n \"VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );\";\n\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);\n \n if( rc != SQLITE_OK ){\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Records created successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}"
},
{
"code": null,
"e": 157681,
"s": 157539,
"text": "When the above program is compiled and executed, it will create the given records in COMPANY table and will display the following two lines −"
},
{
"code": null,
"e": 157740,
"s": 157681,
"text": "Opened database successfully\nRecords created successfully\n"
},
{
"code": null,
"e": 157994,
"s": 157740,
"text": "Before proceeding with actual example to fetch records, let us look at some detail about the callback function, which we are using in our examples. This callback provides a way to obtain results from SELECT statements. It has the following declaration −"
},
{
"code": null,
"e": 158284,
"s": 157994,
"text": "typedef int (*sqlite3_callback)(\n void*, /* Data provided in the 4th argument of sqlite3_exec() */\n int, /* The number of columns in row */\n char**, /* An array of strings representing fields in the row */\n char** /* An array of strings representing column names */\n);"
},
{
"code": null,
"e": 158491,
"s": 158284,
"text": "If the above callback is provided in sqlite_exec() routine as the third argument, SQLite will call this callback function for each record processed in each SELECT statement executed within the SQL argument."
},
{
"code": null,
"e": 158614,
"s": 158491,
"text": "Following C code segment shows how you can fetch and display records from the COMPANY table created in the above example −"
},
{
"code": null,
"e": 159723,
"s": 158614,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h> \n\nstatic int callback(void *data, int argc, char **argv, char **azColName){\n int i;\n fprintf(stderr, \"%s: \", (const char*)data);\n \n for(i = 0; i<argc; i++){\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n \n printf(\"\\n\");\n return 0;\n}\n\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n const char* data = \"Callback function called\";\n\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n \n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n\n /* Create SQL statement */\n sql = \"SELECT * from COMPANY\";\n\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);\n \n if( rc != SQLITE_OK ) {\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Operation done successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}"
},
{
"code": null,
"e": 159810,
"s": 159723,
"text": "When the above program is compiled and executed, it will produce the following result."
},
{
"code": null,
"e": 160232,
"s": 159810,
"text": "Opened database successfully\nCallback function called: ID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 20000.0\n\nCallback function called: ID = 2\nNAME = Allen\nAGE = 25\nADDRESS = Texas\nSALARY = 15000.0\n\nCallback function called: ID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\n\nCallback function called: ID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nOperation done successfully\n"
},
{
"code": null,
"e": 160383,
"s": 160232,
"text": "Following C code segment shows how we can use UPDATE statement to update any record and then fetch and display updated records from the COMPANY table."
},
{
"code": null,
"e": 161559,
"s": 160383,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h> \n\nstatic int callback(void *data, int argc, char **argv, char **azColName){\n int i;\n fprintf(stderr, \"%s: \", (const char*)data);\n \n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\n\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n const char* data = \"Callback function called\";\n\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n \n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n\n /* Create merged SQL statement */\n sql = \"UPDATE COMPANY set SALARY = 25000.00 where ID=1; \" \\\n \"SELECT * from COMPANY\";\n\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);\n \n if( rc != SQLITE_OK ) {\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Operation done successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}"
},
{
"code": null,
"e": 161646,
"s": 161559,
"text": "When the above program is compiled and executed, it will produce the following result."
},
{
"code": null,
"e": 162068,
"s": 161646,
"text": "Opened database successfully\nCallback function called: ID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 25000.0\n\nCallback function called: ID = 2\nNAME = Allen\nAGE = 25\nADDRESS = Texas\nSALARY = 15000.0\n\nCallback function called: ID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\n\nCallback function called: ID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nOperation done successfully\n"
},
{
"code": null,
"e": 162226,
"s": 162068,
"text": "Following C code segment shows how you can use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table."
},
{
"code": null,
"e": 163386,
"s": 162226,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h> \n\nstatic int callback(void *data, int argc, char **argv, char **azColName) {\n int i;\n fprintf(stderr, \"%s: \", (const char*)data);\n \n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\n\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n const char* data = \"Callback function called\";\n\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n \n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n\n /* Create merged SQL statement */\n sql = \"DELETE from COMPANY where ID=2; \" \\\n \"SELECT * from COMPANY\";\n\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);\n \n if( rc != SQLITE_OK ) {\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Operation done successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}"
},
{
"code": null,
"e": 163473,
"s": 163386,
"text": "When the above program is compiled and executed, it will produce the following result."
},
{
"code": null,
"e": 163806,
"s": 163473,
"text": "Opened database successfully\nCallback function called: ID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 20000.0\n\nCallback function called: ID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\n\nCallback function called: ID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nOperation done successfully\n"
},
{
"code": null,
"e": 163874,
"s": 163806,
"text": "In this chapter, you will learn how to use SQLite in Java programs."
},
{
"code": null,
"e": 164132,
"s": 163874,
"text": "Before you start using SQLite in our Java programs, you need to make sure that you have SQLite JDBC Driver and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up SQLite JDBC driver."
},
{
"code": null,
"e": 164214,
"s": 164132,
"text": "Download latest version of sqlite-jdbc-(VERSION).jar from sqlite-jdbc repository."
},
{
"code": null,
"e": 164296,
"s": 164214,
"text": "Download latest version of sqlite-jdbc-(VERSION).jar from sqlite-jdbc repository."
},
{
"code": null,
"e": 164453,
"s": 164296,
"text": "Add downloaded jar file sqlite-jdbc-(VERSION).jar in your class path, or you can use it along with -classpath option as explained in the following examples."
},
{
"code": null,
"e": 164610,
"s": 164453,
"text": "Add downloaded jar file sqlite-jdbc-(VERSION).jar in your class path, or you can use it along with -classpath option as explained in the following examples."
},
{
"code": null,
"e": 164821,
"s": 164610,
"text": "Following section assumes you have little knowledge about Java JDBC concepts. If you don't, then it is suggested to spent half an hour with JDBC Tutorial to become comfortable with the concepts explained below."
},
{
"code": null,
"e": 164995,
"s": 164821,
"text": "Following Java programs shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned."
},
{
"code": null,
"e": 165449,
"s": 164995,
"text": "import java.sql.*;\n\npublic class SQLiteJDBC {\n public static void main( String args[] ) {\n Connection c = null;\n \n try {\n Class.forName(\"org.sqlite.JDBC\");\n c = DriverManager.getConnection(\"jdbc:sqlite:test.db\");\n } catch ( Exception e ) {\n System.err.println( e.getClass().getName() + \": \" + e.getMessage() );\n System.exit(0);\n }\n System.out.println(\"Opened database successfully\");\n }\n}"
},
{
"code": null,
"e": 165708,
"s": 165449,
"text": "Now, let's compile and run the above program to create our database test.db in the current directory. You can change your path as per your requirement. We are assuming the current version of JDBC driver sqlite-jdbc-3.7.2.jar is available in the current path."
},
{
"code": null,
"e": 165812,
"s": 165708,
"text": "$javac SQLiteJDBC.java\n$java -classpath \".:sqlite-jdbc-3.7.2.jar\" SQLiteJDBC\nOpen database successfully"
},
{
"code": null,
"e": 165905,
"s": 165812,
"text": "If you are going to use Windows machine, then you can compile and run your code as follows −"
},
{
"code": null,
"e": 166011,
"s": 165905,
"text": "$javac SQLiteJDBC.java\n$java -classpath \".;sqlite-jdbc-3.7.2.jar\" SQLiteJDBC\nOpened database successfully"
},
{
"code": null,
"e": 166101,
"s": 166011,
"text": "Following Java program will be used to create a table in the previously created database."
},
{
"code": null,
"e": 167104,
"s": 166101,
"text": "import java.sql.*;\n\npublic class SQLiteJDBC {\n\n public static void main( String args[] ) {\n Connection c = null;\n Statement stmt = null;\n \n try {\n Class.forName(\"org.sqlite.JDBC\");\n c = DriverManager.getConnection(\"jdbc:sqlite:test.db\");\n System.out.println(\"Opened database successfully\");\n\n stmt = c.createStatement();\n String sql = \"CREATE TABLE COMPANY \" +\n \"(ID INT PRIMARY KEY NOT NULL,\" +\n \" NAME TEXT NOT NULL, \" + \n \" AGE INT NOT NULL, \" + \n \" ADDRESS CHAR(50), \" + \n \" SALARY REAL)\"; \n stmt.executeUpdate(sql);\n stmt.close();\n c.close();\n } catch ( Exception e ) {\n System.err.println( e.getClass().getName() + \": \" + e.getMessage() );\n System.exit(0);\n }\n System.out.println(\"Table created successfully\");\n }\n}"
},
{
"code": null,
"e": 167249,
"s": 167104,
"text": "When the above program is compiled and executed, it will create COMPANY table in your test.db and final listing of the file will be as follows −"
},
{
"code": null,
"e": 167493,
"s": 167249,
"text": "-rw-r--r--. 1 root root 3201128 Jan 22 19:04 sqlite-jdbc-3.7.2.jar\n-rw-r--r--. 1 root root 1506 May 8 05:43 SQLiteJDBC.class\n-rw-r--r--. 1 root root 832 May 8 05:42 SQLiteJDBC.java\n-rw-r--r--. 1 root root 3072 May 8 05:43 test.db\n"
},
{
"code": null,
"e": 167591,
"s": 167493,
"text": "Following Java program shows how to create records in the COMPANY table created in above example."
},
{
"code": null,
"e": 168978,
"s": 167591,
"text": "import java.sql.*;\n\npublic class SQLiteJDBC {\n\n public static void main( String args[] ) {\n Connection c = null;\n Statement stmt = null;\n \n try {\n Class.forName(\"org.sqlite.JDBC\");\n c = DriverManager.getConnection(\"jdbc:sqlite:test.db\");\n c.setAutoCommit(false);\n System.out.println(\"Opened database successfully\");\n\n stmt = c.createStatement();\n String sql = \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \" +\n \"VALUES (1, 'Paul', 32, 'California', 20000.00 );\"; \n stmt.executeUpdate(sql);\n\n sql = \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \" +\n \"VALUES (2, 'Allen', 25, 'Texas', 15000.00 );\"; \n stmt.executeUpdate(sql);\n\n sql = \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \" +\n \"VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );\"; \n stmt.executeUpdate(sql);\n\n sql = \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \" +\n \"VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );\"; \n stmt.executeUpdate(sql);\n\n stmt.close();\n c.commit();\n c.close();\n } catch ( Exception e ) {\n System.err.println( e.getClass().getName() + \": \" + e.getMessage() );\n System.exit(0);\n }\n System.out.println(\"Records created successfully\");\n }\n}"
},
{
"code": null,
"e": 169107,
"s": 168978,
"text": "When above program is compiled and executed, it will create given records in COMPANY table and will display following two line −"
},
{
"code": null,
"e": 169166,
"s": 169107,
"text": "Opened database successfully\nRecords created successfully\n"
},
{
"code": null,
"e": 169281,
"s": 169166,
"text": "Following Java program shows how to fetch and display records from the COMPANY table created in the above example."
},
{
"code": null,
"e": 170524,
"s": 169281,
"text": "import java.sql.*;\n\npublic class SQLiteJDBC {\n\n public static void main( String args[] ) {\n\n Connection c = null;\n Statement stmt = null;\n try {\n Class.forName(\"org.sqlite.JDBC\");\n c = DriverManager.getConnection(\"jdbc:sqlite:test.db\");\n c.setAutoCommit(false);\n System.out.println(\"Opened database successfully\");\n\n stmt = c.createStatement();\n ResultSet rs = stmt.executeQuery( \"SELECT * FROM COMPANY;\" );\n \n while ( rs.next() ) {\n int id = rs.getInt(\"id\");\n String name = rs.getString(\"name\");\n int age = rs.getInt(\"age\");\n String address = rs.getString(\"address\");\n float salary = rs.getFloat(\"salary\");\n \n System.out.println( \"ID = \" + id );\n System.out.println( \"NAME = \" + name );\n System.out.println( \"AGE = \" + age );\n System.out.println( \"ADDRESS = \" + address );\n System.out.println( \"SALARY = \" + salary );\n System.out.println();\n }\n rs.close();\n stmt.close();\n c.close();\n } catch ( Exception e ) {\n System.err.println( e.getClass().getName() + \": \" + e.getMessage() );\n System.exit(0);\n }\n System.out.println(\"Operation done successfully\");\n }\n}"
},
{
"code": null,
"e": 170611,
"s": 170524,
"text": "When the above program is compiled and executed, it will produce the following result."
},
{
"code": null,
"e": 170929,
"s": 170611,
"text": "Opened database successfully\nID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 20000.0\n\nID = 2\nNAME = Allen\nAGE = 25\nADDRESS = Texas\nSALARY = 15000.0\n\nID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\n\nID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nOperation done successfully\n"
},
{
"code": null,
"e": 171075,
"s": 170929,
"text": "Following Java code shows how to use UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table."
},
{
"code": null,
"e": 172447,
"s": 171075,
"text": "import java.sql.*;\n\npublic class SQLiteJDBC {\n\n public static void main( String args[] ) {\n \n Connection c = null;\n Statement stmt = null;\n \n try {\n Class.forName(\"org.sqlite.JDBC\");\n c = DriverManager.getConnection(\"jdbc:sqlite:test.db\");\n c.setAutoCommit(false);\n System.out.println(\"Opened database successfully\");\n\n stmt = c.createStatement();\n String sql = \"UPDATE COMPANY set SALARY = 25000.00 where ID=1;\";\n stmt.executeUpdate(sql);\n c.commit();\n\n ResultSet rs = stmt.executeQuery( \"SELECT * FROM COMPANY;\" );\n \n while ( rs.next() ) {\n int id = rs.getInt(\"id\");\n String name = rs.getString(\"name\");\n int age = rs.getInt(\"age\");\n String address = rs.getString(\"address\");\n float salary = rs.getFloat(\"salary\");\n \n System.out.println( \"ID = \" + id );\n System.out.println( \"NAME = \" + name );\n System.out.println( \"AGE = \" + age );\n System.out.println( \"ADDRESS = \" + address );\n System.out.println( \"SALARY = \" + salary );\n System.out.println();\n }\n rs.close();\n stmt.close();\n c.close();\n } catch ( Exception e ) {\n System.err.println( e.getClass().getName() + \": \" + e.getMessage() );\n System.exit(0);\n }\n System.out.println(\"Operation done successfully\");\n }\n}"
},
{
"code": null,
"e": 172534,
"s": 172447,
"text": "When the above program is compiled and executed, it will produce the following result."
},
{
"code": null,
"e": 172852,
"s": 172534,
"text": "Opened database successfully\nID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 25000.0\n\nID = 2\nNAME = Allen\nAGE = 25\nADDRESS = Texas\nSALARY = 15000.0\n\nID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\n\nID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nOperation done successfully\n"
},
{
"code": null,
"e": 173008,
"s": 172852,
"text": "Following Java code shows how to use use DELETE statement to delete any record and then fetch and display the remaining records from the our COMPANY table."
},
{
"code": null,
"e": 174420,
"s": 173008,
"text": "import java.sql.*;\n\npublic class SQLiteJDBC {\n\n public static void main( String args[] ) {\n Connection c = null;\n Statement stmt = null;\n \n try {\n Class.forName(\"org.sqlite.JDBC\");\n c = DriverManager.getConnection(\"jdbc:sqlite:test.db\");\n c.setAutoCommit(false);\n System.out.println(\"Opened database successfully\");\n\n stmt = c.createStatement();\n String sql = \"DELETE from COMPANY where ID=2;\";\n stmt.executeUpdate(sql);\n c.commit();\n\n ResultSet rs = stmt.executeQuery( \"SELECT * FROM COMPANY;\" );\n \n while ( rs.next() ) {\n int id = rs.getInt(\"id\");\n String name = rs.getString(\"name\");\n int age = rs.getInt(\"age\");\n String address = rs.getString(\"address\");\n float salary = rs.getFloat(\"salary\");\n \n System.out.println( \"ID = \" + id );\n System.out.println( \"NAME = \" + name );\n System.out.println( \"AGE = \" + age );\n System.out.println( \"ADDRESS = \" + address );\n System.out.println( \"SALARY = \" + salary );\n System.out.println();\n }\n rs.close();\n stmt.close();\n c.close();\n } catch ( Exception e ) {\n System.err.println( e.getClass().getName() + \": \" + e.getMessage() );\n System.exit(0);\n }\n System.out.println(\"Operation done successfully\");\n }\n}"
},
{
"code": null,
"e": 174507,
"s": 174420,
"text": "When the above program is compiled and executed, it will produce the following result."
},
{
"code": null,
"e": 174762,
"s": 174507,
"text": "Opened database successfully\nID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 25000.0\n\nID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\n\nID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nOperation done successfully\n"
},
{
"code": null,
"e": 174829,
"s": 174762,
"text": "In this chapter, you will learn how to use SQLite in PHP programs."
},
{
"code": null,
"e": 174958,
"s": 174829,
"text": "SQLite3 extension is enabled by default as of PHP 5.3.0. It's possible to disable it by using --without-sqlite3 at compile time."
},
{
"code": null,
"e": 175104,
"s": 174958,
"text": "Windows users must enable php_sqlite3.dll in order to use this extension. This DLL is included with Windows distributions of PHP as of PHP 5.3.0."
},
{
"code": null,
"e": 175200,
"s": 175104,
"text": "For detailed installation instructions, kindly check our PHP tutorial and its official website."
},
{
"code": null,
"e": 175432,
"s": 175200,
"text": "Following are important PHP routines which can suffice your requirement to work with SQLite database from your PHP program. If you are looking for a more sophisticated application, then you can look into PHP official documentation."
},
{
"code": null,
"e": 175494,
"s": 175432,
"text": "public void SQLite3::open ( filename, flags, encryption_key )"
},
{
"code": null,
"e": 175590,
"s": 175494,
"text": "Opens SQLite 3 Database. If the build includes encryption, then it will attempt to use the key."
},
{
"code": null,
"e": 175736,
"s": 175590,
"text": "If the filename is given as ':memory:', SQLite3::open() will create an in-memory database in RAM that lasts only for the duration of the session."
},
{
"code": null,
"e": 175935,
"s": 175736,
"text": "If the filename is actual device file name, SQLite3::open() attempts to open the database file by using its value. If no file by that name exists, then a new database file by that name gets created."
},
{
"code": null,
"e": 176069,
"s": 175935,
"text": "Optional flags used to determine how to open the SQLite database. By default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE."
},
{
"code": null,
"e": 176113,
"s": 176069,
"text": "public bool SQLite3::exec ( string $query )"
},
{
"code": null,
"e": 176329,
"s": 176113,
"text": "This routine provides a quick, easy way to execute SQL commands provided by sql argument, which can consist of more than one SQL command. This routine is used to execute a result-less query against a given database."
},
{
"code": null,
"e": 176383,
"s": 176329,
"text": "public SQLite3Result SQLite3::query ( string $query )"
},
{
"code": null,
"e": 176483,
"s": 176383,
"text": "This routine executes an SQL query, returning an SQLite3Result object if the query returns results."
},
{
"code": null,
"e": 176526,
"s": 176483,
"text": "public int SQLite3::lastErrorCode ( void )"
},
{
"code": null,
"e": 176613,
"s": 176526,
"text": "This routine returns the numeric result code of the most recent failed SQLite request."
},
{
"code": null,
"e": 176658,
"s": 176613,
"text": "public string SQLite3::lastErrorMsg ( void )"
},
{
"code": null,
"e": 176742,
"s": 176658,
"text": "This routine returns English text describing the most recent failed SQLite request."
},
{
"code": null,
"e": 176779,
"s": 176742,
"text": "public int SQLite3::changes ( void )"
},
{
"code": null,
"e": 176902,
"s": 176779,
"text": "This routine returns the number of database rows that were updated, inserted, or deleted by the most recent SQL statement."
},
{
"code": null,
"e": 176938,
"s": 176902,
"text": "public bool SQLite3::close ( void )"
},
{
"code": null,
"e": 177028,
"s": 176938,
"text": "This routine closes a database connection previously opened by a call to SQLite3::open()."
},
{
"code": null,
"e": 177082,
"s": 177028,
"text": "public string SQLite3::escapeString ( string $value )"
},
{
"code": null,
"e": 177183,
"s": 177082,
"text": "This routine returns a string that has been properly escaped for safe inclusion in an SQL statement."
},
{
"code": null,
"e": 177348,
"s": 177183,
"text": "Following PHP code shows how to connect to an existing database. If database does not exist, then it will be created and finally a database object will be returned."
},
{
"code": null,
"e": 177595,
"s": 177348,
"text": "<?php\n class MyDB extends SQLite3 {\n function __construct() {\n $this->open('test.db');\n }\n }\n $db = new MyDB();\n if(!$db) {\n echo $db->lastErrorMsg();\n } else {\n echo \"Opened database successfully\\n\";\n }\n?>"
},
{
"code": null,
"e": 177821,
"s": 177595,
"text": "Now, let's run the above program to create our database test.db in the current directory. You can change your path as per your requirement. If the database is successfully created, then it will display the following message −"
},
{
"code": null,
"e": 177849,
"s": 177821,
"text": "Open database successfully\n"
},
{
"code": null,
"e": 177938,
"s": 177849,
"text": "Following PHP program will be used to create a table in the previously created database."
},
{
"code": null,
"e": 178562,
"s": 177938,
"text": "<?php\n class MyDB extends SQLite3 {\n function __construct() {\n $this->open('test.db');\n }\n }\n $db = new MyDB();\n if(!$db) {\n echo $db->lastErrorMsg();\n } else {\n echo \"Opened database successfully\\n\";\n }\n\n $sql =<<<EOF\n CREATE TABLE COMPANY\n (ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL);\nEOF;\n\n $ret = $db->exec($sql);\n if(!$ret){\n echo $db->lastErrorMsg();\n } else {\n echo \"Table created successfully\\n\";\n }\n $db->close();\n?>"
},
{
"code": null,
"e": 178692,
"s": 178562,
"text": "When the above program is executed, it will create the COMPANY table in your test.db and it will display the following messages −"
},
{
"code": null,
"e": 178749,
"s": 178692,
"text": "Opened database successfully\nTable created successfully\n"
},
{
"code": null,
"e": 178850,
"s": 178749,
"text": "Following PHP program shows how to create records in the COMPANY table created in the above example."
},
{
"code": null,
"e": 179712,
"s": 178850,
"text": "<?php\n class MyDB extends SQLite3 {\n function __construct() {\n $this->open('test.db');\n }\n }\n \n $db = new MyDB();\n if(!$db){\n echo $db->lastErrorMsg();\n } else {\n echo \"Opened database successfully\\n\";\n }\n\n $sql =<<<EOF\n INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\n VALUES (1, 'Paul', 32, 'California', 20000.00 );\n\n INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\n VALUES (2, 'Allen', 25, 'Texas', 15000.00 );\n\n INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\n VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );\n\n INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\n VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );\nEOF;\n\n $ret = $db->exec($sql);\n if(!$ret) {\n echo $db->lastErrorMsg();\n } else {\n echo \"Records created successfully\\n\";\n }\n $db->close();\n?>"
},
{
"code": null,
"e": 179844,
"s": 179712,
"text": "When the above program is executed, it will create the given records in the COMPANY table and will display the following two lines."
},
{
"code": null,
"e": 179903,
"s": 179844,
"text": "Opened database successfully\nRecords created successfully\n"
},
{
"code": null,
"e": 180018,
"s": 179903,
"text": "Following PHP program shows how to fetch and display records from the COMPANY table created in the above example −"
},
{
"code": null,
"e": 180640,
"s": 180018,
"text": "<?php\n class MyDB extends SQLite3 {\n function __construct() {\n $this->open('test.db');\n }\n }\n \n $db = new MyDB();\n if(!$db) {\n echo $db->lastErrorMsg();\n } else {\n echo \"Opened database successfully\\n\";\n }\n\n $sql =<<<EOF\n SELECT * from COMPANY;\nEOF;\n\n $ret = $db->query($sql);\n while($row = $ret->fetchArray(SQLITE3_ASSOC) ) {\n echo \"ID = \". $row['ID'] . \"\\n\";\n echo \"NAME = \". $row['NAME'] .\"\\n\";\n echo \"ADDRESS = \". $row['ADDRESS'] .\"\\n\";\n echo \"SALARY = \".$row['SALARY'] .\"\\n\\n\";\n }\n echo \"Operation done successfully\\n\";\n $db->close();\n?>"
},
{
"code": null,
"e": 180714,
"s": 180640,
"text": "When the above program is executed, it will produce the following result."
},
{
"code": null,
"e": 180988,
"s": 180714,
"text": "Opened database successfully\nID = 1\nNAME = Paul\nADDRESS = California\nSALARY = 20000\n\nID = 2\nNAME = Allen\nADDRESS = Texas\nSALARY = 15000\n\nID = 3\nNAME = Teddy\nADDRESS = Norway\nSALARY = 20000\n\nID = 4\nNAME = Mark\nADDRESS = Rich-Mond\nSALARY = 65000\n\nOperation done successfully\n"
},
{
"code": null,
"e": 181133,
"s": 180988,
"text": "Following PHP code shows how to use UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table."
},
{
"code": null,
"e": 181986,
"s": 181133,
"text": "<?php\n class MyDB extends SQLite3 {\n function __construct() {\n $this->open('test.db');\n }\n }\n \n $db = new MyDB();\n if(!$db) {\n echo $db->lastErrorMsg();\n } else {\n echo \"Opened database successfully\\n\";\n }\n $sql =<<<EOF\n UPDATE COMPANY set SALARY = 25000.00 where ID=1;\nEOF;\n $ret = $db->exec($sql);\n if(!$ret) {\n echo $db->lastErrorMsg();\n } else {\n echo $db->changes(), \" Record updated successfully\\n\";\n }\n\n $sql =<<<EOF\n SELECT * from COMPANY;\nEOF;\n \n $ret = $db->query($sql);\n while($row = $ret->fetchArray(SQLITE3_ASSOC) ) {\n echo \"ID = \". $row['ID'] . \"\\n\";\n echo \"NAME = \". $row['NAME'] .\"\\n\";\n echo \"ADDRESS = \". $row['ADDRESS'] .\"\\n\";\n echo \"SALARY = \".$row['SALARY'] .\"\\n\\n\";\n }\n echo \"Operation done successfully\\n\";\n $db->close();\n?>"
},
{
"code": null,
"e": 182060,
"s": 181986,
"text": "When the above program is executed, it will produce the following result."
},
{
"code": null,
"e": 182364,
"s": 182060,
"text": "Opened database successfully\n1 Record updated successfully\nID = 1\nNAME = Paul\nADDRESS = California\nSALARY = 25000\n\nID = 2\nNAME = Allen\nADDRESS = Texas\nSALARY = 15000\n\nID = 3\nNAME = Teddy\nADDRESS = Norway\nSALARY = 20000\n\nID = 4\nNAME = Mark\nADDRESS = Rich-Mond\nSALARY = 65000\n\nOperation done successfully\n"
},
{
"code": null,
"e": 182511,
"s": 182364,
"text": "Following PHP code shows how to use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table."
},
{
"code": null,
"e": 183347,
"s": 182511,
"text": "<?php\n class MyDB extends SQLite3 {\n function __construct() {\n $this->open('test.db');\n }\n }\n \n $db = new MyDB();\n if(!$db) {\n echo $db->lastErrorMsg();\n } else {\n echo \"Opened database successfully\\n\";\n }\n $sql =<<<EOF\n DELETE from COMPANY where ID = 2;\nEOF;\n \n $ret = $db->exec($sql);\n if(!$ret){\n echo $db->lastErrorMsg();\n } else {\n echo $db->changes(), \" Record deleted successfully\\n\";\n }\n\n $sql =<<<EOF\n SELECT * from COMPANY;\nEOF;\n $ret = $db->query($sql);\n while($row = $ret->fetchArray(SQLITE3_ASSOC) ) {\n echo \"ID = \". $row['ID'] . \"\\n\";\n echo \"NAME = \". $row['NAME'] .\"\\n\";\n echo \"ADDRESS = \". $row['ADDRESS'] .\"\\n\";\n echo \"SALARY = \".$row['SALARY'] .\"\\n\\n\";\n }\n echo \"Operation done successfully\\n\";\n $db->close();\n?>"
},
{
"code": null,
"e": 183421,
"s": 183347,
"text": "When the above program is executed, it will produce the following result."
},
{
"code": null,
"e": 183673,
"s": 183421,
"text": "Opened database successfully\n1 Record deleted successfully\nID = 1\nNAME = Paul\nADDRESS = California\nSALARY = 25000\n\nID = 3\nNAME = Teddy\nADDRESS = Norway\nSALARY = 20000\n\nID = 4\nNAME = Mark\nADDRESS = Rich-Mond\nSALARY = 65000\n\nOperation done successfully\n"
},
{
"code": null,
"e": 183741,
"s": 183673,
"text": "In this chapter, you will learn how to use SQLite in Perl programs."
},
{
"code": null,
"e": 183969,
"s": 183741,
"text": "SQLite3 can be integrated with Perl using Perl DBI module, which is a database access module for the Perl programming language. It defines a set of methods, variables, and conventions that provide a standard database interface."
},
{
"code": null,
"e": 184047,
"s": 183969,
"text": "Following are simple steps to install DBI module on your Linux/UNIX machine −"
},
{
"code": null,
"e": 184204,
"s": 184047,
"text": "$ wget http://search.cpan.org/CPAN/authors/id/T/TI/TIMB/DBI-1.625.tar.gz\n$ tar xvfz DBI-1.625.tar.gz\n$ cd DBI-1.625\n$ perl Makefile.PL\n$ make\n$ make install"
},
{
"code": null,
"e": 184288,
"s": 184204,
"text": "If you need to install SQLite driver for DBI, then it can be installed as follows −"
},
{
"code": null,
"e": 184468,
"s": 184288,
"text": "$ wget http://search.cpan.org/CPAN/authors/id/M/MS/MSERGEANT/DBD-SQLite-1.11.tar.gz\n$ tar xvfz DBD-SQLite-1.11.tar.gz\n$ cd DBD-SQLite-1.11\n$ perl Makefile.PL\n$ make\n$ make install"
},
{
"code": null,
"e": 184707,
"s": 184468,
"text": "Following are important DBI routines, which can suffice your requirement to work with SQLite database from your Perl program. If you are looking for a more sophisticated application, then you can look into Perl DBI official documentation."
},
{
"code": null,
"e": 184750,
"s": 184707,
"text": "DBI->connect($data_source, \"\", \"\", \\%attr)"
},
{
"code": null,
"e": 184889,
"s": 184750,
"text": "Establishes a database connection, or session, to the requested $data_source. Returns a database handle object if the connection succeeds."
},
{
"code": null,
"e": 185167,
"s": 184889,
"text": "Datasource has the form like − DBI:SQLite:dbname = 'test.db' where SQLite is SQLite driver name and test.db is the name of SQLite database file. If the filename is given as ':memory:', it will create an in-memory database in RAM that lasts only for the duration of the session."
},
{
"code": null,
"e": 185358,
"s": 185167,
"text": "If the filename is actual device file name, then it attempts to open the database file by using its value. If no file by that name exists, then a new database file by that name gets created."
},
{
"code": null,
"e": 185499,
"s": 185358,
"text": "You keep second and third parameter as blank strings and the last parameter is to pass various attributes as shown in the following example."
},
{
"code": null,
"e": 185514,
"s": 185499,
"text": "$dbh->do($sql)"
},
{
"code": null,
"e": 185778,
"s": 185514,
"text": "This routine prepares and executes a single SQL statement. Returns the number of rows affected or undef on error. A return value of -1 means the number of rows is not known, not applicable, or not available. Here, $dbh is a handle returned by DBI->connect() call."
},
{
"code": null,
"e": 185798,
"s": 185778,
"text": "$dbh->prepare($sql)"
},
{
"code": null,
"e": 185929,
"s": 185798,
"text": "This routine prepares a statement for later execution by the database engine and returns a reference to a statement handle object."
},
{
"code": null,
"e": 185945,
"s": 185929,
"text": "$sth->execute()"
},
{
"code": null,
"e": 186231,
"s": 185945,
"text": "This routine performs whatever processing is necessary to execute the prepared statement. An undef is returned if an error occurs. A successful execute always returns true regardless of the number of rows affected. Here, $sth is a statement handle returned by $dbh->prepare($sql) call."
},
{
"code": null,
"e": 186254,
"s": 186231,
"text": "$sth->fetchrow_array()"
},
{
"code": null,
"e": 186404,
"s": 186254,
"text": "This routine fetches the next row of data and returns it as a list containing the field values. Null fields are returned as undef values in the list."
},
{
"code": null,
"e": 186414,
"s": 186404,
"text": "$DBI::err"
},
{
"code": null,
"e": 186590,
"s": 186414,
"text": "This is equivalent to $h->err, where $h is any of the handle types like $dbh, $sth, or $drh. This returns native database engine error code from the last driver method called."
},
{
"code": null,
"e": 186603,
"s": 186590,
"text": "$DBI::errstr"
},
{
"code": null,
"e": 186786,
"s": 186603,
"text": "This is equivalent to $h->errstr, where $h is any of the handle types like $dbh, $sth, or $drh. This returns the native database engine error message from the last DBI method called."
},
{
"code": null,
"e": 186805,
"s": 186786,
"text": "$dbh->disconnect()"
},
{
"code": null,
"e": 186894,
"s": 186805,
"text": "This routine closes a database connection previously opened by a call to DBI->connect()."
},
{
"code": null,
"e": 187064,
"s": 186894,
"text": "Following Perl code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned."
},
{
"code": null,
"e": 187369,
"s": 187064,
"text": "#!/usr/bin/perl\n\nuse DBI;\nuse strict;\n\nmy $driver = \"SQLite\"; \nmy $database = \"test.db\";\nmy $dsn = \"DBI:$driver:dbname=$database\";\nmy $userid = \"\";\nmy $password = \"\";\nmy $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) \n or die $DBI::errstr;\n\nprint \"Opened database successfully\\n\";"
},
{
"code": null,
"e": 187664,
"s": 187369,
"text": "Now, let's run the above program to create our database test.db in the current directory. You can change your path as per your requirement. Keep the above code in sqlite.pl file and execute it as shown below. If the database is successfully created, then it will display the following message −"
},
{
"code": null,
"e": 187726,
"s": 187664,
"text": "$ chmod +x sqlite.pl\n$ ./sqlite.pl\nOpen database successfully"
},
{
"code": null,
"e": 187811,
"s": 187726,
"text": "Following Perl program is used to create a table in the previously created database."
},
{
"code": null,
"e": 188461,
"s": 187811,
"text": "#!/usr/bin/perl\n\nuse DBI;\nuse strict;\n\nmy $driver = \"SQLite\";\nmy $database = \"test.db\";\nmy $dsn = \"DBI:$driver:dbname=$database\";\nmy $userid = \"\";\nmy $password = \"\";\nmy $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })\n or die $DBI::errstr;\nprint \"Opened database successfully\\n\";\n\nmy $stmt = qq(CREATE TABLE COMPANY\n (ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL););\n\nmy $rv = $dbh->do($stmt);\nif($rv < 0) {\n print $DBI::errstr;\n} else {\n print \"Table created successfully\\n\";\n}\n$dbh->disconnect();"
},
{
"code": null,
"e": 188587,
"s": 188461,
"text": "When the above program is executed, it will create COMPANY table in your test.db and it will display the following messages −"
},
{
"code": null,
"e": 188644,
"s": 188587,
"text": "Opened database successfully\nTable created successfully\n"
},
{
"code": null,
"e": 188713,
"s": 188644,
"text": "NOTE − In case you see the following error in any of the operation −"
},
{
"code": null,
"e": 188784,
"s": 188713,
"text": "DBD::SQLite::st execute failed: not an error(21) at dbdimp.c line 398\n"
},
{
"code": null,
"e": 189028,
"s": 188784,
"text": "In such case, open dbdimp.c file available in DBD-SQLite installation and find out sqlite3_prepare() function and change its third argument to -1 instead of 0. Finally, install DBD::SQLite using make and do make install to resolve the problem."
},
{
"code": null,
"e": 189130,
"s": 189028,
"text": "Following Perl program shows how to create records in the COMPANY table created in the above example."
},
{
"code": null,
"e": 190171,
"s": 189130,
"text": "#!/usr/bin/perl\n\nuse DBI;\nuse strict;\n\nmy $driver = \"SQLite\";\nmy $database = \"test.db\";\nmy $dsn = \"DBI:$driver:dbname=$database\";\nmy $userid = \"\";\nmy $password = \"\";\nmy $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })\n or die $DBI::errstr;\nprint \"Opened database successfully\\n\";\n\nmy $stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\n VALUES (1, 'Paul', 32, 'California', 20000.00 ));\nmy $rv = $dbh->do($stmt) or die $DBI::errstr;\n\n$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\n VALUES (2, 'Allen', 25, 'Texas', 15000.00 ));\n$rv = $dbh->do($stmt) or die $DBI::errstr;\n\n$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\n VALUES (3, 'Teddy', 23, 'Norway', 20000.00 ));\n\n$rv = $dbh->do($stmt) or die $DBI::errstr;\n\n$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\n VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 ););\n\n$rv = $dbh->do($stmt) or die $DBI::errstr;\n\nprint \"Records created successfully\\n\";\n$dbh->disconnect();"
},
{
"code": null,
"e": 190307,
"s": 190171,
"text": "When the above program is executed, it will create the given records in the COMPANY table and it will display the following two lines −"
},
{
"code": null,
"e": 190366,
"s": 190307,
"text": "Opened database successfully\nRecords created successfully\n"
},
{
"code": null,
"e": 190481,
"s": 190366,
"text": "Following Perl program shows how to fetch and display records from the COMPANY table created in the above example."
},
{
"code": null,
"e": 191228,
"s": 190481,
"text": "#!/usr/bin/perl\n\nuse DBI;\nuse strict;\n\nmy $driver = \"SQLite\";\nmy $database = \"test.db\";\nmy $dsn = \"DBI:$driver:dbname=$database\";\nmy $userid = \"\";\nmy $password = \"\";\nmy $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })\n or die $DBI::errstr;\nprint \"Opened database successfully\\n\";\n\nmy $stmt = qq(SELECT id, name, address, salary from COMPANY;);\nmy $sth = $dbh->prepare( $stmt );\nmy $rv = $sth->execute() or die $DBI::errstr;\n\nif($rv < 0) {\n print $DBI::errstr;\n}\n\nwhile(my @row = $sth->fetchrow_array()) {\n print \"ID = \". $row[0] . \"\\n\";\n print \"NAME = \". $row[1] .\"\\n\";\n print \"ADDRESS = \". $row[2] .\"\\n\";\n print \"SALARY = \". $row[3] .\"\\n\\n\";\n}\nprint \"Operation done successfully\\n\";\n$dbh->disconnect();"
},
{
"code": null,
"e": 191302,
"s": 191228,
"text": "When the above program is executed, it will produce the following result."
},
{
"code": null,
"e": 191580,
"s": 191302,
"text": "Opened database successfully\nID = 1\nNAME = Paul\nADDRESS = California\nSALARY = 20000\n\nID = 2\nNAME = Allen\nADDRESS = Texas\nSALARY = 15000\n\nID = 3\nNAME = Teddy\nADDRESS = Norway\nSALARY = 20000\n\nID = 4\nNAME = Mark\nADDRESS = Rich-Mond\nSALARY = 65000\n\nOperation done successfully\n"
},
{
"code": null,
"e": 191722,
"s": 191580,
"text": "Following Perl code shows how to UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table."
},
{
"code": null,
"e": 192676,
"s": 191722,
"text": "#!/usr/bin/perl\n\nuse DBI;\nuse strict;\n\nmy $driver = \"SQLite\";\nmy $database = \"test.db\";\nmy $dsn = \"DBI:$driver:dbname=$database\";\nmy $userid = \"\";\nmy $password = \"\";\nmy $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })\n or die $DBI::errstr;\nprint \"Opened database successfully\\n\";\n\nmy $stmt = qq(UPDATE COMPANY set SALARY = 25000.00 where ID=1;);\nmy $rv = $dbh->do($stmt) or die $DBI::errstr;\n\nif( $rv < 0 ) {\n print $DBI::errstr;\n} else {\n print \"Total number of rows updated : $rv\\n\";\n}\n$stmt = qq(SELECT id, name, address, salary from COMPANY;);\nmy $sth = $dbh->prepare( $stmt );\n$rv = $sth->execute() or die $DBI::errstr;\n\nif($rv < 0) {\n print $DBI::errstr;\n}\n\nwhile(my @row = $sth->fetchrow_array()) {\n print \"ID = \". $row[0] . \"\\n\";\n print \"NAME = \". $row[1] .\"\\n\";\n print \"ADDRESS = \". $row[2] .\"\\n\";\n print \"SALARY = \". $row[3] .\"\\n\\n\";\n}\nprint \"Operation done successfully\\n\";\n$dbh->disconnect();"
},
{
"code": null,
"e": 192750,
"s": 192676,
"text": "When the above program is executed, it will produce the following result."
},
{
"code": null,
"e": 193061,
"s": 192750,
"text": "Opened database successfully\nTotal number of rows updated : 1\nID = 1\nNAME = Paul\nADDRESS = California\nSALARY = 25000\n\nID = 2\nNAME = Allen\nADDRESS = Texas\nSALARY = 15000\n\nID = 3\nNAME = Teddy\nADDRESS = Norway\nSALARY = 20000\n\nID = 4\nNAME = Mark\nADDRESS = Rich-Mond\nSALARY = 65000\n\nOperation done successfully\n"
},
{
"code": null,
"e": 193210,
"s": 193061,
"text": "Following Perl code shows how to use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table −"
},
{
"code": null,
"e": 194150,
"s": 193210,
"text": "#!/usr/bin/perl\n\nuse DBI;\nuse strict;\n\nmy $driver = \"SQLite\";\nmy $database = \"test.db\";\nmy $dsn = \"DBI:$driver:dbname=$database\";\nmy $userid = \"\";\nmy $password = \"\";\nmy $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })\n or die $DBI::errstr;\nprint \"Opened database successfully\\n\";\n\nmy $stmt = qq(DELETE from COMPANY where ID = 2;);\nmy $rv = $dbh->do($stmt) or die $DBI::errstr;\n\nif( $rv < 0 ) {\n print $DBI::errstr;\n} else {\n print \"Total number of rows deleted : $rv\\n\";\n}\n\n$stmt = qq(SELECT id, name, address, salary from COMPANY;);\nmy $sth = $dbh->prepare( $stmt );\n$rv = $sth->execute() or die $DBI::errstr;\n\nif($rv < 0) {\n print $DBI::errstr;\n}\n\nwhile(my @row = $sth->fetchrow_array()) {\n print \"ID = \". $row[0] . \"\\n\";\n print \"NAME = \". $row[1] .\"\\n\";\n print \"ADDRESS = \". $row[2] .\"\\n\";\n print \"SALARY = \". $row[3] .\"\\n\\n\";\n}\nprint \"Operation done successfully\\n\";\n$dbh->disconnect();"
},
{
"code": null,
"e": 194224,
"s": 194150,
"text": "When the above program is executed, it will produce the following result."
},
{
"code": null,
"e": 194479,
"s": 194224,
"text": "Opened database successfully\nTotal number of rows deleted : 1\nID = 1\nNAME = Paul\nADDRESS = California\nSALARY = 25000\n\nID = 3\nNAME = Teddy\nADDRESS = Norway\nSALARY = 20000\n\nID = 4\nNAME = Mark\nADDRESS = Rich-Mond\nSALARY = 65000\n\nOperation done successfully\n"
},
{
"code": null,
"e": 194549,
"s": 194479,
"text": "In this chapter, you will learn how to use SQLite in Python programs."
},
{
"code": null,
"e": 194865,
"s": 194549,
"text": "SQLite3 can be integrated with Python using sqlite3 module, which was written by Gerhard Haring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. You do not need to install this module separately because it is shipped by default along with Python version 2.5.x onwards."
},
{
"code": null,
"e": 195068,
"s": 194865,
"text": "To use sqlite3 module, you must first create a connection object that represents the database and then optionally you can create a cursor object, which will help you in executing all the SQL statements."
},
{
"code": null,
"e": 195335,
"s": 195068,
"text": "Following are important sqlite3 module routines, which can suffice your requirement to work with SQLite database from your Python program. If you are looking for a more sophisticated application, then you can look into Python sqlite3 module's official documentation."
},
{
"code": null,
"e": 195398,
"s": 195335,
"text": "sqlite3.connect(database [,timeout ,other optional arguments])"
},
{
"code": null,
"e": 195630,
"s": 195398,
"text": "This API opens a connection to the SQLite database file. You can use \":memory:\" to open a database connection to a database that resides in RAM instead of on disk. If database is opened successfully, it returns a connection object."
},
{
"code": null,
"e": 195979,
"s": 195630,
"text": "When a database is accessed by multiple connections, and one of the processes modifies the database, the SQLite database is locked until that transaction is committed. The timeout parameter specifies how long the connection should wait for the lock to go away until raising an exception. The default for the timeout parameter is 5.0 (five seconds)."
},
{
"code": null,
"e": 196198,
"s": 195979,
"text": "If the given database name does not exist then this call will create the database. You can specify filename with the required path as well if you want to create a database anywhere else except in the current directory."
},
{
"code": null,
"e": 196231,
"s": 196198,
"text": "connection.cursor([cursorClass])"
},
{
"code": null,
"e": 196471,
"s": 196231,
"text": "This routine creates a cursor which will be used throughout of your database programming with Python. This method accepts a single optional parameter cursorClass. If supplied, this must be a custom cursor class that extends sqlite3.Cursor."
},
{
"code": null,
"e": 196515,
"s": 196471,
"text": "cursor.execute(sql [, optional parameters])"
},
{
"code": null,
"e": 196748,
"s": 196515,
"text": "This routine executes an SQL statement. The SQL statement may be parameterized (i. e. placeholders instead of SQL literals). The sqlite3 module supports two kinds of placeholders: question marks and named placeholders (named style)."
},
{
"code": null,
"e": 196825,
"s": 196748,
"text": "For example − cursor.execute(\"insert into people values (?, ?)\", (who, age))"
},
{
"code": null,
"e": 196873,
"s": 196825,
"text": "connection.execute(sql [, optional parameters])"
},
{
"code": null,
"e": 197099,
"s": 196873,
"text": "This routine is a shortcut of the above execute method provided by the cursor object and it creates an intermediate cursor object by calling the cursor method, then calls the cursor's execute method with the parameters given."
},
{
"code": null,
"e": 197142,
"s": 197099,
"text": "cursor.executemany(sql, seq_of_parameters)"
},
{
"code": null,
"e": 197250,
"s": 197142,
"text": "This routine executes an SQL command against all parameter sequences or mappings found in the sequence sql."
},
{
"code": null,
"e": 197292,
"s": 197250,
"text": "connection.executemany(sql[, parameters])"
},
{
"code": null,
"e": 197462,
"s": 197292,
"text": "This routine is a shortcut that creates an intermediate cursor object by calling the cursor method, then calls the cursor.s executemany method with the parameters given."
},
{
"code": null,
"e": 197495,
"s": 197462,
"text": "cursor.executescript(sql_script)"
},
{
"code": null,
"e": 197734,
"s": 197495,
"text": "This routine executes multiple SQL statements at once provided in the form of script. It issues a COMMIT statement first, then executes the SQL script it gets as a parameter. All the SQL statements should be separated by a semi colon (;)."
},
{
"code": null,
"e": 197771,
"s": 197734,
"text": "connection.executescript(sql_script)"
},
{
"code": null,
"e": 197943,
"s": 197771,
"text": "This routine is a shortcut that creates an intermediate cursor object by calling the cursor method, then calls the cursor's executescript method with the parameters given."
},
{
"code": null,
"e": 197970,
"s": 197943,
"text": "connection.total_changes()"
},
{
"code": null,
"e": 198113,
"s": 197970,
"text": "This routine returns the total number of database rows that have been modified, inserted, or deleted since the database connection was opened."
},
{
"code": null,
"e": 198133,
"s": 198113,
"text": "connection.commit()"
},
{
"code": null,
"e": 198306,
"s": 198133,
"text": "This method commits the current transaction. If you don't call this method, anything you did since the last call to commit() is not visible from other database connections."
},
{
"code": null,
"e": 198328,
"s": 198306,
"text": "connection.rollback()"
},
{
"code": null,
"e": 198412,
"s": 198328,
"text": "This method rolls back any changes to the database since the last call to commit()."
},
{
"code": null,
"e": 198431,
"s": 198412,
"text": "connection.close()"
},
{
"code": null,
"e": 198630,
"s": 198431,
"text": "This method closes the database connection. Note that this does not automatically call commit(). If you just close your database connection without calling commit() first, your changes will be lost!"
},
{
"code": null,
"e": 198648,
"s": 198630,
"text": "cursor.fetchone()"
},
{
"code": null,
"e": 198773,
"s": 198648,
"text": "This method fetches the next row of a query result set, returning a single sequence, or None when no more data is available."
},
{
"code": null,
"e": 198817,
"s": 198773,
"text": "cursor.fetchmany([size = cursor.arraysize])"
},
{
"code": null,
"e": 199030,
"s": 198817,
"text": "This routine fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available. The method tries to fetch as many rows as indicated by the size parameter."
},
{
"code": null,
"e": 199048,
"s": 199030,
"text": "cursor.fetchall()"
},
{
"code": null,
"e": 199181,
"s": 199048,
"text": "This routine fetches all (remaining) rows of a query result, returning a list. An empty list is returned when no rows are available."
},
{
"code": null,
"e": 199353,
"s": 199181,
"text": "Following Python code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned."
},
{
"code": null,
"e": 199461,
"s": 199353,
"text": "#!/usr/bin/python\n\nimport sqlite3\n\nconn = sqlite3.connect('test.db')\n\nprint \"Opened database successfully\";"
},
{
"code": null,
"e": 199853,
"s": 199461,
"text": "Here, you can also supply database name as the special name :memory: to create a database in RAM. Now, let's run the above program to create our database test.db in the current directory. You can change your path as per your requirement. Keep the above code in sqlite.py file and execute it as shown below. If the database is successfully created, then it will display the following message."
},
{
"code": null,
"e": 199914,
"s": 199853,
"text": "$chmod +x sqlite.py\n$./sqlite.py\nOpen database successfully\n"
},
{
"code": null,
"e": 200006,
"s": 199914,
"text": "Following Python program will be used to create a table in the previously created database."
},
{
"code": null,
"e": 200397,
"s": 200006,
"text": "#!/usr/bin/python\n\nimport sqlite3\n\nconn = sqlite3.connect('test.db')\nprint \"Opened database successfully\";\n\nconn.execute('''CREATE TABLE COMPANY\n (ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL);''')\nprint \"Table created successfully\";\n\nconn.close()"
},
{
"code": null,
"e": 200527,
"s": 200397,
"text": "When the above program is executed, it will create the COMPANY table in your test.db and it will display the following messages −"
},
{
"code": null,
"e": 200584,
"s": 200527,
"text": "Opened database successfully\nTable created successfully\n"
},
{
"code": null,
"e": 200688,
"s": 200584,
"text": "Following Python program shows how to create records in the COMPANY table created in the above example."
},
{
"code": null,
"e": 201346,
"s": 200688,
"text": "#!/usr/bin/python\n\nimport sqlite3\n\nconn = sqlite3.connect('test.db')\nprint \"Opened database successfully\";\n\nconn.execute(\"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \\\n VALUES (1, 'Paul', 32, 'California', 20000.00 )\");\n\nconn.execute(\"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \\\n VALUES (2, 'Allen', 25, 'Texas', 15000.00 )\");\n\nconn.execute(\"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \\\n VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )\");\n\nconn.execute(\"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \\\n VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )\");\n\nconn.commit()\nprint \"Records created successfully\";\nconn.close()"
},
{
"code": null,
"e": 201482,
"s": 201346,
"text": "When the above program is executed, it will create the given records in the COMPANY table and it will display the following two lines −"
},
{
"code": null,
"e": 201541,
"s": 201482,
"text": "Opened database successfully\nRecords created successfully\n"
},
{
"code": null,
"e": 201658,
"s": 201541,
"text": "Following Python program shows how to fetch and display records from the COMPANY table created in the above example."
},
{
"code": null,
"e": 202024,
"s": 201658,
"text": "#!/usr/bin/python\n\nimport sqlite3\n\nconn = sqlite3.connect('test.db')\nprint \"Opened database successfully\";\n\ncursor = conn.execute(\"SELECT id, name, address, salary from COMPANY\")\nfor row in cursor:\n print \"ID = \", row[0]\n print \"NAME = \", row[1]\n print \"ADDRESS = \", row[2]\n print \"SALARY = \", row[3], \"\\n\"\n\nprint \"Operation done successfully\";\nconn.close()"
},
{
"code": null,
"e": 202098,
"s": 202024,
"text": "When the above program is executed, it will produce the following result."
},
{
"code": null,
"e": 202380,
"s": 202098,
"text": "Opened database successfully\nID = 1\nNAME = Paul\nADDRESS = California\nSALARY = 20000.0\n\nID = 2\nNAME = Allen\nADDRESS = Texas\nSALARY = 15000.0\n\nID = 3\nNAME = Teddy\nADDRESS = Norway\nSALARY = 20000.0\n\nID = 4\nNAME = Mark\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nOperation done successfully\n"
},
{
"code": null,
"e": 202528,
"s": 202380,
"text": "Following Python code shows how to use UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table."
},
{
"code": null,
"e": 203034,
"s": 202528,
"text": "#!/usr/bin/python\n\nimport sqlite3\n\nconn = sqlite3.connect('test.db')\nprint \"Opened database successfully\";\n\nconn.execute(\"UPDATE COMPANY set SALARY = 25000.00 where ID = 1\")\nconn.commit()\nprint \"Total number of rows updated :\", conn.total_changes\n\ncursor = conn.execute(\"SELECT id, name, address, salary from COMPANY\")\nfor row in cursor:\n print \"ID = \", row[0]\n print \"NAME = \", row[1]\n print \"ADDRESS = \", row[2]\n print \"SALARY = \", row[3], \"\\n\"\n\nprint \"Operation done successfully\";\nconn.close()"
},
{
"code": null,
"e": 203108,
"s": 203034,
"text": "When the above program is executed, it will produce the following result."
},
{
"code": null,
"e": 203423,
"s": 203108,
"text": "Opened database successfully\nTotal number of rows updated : 1\nID = 1\nNAME = Paul\nADDRESS = California\nSALARY = 25000.0\n\nID = 2\nNAME = Allen\nADDRESS = Texas\nSALARY = 15000.0\n\nID = 3\nNAME = Teddy\nADDRESS = Norway\nSALARY = 20000.0\n\nID = 4\nNAME = Mark\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nOperation done successfully\n"
},
{
"code": null,
"e": 203573,
"s": 203423,
"text": "Following Python code shows how to use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table."
},
{
"code": null,
"e": 204063,
"s": 203573,
"text": "#!/usr/bin/python\n\nimport sqlite3\n\nconn = sqlite3.connect('test.db')\nprint \"Opened database successfully\";\n\nconn.execute(\"DELETE from COMPANY where ID = 2;\")\nconn.commit()\nprint \"Total number of rows deleted :\", conn.total_changes\n\ncursor = conn.execute(\"SELECT id, name, address, salary from COMPANY\")\nfor row in cursor:\n print \"ID = \", row[0]\n print \"NAME = \", row[1]\n print \"ADDRESS = \", row[2]\n print \"SALARY = \", row[3], \"\\n\"\n\nprint \"Operation done successfully\";\nconn.close()"
},
{
"code": null,
"e": 204137,
"s": 204063,
"text": "When the above program is executed, it will produce the following result."
},
{
"code": null,
"e": 204398,
"s": 204137,
"text": "Opened database successfully\nTotal number of rows deleted : 1\nID = 1\nNAME = Paul\nADDRESS = California\nSALARY = 20000.0\n\nID = 3\nNAME = Teddy\nADDRESS = Norway\nSALARY = 20000.0\n\nID = 4\nNAME = Mark\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nOperation done successfully\n"
},
{
"code": null,
"e": 204433,
"s": 204398,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 204454,
"s": 204433,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 204487,
"s": 204454,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 204504,
"s": 204487,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 204535,
"s": 204504,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 204548,
"s": 204535,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 204555,
"s": 204548,
"text": " Print"
},
{
"code": null,
"e": 204566,
"s": 204555,
"text": " Add Notes"
}
]
|
GraphFrames in Jupyter: a practical guide | by Steven Van Dorpe | Towards Data Science | Graph analysis, originally a method used in computational biology, has become a more and more prominent data analysis technique for both social network analysis (community mining and modeling author types) and recommender systems. A simple and intuitive example are the once so famous Facebook friend cluster maps, which visualize the hidden structure of your Facebook network.
For a while, power graph analysis has been a discipline for academici or Facebook or Twitter insiders. But since packages such as GraphX and Graphframes were released, everyone with a little bit of data and a Jupyter Notebook can easily play around in the fascinating world of graphs.
In this article I provide an extensive teaser about the Graphframes API in Jupyter Notebooks. First we walk through setting up the Jupyter Notebook environment for using the GraphFrames package (on a Windows machine). Then we discover the basic functionalities and how to import data into the frames, to finish off with an explanation of some of the commonly used high-level function. Please note that this article assumes you have a basic knowledge about Spark and Spark DataFrames.
GraphX is to RDDs as GraphFrames are to DataFrames.
The functionality of GraphFrames and GraphX is essentially the same, the only difference is that GraphFrames are based upon Spark DataFrames, rather than RDDs. If you are used to work with GraphX, Graphframes should be easy to learn just by browsing through the API documentation.
The first thing you want to check before proceeding, is making sure Spark and pyspark are properly installed on your machine. For simplicity we wil run spark in local mode during this tutorial. The easiest way to check this is to enter pyspark in the shell of your Python distribution. You should see something like this if both are installed properly:
Welcome to ____ __ / __/__ ___ _____/ /__ _\ \/ _ \/ _ `/ __/ '_/ /__ / .__/\_,_/_/ /_/\_\ version 2.xx.xx /_/Using Python version 3.xx.xx
For more information about setting up Apache Spark and pyspark I recommend this tutorial and the official documentation.
Next, you want to set your environment variables to run pyspark in the Jupyter Notebook (as opposed to the shell). This can be achieved easily by adding two environment variables:
set PYSPARK_DRIVER_PYTHON=jupyterset PYSPARK_DRIVER_PYTHON_OPTS=notebook
Then navigate to the location where you want to store the new notebook and run pyspark again in your shell, but add a packages flag and indicate you want to use the GraphFrames package. Here, the newest version is used, but any older version can be used by changing the last part of the argument:
pyspark --packages graphframes:graphframes:0.5.0-spark2.1-s_2.11
Create a new Notebook and make sure you can successfully run:
from graphframes import *
The core class of the package is —surprisingly — the GraphFrame. A GraphFrame is always created from a vertex DataFrame (e.g. users) and an edges DataFrame (e.g. relationships between users). The schema of both DataFrames has some mandatory columns. The vertex DataFrame must contain a column named id that stores unique vertex IDs. The edges DataFrame must contain a column named src that stores the source of the edge and a column named dst that stores the destination of the edge. All other columns are optional and can be added depending on one’s needs.
An easy example can be:
from pyspark import *from pyspark.sql import *spark = SparkSession.builder.appName('fun').getOrCreate()vertices = spark.createDataFrame([('1', 'Carter', 'Derrick', 50), ('2', 'May', 'Derrick', 26), ('3', 'Mills', 'Jeff', 80), ('4', 'Hood', 'Robert', 65), ('5', 'Banks', 'Mike', 93), ('98', 'Berg', 'Tim', 28), ('99', 'Page', 'Allan', 16)], ['id', 'name', 'firstname', 'age'])edges = spark.createDataFrame([('1', '2', 'friend'), ('2', '1', 'friend'), ('3', '1', 'friend'), ('1', '3', 'friend'), ('2', '3', 'follows'), ('3', '4', 'friend'), ('4', '3', 'friend'), ('5', '3', 'friend'), ('3', '5', 'friend'), ('4', '5', 'follows'), ('98', '99', 'friend'), ('99', '98', 'friend')], ['src', 'dst', 'type'])g = GraphFrame(vertices, edges)## Take a look at the DataFramesg.vertices.show()g.edges.show()## Check the number of edges of each vertexg.degrees.show()
Of course you want to use real-life, actual data. You can import anything from a simple csv-file to a Parquet-file into a DataFrame. Then name your columns appropriately, filter (if needed) and move on from there. More information about importing data into a Spark Dataframe can be found in the documentation.
The GraphFrame we just created is a directed one, and can be visualized as follows:
Undirected graphs have edges that do not have a direction. The edges indicate a two-way relationship, in that each edge can be traversed in both directions. If your DataFrame only consist of two-way directed edges, you may be interested in analyzing undirected edges. You can convert your graph by mapping a function over the edges DataFrame that deletes the row if src ≥ dst (or the other way around). In GraphX you could use to_undirected() to create a deep, undirected copy of the Graph, unfortunately GraphFrames does not support this functionality.
An easy example to work around this missing functionality can be found in the following code snippet. Please note that the ‘follows’ edge doesn’t really make sense in an undirected graph, since doesn’t represent a two-way relationship.
copy = edgesfrom pyspark.sql.functions import udf@udf("string")def to_undir(src, dst): if src >= dst: return 'Delete' else : return 'Keep'copy.withColumn('undir', to_undir(copy.src, copy.dst))\.filter('undir == "Keep"').drop('undir').show()## for efficiency, it's better to avoid udf functions where possible ## and use built-in pyspark.sql.functions instead.
A GraphFrame itself can’t be filtered, but DataFrames deducted from a Graph can. Consequently, the filter-function (or any other function) can be used just as you would use it with DataFrames. The only trap-hole might be the correct use of quotation marks: the whole condition should be quoted. The examples below should clarify this.
g.vertices.filter("age > 30").show()g.inDegrees.filter("inDegree >= 2").sort("inDegree", ascending=False).show()g.edges.filter('type == "friend"')
A connected component of a graph is a subgraph in which any two vertices are connected to each other by one or more edges, and which is connected to no additional vertices in the supergraph. In the (undirected) example below there are three connected components. Connected components detection can be interesting for clustering, but also to make your computations more efficient.
Practically, GraphFrames requires you to set a directory where it can save checkpoints. Create such a folder in your working directory and drop the following line (where graphframes_cps is your new folder) in Jupyter to set the checkpoint directory.
sc.setCheckpointDir('graphframes_cps')
Then, the connected components can easily be computed with the connectedComponents-function.
g.connectedComponents().show()
Our mini-graph has two connected components, which are described for each vertex in the component column.
+---+------+---------+---+------------+| id| name|firstname|age| component|+---+------+---------+---+------------+| 1|Carter| Derrick| 50|154618822656|| 2| May| Derrick| 26|154618822656|| 3| Mills| Jeff| 80|154618822656|| 4| Hood| Robert| 65|154618822656|| 5| Banks| Mike| 93|154618822656|| 98| Berg| Tim| 28|317827579904|| 99| Page| Allan| 16|317827579904|+---+------+---------+---+------------+
Finding motifs helps to execute queries to discover structural patterns in graphs. Network motifs are patterns that occur repeatedly in the graph and represent the relationships between the vertices. GraphFrames motif finding uses a declarative Domain Specific Language (DSL) for expressing structural queries.
The query can be invoked by using the find-function, where the motif (in quotation marks) is expressed as the first parameter of the function.
The following example will search for pairs of vertices a,b connected by edge e and pairs of vertices b,c connected by edge e2. It will return a DataFrame of all such structures in the graph, with columns for each of the named elements (vertices or edges) in the motif.
g.find("(a)-[e]->(b); (b)-[e2]->(a)").show()
If edges and/or vertices are anonymous, they won’t be displayed in the resulting DataFrame. Motifs can be joined by a semicolon and can be negated with a exclamation mark. More details about the Domain Specific Language can be found in the documentation.
As an example we can try to find the mutual friends for any pair of users a and c. In order to be a mutual friend b, b must be a friend with both a and c (and not just followed by c, for example).
mutualFriends = g.find("(a)-[]->(b); (b)-[]->(c); (c)-[]->(b); (b)-[]->(a)")\.dropDuplicates()
To query all the mutual friends between 2 and 3 we can filter the DataFrame.
mutualFriends.filter('a.id == 2 and c.id == 3').show()
The b-column will show all the mutual friends (just one in this case).
+--------------------+--------------------+--------------------+| a| b| c|+--------------------+--------------------+--------------------+|[2, May, Derrick,...|[1, Carter, Derri...|[3, Mills, Jeff, 80]|+--------------------+--------------------+--------------------+
To finish up, we’ll discover two additional built-in algorithms. TriangleCount counts the number of triangles passing through each vertex in this graph. A triangle can be defined as a group of three vertices that is interrelated, i.e. a has an edge to b, b has an edge to c, and c has an edge to a. The example below shows a graph with two triangles.
In the GraphFrames package you can count the number of triangles passing through each vertex by invoking the triangleCount-function. Note that our simple example has only two triangles in total. Triangles are used for various tasks for real‐life networks, including community discovery, link prediction, and spam filtering.
g.triangleCount().show()
The last function we discuss is PageRank. PageRank works by counting the number and quality of links to a page to determine a rough estimate of how important the website is. The underlying assumption is that more important websites are likely to receive more links from other websites.
The PageRank algorithm holds that an imaginary surfer who is randomly clicking on links will eventually stop clicking. The probability, at any step, that the person will continue is a damping factor. The damping factor can be be set by changing the resetProbability parameter. Other important parameters are the tolerance (tol) and the maximum number of iterations (maxIter).
pr = g.pageRank(resetProbability=0.15, tol=0.01)## look at the pagerank score for every vertexpr.vertices.show()## look at the weight of every edgepr.edges.show() | [
{
"code": null,
"e": 550,
"s": 172,
"text": "Graph analysis, originally a method used in computational biology, has become a more and more prominent data analysis technique for both social network analysis (community mining and modeling author types) and recommender systems. A simple and intuitive example are the once so famous Facebook friend cluster maps, which visualize the hidden structure of your Facebook network."
},
{
"code": null,
"e": 835,
"s": 550,
"text": "For a while, power graph analysis has been a discipline for academici or Facebook or Twitter insiders. But since packages such as GraphX and Graphframes were released, everyone with a little bit of data and a Jupyter Notebook can easily play around in the fascinating world of graphs."
},
{
"code": null,
"e": 1319,
"s": 835,
"text": "In this article I provide an extensive teaser about the Graphframes API in Jupyter Notebooks. First we walk through setting up the Jupyter Notebook environment for using the GraphFrames package (on a Windows machine). Then we discover the basic functionalities and how to import data into the frames, to finish off with an explanation of some of the commonly used high-level function. Please note that this article assumes you have a basic knowledge about Spark and Spark DataFrames."
},
{
"code": null,
"e": 1371,
"s": 1319,
"text": "GraphX is to RDDs as GraphFrames are to DataFrames."
},
{
"code": null,
"e": 1652,
"s": 1371,
"text": "The functionality of GraphFrames and GraphX is essentially the same, the only difference is that GraphFrames are based upon Spark DataFrames, rather than RDDs. If you are used to work with GraphX, Graphframes should be easy to learn just by browsing through the API documentation."
},
{
"code": null,
"e": 2005,
"s": 1652,
"text": "The first thing you want to check before proceeding, is making sure Spark and pyspark are properly installed on your machine. For simplicity we wil run spark in local mode during this tutorial. The easiest way to check this is to enter pyspark in the shell of your Python distribution. You should see something like this if both are installed properly:"
},
{
"code": null,
"e": 2180,
"s": 2005,
"text": "Welcome to ____ __ / __/__ ___ _____/ /__ _\\ \\/ _ \\/ _ `/ __/ '_/ /__ / .__/\\_,_/_/ /_/\\_\\ version 2.xx.xx /_/Using Python version 3.xx.xx"
},
{
"code": null,
"e": 2301,
"s": 2180,
"text": "For more information about setting up Apache Spark and pyspark I recommend this tutorial and the official documentation."
},
{
"code": null,
"e": 2481,
"s": 2301,
"text": "Next, you want to set your environment variables to run pyspark in the Jupyter Notebook (as opposed to the shell). This can be achieved easily by adding two environment variables:"
},
{
"code": null,
"e": 2554,
"s": 2481,
"text": "set PYSPARK_DRIVER_PYTHON=jupyterset PYSPARK_DRIVER_PYTHON_OPTS=notebook"
},
{
"code": null,
"e": 2851,
"s": 2554,
"text": "Then navigate to the location where you want to store the new notebook and run pyspark again in your shell, but add a packages flag and indicate you want to use the GraphFrames package. Here, the newest version is used, but any older version can be used by changing the last part of the argument:"
},
{
"code": null,
"e": 2916,
"s": 2851,
"text": "pyspark --packages graphframes:graphframes:0.5.0-spark2.1-s_2.11"
},
{
"code": null,
"e": 2978,
"s": 2916,
"text": "Create a new Notebook and make sure you can successfully run:"
},
{
"code": null,
"e": 3004,
"s": 2978,
"text": "from graphframes import *"
},
{
"code": null,
"e": 3562,
"s": 3004,
"text": "The core class of the package is —surprisingly — the GraphFrame. A GraphFrame is always created from a vertex DataFrame (e.g. users) and an edges DataFrame (e.g. relationships between users). The schema of both DataFrames has some mandatory columns. The vertex DataFrame must contain a column named id that stores unique vertex IDs. The edges DataFrame must contain a column named src that stores the source of the edge and a column named dst that stores the destination of the edge. All other columns are optional and can be added depending on one’s needs."
},
{
"code": null,
"e": 3586,
"s": 3562,
"text": "An easy example can be:"
},
{
"code": null,
"e": 5024,
"s": 3586,
"text": "from pyspark import *from pyspark.sql import *spark = SparkSession.builder.appName('fun').getOrCreate()vertices = spark.createDataFrame([('1', 'Carter', 'Derrick', 50), ('2', 'May', 'Derrick', 26), ('3', 'Mills', 'Jeff', 80), ('4', 'Hood', 'Robert', 65), ('5', 'Banks', 'Mike', 93), ('98', 'Berg', 'Tim', 28), ('99', 'Page', 'Allan', 16)], ['id', 'name', 'firstname', 'age'])edges = spark.createDataFrame([('1', '2', 'friend'), ('2', '1', 'friend'), ('3', '1', 'friend'), ('1', '3', 'friend'), ('2', '3', 'follows'), ('3', '4', 'friend'), ('4', '3', 'friend'), ('5', '3', 'friend'), ('3', '5', 'friend'), ('4', '5', 'follows'), ('98', '99', 'friend'), ('99', '98', 'friend')], ['src', 'dst', 'type'])g = GraphFrame(vertices, edges)## Take a look at the DataFramesg.vertices.show()g.edges.show()## Check the number of edges of each vertexg.degrees.show()"
},
{
"code": null,
"e": 5334,
"s": 5024,
"text": "Of course you want to use real-life, actual data. You can import anything from a simple csv-file to a Parquet-file into a DataFrame. Then name your columns appropriately, filter (if needed) and move on from there. More information about importing data into a Spark Dataframe can be found in the documentation."
},
{
"code": null,
"e": 5418,
"s": 5334,
"text": "The GraphFrame we just created is a directed one, and can be visualized as follows:"
},
{
"code": null,
"e": 5972,
"s": 5418,
"text": "Undirected graphs have edges that do not have a direction. The edges indicate a two-way relationship, in that each edge can be traversed in both directions. If your DataFrame only consist of two-way directed edges, you may be interested in analyzing undirected edges. You can convert your graph by mapping a function over the edges DataFrame that deletes the row if src ≥ dst (or the other way around). In GraphX you could use to_undirected() to create a deep, undirected copy of the Graph, unfortunately GraphFrames does not support this functionality."
},
{
"code": null,
"e": 6208,
"s": 5972,
"text": "An easy example to work around this missing functionality can be found in the following code snippet. Please note that the ‘follows’ edge doesn’t really make sense in an undirected graph, since doesn’t represent a two-way relationship."
},
{
"code": null,
"e": 6589,
"s": 6208,
"text": "copy = edgesfrom pyspark.sql.functions import udf@udf(\"string\")def to_undir(src, dst): if src >= dst: return 'Delete' else : return 'Keep'copy.withColumn('undir', to_undir(copy.src, copy.dst))\\.filter('undir == \"Keep\"').drop('undir').show()## for efficiency, it's better to avoid udf functions where possible ## and use built-in pyspark.sql.functions instead."
},
{
"code": null,
"e": 6924,
"s": 6589,
"text": "A GraphFrame itself can’t be filtered, but DataFrames deducted from a Graph can. Consequently, the filter-function (or any other function) can be used just as you would use it with DataFrames. The only trap-hole might be the correct use of quotation marks: the whole condition should be quoted. The examples below should clarify this."
},
{
"code": null,
"e": 7071,
"s": 6924,
"text": "g.vertices.filter(\"age > 30\").show()g.inDegrees.filter(\"inDegree >= 2\").sort(\"inDegree\", ascending=False).show()g.edges.filter('type == \"friend\"')"
},
{
"code": null,
"e": 7451,
"s": 7071,
"text": "A connected component of a graph is a subgraph in which any two vertices are connected to each other by one or more edges, and which is connected to no additional vertices in the supergraph. In the (undirected) example below there are three connected components. Connected components detection can be interesting for clustering, but also to make your computations more efficient."
},
{
"code": null,
"e": 7701,
"s": 7451,
"text": "Practically, GraphFrames requires you to set a directory where it can save checkpoints. Create such a folder in your working directory and drop the following line (where graphframes_cps is your new folder) in Jupyter to set the checkpoint directory."
},
{
"code": null,
"e": 7740,
"s": 7701,
"text": "sc.setCheckpointDir('graphframes_cps')"
},
{
"code": null,
"e": 7833,
"s": 7740,
"text": "Then, the connected components can easily be computed with the connectedComponents-function."
},
{
"code": null,
"e": 7864,
"s": 7833,
"text": "g.connectedComponents().show()"
},
{
"code": null,
"e": 7970,
"s": 7864,
"text": "Our mini-graph has two connected components, which are described for each vertex in the component column."
},
{
"code": null,
"e": 8400,
"s": 7970,
"text": "+---+------+---------+---+------------+| id| name|firstname|age| component|+---+------+---------+---+------------+| 1|Carter| Derrick| 50|154618822656|| 2| May| Derrick| 26|154618822656|| 3| Mills| Jeff| 80|154618822656|| 4| Hood| Robert| 65|154618822656|| 5| Banks| Mike| 93|154618822656|| 98| Berg| Tim| 28|317827579904|| 99| Page| Allan| 16|317827579904|+---+------+---------+---+------------+"
},
{
"code": null,
"e": 8711,
"s": 8400,
"text": "Finding motifs helps to execute queries to discover structural patterns in graphs. Network motifs are patterns that occur repeatedly in the graph and represent the relationships between the vertices. GraphFrames motif finding uses a declarative Domain Specific Language (DSL) for expressing structural queries."
},
{
"code": null,
"e": 8854,
"s": 8711,
"text": "The query can be invoked by using the find-function, where the motif (in quotation marks) is expressed as the first parameter of the function."
},
{
"code": null,
"e": 9124,
"s": 8854,
"text": "The following example will search for pairs of vertices a,b connected by edge e and pairs of vertices b,c connected by edge e2. It will return a DataFrame of all such structures in the graph, with columns for each of the named elements (vertices or edges) in the motif."
},
{
"code": null,
"e": 9169,
"s": 9124,
"text": "g.find(\"(a)-[e]->(b); (b)-[e2]->(a)\").show()"
},
{
"code": null,
"e": 9424,
"s": 9169,
"text": "If edges and/or vertices are anonymous, they won’t be displayed in the resulting DataFrame. Motifs can be joined by a semicolon and can be negated with a exclamation mark. More details about the Domain Specific Language can be found in the documentation."
},
{
"code": null,
"e": 9621,
"s": 9424,
"text": "As an example we can try to find the mutual friends for any pair of users a and c. In order to be a mutual friend b, b must be a friend with both a and c (and not just followed by c, for example)."
},
{
"code": null,
"e": 9716,
"s": 9621,
"text": "mutualFriends = g.find(\"(a)-[]->(b); (b)-[]->(c); (c)-[]->(b); (b)-[]->(a)\")\\.dropDuplicates()"
},
{
"code": null,
"e": 9793,
"s": 9716,
"text": "To query all the mutual friends between 2 and 3 we can filter the DataFrame."
},
{
"code": null,
"e": 9848,
"s": 9793,
"text": "mutualFriends.filter('a.id == 2 and c.id == 3').show()"
},
{
"code": null,
"e": 9919,
"s": 9848,
"text": "The b-column will show all the mutual friends (just one in this case)."
},
{
"code": null,
"e": 10240,
"s": 9919,
"text": "+--------------------+--------------------+--------------------+| a| b| c|+--------------------+--------------------+--------------------+|[2, May, Derrick,...|[1, Carter, Derri...|[3, Mills, Jeff, 80]|+--------------------+--------------------+--------------------+"
},
{
"code": null,
"e": 10591,
"s": 10240,
"text": "To finish up, we’ll discover two additional built-in algorithms. TriangleCount counts the number of triangles passing through each vertex in this graph. A triangle can be defined as a group of three vertices that is interrelated, i.e. a has an edge to b, b has an edge to c, and c has an edge to a. The example below shows a graph with two triangles."
},
{
"code": null,
"e": 10915,
"s": 10591,
"text": "In the GraphFrames package you can count the number of triangles passing through each vertex by invoking the triangleCount-function. Note that our simple example has only two triangles in total. Triangles are used for various tasks for real‐life networks, including community discovery, link prediction, and spam filtering."
},
{
"code": null,
"e": 10940,
"s": 10915,
"text": "g.triangleCount().show()"
},
{
"code": null,
"e": 11226,
"s": 10940,
"text": "The last function we discuss is PageRank. PageRank works by counting the number and quality of links to a page to determine a rough estimate of how important the website is. The underlying assumption is that more important websites are likely to receive more links from other websites."
},
{
"code": null,
"e": 11602,
"s": 11226,
"text": "The PageRank algorithm holds that an imaginary surfer who is randomly clicking on links will eventually stop clicking. The probability, at any step, that the person will continue is a damping factor. The damping factor can be be set by changing the resetProbability parameter. Other important parameters are the tolerance (tol) and the maximum number of iterations (maxIter)."
}
]
|
One line function for factorial of a number | 11 Jul, 2022
Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n.
Example :
Factorial of 6 is 6 * 5 * 4 * 3 * 2 * 1 which is 720.
We can find the factorial of a number in one line with the help of Ternary operator or commonly known as Conditional operator in recursion.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find factorial of given number#include<iostream> int factorial(int n){ // single line to find factorial return (n==1 || n==0) ? 1: n * factorial(n - 1);} // Driver Codeint main(){ int num = 5; printf ("Factorial of %d is %d", num, factorial(num)); return 0;}
// Java program to find factorial of given number import java.io.*; class GFG { static int factorial(int n) { // single line to find factorial return (n == 1 || n == 0) ? 1 : n * factorial(n - 1); } public static void main(String[] args) { int num = 5; System.out.println("Factorial of " + num + " is " + factorial(num)); }} // This code is contributed by Ajit.
# Python3 program to find# factorial of given number def factorial(n): # single line to # find factorial return 1 if (n == 1 or n == 0) else n * factorial(n - 1); # Driver Codenum = 5;print("Factorial of", num, "is", factorial(num)); # This is contributed by mits
// C# program to find factorial// of given numberusing System; class GFG{ // Function to calculate factorial static int factorial(int n) { // single line to find factorial return (n == 1 || n == 0) ? 1 : n * factorial(n - 1); } public static void Main() { int num = 5; Console.WriteLine("Factorial of " + num + " is " + factorial(num)); }} // This code is contributed by vt_m.
<?php// PHP program to find// factorial of given number function factorial($n){ // single line to find factorial return ($n==1 || $n==0) ? 1 : $n * factorial($n - 1);} // Driver Code$num = 5;echo "Factorial of ", $num, " is ", factorial($num); // This code is contributed by Ajit.?>
<script>// Javascript program to find// factorial of given number function factorial(n){ // single line to find factorial return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);} // Driver Codelet num = 5;document.write("Factorial of ", num, " is ", factorial(num)); // This code is contributed by _saurabh_jaiswal.</script>
Output :
Factorial of 5 is 120
Time complexity: O(n) where n is given number
Auxiliary Space: O(n)
vt_m
jit_t
Mithun Kumar
_saurabh_jaiswal
technophpfij
factorial
Mathematical
School Programming
Mathematical
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 154,
"s": 53,
"text": "Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. "
},
{
"code": null,
"e": 219,
"s": 154,
"text": "Example :\n\nFactorial of 6 is 6 * 5 * 4 * 3 * 2 * 1 which is 720."
},
{
"code": null,
"e": 360,
"s": 219,
"text": "We can find the factorial of a number in one line with the help of Ternary operator or commonly known as Conditional operator in recursion. "
},
{
"code": null,
"e": 366,
"s": 362,
"text": "C++"
},
{
"code": null,
"e": 371,
"s": 366,
"text": "Java"
},
{
"code": null,
"e": 379,
"s": 371,
"text": "Python3"
},
{
"code": null,
"e": 382,
"s": 379,
"text": "C#"
},
{
"code": null,
"e": 386,
"s": 382,
"text": "PHP"
},
{
"code": null,
"e": 397,
"s": 386,
"text": "Javascript"
},
{
"code": "// C++ program to find factorial of given number#include<iostream> int factorial(int n){ // single line to find factorial return (n==1 || n==0) ? 1: n * factorial(n - 1);} // Driver Codeint main(){ int num = 5; printf (\"Factorial of %d is %d\", num, factorial(num)); return 0;}",
"e": 689,
"s": 397,
"text": null
},
{
"code": "// Java program to find factorial of given number import java.io.*; class GFG { static int factorial(int n) { // single line to find factorial return (n == 1 || n == 0) ? 1 : n * factorial(n - 1); } public static void main(String[] args) { int num = 5; System.out.println(\"Factorial of \" + num + \" is \" + factorial(num)); }} // This code is contributed by Ajit.",
"e": 1183,
"s": 689,
"text": null
},
{
"code": "# Python3 program to find# factorial of given number def factorial(n): # single line to # find factorial return 1 if (n == 1 or n == 0) else n * factorial(n - 1); # Driver Codenum = 5;print(\"Factorial of\", num, \"is\", factorial(num)); # This is contributed by mits",
"e": 1466,
"s": 1183,
"text": null
},
{
"code": "// C# program to find factorial// of given numberusing System; class GFG{ // Function to calculate factorial static int factorial(int n) { // single line to find factorial return (n == 1 || n == 0) ? 1 : n * factorial(n - 1); } public static void Main() { int num = 5; Console.WriteLine(\"Factorial of \" + num + \" is \" + factorial(num)); }} // This code is contributed by vt_m.",
"e": 1950,
"s": 1466,
"text": null
},
{
"code": "<?php// PHP program to find// factorial of given number function factorial($n){ // single line to find factorial return ($n==1 || $n==0) ? 1 : $n * factorial($n - 1);} // Driver Code$num = 5;echo \"Factorial of \", $num, \" is \", factorial($num); // This code is contributed by Ajit.?>",
"e": 2254,
"s": 1950,
"text": null
},
{
"code": "<script>// Javascript program to find// factorial of given number function factorial(n){ // single line to find factorial return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);} // Driver Codelet num = 5;document.write(\"Factorial of \", num, \" is \", factorial(num)); // This code is contributed by _saurabh_jaiswal.</script>",
"e": 2598,
"s": 2254,
"text": null
},
{
"code": null,
"e": 2607,
"s": 2598,
"text": "Output :"
},
{
"code": null,
"e": 2630,
"s": 2607,
"text": " Factorial of 5 is 120"
},
{
"code": null,
"e": 2676,
"s": 2630,
"text": "Time complexity: O(n) where n is given number"
},
{
"code": null,
"e": 2699,
"s": 2676,
"text": "Auxiliary Space: O(n) "
},
{
"code": null,
"e": 2704,
"s": 2699,
"text": "vt_m"
},
{
"code": null,
"e": 2710,
"s": 2704,
"text": "jit_t"
},
{
"code": null,
"e": 2723,
"s": 2710,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 2740,
"s": 2723,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 2753,
"s": 2740,
"text": "technophpfij"
},
{
"code": null,
"e": 2763,
"s": 2753,
"text": "factorial"
},
{
"code": null,
"e": 2776,
"s": 2763,
"text": "Mathematical"
},
{
"code": null,
"e": 2795,
"s": 2776,
"text": "School Programming"
},
{
"code": null,
"e": 2808,
"s": 2795,
"text": "Mathematical"
},
{
"code": null,
"e": 2818,
"s": 2808,
"text": "factorial"
}
]
|
Sniffing using bettercap in Linux | 18 Jan, 2021
Sniffing is the process of capturing and monitoring data packets that are passed through the network. It is used to capture the data of the victim and bettercap is a powerful tool used to perform various MITM(man in the middle) attacks on a network. Also, ARP Spoofing is a type of attack in which an attacker sends false ARP (Address Resolution Protocol) messages over a LAN(local area network).
Prerequisites: Kali Linux, laptop or computer with WIFI modem, and bettercap installed in it.
Note: You need to be connected with the network on which you want to sniff. Type these all command on the terminal
Step 1: Selecting the interface of wlan0 i.e Wi-Fi. You can also try it with LAN (local area network ), It will work the same as with Wi-Fi. -iface command is used for selecting the interface. You can use the command ifconfig to get all the interfaces for example if you are connected with an eth0 you need to type bettercap -iface eth0 to get into the bettercap interface.
bettercap -iface wlan0
Step 2: To show all the devices that are connected to the same network with their IP, MAC, Name, etc. Now we need to copy the IP address of the devices on which we want to sniff.
net.show
Step 3: This will provide you with the Modules of bettercap with their status ( i.e running or not running )
help
Step 4: This will send various probe packets to each IP in order and in the present subnet so that net.recon module may detect them with ease.
net.probe on
Step 5: In order to attack both the targets and the gateway, we will have to set arp.spoof.fullduplex to true.
set arp.spoof.fullduplex true
Step 6: Set the target to the IP you can add any number of IPs here by using “,”. For example 192.168.43.157 ,192.168.43.152
set arp.spoof.targets 192.168.43.157(IP address of the target Device)
Step 7: Start the ARP spoofer
set arp.spoof on
Step 8: Setting it to true will consider packets from/to this computer, otherwise it will skip them. As we are MITM (man in the middle) that means all the data is transferring from our computer
set net.sniff.local true
Step 9: Turning on the sniffing and catching the packets.
net.sniff on
Note: After these all steps you can get the data of the targets only for the unsecured sites like the sites with the “http” for the https and the hsts there are some more steps involved in it. For now, you can get all the data entered by the target on the unsecured sites even the passwords. Just perform these steps on the website after signing off a written agreement with the owner of the website.
Technical Scripter 2020
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 450,
"s": 52,
"text": "Sniffing is the process of capturing and monitoring data packets that are passed through the network. It is used to capture the data of the victim and bettercap is a powerful tool used to perform various MITM(man in the middle) attacks on a network. Also, ARP Spoofing is a type of attack in which an attacker sends false ARP (Address Resolution Protocol) messages over a LAN(local area network). "
},
{
"code": null,
"e": 544,
"s": 450,
"text": "Prerequisites: Kali Linux, laptop or computer with WIFI modem, and bettercap installed in it."
},
{
"code": null,
"e": 659,
"s": 544,
"text": "Note: You need to be connected with the network on which you want to sniff. Type these all command on the terminal"
},
{
"code": null,
"e": 1033,
"s": 659,
"text": "Step 1: Selecting the interface of wlan0 i.e Wi-Fi. You can also try it with LAN (local area network ), It will work the same as with Wi-Fi. -iface command is used for selecting the interface. You can use the command ifconfig to get all the interfaces for example if you are connected with an eth0 you need to type bettercap -iface eth0 to get into the bettercap interface."
},
{
"code": null,
"e": 1057,
"s": 1033,
"text": "bettercap -iface wlan0"
},
{
"code": null,
"e": 1238,
"s": 1057,
"text": "Step 2: To show all the devices that are connected to the same network with their IP, MAC, Name, etc. Now we need to copy the IP address of the devices on which we want to sniff. "
},
{
"code": null,
"e": 1247,
"s": 1238,
"text": "net.show"
},
{
"code": null,
"e": 1356,
"s": 1247,
"text": "Step 3: This will provide you with the Modules of bettercap with their status ( i.e running or not running )"
},
{
"code": null,
"e": 1361,
"s": 1356,
"text": "help"
},
{
"code": null,
"e": 1504,
"s": 1361,
"text": "Step 4: This will send various probe packets to each IP in order and in the present subnet so that net.recon module may detect them with ease."
},
{
"code": null,
"e": 1517,
"s": 1504,
"text": "net.probe on"
},
{
"code": null,
"e": 1628,
"s": 1517,
"text": "Step 5: In order to attack both the targets and the gateway, we will have to set arp.spoof.fullduplex to true."
},
{
"code": null,
"e": 1658,
"s": 1628,
"text": "set arp.spoof.fullduplex true"
},
{
"code": null,
"e": 1783,
"s": 1658,
"text": "Step 6: Set the target to the IP you can add any number of IPs here by using “,”. For example 192.168.43.157 ,192.168.43.152"
},
{
"code": null,
"e": 1853,
"s": 1783,
"text": "set arp.spoof.targets 192.168.43.157(IP address of the target Device)"
},
{
"code": null,
"e": 1884,
"s": 1853,
"text": "Step 7: Start the ARP spoofer "
},
{
"code": null,
"e": 1901,
"s": 1884,
"text": "set arp.spoof on"
},
{
"code": null,
"e": 2095,
"s": 1901,
"text": "Step 8: Setting it to true will consider packets from/to this computer, otherwise it will skip them. As we are MITM (man in the middle) that means all the data is transferring from our computer"
},
{
"code": null,
"e": 2120,
"s": 2095,
"text": "set net.sniff.local true"
},
{
"code": null,
"e": 2178,
"s": 2120,
"text": "Step 9: Turning on the sniffing and catching the packets."
},
{
"code": null,
"e": 2191,
"s": 2178,
"text": "net.sniff on"
},
{
"code": null,
"e": 2592,
"s": 2191,
"text": "Note: After these all steps you can get the data of the targets only for the unsecured sites like the sites with the “http” for the https and the hsts there are some more steps involved in it. For now, you can get all the data entered by the target on the unsecured sites even the passwords. Just perform these steps on the website after signing off a written agreement with the owner of the website."
},
{
"code": null,
"e": 2616,
"s": 2592,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2627,
"s": 2616,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2646,
"s": 2627,
"text": "Technical Scripter"
}
]
|
How to Navigate through a ResultSet using a JDBC program? | The next() method of the ResultSet interface moves the pointer/Cursor of the current ResultSet object to the next row from the current position. This method returns a boolean value. If there are no rows next to its current position this method returns false, else it returns true.
Therefore, using this method in the while loop you can iterate the contents of the ResultSet object.
while(rs.next()){
}
The ResultSet interface (also) provides getter methods (getXXX()) to retrieve values in each column of a row, each getter methods has two variants:
getXXX(int columnIndex): Accepts an integer value representing the index of the column and returns its value.
getXXX(int columnIndex): Accepts an integer value representing the index of the column and returns its value.
getXXX(String columnLabel ): Accepts a String value representing the name of the column and returns its value.
getXXX(String columnLabel ): Accepts a String value representing the name of the column and returns its value.
You need to use the respective getter method based on the datatype of the column in the table.
while(rs.next()) {
System.out.print("Brand: "+rs.getString("Column_Name")+", ");
System.out.print("Sale: "+rs.getString("Column_Name "));
...........................
...........................
System.out.println("");
}
In the same way if it is a bi-directional ResultSet object you can navigate backwards using the previous() method.
Since the pointer of the ResultSet object is positioned before 1st row by default. To navigate backwards you need to shift the pointer/cursor to the next row after the last and, navigate backwards as:
rs.afterLast();
System.out.println("Contents of the table");
while(rs.previous()) {
System.out.print("Brand: "+rs.getString("Mobile_Brand")+", ");
System.out.print("Sale: "+rs.getString("Unit_Sale"));
System.out.println("");
} | [
{
"code": null,
"e": 1468,
"s": 1187,
"text": "The next() method of the ResultSet interface moves the pointer/Cursor of the current ResultSet object to the next row from the current position. This method returns a boolean value. If there are no rows next to its current position this method returns false, else it returns true."
},
{
"code": null,
"e": 1569,
"s": 1468,
"text": "Therefore, using this method in the while loop you can iterate the contents of the ResultSet object."
},
{
"code": null,
"e": 1589,
"s": 1569,
"text": "while(rs.next()){\n}"
},
{
"code": null,
"e": 1737,
"s": 1589,
"text": "The ResultSet interface (also) provides getter methods (getXXX()) to retrieve values in each column of a row, each getter methods has two variants:"
},
{
"code": null,
"e": 1847,
"s": 1737,
"text": "getXXX(int columnIndex): Accepts an integer value representing the index of the column and returns its value."
},
{
"code": null,
"e": 1957,
"s": 1847,
"text": "getXXX(int columnIndex): Accepts an integer value representing the index of the column and returns its value."
},
{
"code": null,
"e": 2068,
"s": 1957,
"text": "getXXX(String columnLabel ): Accepts a String value representing the name of the column and returns its value."
},
{
"code": null,
"e": 2179,
"s": 2068,
"text": "getXXX(String columnLabel ): Accepts a String value representing the name of the column and returns its value."
},
{
"code": null,
"e": 2274,
"s": 2179,
"text": "You need to use the respective getter method based on the datatype of the column in the table."
},
{
"code": null,
"e": 2509,
"s": 2274,
"text": "while(rs.next()) {\n System.out.print(\"Brand: \"+rs.getString(\"Column_Name\")+\", \");\n System.out.print(\"Sale: \"+rs.getString(\"Column_Name \"));\n ...........................\n ...........................\n System.out.println(\"\");\n}"
},
{
"code": null,
"e": 2624,
"s": 2509,
"text": "In the same way if it is a bi-directional ResultSet object you can navigate backwards using the previous() method."
},
{
"code": null,
"e": 2825,
"s": 2624,
"text": "Since the pointer of the ResultSet object is positioned before 1st row by default. To navigate backwards you need to shift the pointer/cursor to the next row after the last and, navigate backwards as:"
},
{
"code": null,
"e": 3062,
"s": 2825,
"text": "rs.afterLast();\n\nSystem.out.println(\"Contents of the table\");\nwhile(rs.previous()) {\n System.out.print(\"Brand: \"+rs.getString(\"Mobile_Brand\")+\", \");\n System.out.print(\"Sale: \"+rs.getString(\"Unit_Sale\"));\n System.out.println(\"\");\n}"
}
]
|
How to create a Reset Button in form using HTML ? | 30 Sep, 2021
In this article, we will learn how to create a Reset Button in HTML forms. Basically, the reset button is used to reset all the form data value and set to its initial default value. In case of user entered the wrong data then the user can easily correct it by clicking on “Reset Button”.
Approach: Here is a simple approach to add a reset Button –
First, we create an HTML document that contains a <form> element.
Create an <input> element under the form element.
Use the type attribute with the <input> element.
Set the type attribute to value “reset”.
Syntax
<input type="reset">
Example:
HTML
<!DOCTYPE html><html> <head> <title> How to Create a Reset Button in form using HTML? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2> How to Create a Reset Button in form using HTML? </h2> <form> Email ID: <input type="email"> <br> <br> Password: <input type="password"> <br><br> <input type="submit"> <input type="reset"> </form></body> </html>
Output:
HTML-Questions
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 317,
"s": 28,
"text": "In this article, we will learn how to create a Reset Button in HTML forms. Basically, the reset button is used to reset all the form data value and set to its initial default value. In case of user entered the wrong data then the user can easily correct it by clicking on “Reset Button”."
},
{
"code": null,
"e": 377,
"s": 317,
"text": "Approach: Here is a simple approach to add a reset Button –"
},
{
"code": null,
"e": 443,
"s": 377,
"text": "First, we create an HTML document that contains a <form> element."
},
{
"code": null,
"e": 493,
"s": 443,
"text": "Create an <input> element under the form element."
},
{
"code": null,
"e": 542,
"s": 493,
"text": "Use the type attribute with the <input> element."
},
{
"code": null,
"e": 583,
"s": 542,
"text": "Set the type attribute to value “reset”."
},
{
"code": null,
"e": 590,
"s": 583,
"text": "Syntax"
},
{
"code": null,
"e": 611,
"s": 590,
"text": "<input type=\"reset\">"
},
{
"code": null,
"e": 620,
"s": 611,
"text": "Example:"
},
{
"code": null,
"e": 625,
"s": 620,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to Create a Reset Button in form using HTML? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2> How to Create a Reset Button in form using HTML? </h2> <form> Email ID: <input type=\"email\"> <br> <br> Password: <input type=\"password\"> <br><br> <input type=\"submit\"> <input type=\"reset\"> </form></body> </html>",
"e": 1152,
"s": 625,
"text": null
},
{
"code": null,
"e": 1160,
"s": 1152,
"text": "Output:"
},
{
"code": null,
"e": 1175,
"s": 1160,
"text": "HTML-Questions"
},
{
"code": null,
"e": 1185,
"s": 1175,
"text": "HTML-Tags"
},
{
"code": null,
"e": 1190,
"s": 1185,
"text": "HTML"
},
{
"code": null,
"e": 1207,
"s": 1190,
"text": "Web Technologies"
},
{
"code": null,
"e": 1212,
"s": 1207,
"text": "HTML"
}
]
|
TCS NQT 2020 | Trains | 29 Oct, 2020
Problem:
In one pass, Train A can start from the source station at time T[0], halt at each station for h unit of time until it reaches the last station at time T[N – 1], where N is the positive integer representing a total number of stations.
Given, Train A’s timings at each unit of time as T[] = {10.00, 10.04, 10.09, 10.15, 10.19, 10.22}.
Now, suppose Railway Admin wants to add more trains to increase the frequency. So, to launch other Train B, for the same stations as of Train A’s. Provided the Train B starts at time t, they would like to know the timings for Train B. The program should return a String array S (timestamp(in float) for Train B at each station from first to the last station like train A).
Note:
The time is represented in 24-Hour.
Start Hour should be in the range [0, 23].
Start Minute should be in the range [0, 59].
Enter start time(24 Hrs)
Examples:
Input: t = 11.00Output: 11.00 11.04 11.09 11.15 11.19 11.22Explanation: Start time for train B is 11.00 and also the time difference between the stations for train B is same as for train A.
Input: t = -26.15Output: Invalid InputExplanation: No such time as -26.15 exists. Hence, print “Invalid Input”.
Approach: The idea is to calculate the time differences between the stations from the given timings of Train A. Follow the steps below to solve the problem:
From the given array T[], generate an array train_B[] where train_B[i] is the time difference between T[i] and T[i – 1], where train_B[0] = 0.00 and 1 ≤ i ≤ 5.
Therefore, train_B[] = {0.00, 0.04, 0.05, 0.06, 0.04, 0.03}.
If the integer part of t is not in the range [0, 24] or the decimal part of t is not in the range [0, 60], then print “Invalid Input” because the integer part represents the hours and the decimal part represents the minutes.
Otherwise, traverse over the range [0, 5] and print t + train_B[i] denoting the time for train B for the ith station. Then update t as t = t + train_B[i].
Below is the implementation of the above approach:
C
// C program for the above approach #include <stdio.h>#include <string.h> // Function to find the timings for// train B having same time difference// as train_Avoid findTime(float train_A[], int N, float t){ float x; // Stores the time for train_B float train_B[N]; train_B[0] = 0.00; for (int i = 1; i < N; i++) { train_B[i] = train_A[i] - train_A[i - 1]; } // Variables for typecasting int it, ix; it = (int)t; // Check if t is valid if (t >= 0.0 && t <= 24.0 && (t - it) <= 60.0) { // Traverse from 0 to 5 for (int i = 0; i < 6; i++) { // Update t x = t + train_B[i]; ix = (int)x; if (x - ix >= 0.60) x = x + 0.40; if (x > 24.00) x = x - 24.0; // Print the current time printf("%.2f ", x); t = x; } } // If no answer exist else { printf("Invalid Input"); }} // Driver Codeint main(){ // Given timings of train A // at each station float train_A[] = { 10.00, 10.04, 10.09, 10.15, 10.19, 10.22 }; int N = sizeof(train_A) / sizeof(train_A[0]); // Given start time t float t = 11.00; // Function Call findTime(train_A, N, t); return 0;}
11.00 11.04 11.09 11.15 11.19 11.22
Time Complexity: O(1)Auxiliary Space: O(1)
interview-preparation
prefix-sum
TCS
TCS-coding-questions
Arrays
Mathematical
TCS
prefix-sum
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Oct, 2020"
},
{
"code": null,
"e": 63,
"s": 54,
"text": "Problem:"
},
{
"code": null,
"e": 298,
"s": 63,
"text": "In one pass, Train A can start from the source station at time T[0], halt at each station for h unit of time until it reaches the last station at time T[N – 1], where N is the positive integer representing a total number of stations. "
},
{
"code": null,
"e": 397,
"s": 298,
"text": "Given, Train A’s timings at each unit of time as T[] = {10.00, 10.04, 10.09, 10.15, 10.19, 10.22}."
},
{
"code": null,
"e": 772,
"s": 397,
"text": "Now, suppose Railway Admin wants to add more trains to increase the frequency. So, to launch other Train B, for the same stations as of Train A’s. Provided the Train B starts at time t, they would like to know the timings for Train B. The program should return a String array S (timestamp(in float) for Train B at each station from first to the last station like train A). "
},
{
"code": null,
"e": 778,
"s": 772,
"text": "Note:"
},
{
"code": null,
"e": 814,
"s": 778,
"text": "The time is represented in 24-Hour."
},
{
"code": null,
"e": 857,
"s": 814,
"text": "Start Hour should be in the range [0, 23]."
},
{
"code": null,
"e": 902,
"s": 857,
"text": "Start Minute should be in the range [0, 59]."
},
{
"code": null,
"e": 927,
"s": 902,
"text": "Enter start time(24 Hrs)"
},
{
"code": null,
"e": 937,
"s": 927,
"text": "Examples:"
},
{
"code": null,
"e": 1127,
"s": 937,
"text": "Input: t = 11.00Output: 11.00 11.04 11.09 11.15 11.19 11.22Explanation: Start time for train B is 11.00 and also the time difference between the stations for train B is same as for train A."
},
{
"code": null,
"e": 1239,
"s": 1127,
"text": "Input: t = -26.15Output: Invalid InputExplanation: No such time as -26.15 exists. Hence, print “Invalid Input”."
},
{
"code": null,
"e": 1396,
"s": 1239,
"text": "Approach: The idea is to calculate the time differences between the stations from the given timings of Train A. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1556,
"s": 1396,
"text": "From the given array T[], generate an array train_B[] where train_B[i] is the time difference between T[i] and T[i – 1], where train_B[0] = 0.00 and 1 ≤ i ≤ 5."
},
{
"code": null,
"e": 1617,
"s": 1556,
"text": "Therefore, train_B[] = {0.00, 0.04, 0.05, 0.06, 0.04, 0.03}."
},
{
"code": null,
"e": 1842,
"s": 1617,
"text": "If the integer part of t is not in the range [0, 24] or the decimal part of t is not in the range [0, 60], then print “Invalid Input” because the integer part represents the hours and the decimal part represents the minutes."
},
{
"code": null,
"e": 1997,
"s": 1842,
"text": "Otherwise, traverse over the range [0, 5] and print t + train_B[i] denoting the time for train B for the ith station. Then update t as t = t + train_B[i]."
},
{
"code": null,
"e": 2048,
"s": 1997,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2050,
"s": 2048,
"text": "C"
},
{
"code": "// C program for the above approach #include <stdio.h>#include <string.h> // Function to find the timings for// train B having same time difference// as train_Avoid findTime(float train_A[], int N, float t){ float x; // Stores the time for train_B float train_B[N]; train_B[0] = 0.00; for (int i = 1; i < N; i++) { train_B[i] = train_A[i] - train_A[i - 1]; } // Variables for typecasting int it, ix; it = (int)t; // Check if t is valid if (t >= 0.0 && t <= 24.0 && (t - it) <= 60.0) { // Traverse from 0 to 5 for (int i = 0; i < 6; i++) { // Update t x = t + train_B[i]; ix = (int)x; if (x - ix >= 0.60) x = x + 0.40; if (x > 24.00) x = x - 24.0; // Print the current time printf(\"%.2f \", x); t = x; } } // If no answer exist else { printf(\"Invalid Input\"); }} // Driver Codeint main(){ // Given timings of train A // at each station float train_A[] = { 10.00, 10.04, 10.09, 10.15, 10.19, 10.22 }; int N = sizeof(train_A) / sizeof(train_A[0]); // Given start time t float t = 11.00; // Function Call findTime(train_A, N, t); return 0;}",
"e": 3407,
"s": 2050,
"text": null
},
{
"code": null,
"e": 3444,
"s": 3407,
"text": "11.00 11.04 11.09 11.15 11.19 11.22\n"
},
{
"code": null,
"e": 3487,
"s": 3444,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3509,
"s": 3487,
"text": "interview-preparation"
},
{
"code": null,
"e": 3520,
"s": 3509,
"text": "prefix-sum"
},
{
"code": null,
"e": 3524,
"s": 3520,
"text": "TCS"
},
{
"code": null,
"e": 3545,
"s": 3524,
"text": "TCS-coding-questions"
},
{
"code": null,
"e": 3552,
"s": 3545,
"text": "Arrays"
},
{
"code": null,
"e": 3565,
"s": 3552,
"text": "Mathematical"
},
{
"code": null,
"e": 3569,
"s": 3565,
"text": "TCS"
},
{
"code": null,
"e": 3580,
"s": 3569,
"text": "prefix-sum"
},
{
"code": null,
"e": 3587,
"s": 3580,
"text": "Arrays"
},
{
"code": null,
"e": 3600,
"s": 3587,
"text": "Mathematical"
},
{
"code": null,
"e": 3698,
"s": 3600,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3766,
"s": 3698,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 3810,
"s": 3766,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 3842,
"s": 3810,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3890,
"s": 3842,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 3904,
"s": 3890,
"text": "Linear Search"
},
{
"code": null,
"e": 3934,
"s": 3904,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 3977,
"s": 3934,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4037,
"s": 3977,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 4052,
"s": 4037,
"text": "C++ Data Types"
}
]
|
Python program to validate an IP Address | 15 Jul, 2021
Prerequisite: Python Regex
Given an IP address as input, write a Python program to check whether the given IP Address is Valid or not.
What is an IP (Internet Protocol) Address? Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) address. An IP address (version 4) consists of four numbers (each between 0 and 255) separated by periods. The format of an IP address is a 32-bit numeric address written as four decimal numbers (called octets) separated by periods; each number can be written as 0 to 255 (E.g. – 0.0.0.0 to 255.255.255.255).
Examples:
Input: 192.168.0.1
Output: Valid Ip address
Input: 110.234.52.124
Output: Valid Ip address
Input: 666.1.2.2
Output: Invalid Ip address
Input:25.99.208.255
Output: Valid Ip address
In this program, we are using search() method of re module. re.search() : This method either returns None (if the pattern doesn’t match), or re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data.
Let’s see the Python program to validate an IP address :
Python3
# Python program to validate an Ip address # re module provides support# for regular expressionsimport re # Make a regular expression# for validating an Ip-addressregex = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$" # Define a function for# validate an Ip addressdef check(Ip): # pass the regular expression # and the string in search() method if(re.search(regex, Ip)): print("Valid Ip address") else: print("Invalid Ip address") # Driver Codeif __name__ == '__main__' : # Enter the Ip address Ip = "192.168.0.1" # calling run function check(Ip) Ip = "110.234.52.124" check(Ip) Ip = "366.1.2.2" check(Ip)
Valid Ip address
Valid Ip address
Invalid Ip address
kvs1389
anshuman350
surinderdawra388
simmytarika5
Python Regex-programs
python-regex
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 80,
"s": 52,
"text": "Prerequisite: Python Regex "
},
{
"code": null,
"e": 188,
"s": 80,
"text": "Given an IP address as input, write a Python program to check whether the given IP Address is Valid or not."
},
{
"code": null,
"e": 661,
"s": 188,
"text": "What is an IP (Internet Protocol) Address? Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) address. An IP address (version 4) consists of four numbers (each between 0 and 255) separated by periods. The format of an IP address is a 32-bit numeric address written as four decimal numbers (called octets) separated by periods; each number can be written as 0 to 255 (E.g. – 0.0.0.0 to 255.255.255.255)."
},
{
"code": null,
"e": 672,
"s": 661,
"text": "Examples: "
},
{
"code": null,
"e": 859,
"s": 672,
"text": "Input: 192.168.0.1\nOutput: Valid Ip address\n\nInput: 110.234.52.124\nOutput: Valid Ip address\n\nInput: 666.1.2.2\nOutput: Invalid Ip address \n \nInput:25.99.208.255 \nOutput: Valid Ip address"
},
{
"code": null,
"e": 1205,
"s": 859,
"text": "In this program, we are using search() method of re module. re.search() : This method either returns None (if the pattern doesn’t match), or re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. "
},
{
"code": null,
"e": 1263,
"s": 1205,
"text": "Let’s see the Python program to validate an IP address : "
},
{
"code": null,
"e": 1271,
"s": 1263,
"text": "Python3"
},
{
"code": "# Python program to validate an Ip address # re module provides support# for regular expressionsimport re # Make a regular expression# for validating an Ip-addressregex = \"^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$\" # Define a function for# validate an Ip addressdef check(Ip): # pass the regular expression # and the string in search() method if(re.search(regex, Ip)): print(\"Valid Ip address\") else: print(\"Invalid Ip address\") # Driver Codeif __name__ == '__main__' : # Enter the Ip address Ip = \"192.168.0.1\" # calling run function check(Ip) Ip = \"110.234.52.124\" check(Ip) Ip = \"366.1.2.2\" check(Ip)",
"e": 2016,
"s": 1271,
"text": null
},
{
"code": null,
"e": 2069,
"s": 2016,
"text": "Valid Ip address\nValid Ip address\nInvalid Ip address"
},
{
"code": null,
"e": 2079,
"s": 2071,
"text": "kvs1389"
},
{
"code": null,
"e": 2091,
"s": 2079,
"text": "anshuman350"
},
{
"code": null,
"e": 2108,
"s": 2091,
"text": "surinderdawra388"
},
{
"code": null,
"e": 2121,
"s": 2108,
"text": "simmytarika5"
},
{
"code": null,
"e": 2143,
"s": 2121,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 2156,
"s": 2143,
"text": "python-regex"
},
{
"code": null,
"e": 2163,
"s": 2156,
"text": "Python"
},
{
"code": null,
"e": 2179,
"s": 2163,
"text": "Python Programs"
},
{
"code": null,
"e": 2277,
"s": 2179,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2295,
"s": 2277,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2337,
"s": 2295,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2359,
"s": 2337,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2394,
"s": 2359,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2420,
"s": 2394,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2463,
"s": 2420,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2485,
"s": 2463,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2524,
"s": 2485,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2562,
"s": 2524,
"text": "Python | Convert a list to dictionary"
}
]
|
Matplotlib.colors.Normalize class in Python | 07 Dec, 2021
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.colors.Normalize class belongs to the matplotlib.colors module. The matplotlib.colors module is used for converting color or numbers arguments to RGBA or RGB.This module is used for mapping numbers to colors or color specification conversion in a 1-D array of colors also known as colormap.The matplotlib.colors.Normalize class is used to normalize data into the interval of [0.0, 1.0].Syntax:
class matplotlib.colors.Normalize(vmin=None, vmax=None, clip=False)
If either of vmin or vmax is not set then it initializes from the minimum and maximum value of the first input processed respectively. In other words, __call__(Data) calls autoscale_None(Data). If the value of clip is set to True and the given value is out of range then it returns 0 or 1, whichever is the closest. If vmax==vmin then it returns 0. It operates with both scalar or arrays including masked arrays. The masked values are set to 1 if clip is True, else they remain masked.Methods:
autoscale(self, A): This method sets the vmin to min and vmax to max of A. autoscale_None(self, A): This method autoscales only vmin and vmax with None value. inverse(self, value): It interchanges the values of vmin and vmax. static process_value(value): The value parameter in this method can be a scalar or a sequence. It is used to homogenize input values for efficient and simple normalization. This method returns a masked array of matching values. All float data types are preserved and integer data types with two or smaller bytes are transformed to np.float32, while the larger bytes type are transformed into np.float64. This is done to improve speed for larger arrays by preserving float32 values whenever possible through using in-place operations. scaled(self): It returns a boolean to check if vmin or vmax is set.
autoscale(self, A): This method sets the vmin to min and vmax to max of A.
autoscale_None(self, A): This method autoscales only vmin and vmax with None value.
inverse(self, value): It interchanges the values of vmin and vmax.
static process_value(value): The value parameter in this method can be a scalar or a sequence. It is used to homogenize input values for efficient and simple normalization. This method returns a masked array of matching values. All float data types are preserved and integer data types with two or smaller bytes are transformed to np.float32, while the larger bytes type are transformed into np.float64. This is done to improve speed for larger arrays by preserving float32 values whenever possible through using in-place operations.
scaled(self): It returns a boolean to check if vmin or vmax is set.
Example 1:
Python3
import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatter # set a random state for# reproducibilitynp.random.seed(19687581) total_points = 500000total_bins = 100 # Centering at a = 0 and b = 5# generate normal distributionsa = np.random.randn(total_points)b = .4 * a + np.random.randn(500000) + 5 figure, axes = plt.subplots(1, 2, tight_layout = True) # C is the count in each binC, bins, patches = axes[0].hist(a, bins = total_bins) # We'll color code by height,# but you could use any scalarfracs = C / C.max() # Normalize of the data to 0..1# for covering the full range of# the colormapnorm = colors.Normalize(fracs.min(), fracs.max()) # looping through the objects and# setting the color of each accordinglyfor thisfrac, thispatch in zip(fracs, patches): color = plt.cm.viridis(norm(thisfrac)) thispatch.set_facecolor(color) # normalize the inputs by Caxes[1].hist(a, bins = total_bins, density = True) # formating the y-axis for displaying# percentageaxes[1].yaxis.set_major_formatter(PercentFormatter(xmax = 1))
Output:
Example 2:
Python3
import matplotlib.pyplot as pltimport matplotlib as mpl figure, axes = plt.subplots(figsize =(6, 1))figure.subplots_adjust(bottom = 0.5) color_map = mpl.cm.coolnormalizer = mpl.colors.Normalize(vmin = 0, vmax = 5) figure.colorbar(mpl.cm.ScalarMappable(norm = normalizer, cmap = color_map), cax = axes, orientation ='horizontal', label ='Arbitrary Units')
Output:
gabaa406
clintra
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Similarities and Difference between Java and C++ | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Dec, 2021"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. "
},
{
"code": null,
"e": 652,
"s": 242,
"text": "The matplotlib.colors.Normalize class belongs to the matplotlib.colors module. The matplotlib.colors module is used for converting color or numbers arguments to RGBA or RGB.This module is used for mapping numbers to colors or color specification conversion in a 1-D array of colors also known as colormap.The matplotlib.colors.Normalize class is used to normalize data into the interval of [0.0, 1.0].Syntax: "
},
{
"code": null,
"e": 720,
"s": 652,
"text": "class matplotlib.colors.Normalize(vmin=None, vmax=None, clip=False)"
},
{
"code": null,
"e": 1216,
"s": 720,
"text": "If either of vmin or vmax is not set then it initializes from the minimum and maximum value of the first input processed respectively. In other words, __call__(Data) calls autoscale_None(Data). If the value of clip is set to True and the given value is out of range then it returns 0 or 1, whichever is the closest. If vmax==vmin then it returns 0. It operates with both scalar or arrays including masked arrays. The masked values are set to 1 if clip is True, else they remain masked.Methods: "
},
{
"code": null,
"e": 2046,
"s": 1216,
"text": "autoscale(self, A): This method sets the vmin to min and vmax to max of A. autoscale_None(self, A): This method autoscales only vmin and vmax with None value. inverse(self, value): It interchanges the values of vmin and vmax. static process_value(value): The value parameter in this method can be a scalar or a sequence. It is used to homogenize input values for efficient and simple normalization. This method returns a masked array of matching values. All float data types are preserved and integer data types with two or smaller bytes are transformed to np.float32, while the larger bytes type are transformed into np.float64. This is done to improve speed for larger arrays by preserving float32 values whenever possible through using in-place operations. scaled(self): It returns a boolean to check if vmin or vmax is set. "
},
{
"code": null,
"e": 2122,
"s": 2046,
"text": "autoscale(self, A): This method sets the vmin to min and vmax to max of A. "
},
{
"code": null,
"e": 2207,
"s": 2122,
"text": "autoscale_None(self, A): This method autoscales only vmin and vmax with None value. "
},
{
"code": null,
"e": 2275,
"s": 2207,
"text": "inverse(self, value): It interchanges the values of vmin and vmax. "
},
{
"code": null,
"e": 2810,
"s": 2275,
"text": "static process_value(value): The value parameter in this method can be a scalar or a sequence. It is used to homogenize input values for efficient and simple normalization. This method returns a masked array of matching values. All float data types are preserved and integer data types with two or smaller bytes are transformed to np.float32, while the larger bytes type are transformed into np.float64. This is done to improve speed for larger arrays by preserving float32 values whenever possible through using in-place operations. "
},
{
"code": null,
"e": 2880,
"s": 2810,
"text": "scaled(self): It returns a boolean to check if vmin or vmax is set. "
},
{
"code": null,
"e": 2893,
"s": 2880,
"text": "Example 1: "
},
{
"code": null,
"e": 2901,
"s": 2893,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatter # set a random state for# reproducibilitynp.random.seed(19687581) total_points = 500000total_bins = 100 # Centering at a = 0 and b = 5# generate normal distributionsa = np.random.randn(total_points)b = .4 * a + np.random.randn(500000) + 5 figure, axes = plt.subplots(1, 2, tight_layout = True) # C is the count in each binC, bins, patches = axes[0].hist(a, bins = total_bins) # We'll color code by height,# but you could use any scalarfracs = C / C.max() # Normalize of the data to 0..1# for covering the full range of# the colormapnorm = colors.Normalize(fracs.min(), fracs.max()) # looping through the objects and# setting the color of each accordinglyfor thisfrac, thispatch in zip(fracs, patches): color = plt.cm.viridis(norm(thisfrac)) thispatch.set_facecolor(color) # normalize the inputs by Caxes[1].hist(a, bins = total_bins, density = True) # formating the y-axis for displaying# percentageaxes[1].yaxis.set_major_formatter(PercentFormatter(xmax = 1))",
"e": 4053,
"s": 2901,
"text": null
},
{
"code": null,
"e": 4063,
"s": 4053,
"text": "Output: "
},
{
"code": null,
"e": 4076,
"s": 4063,
"text": "Example 2: "
},
{
"code": null,
"e": 4084,
"s": 4076,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport matplotlib as mpl figure, axes = plt.subplots(figsize =(6, 1))figure.subplots_adjust(bottom = 0.5) color_map = mpl.cm.coolnormalizer = mpl.colors.Normalize(vmin = 0, vmax = 5) figure.colorbar(mpl.cm.ScalarMappable(norm = normalizer, cmap = color_map), cax = axes, orientation ='horizontal', label ='Arbitrary Units')",
"e": 4481,
"s": 4084,
"text": null
},
{
"code": null,
"e": 4491,
"s": 4481,
"text": "Output: "
},
{
"code": null,
"e": 4502,
"s": 4493,
"text": "gabaa406"
},
{
"code": null,
"e": 4510,
"s": 4502,
"text": "clintra"
},
{
"code": null,
"e": 4528,
"s": 4510,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 4535,
"s": 4528,
"text": "Python"
},
{
"code": null,
"e": 4551,
"s": 4535,
"text": "Write From Home"
},
{
"code": null,
"e": 4649,
"s": 4551,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4691,
"s": 4649,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4713,
"s": 4691,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4745,
"s": 4713,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4774,
"s": 4745,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4801,
"s": 4774,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4837,
"s": 4801,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 4873,
"s": 4837,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 4934,
"s": 4873,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 4950,
"s": 4934,
"text": "Python infinity"
}
]
|
JavaScript | Nested Classes | 28 May, 2020
Let us try to understand, what is class. A class in JavaScript is a type of function, which can be initialized through both function keyword as well as through class keyword. In this article, we will cover the inner class in javascript through the use of a function keyword. Here’s an example of the class using the function keyword.
Example:
<!DOCTYPE html><html> <head> <title>Class as a function</title> <meta charset="utf-8" /> <script> // Write Javascript code here function Employee() { // Here we have created a property // name of class Employee; this.name = ""; this.employeeId = 0; } // An (global) object of type Employee // is created. var emp = new Employee(); emp.name = "miss anonymous"; emp.employeeId = 101; function showName() { alert(emp.name); } </script> </head> <body> <button type="button" onclick="showName()"> Click Me </button> </body></html>
Output:
miss anonymous
The difference between class as a function and function is that we make use of this keyword in a function definition that makes it work as a class. Now, an inner class is defined in a similar way.
As you can see in this code, we have created an OuterClass and InnerClass in it just the same way as we did before. But, to access the properties of the outer class we need to have the address of the object. And that is the only right way to do it. As you can see in the example above, in order to access the property x of OuterClass we have used the variable objOuterClass (which stores the address of the current instance of the class) and using that address of object we can easily access any property or method of the outer class in the inner class.
Now, the same trick can be applied while trying to access the members or properties of the inner class. As you can see, we have created an inner class object outside the inner class. So every time the object of Outer Class is created we are creating the object of inner class ad storing its address in the variable innerObj.
Example:
<!DOCTYPE html><html> <head> <title>Inner class in JS</title> <meta charset="utf-8" /> <script> function OuterClass() { // Property x of OuterClass this.x = 0; this.y = 30; // Assign the variable objOuterClass the address // of the particular instance of OuterClass var objOuterClass = this; // Inner class function InnerClass() { this.z = 10; this.someFuncton = function () { alert("inner class function"); }; // Assign the address of the anonymous function. // to access the value of property of outer class // in inner class. this.accessOuter = function () { alert("value of x property:" + objOuterClass.x); }; } // InnerClass ends to access the inner class // properties or methods. this.innerObj = new InnerClass(); } function show() { var outerClassObj = new OuterClass(); alert("Inner class Property z:" + outerClassObj.innerObj.z); } </script> </head> <body> <button type="button" onclick="show()"> Click Me </button> </body></html>
Output:
Inner class Property z:10
javascript-oop
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 362,
"s": 28,
"text": "Let us try to understand, what is class. A class in JavaScript is a type of function, which can be initialized through both function keyword as well as through class keyword. In this article, we will cover the inner class in javascript through the use of a function keyword. Here’s an example of the class using the function keyword."
},
{
"code": null,
"e": 371,
"s": 362,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Class as a function</title> <meta charset=\"utf-8\" /> <script> // Write Javascript code here function Employee() { // Here we have created a property // name of class Employee; this.name = \"\"; this.employeeId = 0; } // An (global) object of type Employee // is created. var emp = new Employee(); emp.name = \"miss anonymous\"; emp.employeeId = 101; function showName() { alert(emp.name); } </script> </head> <body> <button type=\"button\" onclick=\"showName()\"> Click Me </button> </body></html>",
"e": 1189,
"s": 371,
"text": null
},
{
"code": null,
"e": 1197,
"s": 1189,
"text": "Output:"
},
{
"code": null,
"e": 1212,
"s": 1197,
"text": "miss anonymous"
},
{
"code": null,
"e": 1409,
"s": 1212,
"text": "The difference between class as a function and function is that we make use of this keyword in a function definition that makes it work as a class. Now, an inner class is defined in a similar way."
},
{
"code": null,
"e": 1963,
"s": 1409,
"text": "As you can see in this code, we have created an OuterClass and InnerClass in it just the same way as we did before. But, to access the properties of the outer class we need to have the address of the object. And that is the only right way to do it. As you can see in the example above, in order to access the property x of OuterClass we have used the variable objOuterClass (which stores the address of the current instance of the class) and using that address of object we can easily access any property or method of the outer class in the inner class."
},
{
"code": null,
"e": 2288,
"s": 1963,
"text": "Now, the same trick can be applied while trying to access the members or properties of the inner class. As you can see, we have created an inner class object outside the inner class. So every time the object of Outer Class is created we are creating the object of inner class ad storing its address in the variable innerObj."
},
{
"code": null,
"e": 2297,
"s": 2288,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Inner class in JS</title> <meta charset=\"utf-8\" /> <script> function OuterClass() { // Property x of OuterClass this.x = 0; this.y = 30; // Assign the variable objOuterClass the address // of the particular instance of OuterClass var objOuterClass = this; // Inner class function InnerClass() { this.z = 10; this.someFuncton = function () { alert(\"inner class function\"); }; // Assign the address of the anonymous function. // to access the value of property of outer class // in inner class. this.accessOuter = function () { alert(\"value of x property:\" + objOuterClass.x); }; } // InnerClass ends to access the inner class // properties or methods. this.innerObj = new InnerClass(); } function show() { var outerClassObj = new OuterClass(); alert(\"Inner class Property z:\" + outerClassObj.innerObj.z); } </script> </head> <body> <button type=\"button\" onclick=\"show()\"> Click Me </button> </body></html>",
"e": 3754,
"s": 2297,
"text": null
},
{
"code": null,
"e": 3762,
"s": 3754,
"text": "Output:"
},
{
"code": null,
"e": 3788,
"s": 3762,
"text": "Inner class Property z:10"
},
{
"code": null,
"e": 3803,
"s": 3788,
"text": "javascript-oop"
},
{
"code": null,
"e": 3814,
"s": 3803,
"text": "JavaScript"
},
{
"code": null,
"e": 3831,
"s": 3814,
"text": "Web Technologies"
}
]
|
list::push_front() and list::push_back() in C++ STL | 23 Jun, 2022
Lists are containers used in C++ to store data in a non-contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists.
list::push_front()
push_front() function is used to push elements into a list from the front. The new value is inserted into the list at the beginning, before the current first element and the container size is increased by 1.
Syntax :
listname.push_front(value)
Parameters :
The value to be added in the front is
passed as the parameter
Result :
Adds the value mentioned as the parameter
to the front of the list named as listname
Examples:
Input : list list{1, 2, 3, 4, 5};
list.push_front(6);
Output : 6, 1, 2, 3, 4, 5
Input : list list{5, 4, 3, 2, 1};
list.push_front(6);
Output :6, 5, 4, 3, 2, 1
Errors and Exceptions
Strong exception guarantee – if an exception is thrown, there are no changes in the container.If the value passed as argument is not supported by the list, it shows undefined behavior.
Strong exception guarantee – if an exception is thrown, there are no changes in the container.
If the value passed as argument is not supported by the list, it shows undefined behavior.
C++
// CPP program to illustrate// push_front() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{ 1, 2, 3, 4, 5 }; mylist.push_front(6); // list becomes 6, 1, 2, 3, 4, 5 for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it;}
Output:
6 1 2 3 4 5
Application: Input an empty list with the following numbers and order using push_front() function and sort the given list.
Input : 7, 89, 45, 6, 24, 58, 43
Output : 6, 7, 24, 43, 45, 58, 89
C++
// CPP program to illustrate// application Of push_front() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{}; mylist.push_front(43); mylist.push_front(58); mylist.push_front(24); mylist.push_front(6); mylist.push_front(45); mylist.push_front(89); mylist.push_front(7); // list becomes 7, 89, 45, 6, 24, 58, 43 // Sorting function mylist.sort(); for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it;}
Output:
6 7 24 43 45 58 89
list::push_back()
push_back() function is used to push elements into a list from the back. The new value is inserted into the list at the end, after the current last element and the container size is increased by 1.
Syntax :
listname.push_back(value)
Parameters :
The value to be added in the back is
passed as the parameter
Result :
Adds the value mentioned as the parameter
to the back of the list named as listname
Examples:
Input : list list{1, 2, 3, 4, 5};
list.push_back(6);
Output :1, 2, 3, 4, 5, 6
Input : list list{5, 4, 3, 2, 1};
list.push_back(0);
Output :5, 4, 3, 2, 1, 0
Errors and Exceptions
Strong exception guarantee – if an exception is thrown, there are no changes in the container.If the value passed as argument is not supported by the list, it shows undefined behavior.
Strong exception guarantee – if an exception is thrown, there are no changes in the container.
If the value passed as argument is not supported by the list, it shows undefined behavior.
C++
// CPP program to illustrate// push_back() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{ 1, 2, 3, 4, 5 }; mylist.push_back(6); // list becomes 1, 2, 3, 4, 5, 6 for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it;}
Output:
1 2 3 4 5 6
Application: Input an empty list with the following numbers and order using push_back() function and sort the given list.
Input : 7, 89, 45, 6, 24, 58, 43
Output : 6, 7, 24, 43, 45, 58, 89
C++
// CPP program to illustrate// application Of push_back() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{}; mylist.push_back(7); mylist.push_back(89); mylist.push_back(45); mylist.push_back(6); mylist.push_back(24); mylist.push_back(58); mylist.push_back(43); // list becomes 7, 89, 45, 6, 24, 58, 43 // Sorting function mylist.sort(); for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it;}
Output:
6 7 24 43 45 58 89
Let us see the differences in a tabular form -:
Its syntax is -:
push_back (const value_type& val);
chhabradhanvi
rutughumkar33
mayank007rawa
CPP-Library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Polymorphism in C++
List in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Command line arguments in C/C++
Exception Handling in C++
Sorting a vector in C++
Operators in C / C++
Destructors in C++
Power Function in C/C++
Pure Virtual Functions and Abstract Classes in C++ | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 305,
"s": 53,
"text": "Lists are containers used in C++ to store data in a non-contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. "
},
{
"code": null,
"e": 324,
"s": 305,
"text": "list::push_front()"
},
{
"code": null,
"e": 532,
"s": 324,
"text": "push_front() function is used to push elements into a list from the front. The new value is inserted into the list at the beginning, before the current first element and the container size is increased by 1."
},
{
"code": null,
"e": 542,
"s": 532,
"text": "Syntax : "
},
{
"code": null,
"e": 740,
"s": 542,
"text": "listname.push_front(value)\nParameters :\nThe value to be added in the front is \npassed as the parameter\nResult :\nAdds the value mentioned as the parameter \nto the front of the list named as listname"
},
{
"code": null,
"e": 751,
"s": 740,
"text": "Examples: "
},
{
"code": null,
"e": 927,
"s": 751,
"text": "Input : list list{1, 2, 3, 4, 5};\n list.push_front(6);\nOutput : 6, 1, 2, 3, 4, 5\n\nInput : list list{5, 4, 3, 2, 1};\n list.push_front(6);\nOutput :6, 5, 4, 3, 2, 1"
},
{
"code": null,
"e": 950,
"s": 927,
"text": "Errors and Exceptions "
},
{
"code": null,
"e": 1135,
"s": 950,
"text": "Strong exception guarantee – if an exception is thrown, there are no changes in the container.If the value passed as argument is not supported by the list, it shows undefined behavior."
},
{
"code": null,
"e": 1230,
"s": 1135,
"text": "Strong exception guarantee – if an exception is thrown, there are no changes in the container."
},
{
"code": null,
"e": 1321,
"s": 1230,
"text": "If the value passed as argument is not supported by the list, it shows undefined behavior."
},
{
"code": null,
"e": 1325,
"s": 1321,
"text": "C++"
},
{
"code": "// CPP program to illustrate// push_front() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{ 1, 2, 3, 4, 5 }; mylist.push_front(6); // list becomes 6, 1, 2, 3, 4, 5 for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it;}",
"e": 1633,
"s": 1325,
"text": null
},
{
"code": null,
"e": 1642,
"s": 1633,
"text": "Output: "
},
{
"code": null,
"e": 1654,
"s": 1642,
"text": "6 1 2 3 4 5"
},
{
"code": null,
"e": 1778,
"s": 1654,
"text": "Application: Input an empty list with the following numbers and order using push_front() function and sort the given list. "
},
{
"code": null,
"e": 1846,
"s": 1778,
"text": "Input : 7, 89, 45, 6, 24, 58, 43\nOutput : 6, 7, 24, 43, 45, 58, 89"
},
{
"code": null,
"e": 1850,
"s": 1846,
"text": "C++"
},
{
"code": "// CPP program to illustrate// application Of push_front() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{}; mylist.push_front(43); mylist.push_front(58); mylist.push_front(24); mylist.push_front(6); mylist.push_front(45); mylist.push_front(89); mylist.push_front(7); // list becomes 7, 89, 45, 6, 24, 58, 43 // Sorting function mylist.sort(); for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it;}",
"e": 2363,
"s": 1850,
"text": null
},
{
"code": null,
"e": 2372,
"s": 2363,
"text": "Output: "
},
{
"code": null,
"e": 2392,
"s": 2372,
"text": " 6 7 24 43 45 58 89"
},
{
"code": null,
"e": 2410,
"s": 2392,
"text": "list::push_back()"
},
{
"code": null,
"e": 2608,
"s": 2410,
"text": "push_back() function is used to push elements into a list from the back. The new value is inserted into the list at the end, after the current last element and the container size is increased by 1."
},
{
"code": null,
"e": 2619,
"s": 2608,
"text": "Syntax : "
},
{
"code": null,
"e": 2814,
"s": 2619,
"text": "listname.push_back(value)\nParameters :\nThe value to be added in the back is \npassed as the parameter\nResult :\nAdds the value mentioned as the parameter \nto the back of the list named as listname"
},
{
"code": null,
"e": 2825,
"s": 2814,
"text": "Examples: "
},
{
"code": null,
"e": 2998,
"s": 2825,
"text": "Input : list list{1, 2, 3, 4, 5};\n list.push_back(6);\nOutput :1, 2, 3, 4, 5, 6\n\nInput : list list{5, 4, 3, 2, 1};\n list.push_back(0);\nOutput :5, 4, 3, 2, 1, 0"
},
{
"code": null,
"e": 3021,
"s": 2998,
"text": "Errors and Exceptions "
},
{
"code": null,
"e": 3206,
"s": 3021,
"text": "Strong exception guarantee – if an exception is thrown, there are no changes in the container.If the value passed as argument is not supported by the list, it shows undefined behavior."
},
{
"code": null,
"e": 3301,
"s": 3206,
"text": "Strong exception guarantee – if an exception is thrown, there are no changes in the container."
},
{
"code": null,
"e": 3392,
"s": 3301,
"text": "If the value passed as argument is not supported by the list, it shows undefined behavior."
},
{
"code": null,
"e": 3396,
"s": 3392,
"text": "C++"
},
{
"code": "// CPP program to illustrate// push_back() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{ 1, 2, 3, 4, 5 }; mylist.push_back(6); // list becomes 1, 2, 3, 4, 5, 6 for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it;}",
"e": 3702,
"s": 3396,
"text": null
},
{
"code": null,
"e": 3711,
"s": 3702,
"text": "Output: "
},
{
"code": null,
"e": 3723,
"s": 3711,
"text": "1 2 3 4 5 6"
},
{
"code": null,
"e": 3847,
"s": 3723,
"text": "Application: Input an empty list with the following numbers and order using push_back() function and sort the given list. "
},
{
"code": null,
"e": 3915,
"s": 3847,
"text": "Input : 7, 89, 45, 6, 24, 58, 43\nOutput : 6, 7, 24, 43, 45, 58, 89"
},
{
"code": null,
"e": 3919,
"s": 3915,
"text": "C++"
},
{
"code": "// CPP program to illustrate// application Of push_back() function#include <iostream>#include <list>using namespace std; int main(){ list<int> mylist{}; mylist.push_back(7); mylist.push_back(89); mylist.push_back(45); mylist.push_back(6); mylist.push_back(24); mylist.push_back(58); mylist.push_back(43); // list becomes 7, 89, 45, 6, 24, 58, 43 // Sorting function mylist.sort(); for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it;}",
"e": 4424,
"s": 3919,
"text": null
},
{
"code": null,
"e": 4433,
"s": 4424,
"text": "Output: "
},
{
"code": null,
"e": 4453,
"s": 4433,
"text": " 6 7 24 43 45 58 89"
},
{
"code": null,
"e": 4501,
"s": 4453,
"text": "Let us see the differences in a tabular form -:"
},
{
"code": null,
"e": 4518,
"s": 4501,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 4553,
"s": 4518,
"text": "push_back (const value_type& val);"
},
{
"code": null,
"e": 4569,
"s": 4555,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 4583,
"s": 4569,
"text": "rutughumkar33"
},
{
"code": null,
"e": 4597,
"s": 4583,
"text": "mayank007rawa"
},
{
"code": null,
"e": 4609,
"s": 4597,
"text": "CPP-Library"
},
{
"code": null,
"e": 4613,
"s": 4609,
"text": "STL"
},
{
"code": null,
"e": 4617,
"s": 4613,
"text": "C++"
},
{
"code": null,
"e": 4621,
"s": 4617,
"text": "STL"
},
{
"code": null,
"e": 4625,
"s": 4621,
"text": "CPP"
},
{
"code": null,
"e": 4723,
"s": 4625,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4743,
"s": 4723,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 4787,
"s": 4743,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4832,
"s": 4787,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4864,
"s": 4832,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 4890,
"s": 4864,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 4914,
"s": 4890,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 4935,
"s": 4914,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4954,
"s": 4935,
"text": "Destructors in C++"
},
{
"code": null,
"e": 4978,
"s": 4954,
"text": "Power Function in C/C++"
}
]
|
How to import a class from another file in Python ? | 30 Apr, 2021
In this article, we will see How to import a class from another file in Python.
Import in Python is analogous to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it’s not the sole way. The import statement consists of the import keyword alongside the name of the module.
Here we have created a class named GFG which has two methods: add() and sub(). Apart from that an explicit function is created named method() in the same python file. This file will act as a module for the main python file.
Python
class GFG: # methods def add(self, a, b): return a + b def sub(self, a, b): return a - b # explicit function def method(): print("GFG")
Let the name of the above python file be module.py.
It’s now time to import the module and start trying out our new class and functions. Here, we will import a module named module and create the object of the class named GFG inside that module. Now, we can use its methods and variables.
Python
import module # Created a class objectobject = module.GFG() # Calling and printing class methodsprint(object.add(15,5))print(object.sub(15,5)) # Calling the functionmodule.method()
Output:
20
10
GFG
Importing the module as we mentioned earlier will automatically bring over every single class and performance within the module into the namespace. If you’re only getting to use one function, you’ll prevent the namespace from being cluttered by only importing that function as demonstrated in the program below:
Python
# import modulefrom module import method # call method from that module method()
Output:
GFG
In this way, we can use class to import from another file.
Picked
python-modules
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 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 108,
"s": 28,
"text": "In this article, we will see How to import a class from another file in Python."
},
{
"code": null,
"e": 469,
"s": 108,
"text": "Import in Python is analogous to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it’s not the sole way. The import statement consists of the import keyword alongside the name of the module."
},
{
"code": null,
"e": 693,
"s": 469,
"text": "Here we have created a class named GFG which has two methods: add() and sub(). Apart from that an explicit function is created named method() in the same python file. This file will act as a module for the main python file."
},
{
"code": null,
"e": 700,
"s": 693,
"text": "Python"
},
{
"code": "class GFG: # methods def add(self, a, b): return a + b def sub(self, a, b): return a - b # explicit function def method(): print(\"GFG\")",
"e": 874,
"s": 700,
"text": null
},
{
"code": null,
"e": 926,
"s": 874,
"text": "Let the name of the above python file be module.py."
},
{
"code": null,
"e": 1162,
"s": 926,
"text": "It’s now time to import the module and start trying out our new class and functions. Here, we will import a module named module and create the object of the class named GFG inside that module. Now, we can use its methods and variables."
},
{
"code": null,
"e": 1169,
"s": 1162,
"text": "Python"
},
{
"code": "import module # Created a class objectobject = module.GFG() # Calling and printing class methodsprint(object.add(15,5))print(object.sub(15,5)) # Calling the functionmodule.method()",
"e": 1356,
"s": 1169,
"text": null
},
{
"code": null,
"e": 1364,
"s": 1356,
"text": "Output:"
},
{
"code": null,
"e": 1374,
"s": 1364,
"text": "20\n10\nGFG"
},
{
"code": null,
"e": 1686,
"s": 1374,
"text": "Importing the module as we mentioned earlier will automatically bring over every single class and performance within the module into the namespace. If you’re only getting to use one function, you’ll prevent the namespace from being cluttered by only importing that function as demonstrated in the program below:"
},
{
"code": null,
"e": 1693,
"s": 1686,
"text": "Python"
},
{
"code": "# import modulefrom module import method # call method from that module method()",
"e": 1777,
"s": 1693,
"text": null
},
{
"code": null,
"e": 1785,
"s": 1777,
"text": "Output:"
},
{
"code": null,
"e": 1789,
"s": 1785,
"text": "GFG"
},
{
"code": null,
"e": 1848,
"s": 1789,
"text": "In this way, we can use class to import from another file."
},
{
"code": null,
"e": 1855,
"s": 1848,
"text": "Picked"
},
{
"code": null,
"e": 1870,
"s": 1855,
"text": "python-modules"
},
{
"code": null,
"e": 1877,
"s": 1870,
"text": "Python"
},
{
"code": null,
"e": 1975,
"s": 1877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2007,
"s": 1975,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2034,
"s": 2007,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2055,
"s": 2034,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2078,
"s": 2055,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2109,
"s": 2078,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2165,
"s": 2109,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2207,
"s": 2165,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2249,
"s": 2207,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2288,
"s": 2249,
"text": "Python | Get unique values from a list"
}
]
|
Programming Paradigms in Python | 21 Apr, 2020
Paradigm can also be termed as a method to solve some problems or do some tasks. A programming paradigm is an approach to solve the problem using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach. There are lots of programming languages that are known but all of them need to follow some strategy when they are implemented and this methodology/strategy is paradigms. Apart from varieties of programming languages, there are lots of paradigms to fulfill each and every demand.
Python supports three types of Programming paradigms
Object Oriented programming paradigms
Procedure Oriented programming paradigms
Functional programming paradigms
In the object-oriented programming paradigm, objects are the key element of paradigms. Objects can simply be defined as the instance of a class that contains both data members and the method functions. Moreover, the object-oriented style relates data members and methods functions that support encapsulation and with the help of the concept of an inheritance, the code can be easily reusable but the major disadvantage of object-oriented programming paradigm is that if the code is not written properly then the program becomes a monster.
Advantages
Relation with Real world entities
Code reusability
Abstraction or data hiding
Disadvantages
Data protection
Not suitable for all types of problems
Slow Speed
Example:
# class Emp has been defined hereclass Emp: def __init__(self, name, age): self.name = name self.age = age def info(self): print("Hello, % s. You are % s old." % (self.name, self.age)) # Objects of class Emp has been # made here Emps = [Emp("John", 43), Emp("Hilbert", 16), Emp("Alice", 30)] # Objects of class Emp has been# used herefor emp in Emps: emp.info()
Output:
Hello, John. You are 43 old.
Hello, Hilbert. You are 16 old.
Hello, Alice. You are 30 old.
Note: For more information, refer to Object Oriented Programming in Python
In Procedure Oriented programming paradigms, series of computational steps are divided modules which means that the code is grouped in functions and the code is serially executed step by step so basically, it combines the serial code to instruct a computer with each step to perform a certain task. This paradigm helps in the modularity of code and modularization is usually done by the functional implementation. This programming paradigm helps in an easy organization related items without difficulty and so each file acts as a container.
Advantages
General-purpose programming
Code reusability
Portable source code
Disadvantages
Data protection
Not suitable for real-world objects
Harder to write
Example:
# Procedural way of finding sum # of a list mylist = [10, 20, 30, 40] # modularization is done by # functional approachdef sum_the_list(mylist): res = 0 for val in mylist: res += val return res print(sum_the_list(mylist))
Output:
100
Functional programming paradigms is a paradigm in which everything is bind in pure mathematical functions style. It is known as declarative paradigms because it uses declarations overstatements. It uses the mathematical function and treats every statement as functional expression as an expression is executed to produce a value. Lambda functions or Recursion are basic approaches used for its implementation. The paradigms mainly focus on “what to solve” rather than “how to solve”. The ability to treat functions as values and pass them as an argument make the code more readable and understandable.
Advantages
Simple to understand
Making debugging and testing easier
Enhances the comprehension and readability of the code
Disadvantages
Low performance
Writing programs is a daunting task
Low readability of the code
Example:
# Functional way of finding sum of a list import functools mylist = [11, 22, 33, 44] # Recursive Functional approachdef sum_the_list(mylist): if len(mylist) == 1: return mylist[0] else: return mylist[0] + sum_the_list(mylist[1:]) # lambda function is usedprint(functools.reduce(lambda x, y: x + y, mylist))
Output:
110
Note: For more information, refer to Functional Programming in Python
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 635,
"s": 54,
"text": "Paradigm can also be termed as a method to solve some problems or do some tasks. A programming paradigm is an approach to solve the problem using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach. There are lots of programming languages that are known but all of them need to follow some strategy when they are implemented and this methodology/strategy is paradigms. Apart from varieties of programming languages, there are lots of paradigms to fulfill each and every demand."
},
{
"code": null,
"e": 688,
"s": 635,
"text": "Python supports three types of Programming paradigms"
},
{
"code": null,
"e": 726,
"s": 688,
"text": "Object Oriented programming paradigms"
},
{
"code": null,
"e": 767,
"s": 726,
"text": "Procedure Oriented programming paradigms"
},
{
"code": null,
"e": 800,
"s": 767,
"text": "Functional programming paradigms"
},
{
"code": null,
"e": 1339,
"s": 800,
"text": "In the object-oriented programming paradigm, objects are the key element of paradigms. Objects can simply be defined as the instance of a class that contains both data members and the method functions. Moreover, the object-oriented style relates data members and methods functions that support encapsulation and with the help of the concept of an inheritance, the code can be easily reusable but the major disadvantage of object-oriented programming paradigm is that if the code is not written properly then the program becomes a monster."
},
{
"code": null,
"e": 1350,
"s": 1339,
"text": "Advantages"
},
{
"code": null,
"e": 1384,
"s": 1350,
"text": "Relation with Real world entities"
},
{
"code": null,
"e": 1401,
"s": 1384,
"text": "Code reusability"
},
{
"code": null,
"e": 1428,
"s": 1401,
"text": "Abstraction or data hiding"
},
{
"code": null,
"e": 1442,
"s": 1428,
"text": "Disadvantages"
},
{
"code": null,
"e": 1458,
"s": 1442,
"text": "Data protection"
},
{
"code": null,
"e": 1497,
"s": 1458,
"text": "Not suitable for all types of problems"
},
{
"code": null,
"e": 1508,
"s": 1497,
"text": "Slow Speed"
},
{
"code": null,
"e": 1517,
"s": 1508,
"text": "Example:"
},
{
"code": "# class Emp has been defined hereclass Emp: def __init__(self, name, age): self.name = name self.age = age def info(self): print(\"Hello, % s. You are % s old.\" % (self.name, self.age)) # Objects of class Emp has been # made here Emps = [Emp(\"John\", 43), Emp(\"Hilbert\", 16), Emp(\"Alice\", 30)] # Objects of class Emp has been# used herefor emp in Emps: emp.info()",
"e": 1930,
"s": 1517,
"text": null
},
{
"code": null,
"e": 1938,
"s": 1930,
"text": "Output:"
},
{
"code": null,
"e": 2029,
"s": 1938,
"text": "Hello, John. You are 43 old.\nHello, Hilbert. You are 16 old.\nHello, Alice. You are 30 old."
},
{
"code": null,
"e": 2104,
"s": 2029,
"text": "Note: For more information, refer to Object Oriented Programming in Python"
},
{
"code": null,
"e": 2645,
"s": 2104,
"text": "In Procedure Oriented programming paradigms, series of computational steps are divided modules which means that the code is grouped in functions and the code is serially executed step by step so basically, it combines the serial code to instruct a computer with each step to perform a certain task. This paradigm helps in the modularity of code and modularization is usually done by the functional implementation. This programming paradigm helps in an easy organization related items without difficulty and so each file acts as a container."
},
{
"code": null,
"e": 2656,
"s": 2645,
"text": "Advantages"
},
{
"code": null,
"e": 2684,
"s": 2656,
"text": "General-purpose programming"
},
{
"code": null,
"e": 2701,
"s": 2684,
"text": "Code reusability"
},
{
"code": null,
"e": 2722,
"s": 2701,
"text": "Portable source code"
},
{
"code": null,
"e": 2736,
"s": 2722,
"text": "Disadvantages"
},
{
"code": null,
"e": 2752,
"s": 2736,
"text": "Data protection"
},
{
"code": null,
"e": 2788,
"s": 2752,
"text": "Not suitable for real-world objects"
},
{
"code": null,
"e": 2804,
"s": 2788,
"text": "Harder to write"
},
{
"code": null,
"e": 2813,
"s": 2804,
"text": "Example:"
},
{
"code": "# Procedural way of finding sum # of a list mylist = [10, 20, 30, 40] # modularization is done by # functional approachdef sum_the_list(mylist): res = 0 for val in mylist: res += val return res print(sum_the_list(mylist))",
"e": 3055,
"s": 2813,
"text": null
},
{
"code": null,
"e": 3063,
"s": 3055,
"text": "Output:"
},
{
"code": null,
"e": 3067,
"s": 3063,
"text": "100"
},
{
"code": null,
"e": 3669,
"s": 3067,
"text": "Functional programming paradigms is a paradigm in which everything is bind in pure mathematical functions style. It is known as declarative paradigms because it uses declarations overstatements. It uses the mathematical function and treats every statement as functional expression as an expression is executed to produce a value. Lambda functions or Recursion are basic approaches used for its implementation. The paradigms mainly focus on “what to solve” rather than “how to solve”. The ability to treat functions as values and pass them as an argument make the code more readable and understandable."
},
{
"code": null,
"e": 3680,
"s": 3669,
"text": "Advantages"
},
{
"code": null,
"e": 3701,
"s": 3680,
"text": "Simple to understand"
},
{
"code": null,
"e": 3737,
"s": 3701,
"text": "Making debugging and testing easier"
},
{
"code": null,
"e": 3792,
"s": 3737,
"text": "Enhances the comprehension and readability of the code"
},
{
"code": null,
"e": 3806,
"s": 3792,
"text": "Disadvantages"
},
{
"code": null,
"e": 3822,
"s": 3806,
"text": "Low performance"
},
{
"code": null,
"e": 3858,
"s": 3822,
"text": "Writing programs is a daunting task"
},
{
"code": null,
"e": 3886,
"s": 3858,
"text": "Low readability of the code"
},
{
"code": null,
"e": 3895,
"s": 3886,
"text": "Example:"
},
{
"code": "# Functional way of finding sum of a list import functools mylist = [11, 22, 33, 44] # Recursive Functional approachdef sum_the_list(mylist): if len(mylist) == 1: return mylist[0] else: return mylist[0] + sum_the_list(mylist[1:]) # lambda function is usedprint(functools.reduce(lambda x, y: x + y, mylist))",
"e": 4233,
"s": 3895,
"text": null
},
{
"code": null,
"e": 4241,
"s": 4233,
"text": "Output:"
},
{
"code": null,
"e": 4245,
"s": 4241,
"text": "110"
},
{
"code": null,
"e": 4315,
"s": 4245,
"text": "Note: For more information, refer to Functional Programming in Python"
},
{
"code": null,
"e": 4322,
"s": 4315,
"text": "Python"
}
]
|
Shift matrix elements row-wise by k | 14 Jun, 2022
Given a square matrix mat[][] and a number k. The task is to shift the first k elements of each row to the right of the matrix.
Examples :
Input : mat[N][N] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}
k = 2
Output :mat[N][N] = {{3, 1, 2}
{6, 4, 5}
{9, 7, 8}}
Input : mat[N][N] = {{1, 2, 3, 4}
{5, 6, 7, 8}
{9, 10, 11, 12}
{13, 14, 15, 16}}
k = 2
Output :mat[N][N] = {{3, 4, 1, 2}
{7, 8, 5, 6}
{11, 12, 9, 10}
{15, 16, 13, 14}}
Note: Matrix should be a square matrix
C++
Java
Python3
C#
PHP
Javascript
// C++ program to shift k elements in a matrix.#include <bits/stdc++.h>using namespace std;#define N 4 // Function to shift first k elements of// each row of matrix.void shiftMatrixByK(int mat[N][N], int k){ if (k > N) { cout << "shifting is not possible" << endl; return; } int j = 0; while (j < N) { // Print elements from index k for (int i = k; i < N; i++) cout << mat[j][i] << " "; // Print elements before index k for (int i = 0; i < k; i++) cout << mat[j][i] << " "; cout << endl; j++; }} // Driver codeint main(){ int mat[N][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int k = 2; // Function call shiftMatrixByK(mat, k); return 0;}
// Java program to shift k elements in a// matrix.import java.io.*;import java.util.*; public class GFG { static int N = 4; // Function to shift first k elements // of each row of matrix. static void shiftMatrixByK(int [][]mat, int k) { if (k > N) { System.out.print("Shifting is" + " not possible"); return; } int j = 0; while (j < N) { // Print elements from index k for (int i = k; i < N; i++) System.out.print(mat[j][i] + " "); // Print elements before index k for (int i = 0; i < k; i++) System.out.print(mat[j][i] + " "); System.out.println(); j++; } } // Driver code public static void main(String args[]) { int [][]mat = new int [][] { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; int k = 2; // Function call shiftMatrixByK(mat, k); }} // This code is contributed by Manish Shaw// (manishshaw1)
# Python3 program to shift k# elements in a matrix. N = 4# Function to shift first k# elements of each row of# matrix.def shiftMatrixByK(mat, k): if (k > N) : print ("shifting is" " not possible") return j = 0 while (j < N) : # Print elements from # index k for i in range(k, N): print ("{} " . format(mat[j][i]), end="") # Print elements before # index k for i in range(0, k): print ("{} " . format(mat[j][i]), end="") print ("") j = j + 1 # Driver codemat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]k = 2 # Function callshiftMatrixByK(mat, k) # This code is contributed by# Manish Shaw (manishshaw1)
// C# program to shift k elements in a// matrix.using System; class GFG { static int N = 4; // Function to shift first k elements // of each row of matrix. static void shiftMatrixByK(int [,]mat, int k) { if (k > N) { Console.WriteLine("shifting is" + " not possible"); return; } int j = 0; while (j < N) { // Print elements from index k for (int i = k; i < N; i++) Console.Write(mat[j,i] + " "); // Print elements before index k for (int i = 0; i < k; i++) Console.Write(mat[j,i] + " "); Console.WriteLine(); j++; } } // Driver code public static void Main() { int [,]mat = new int [,] { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; int k = 2; // Function call shiftMatrixByK(mat, k); }} // This code is contributed by Manish Shaw// (manishshaw1)
<?php// PHP program to shift k// elements in a matrix. // Function to shift first k// elements of each row of matrix.function shiftMatrixByK($mat, $k){ $N = 4; if ($k > $N) { echo ("shifting is not possible\n"); return; } $j = 0; while ($j < $N) { // Print elements from index k for ($i = $k; $i < $N; $i++) echo ($mat[$j][$i]." "); // Print elements before index k for ($i = 0; $i < $k; $i++) echo ($mat[$j][$i]." "); echo ("\n"); $j++; }} // Driver code$mat = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16));$k = 2; // Function callshiftMatrixByK($mat, $k); // This code is contributed by// Manish Shaw(manishshaw1)?>
<script>// Java Script program to shift k elements in a// matrix.let N = 4; // Function to shift first k elements// of each row of matrix.function shiftMatrixByK(mat,k){ if (k > N) { document.write("Shifting is not possible"); return; } let j = 0; while (j < N) { // Print elements from index k for (let i = k; i < N; i++) document.write(mat[j][i] + " "); // Print elements before index k for (let i = 0; i < k; i++) document.write(mat[j][i] + " "); document.write("<br>"); j++; }} // Driver code let mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; let k = 2; // Function call shiftMatrixByK(mat, k); // This code is contributed by sravan kumar G</script>
3 4 1 2
7 8 5 6
11 12 9 10
15 16 13 14
Time Complexity: O(n2),
Auxiliary Space: O(1)
manishshaw1
sravankumar8128
adi1212
Matrix
School Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 180,
"s": 52,
"text": "Given a square matrix mat[][] and a number k. The task is to shift the first k elements of each row to the right of the matrix."
},
{
"code": null,
"e": 193,
"s": 180,
"text": "Examples : "
},
{
"code": null,
"e": 741,
"s": 193,
"text": "Input : mat[N][N] = {{1, 2, 3},\n {4, 5, 6},\n {7, 8, 9}}\n k = 2\nOutput :mat[N][N] = {{3, 1, 2}\n {6, 4, 5}\n {9, 7, 8}}\n\nInput : mat[N][N] = {{1, 2, 3, 4}\n {5, 6, 7, 8}\n {9, 10, 11, 12}\n {13, 14, 15, 16}}\n k = 2\nOutput :mat[N][N] = {{3, 4, 1, 2}\n {7, 8, 5, 6}\n {11, 12, 9, 10}\n {15, 16, 13, 14}}\n\nNote: Matrix should be a square matrix "
},
{
"code": null,
"e": 745,
"s": 741,
"text": "C++"
},
{
"code": null,
"e": 750,
"s": 745,
"text": "Java"
},
{
"code": null,
"e": 758,
"s": 750,
"text": "Python3"
},
{
"code": null,
"e": 761,
"s": 758,
"text": "C#"
},
{
"code": null,
"e": 765,
"s": 761,
"text": "PHP"
},
{
"code": null,
"e": 776,
"s": 765,
"text": "Javascript"
},
{
"code": "// C++ program to shift k elements in a matrix.#include <bits/stdc++.h>using namespace std;#define N 4 // Function to shift first k elements of// each row of matrix.void shiftMatrixByK(int mat[N][N], int k){ if (k > N) { cout << \"shifting is not possible\" << endl; return; } int j = 0; while (j < N) { // Print elements from index k for (int i = k; i < N; i++) cout << mat[j][i] << \" \"; // Print elements before index k for (int i = 0; i < k; i++) cout << mat[j][i] << \" \"; cout << endl; j++; }} // Driver codeint main(){ int mat[N][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int k = 2; // Function call shiftMatrixByK(mat, k); return 0;}",
"e": 1660,
"s": 776,
"text": null
},
{
"code": "// Java program to shift k elements in a// matrix.import java.io.*;import java.util.*; public class GFG { static int N = 4; // Function to shift first k elements // of each row of matrix. static void shiftMatrixByK(int [][]mat, int k) { if (k > N) { System.out.print(\"Shifting is\" + \" not possible\"); return; } int j = 0; while (j < N) { // Print elements from index k for (int i = k; i < N; i++) System.out.print(mat[j][i] + \" \"); // Print elements before index k for (int i = 0; i < k; i++) System.out.print(mat[j][i] + \" \"); System.out.println(); j++; } } // Driver code public static void main(String args[]) { int [][]mat = new int [][] { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; int k = 2; // Function call shiftMatrixByK(mat, k); }} // This code is contributed by Manish Shaw// (manishshaw1)",
"e": 2923,
"s": 1660,
"text": null
},
{
"code": "# Python3 program to shift k# elements in a matrix. N = 4# Function to shift first k# elements of each row of# matrix.def shiftMatrixByK(mat, k): if (k > N) : print (\"shifting is\" \" not possible\") return j = 0 while (j < N) : # Print elements from # index k for i in range(k, N): print (\"{} \" . format(mat[j][i]), end=\"\") # Print elements before # index k for i in range(0, k): print (\"{} \" . format(mat[j][i]), end=\"\") print (\"\") j = j + 1 # Driver codemat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]k = 2 # Function callshiftMatrixByK(mat, k) # This code is contributed by# Manish Shaw (manishshaw1)",
"e": 3739,
"s": 2923,
"text": null
},
{
"code": "// C# program to shift k elements in a// matrix.using System; class GFG { static int N = 4; // Function to shift first k elements // of each row of matrix. static void shiftMatrixByK(int [,]mat, int k) { if (k > N) { Console.WriteLine(\"shifting is\" + \" not possible\"); return; } int j = 0; while (j < N) { // Print elements from index k for (int i = k; i < N; i++) Console.Write(mat[j,i] + \" \"); // Print elements before index k for (int i = 0; i < k; i++) Console.Write(mat[j,i] + \" \"); Console.WriteLine(); j++; } } // Driver code public static void Main() { int [,]mat = new int [,] { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; int k = 2; // Function call shiftMatrixByK(mat, k); }} // This code is contributed by Manish Shaw// (manishshaw1)",
"e": 4937,
"s": 3739,
"text": null
},
{
"code": "<?php// PHP program to shift k// elements in a matrix. // Function to shift first k// elements of each row of matrix.function shiftMatrixByK($mat, $k){ $N = 4; if ($k > $N) { echo (\"shifting is not possible\\n\"); return; } $j = 0; while ($j < $N) { // Print elements from index k for ($i = $k; $i < $N; $i++) echo ($mat[$j][$i].\" \"); // Print elements before index k for ($i = 0; $i < $k; $i++) echo ($mat[$j][$i].\" \"); echo (\"\\n\"); $j++; }} // Driver code$mat = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16));$k = 2; // Function callshiftMatrixByK($mat, $k); // This code is contributed by// Manish Shaw(manishshaw1)?>",
"e": 5780,
"s": 4937,
"text": null
},
{
"code": "<script>// Java Script program to shift k elements in a// matrix.let N = 4; // Function to shift first k elements// of each row of matrix.function shiftMatrixByK(mat,k){ if (k > N) { document.write(\"Shifting is not possible\"); return; } let j = 0; while (j < N) { // Print elements from index k for (let i = k; i < N; i++) document.write(mat[j][i] + \" \"); // Print elements before index k for (let i = 0; i < k; i++) document.write(mat[j][i] + \" \"); document.write(\"<br>\"); j++; }} // Driver code let mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; let k = 2; // Function call shiftMatrixByK(mat, k); // This code is contributed by sravan kumar G</script>",
"e": 6711,
"s": 5780,
"text": null
},
{
"code": null,
"e": 6753,
"s": 6711,
"text": "3 4 1 2 \n7 8 5 6 \n11 12 9 10 \n15 16 13 14"
},
{
"code": null,
"e": 6780,
"s": 6755,
"text": "Time Complexity: O(n2), "
},
{
"code": null,
"e": 6802,
"s": 6780,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6814,
"s": 6802,
"text": "manishshaw1"
},
{
"code": null,
"e": 6830,
"s": 6814,
"text": "sravankumar8128"
},
{
"code": null,
"e": 6838,
"s": 6830,
"text": "adi1212"
},
{
"code": null,
"e": 6845,
"s": 6838,
"text": "Matrix"
},
{
"code": null,
"e": 6864,
"s": 6845,
"text": "School Programming"
},
{
"code": null,
"e": 6871,
"s": 6864,
"text": "Matrix"
}
]
|
unordered_map erase in C++ STL | 24 Dec, 2018
erase function is used to erase elements from the unordered_map. There are three type of erase functions supported by unordered_map :
erasing by iterator: It takes an iterator as a parameter and erases the key and value present at that iterator.Syntaxunordered_map.erase(const iterator);erasing by key: It takes a key as a parameter and erases the key and value.Syntaxunordered_map.erase(const key);erase by range: It takes two iterators as a parameter and erases all the key and values present in between (including the starting iterator and excluding the end iterator).Syntax:unordered_map.erase(const iteratorStart, const iteratorEnd);
erasing by iterator: It takes an iterator as a parameter and erases the key and value present at that iterator.Syntaxunordered_map.erase(const iterator);
unordered_map.erase(const iterator);
erasing by key: It takes a key as a parameter and erases the key and value.Syntaxunordered_map.erase(const key);
unordered_map.erase(const key);
erase by range: It takes two iterators as a parameter and erases all the key and values present in between (including the starting iterator and excluding the end iterator).Syntax:unordered_map.erase(const iteratorStart, const iteratorEnd);
unordered_map.erase(const iteratorStart, const iteratorEnd);
// CPP program to demonstrate implementation of// erase function in unordered_map.#include <bits/stdc++.h>using namespace std; int main(){ unordered_map<int, bool> um; // Adding some elements in the map. um[12] = true; um[4189] = false; um[519] = true; um[40] = false; um[4991] = true; cout << "Contents of the unordered_map : \n"; for (auto p : um) cout << p.first << "==>" << p.second << "\n"; cout << "\n"; // erase by iterator cout << "After erasing by Iterator : \n"; um.erase(um.begin()); for (auto p : um) cout << p.first << "==>" << p.second << "\n"; cout << "\n"; // erase by value cout << "After erasing by Key : \n"; um.erase(4189); for (auto p : um) cout << p.first << "==>" << p.second << "\n"; cout << "\n"; // erase by range cout << "After erasing by Range : \n"; auto it = um.begin(); it++; // Returns iterator pointing to second element um.erase(it, um.end()); for (auto p : um) cout << p.first << "==>" << p.second << "\n"; cout << "\n"; return 0;}
Contents of the unordered_map :
4991==>1
519==>1
40==>0
12==>1
4189==>0
After erasing by Iterator :
519==>1
40==>0
12==>1
4189==>0
After erasing by Key :
519==>1
40==>0
12==>1
After erasing by Range :
519==>1
cpp-unordered_map
cpp-unordered_map-functions
Picked
STL
Technical Scripter 2018
C++
Technical Scripter
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
vector erase() and clear() in C++
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
Object Oriented Programming in C++
2D Vector In C++ With User Defined Size | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Dec, 2018"
},
{
"code": null,
"e": 186,
"s": 52,
"text": "erase function is used to erase elements from the unordered_map. There are three type of erase functions supported by unordered_map :"
},
{
"code": null,
"e": 691,
"s": 186,
"text": "erasing by iterator: It takes an iterator as a parameter and erases the key and value present at that iterator.Syntaxunordered_map.erase(const iterator);erasing by key: It takes a key as a parameter and erases the key and value.Syntaxunordered_map.erase(const key);erase by range: It takes two iterators as a parameter and erases all the key and values present in between (including the starting iterator and excluding the end iterator).Syntax:unordered_map.erase(const iteratorStart, const iteratorEnd);"
},
{
"code": null,
"e": 845,
"s": 691,
"text": "erasing by iterator: It takes an iterator as a parameter and erases the key and value present at that iterator.Syntaxunordered_map.erase(const iterator);"
},
{
"code": null,
"e": 882,
"s": 845,
"text": "unordered_map.erase(const iterator);"
},
{
"code": null,
"e": 995,
"s": 882,
"text": "erasing by key: It takes a key as a parameter and erases the key and value.Syntaxunordered_map.erase(const key);"
},
{
"code": null,
"e": 1027,
"s": 995,
"text": "unordered_map.erase(const key);"
},
{
"code": null,
"e": 1267,
"s": 1027,
"text": "erase by range: It takes two iterators as a parameter and erases all the key and values present in between (including the starting iterator and excluding the end iterator).Syntax:unordered_map.erase(const iteratorStart, const iteratorEnd);"
},
{
"code": null,
"e": 1328,
"s": 1267,
"text": "unordered_map.erase(const iteratorStart, const iteratorEnd);"
},
{
"code": "// CPP program to demonstrate implementation of// erase function in unordered_map.#include <bits/stdc++.h>using namespace std; int main(){ unordered_map<int, bool> um; // Adding some elements in the map. um[12] = true; um[4189] = false; um[519] = true; um[40] = false; um[4991] = true; cout << \"Contents of the unordered_map : \\n\"; for (auto p : um) cout << p.first << \"==>\" << p.second << \"\\n\"; cout << \"\\n\"; // erase by iterator cout << \"After erasing by Iterator : \\n\"; um.erase(um.begin()); for (auto p : um) cout << p.first << \"==>\" << p.second << \"\\n\"; cout << \"\\n\"; // erase by value cout << \"After erasing by Key : \\n\"; um.erase(4189); for (auto p : um) cout << p.first << \"==>\" << p.second << \"\\n\"; cout << \"\\n\"; // erase by range cout << \"After erasing by Range : \\n\"; auto it = um.begin(); it++; // Returns iterator pointing to second element um.erase(it, um.end()); for (auto p : um) cout << p.first << \"==>\" << p.second << \"\\n\"; cout << \"\\n\"; return 0;}",
"e": 2422,
"s": 1328,
"text": null
},
{
"code": null,
"e": 2638,
"s": 2422,
"text": "Contents of the unordered_map :\n4991==>1\n519==>1\n40==>0\n12==>1\n4189==>0\n\nAfter erasing by Iterator :\n519==>1\n40==>0\n12==>1\n4189==>0\n\nAfter erasing by Key :\n519==>1\n40==>0\n12==>1\n\nAfter erasing by Range :\n519==>1\n \n\n"
},
{
"code": null,
"e": 2656,
"s": 2638,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 2684,
"s": 2656,
"text": "cpp-unordered_map-functions"
},
{
"code": null,
"e": 2691,
"s": 2684,
"text": "Picked"
},
{
"code": null,
"e": 2695,
"s": 2691,
"text": "STL"
},
{
"code": null,
"e": 2719,
"s": 2695,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 2723,
"s": 2719,
"text": "C++"
},
{
"code": null,
"e": 2742,
"s": 2723,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2746,
"s": 2742,
"text": "STL"
},
{
"code": null,
"e": 2750,
"s": 2746,
"text": "CPP"
},
{
"code": null,
"e": 2848,
"s": 2750,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2875,
"s": 2848,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 2909,
"s": 2875,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 2928,
"s": 2909,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 2982,
"s": 2928,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3022,
"s": 2982,
"text": "The C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3046,
"s": 3022,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3063,
"s": 3046,
"text": "Substring in C++"
},
{
"code": null,
"e": 3087,
"s": 3063,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 3122,
"s": 3087,
"text": "Object Oriented Programming in C++"
}
]
|
Python | Tuple multiplication | 21 Nov, 2019
Sometimes, while working with records, we can have a problem in which we may need to perform multiplication of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using zip() + generator expressionThe combination of above functions can be used to perform this task. In this, we perform the task of multiplication using generator expression and mapping index of each tuple is done by zip().
# Python3 code to demonstrate working of# Tuple multiplication# using zip() + generator expression # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 6, 7, 5) # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Tuple multiplication# using zip() + generator expressionres = tuple(ele1 * ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) # printing resultprint("The multiplied tuple : " + str(res))
The original tuple 1 : (10, 4, 5, 6)
The original tuple 2 : (5, 6, 7, 5)
The multiplied tuple : (50, 24, 35, 30)
Method #2 : Using map() + mulThe combination of above functionalities can also perform this task. In this, we perform the task of extending logic of multiplication using mul and mapping is done by map().
# Python3 code to demonstrate working of# Tuple multiplication# using map() + mulfrom operator import mul # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 6, 7, 5) # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Tuple multiplication# using map() + mulres = tuple(map(mul, test_tup1, test_tup2)) # printing resultprint("The multiplied tuple : " + str(res))
The original tuple 1 : (10, 4, 5, 6)
The original tuple 2 : (5, 6, 7, 5)
The multiplied tuple : (50, 24, 35, 30)
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Nov, 2019"
},
{
"code": null,
"e": 258,
"s": 28,
"text": "Sometimes, while working with records, we can have a problem in which we may need to perform multiplication of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 497,
"s": 258,
"text": "Method #1 : Using zip() + generator expressionThe combination of above functions can be used to perform this task. In this, we perform the task of multiplication using generator expression and mapping index of each tuple is done by zip()."
},
{
"code": "# Python3 code to demonstrate working of# Tuple multiplication# using zip() + generator expression # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 6, 7, 5) # printing original tuplesprint(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Tuple multiplication# using zip() + generator expressionres = tuple(ele1 * ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) # printing resultprint(\"The multiplied tuple : \" + str(res))",
"e": 982,
"s": 497,
"text": null
},
{
"code": null,
"e": 1096,
"s": 982,
"text": "The original tuple 1 : (10, 4, 5, 6)\nThe original tuple 2 : (5, 6, 7, 5)\nThe multiplied tuple : (50, 24, 35, 30)\n"
},
{
"code": null,
"e": 1302,
"s": 1098,
"text": "Method #2 : Using map() + mulThe combination of above functionalities can also perform this task. In this, we perform the task of extending logic of multiplication using mul and mapping is done by map()."
},
{
"code": "# Python3 code to demonstrate working of# Tuple multiplication# using map() + mulfrom operator import mul # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 6, 7, 5) # printing original tuplesprint(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Tuple multiplication# using map() + mulres = tuple(map(mul, test_tup1, test_tup2)) # printing resultprint(\"The multiplied tuple : \" + str(res))",
"e": 1752,
"s": 1302,
"text": null
},
{
"code": null,
"e": 1866,
"s": 1752,
"text": "The original tuple 1 : (10, 4, 5, 6)\nThe original tuple 2 : (5, 6, 7, 5)\nThe multiplied tuple : (50, 24, 35, 30)\n"
},
{
"code": null,
"e": 1888,
"s": 1866,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 1895,
"s": 1888,
"text": "Python"
},
{
"code": null,
"e": 1911,
"s": 1895,
"text": "Python Programs"
}
]
|
C Program to check Armstrong Number | 24 Jun, 2022
Given a number x, determine whether the given number is Armstrong number or not.
A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if.
abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....
Example:
Input: 153
Output: Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153
Input: 120
Output: No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9
Input: 1253
Output: No
1253 is not a Armstrong Number
1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723
Input: 1634
Output: Yes
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634
Approach: The idea is to first count number digits (or find order). Let the number of digits be n. For every digit r in input number x, compute rn. If sum of all such values is equal to n, then return true, else false.
C
// C program to find Armstrong number#include <stdio.h> // Function to calculate x// raised to the power yint power(int x, unsigned int y){ if (y == 0) return 1; if (y % 2 == 0) return (power(x, y / 2) * power(x, y / 2)); return (x * power(x, y / 2) * power(x, y / 2));} // Function to calculate// order of the numberint order(int x){ int n = 0; while (x) { n++; x = x / 10; } return n;} // Function to check whether the// given number is Armstrong// number or notint isArmstrong(int x){ // Calling order function int n = order(x); int temp = x, sum = 0; while (temp) { int r = temp % 10; sum += power(r, n); temp = temp / 10; } // If satisfies Armstrong condition if (sum == x) return 1; else return 0;} // Driver Programint main(){ int x = 153; if (isArmstrong(x) == 1) printf("True\n"); else printf("False\n"); x = 1253; if (isArmstrong(x) == 1) printf("True\n"); else printf("False\n"); return 0;}
true
false
Time Complexity: O(logx*log(logx))
Auxiliary Space: O(1)
The above approach can also be implemented in a shorter way as:
C
// C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ int n = 153; int temp = n; int p = 0; // Function to calculate // the sum of individual digits while (n > 0) { int rem = n % 10; p = (p) + (rem * rem * rem); n = n / 10; } // Condition to check whether the // value of P equals to user input // or not. if (temp == p) { printf("Yes. It is Armstrong No."); } else { printf("No. It is not an Armstrong No."); } return 0;} // This code is contributed by sathiyamoorthics19
Yes. It is Armstrong No.
Time Complexity: O(logn)
Auxiliary Space: O(1)
Please refer complete article on Program for Armstrong Numbers for more details!
jayanth_mkv
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Difference between break and continue statement in C
C Hello World Program
C program to find the length of a string
Exit codes in C/C++ with Examples
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Handling multiple clients on server with multithreading using Socket Programming in C/C++
C Program to concatenate two strings without using strcat
Conditional wait and signal in multi-threading | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 135,
"s": 53,
"text": "Given a number x, determine whether the given number is Armstrong number or not. "
},
{
"code": null,
"e": 240,
"s": 135,
"text": "A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if. "
},
{
"code": null,
"e": 300,
"s": 240,
"text": "abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + .... "
},
{
"code": null,
"e": 310,
"s": 300,
"text": "Example: "
},
{
"code": null,
"e": 321,
"s": 310,
"text": "Input: 153"
},
{
"code": null,
"e": 333,
"s": 321,
"text": "Output: Yes"
},
{
"code": null,
"e": 361,
"s": 333,
"text": "153 is an Armstrong number."
},
{
"code": null,
"e": 389,
"s": 361,
"text": "1*1*1 + 5*5*5 + 3*3*3 = 153"
},
{
"code": null,
"e": 400,
"s": 389,
"text": "Input: 120"
},
{
"code": null,
"e": 411,
"s": 400,
"text": "Output: No"
},
{
"code": null,
"e": 442,
"s": 411,
"text": "120 is not a Armstrong number."
},
{
"code": null,
"e": 468,
"s": 442,
"text": "1*1*1 + 2*2*2 + 0*0*0 = 9"
},
{
"code": null,
"e": 480,
"s": 468,
"text": "Input: 1253"
},
{
"code": null,
"e": 491,
"s": 480,
"text": "Output: No"
},
{
"code": null,
"e": 522,
"s": 491,
"text": "1253 is not a Armstrong Number"
},
{
"code": null,
"e": 566,
"s": 522,
"text": "1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723"
},
{
"code": null,
"e": 578,
"s": 566,
"text": "Input: 1634"
},
{
"code": null,
"e": 590,
"s": 578,
"text": "Output: Yes"
},
{
"code": null,
"e": 635,
"s": 590,
"text": "1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634"
},
{
"code": null,
"e": 854,
"s": 635,
"text": "Approach: The idea is to first count number digits (or find order). Let the number of digits be n. For every digit r in input number x, compute rn. If sum of all such values is equal to n, then return true, else false."
},
{
"code": null,
"e": 856,
"s": 854,
"text": "C"
},
{
"code": "// C program to find Armstrong number#include <stdio.h> // Function to calculate x// raised to the power yint power(int x, unsigned int y){ if (y == 0) return 1; if (y % 2 == 0) return (power(x, y / 2) * power(x, y / 2)); return (x * power(x, y / 2) * power(x, y / 2));} // Function to calculate// order of the numberint order(int x){ int n = 0; while (x) { n++; x = x / 10; } return n;} // Function to check whether the// given number is Armstrong// number or notint isArmstrong(int x){ // Calling order function int n = order(x); int temp = x, sum = 0; while (temp) { int r = temp % 10; sum += power(r, n); temp = temp / 10; } // If satisfies Armstrong condition if (sum == x) return 1; else return 0;} // Driver Programint main(){ int x = 153; if (isArmstrong(x) == 1) printf(\"True\\n\"); else printf(\"False\\n\"); x = 1253; if (isArmstrong(x) == 1) printf(\"True\\n\"); else printf(\"False\\n\"); return 0;}",
"e": 1951,
"s": 856,
"text": null
},
{
"code": null,
"e": 1962,
"s": 1951,
"text": "true\nfalse"
},
{
"code": null,
"e": 1997,
"s": 1962,
"text": "Time Complexity: O(logx*log(logx))"
},
{
"code": null,
"e": 2019,
"s": 1997,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2083,
"s": 2019,
"text": "The above approach can also be implemented in a shorter way as:"
},
{
"code": null,
"e": 2085,
"s": 2083,
"text": "C"
},
{
"code": "// C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ int n = 153; int temp = n; int p = 0; // Function to calculate // the sum of individual digits while (n > 0) { int rem = n % 10; p = (p) + (rem * rem * rem); n = n / 10; } // Condition to check whether the // value of P equals to user input // or not. if (temp == p) { printf(\"Yes. It is Armstrong No.\"); } else { printf(\"No. It is not an Armstrong No.\"); } return 0;} // This code is contributed by sathiyamoorthics19",
"e": 2774,
"s": 2085,
"text": null
},
{
"code": null,
"e": 2799,
"s": 2774,
"text": "Yes. It is Armstrong No."
},
{
"code": null,
"e": 2824,
"s": 2799,
"text": "Time Complexity: O(logn)"
},
{
"code": null,
"e": 2846,
"s": 2824,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2927,
"s": 2846,
"text": "Please refer complete article on Program for Armstrong Numbers for more details!"
},
{
"code": null,
"e": 2939,
"s": 2927,
"text": "jayanth_mkv"
},
{
"code": null,
"e": 2950,
"s": 2939,
"text": "C Programs"
},
{
"code": null,
"e": 3048,
"s": 2950,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3089,
"s": 3048,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 3120,
"s": 3089,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 3173,
"s": 3120,
"text": "Difference between break and continue statement in C"
},
{
"code": null,
"e": 3195,
"s": 3173,
"text": "C Hello World Program"
},
{
"code": null,
"e": 3236,
"s": 3195,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 3270,
"s": 3236,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 3341,
"s": 3270,
"text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 3431,
"s": 3341,
"text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++"
},
{
"code": null,
"e": 3489,
"s": 3431,
"text": "C Program to concatenate two strings without using strcat"
}
]
|
Check if the number is balanced | 07 May, 2021
Given a number N in the form of a string, the task is to check whether the given number is balanced or not.
Balanced Number: A number is said to be balanced if the sum of digits in the first half of it is equal to the sum of the digits in the second half. Note: All Palindromic numbers are balanced numbers.
Examples:
Input: N = 19091 Output: Balanced Explanation: middle element is 0 Sum of left half = 1 + 9 = 10 Sum of right half = 9 + 1 = 10 Hence, the given number is a Balanced number.
Input: N = 133423 Output: Not Balanced Explanation: Sum of left half = 1 + 3 + 3 (7) Sum of right half = 4 + 2 + 3 (9) Hence, the given number is not Balanced
Approach:Iterate over half the length of the number from the beginning. Calculate the sum of digits of the first half and the second half simultaneously by adding s[i] and s[number of digits – 1 – i] to leftSum and rightSum respectively. Finally, check if the leftSum and rightSum are equal or not.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to check// if a number is// Balanced or not #include <bits/stdc++.h>using namespace std; // Function to check whether N is// Balanced Number or notvoid BalancedNumber(string s){ int Leftsum = 0; int Rightsum = 0; // Calculating the Leftsum // and rightSum simultaneously for (int i = 0; i < s.size() / 2; i++) { // Typecasting each character // to integer and adding the // digit to respective sums Leftsum += int(s[i] - '0'); Rightsum += int(s[s.size() - 1 - i] - '0'); } if (Leftsum == Rightsum) cout << "Balanced" << endl; else cout << "Not Balanced" << endl;} // Driver Codeint main(){ string s = "12321"; // Function call BalancedNumber(s); return 0;}
// Java program to check if a number// is Balanced or notimport java.io.*; class GFG{ // Function to check whether N is// Balanced Number or notprivate static void BalancedNumber(String s){ int Leftsum = 0; int Rightsum = 0; // Calculating the Leftsum // and rightSum simultaneously for(int i = 0; i < s.length() / 2; i++) { // Typecasting each character // to integer and adding the // digit to respective sums Leftsum += (int)(s.charAt(i) - '0'); Rightsum += (int)(s.charAt( s.length() - 1 - i) - '0'); } if (Leftsum == Rightsum) System.out.println("Balanced"); else System.out.println("Not Balanced");} // Driver Codepublic static void main (String[] args){ String s = "12321"; // Function call BalancedNumber(s);}} // This code is contributed by jithin
# Python3 program to check# if a number is# Balanced or not # Function to check whether N is# Balanced Number or notdef BalancedNumber(s): Leftsum = 0 Rightsum = 0 # Calculating the Leftsum # and rightSum simultaneously for i in range(0, int(len(s) / 2)): # Typecasting each character # to integer and adding the # digit to respective sums Leftsum = Leftsum + int(s[i]) Rightsum = (Rightsum + int(s[len(s) - 1 - i])) if (Leftsum == Rightsum): print("Balanced", end = '\n') else: print("Not Balanced", end = '\n') # Driver Codes = "12321" # Function callBalancedNumber(s) # This code is contributed by PratikBasu
// C# program to check// if a number is// Balanced or notusing System;class GFG{ // Function to check whether N is// Balanced Number or notstatic void BalancedNumber(string s){ int Leftsum = 0; int Rightsum = 0; // Calculating the Leftsum // and rightSum simultaneously for (int i = 0; i < s.Length / 2; i++) { // Typecasting each character // to integer and adding the // digit to respective sums Leftsum += (int)(Char.GetNumericValue(s[i]) - Char.GetNumericValue('0')); Rightsum += (int)(Char.GetNumericValue(s[s.Length - 1 - i]) - Char.GetNumericValue('0')); } if (Leftsum == Rightsum) Console.WriteLine("Balanced"); else Console.WriteLine("Not Balanced");} // Driver codestatic void Main(){ string s = "12321"; // Function call BalancedNumber(s);}} // This code is contributed by divyeshrabadiya07
<script> // JavaScript program to check if a number// is Balanced or not // Function to check whether N is// Balanced Number or notfunction BalancedNumber(s){ let Leftsum = 0; let Rightsum = 0; // Calculating the Leftsum // and rightSum simultaneously for(let i = 0; i < s.length / 2; i++) { // Typecasting each character // to integer and adding the // digit to respective sums Leftsum += (s[i] - '0'); Rightsum += (s[ s.length - 1 - i] - '0'); } if (Leftsum == Rightsum) document.write("Balanced"); else document.write("Not Balanced");} // Driver Code let s = "12321"; // Function call BalancedNumber(s); </script>
Balanced
PratikBasu
divyeshrabadiya07
jithin
code_hunt
number-digits
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
Write a program to reverse an array or string
Reverse a string in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Different Methods to Reverse a String in C++
Longest Common Subsequence | DP-4 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "Given a number N in the form of a string, the task is to check whether the given number is balanced or not."
},
{
"code": null,
"e": 337,
"s": 136,
"text": "Balanced Number: A number is said to be balanced if the sum of digits in the first half of it is equal to the sum of the digits in the second half. Note: All Palindromic numbers are balanced numbers. "
},
{
"code": null,
"e": 347,
"s": 337,
"text": "Examples:"
},
{
"code": null,
"e": 521,
"s": 347,
"text": "Input: N = 19091 Output: Balanced Explanation: middle element is 0 Sum of left half = 1 + 9 = 10 Sum of right half = 9 + 1 = 10 Hence, the given number is a Balanced number."
},
{
"code": null,
"e": 681,
"s": 521,
"text": "Input: N = 133423 Output: Not Balanced Explanation: Sum of left half = 1 + 3 + 3 (7) Sum of right half = 4 + 2 + 3 (9) Hence, the given number is not Balanced "
},
{
"code": null,
"e": 980,
"s": 681,
"text": "Approach:Iterate over half the length of the number from the beginning. Calculate the sum of digits of the first half and the second half simultaneously by adding s[i] and s[number of digits – 1 – i] to leftSum and rightSum respectively. Finally, check if the leftSum and rightSum are equal or not."
},
{
"code": null,
"e": 1033,
"s": 980,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 1037,
"s": 1033,
"text": "C++"
},
{
"code": null,
"e": 1042,
"s": 1037,
"text": "Java"
},
{
"code": null,
"e": 1050,
"s": 1042,
"text": "Python3"
},
{
"code": null,
"e": 1053,
"s": 1050,
"text": "C#"
},
{
"code": null,
"e": 1064,
"s": 1053,
"text": "Javascript"
},
{
"code": "// C++ program to check// if a number is// Balanced or not #include <bits/stdc++.h>using namespace std; // Function to check whether N is// Balanced Number or notvoid BalancedNumber(string s){ int Leftsum = 0; int Rightsum = 0; // Calculating the Leftsum // and rightSum simultaneously for (int i = 0; i < s.size() / 2; i++) { // Typecasting each character // to integer and adding the // digit to respective sums Leftsum += int(s[i] - '0'); Rightsum += int(s[s.size() - 1 - i] - '0'); } if (Leftsum == Rightsum) cout << \"Balanced\" << endl; else cout << \"Not Balanced\" << endl;} // Driver Codeint main(){ string s = \"12321\"; // Function call BalancedNumber(s); return 0;}",
"e": 1849,
"s": 1064,
"text": null
},
{
"code": "// Java program to check if a number// is Balanced or notimport java.io.*; class GFG{ // Function to check whether N is// Balanced Number or notprivate static void BalancedNumber(String s){ int Leftsum = 0; int Rightsum = 0; // Calculating the Leftsum // and rightSum simultaneously for(int i = 0; i < s.length() / 2; i++) { // Typecasting each character // to integer and adding the // digit to respective sums Leftsum += (int)(s.charAt(i) - '0'); Rightsum += (int)(s.charAt( s.length() - 1 - i) - '0'); } if (Leftsum == Rightsum) System.out.println(\"Balanced\"); else System.out.println(\"Not Balanced\");} // Driver Codepublic static void main (String[] args){ String s = \"12321\"; // Function call BalancedNumber(s);}} // This code is contributed by jithin",
"e": 2728,
"s": 1849,
"text": null
},
{
"code": "# Python3 program to check# if a number is# Balanced or not # Function to check whether N is# Balanced Number or notdef BalancedNumber(s): Leftsum = 0 Rightsum = 0 # Calculating the Leftsum # and rightSum simultaneously for i in range(0, int(len(s) / 2)): # Typecasting each character # to integer and adding the # digit to respective sums Leftsum = Leftsum + int(s[i]) Rightsum = (Rightsum + int(s[len(s) - 1 - i])) if (Leftsum == Rightsum): print(\"Balanced\", end = '\\n') else: print(\"Not Balanced\", end = '\\n') # Driver Codes = \"12321\" # Function callBalancedNumber(s) # This code is contributed by PratikBasu",
"e": 3433,
"s": 2728,
"text": null
},
{
"code": "// C# program to check// if a number is// Balanced or notusing System;class GFG{ // Function to check whether N is// Balanced Number or notstatic void BalancedNumber(string s){ int Leftsum = 0; int Rightsum = 0; // Calculating the Leftsum // and rightSum simultaneously for (int i = 0; i < s.Length / 2; i++) { // Typecasting each character // to integer and adding the // digit to respective sums Leftsum += (int)(Char.GetNumericValue(s[i]) - Char.GetNumericValue('0')); Rightsum += (int)(Char.GetNumericValue(s[s.Length - 1 - i]) - Char.GetNumericValue('0')); } if (Leftsum == Rightsum) Console.WriteLine(\"Balanced\"); else Console.WriteLine(\"Not Balanced\");} // Driver codestatic void Main(){ string s = \"12321\"; // Function call BalancedNumber(s);}} // This code is contributed by divyeshrabadiya07",
"e": 4361,
"s": 3433,
"text": null
},
{
"code": "<script> // JavaScript program to check if a number// is Balanced or not // Function to check whether N is// Balanced Number or notfunction BalancedNumber(s){ let Leftsum = 0; let Rightsum = 0; // Calculating the Leftsum // and rightSum simultaneously for(let i = 0; i < s.length / 2; i++) { // Typecasting each character // to integer and adding the // digit to respective sums Leftsum += (s[i] - '0'); Rightsum += (s[ s.length - 1 - i] - '0'); } if (Leftsum == Rightsum) document.write(\"Balanced\"); else document.write(\"Not Balanced\");} // Driver Code let s = \"12321\"; // Function call BalancedNumber(s); </script>",
"e": 5117,
"s": 4361,
"text": null
},
{
"code": null,
"e": 5126,
"s": 5117,
"text": "Balanced"
},
{
"code": null,
"e": 5139,
"s": 5128,
"text": "PratikBasu"
},
{
"code": null,
"e": 5157,
"s": 5139,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 5164,
"s": 5157,
"text": "jithin"
},
{
"code": null,
"e": 5174,
"s": 5164,
"text": "code_hunt"
},
{
"code": null,
"e": 5188,
"s": 5174,
"text": "number-digits"
},
{
"code": null,
"e": 5201,
"s": 5188,
"text": "Mathematical"
},
{
"code": null,
"e": 5209,
"s": 5201,
"text": "Strings"
},
{
"code": null,
"e": 5217,
"s": 5209,
"text": "Strings"
},
{
"code": null,
"e": 5230,
"s": 5217,
"text": "Mathematical"
},
{
"code": null,
"e": 5328,
"s": 5230,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5360,
"s": 5328,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 5406,
"s": 5360,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 5450,
"s": 5406,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 5499,
"s": 5450,
"text": "Find next greater number with same set of digits"
},
{
"code": null,
"e": 5541,
"s": 5499,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 5587,
"s": 5541,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 5612,
"s": 5587,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5687,
"s": 5612,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 5732,
"s": 5687,
"text": "Different Methods to Reverse a String in C++"
}
]
|
Sort the array in a given index range | 15 Jun, 2022
Given an array arr[] of N integers and an index range [a, b]. The task is to sort the array in this given index range i.e., sort the elements of the array from arr[a] to arr[b] while keeping the positions of other elements intact and print the modified array. Note: There is no relation between a and b i.e., a can be less than, equal to or greater than b. Also, 0 ≤ a, b < N
Examples:
Input: arr[] = {7, 8, 4, 5, 2}, a = 1, b = 4 Output: 7 2 4 5 8 For the index range [1, 4] we get the elements 8, 4, 5 and 2 On sorting these elements we get 2, 4, 5 and 8. So the array is modified as {7, 2, 4, 5, 8}
Input: arr[] = {20, 10, 3, 8}, a = 3, b = 1 Output: 20 3 8 10
Approach:
Make a temporary array of the elements for the given index range of the array.Sort this temporary array.Now modify the original array with these sorted elements of temporary array for the given index range.
Make a temporary array of the elements for the given index range of the array.
Sort this temporary array.
Now modify the original array with these sorted elements of temporary array for the given index range.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to sort the// array in a given index range #include <bits/stdc++.h>using namespace std; // Function to sort the elements of the array// from index a to index bvoid partSort(int arr[], int N, int a, int b){ // Variables to store start and // end of the index range int l = min(a, b); int r = max(a, b); // Temporary array int temp[r - l + 1]; int j = 0; for (int i = l; i <= r; i++) { temp[j] = arr[i]; j++; } // Sort the temporary array sort(temp, temp + r - l + 1); // Modifying original array with // temporary array elements j = 0; for (int i = l; i <= r; i++) { arr[i] = temp[j]; j++; } // Print the modified array for (int i = 0; i < N; i++) { cout << arr[i] << " " ; } } // Driver codeint main(){ int arr[] = { 7, 8, 4, 5, 2 } ; int a = 1 ; int b = 4; // length of the array int N = sizeof(arr) / sizeof(arr[0]); partSort(arr, N, a, b); return 0;}// This code is contributed by Ryuga
// Java program to sort the array in a given index rangeimport java.io.*;import java.util.*;import java.lang.*; class GFG { // Function to sort the elements of the array // from index a to index b static void partSort(int[] arr, int N, int a, int b) { // Variables to store start and end of the index range int l = Math.min(a, b); int r = Math.max(a, b); // Temporary array int[] temp = new int[r - l + 1]; int j = 0; for (int i = l; i <= r; i++) { temp[j] = arr[i]; j++; } // Sort the temporary array Arrays.sort(temp); // Modifying original array with temporary array elements j = 0; for (int i = l; i <= r; i++) { arr[i] = temp[j]; j++; } // Print the modified array for (int i = 0; i < N; i++) { System.out.print(arr[i] + " "); } } // Driver code public static void main(String args[]) { int[] arr = { 7, 8, 4, 5, 2 }; int a = 1, b = 4; // length of the array int N = arr.length; partSort(arr, N, a, b); }}
# Python 3 program to sort the# array in a given index range # Function to sort the elements of# the array from index a to index bdef partSort(arr, N, a, b): # Variables to store start and # end of the index range l = min(a, b) r = max(a, b) # Temporary array temp = [0 for i in range(r - l + 1)] j = 0 for i in range(l, r + 1, 1): temp[j] = arr[i] j += 1 # Sort the temporary array temp.sort(reverse = False) # Modifying original array with # temporary array elements j = 0 for i in range(l, r + 1, 1): arr[i] = temp[j] j += 1 # Print the modified array for i in range(0, N, 1): print(arr[i], end = " ") # Driver codeif __name__ == '__main__': arr = [7, 8, 4, 5, 2] a = 1 b = 4 # length of the array N = len(arr) partSort(arr, N, a, b) # This code is contributed by# Surendra_Gangwar
// C# program to sort the array in a given index rangeusing System;class GFG { // Function to sort the elements of the array // from index a to index b static void partSort(int[] arr, int N, int a, int b) { // Variables to store start and end of the index range int l = Math.Min(a, b); int r = Math.Max(a, b); // Temporary array int[] temp = new int[r - l + 1]; int j = 0; for (int i = l; i <= r; i++) { temp[j] = arr[i]; j++; } // Sort the temporary array Array.Sort(temp); // Modifying original array with temporary array elements j = 0; for (int i = l; i <= r; i++) { arr[i] = temp[j]; j++; } // Print the modified array for (int i = 0; i < N; i++) { Console.Write(arr[i] + " "); } } // Driver code public static void Main() { int[] arr = { 7, 8, 4, 5, 2 }; int a = 1, b = 4; // length of the array int N = arr.Length; partSort(arr, N, a, b); }}// This code is contributed by anuj_67
<?php# PHP program to sort the# array in a given index range // Function to sort the elements of the array// from index a to index bfunction partSort( $arr, $N, $a, $b){ // Variables to store start and // end of the index range $l = min($a, $b); $r = max($a, $b); // Temporary array $temp = array(); $j = 0; for ($i = $l; $i <= $r; $i++) { $temp[$j] = $arr[$i]; $j++; } // Sort the temporary array sort($temp); // Modifying original array with // temporary array elements $j = 0; for ($i = $l; $i <= $r; $i++) { $arr[$i] = $temp[$j]; $j++; } // Print the modified array for ($i = 0; $i < $N; $i++) { echo $arr[$i]." " ; } } $arr = array( 7, 8, 4, 5, 2 ) ; $a = 1 ; $b = 4; // length of the array $N = count($arr); partSort($arr, $N, $a, $b); //This code is contributed by 29AjayKumar ?>
<script> // Javascript program to sort the array in a given index range // Function to sort the elements of the array // from index a to index b function partSort(arr, N, a, b) { // Variables to store start and end of the index range let l = Math.min(a, b); let r = Math.max(a, b); // Temporary array let temp = new Array(r - l + 1); temp.fill(0); let j = 0; for (let i = l; i <= r; i++) { temp[j] = arr[i]; j++; } // Sort the temporary array temp.sort(function(a, b){return a - b}); // Modifying original array with temporary array elements j = 0; for (let i = l; i <= r; i++) { arr[i] = temp[j]; j++; } // Print the modified array for (let i = 0; i < N; i++) { document.write(arr[i] + " "); } } let arr = [ 7, 8, 4, 5, 2 ]; let a = 1, b = 4; // length of the array let N = arr.length; partSort(arr, N, a, b); </script>
7 2 4 5 8
Time Complexity: O(nlog(n))Auxiliary Space: O(n)
Below is a direct solution using Arrays.sort()
C++
Java
Python3
C#
Javascript
// C++ program to sort the array in a given index range#include<bits/stdc++.h>using namespace std; // Function to sort the elements of the array // from index a to index b void partSort(int arr[], int N, int a, int b) { // Variables to store start and end // of the index range int l = min(a, b); int r = max(a, b); vector<int> v(arr, arr + N); // Sort the subarray from arr[l] to // arr[r] sort(v.begin() + l, v.begin() + r + 1); // Print the modified array for (int i = 0; i < N; i++) cout << v[i] << " "; } // Driver code int main() { int arr[] = { 7, 8, 4, 5, 2 }; int a = 1, b = 4; int N = sizeof(arr)/sizeof(arr[0]); partSort(arr, N, a, b); } // This code is contributed by// Sanjit_Prasad
// Java program to sort the array in a given index rangeimport java.io.*;import java.util.*;import java.lang.*; class GFG { // Function to sort the elements of the array // from index a to index b static void partSort(int[] arr, int N, int a, int b) { // Variables to store start and end // of the index range int l = Math.min(a, b); int r = Math.max(a, b); // Sort the subarray from arr[l] to // arr[r] Arrays.sort(arr, l, r + 1); // Print the modified array for (int i = 0; i < N; i++) System.out.print(arr[i] + " "); } // Driver code public static void main(String args[]) { int[] arr = { 7, 8, 4, 5, 2 }; int a = 1, b = 4; int N = arr.length; partSort(arr, N, a, b); }}
# Python3 program to sort the# array in a given index range # Function to sort the elements of# the array from index a to index bdef partSort(arr, N, a, b): # Variables to store start and # end of the index range l = min(a, b) r = max(a, b) arr = (arr[0 : l] + sorted(arr[l : r + 1]) + arr[r : N]) # Print the modified array for i in range(0, N, 1): print(arr[i], end = " ") # Driver codeif __name__ == '__main__': arr = [ 7, 8, 4, 5, 2 ] a = 1 b = 4 # Length of the array N = len(arr) partSort(arr, N, a, b) # This code is contributed by grand_master
// C# program to sort the array in a given index rangeusing System; class GFG { // Function to sort the elements of the array // from index a to index b static void partSort(int[] arr, int N, int a, int b) { // Variables to store start and end // of the index range int l = Math.Min(a, b); int r = Math.Max(a, b); // Sort the subarray from arr[l] to // arr[r] Array.Sort(arr, l, r); // Print the modified array for (int i = 0; i < N; i++) Console.Write(arr[i] + " "); } // Driver code static void Main() { int[] arr = { 7, 8, 4, 5, 2 }; int a = 1, b = 4; int N = arr.Length; partSort(arr, N, a, b); }} // This code is contributed by mits
<script>// javascript program to sort the array in a given index range// Function to sort the elements of the array// from index a to index bfunction swap(arr, xp, yp){ var temp = arr[xp]; arr[xp] = arr[yp]; arr[yp] = temp;} function partSort(arr , N , a , b) { // Variables to store start and end // of the index range var l = Math.min(a, b); var r = Math.max(a, b); // Sort the subarray from arr[l] to // arr[r] //.sort(arr, l, r + 1); var i, j; for (i = l; i < r + 1 + 1; i++) { for (j = l; j < r - i + 1; j++) { if (arr[j] > arr[j + 1]) { swap(arr, j, j + 1); } } } // Print the modified array for (i = 0; i < N; i++) document.write(arr[i] + " "); } // Driver code var arr = [ 7, 8, 4, 5, 2 ]; var a = 1, b = 4; var N = arr.length; partSort(arr, N, a, b); // This code is contributed by gauravrajput1</script>
7 2 4 5 8
Time Complexity: O(nlog(n))Auxiliary Space: O(n)
vt_m
ankthon
SURENDRA_GANGWAR
29AjayKumar
Sanjit_Prasad
Mithun Kumar
grand_master
decode2207
GauravRajput1
simranarora5sos
pushpeshrajdx01
Arrays
Sorting Quiz
Arrays
Java Programs
Sorting
Technical Scripter
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find the smallest positive integer value that cannot be represented as sum of any subset of a given array
Find a triplet that sum to a given value
Product of Array except itself
Median of two sorted arrays of same size
Smallest subarray with sum greater than a given value
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 429,
"s": 53,
"text": "Given an array arr[] of N integers and an index range [a, b]. The task is to sort the array in this given index range i.e., sort the elements of the array from arr[a] to arr[b] while keeping the positions of other elements intact and print the modified array. Note: There is no relation between a and b i.e., a can be less than, equal to or greater than b. Also, 0 ≤ a, b < N"
},
{
"code": null,
"e": 440,
"s": 429,
"text": "Examples: "
},
{
"code": null,
"e": 656,
"s": 440,
"text": "Input: arr[] = {7, 8, 4, 5, 2}, a = 1, b = 4 Output: 7 2 4 5 8 For the index range [1, 4] we get the elements 8, 4, 5 and 2 On sorting these elements we get 2, 4, 5 and 8. So the array is modified as {7, 2, 4, 5, 8}"
},
{
"code": null,
"e": 719,
"s": 656,
"text": "Input: arr[] = {20, 10, 3, 8}, a = 3, b = 1 Output: 20 3 8 10 "
},
{
"code": null,
"e": 730,
"s": 719,
"text": "Approach: "
},
{
"code": null,
"e": 937,
"s": 730,
"text": "Make a temporary array of the elements for the given index range of the array.Sort this temporary array.Now modify the original array with these sorted elements of temporary array for the given index range."
},
{
"code": null,
"e": 1016,
"s": 937,
"text": "Make a temporary array of the elements for the given index range of the array."
},
{
"code": null,
"e": 1043,
"s": 1016,
"text": "Sort this temporary array."
},
{
"code": null,
"e": 1146,
"s": 1043,
"text": "Now modify the original array with these sorted elements of temporary array for the given index range."
},
{
"code": null,
"e": 1199,
"s": 1146,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1203,
"s": 1199,
"text": "C++"
},
{
"code": null,
"e": 1208,
"s": 1203,
"text": "Java"
},
{
"code": null,
"e": 1216,
"s": 1208,
"text": "Python3"
},
{
"code": null,
"e": 1219,
"s": 1216,
"text": "C#"
},
{
"code": null,
"e": 1223,
"s": 1219,
"text": "PHP"
},
{
"code": null,
"e": 1234,
"s": 1223,
"text": "Javascript"
},
{
"code": "// C++ program to sort the// array in a given index range #include <bits/stdc++.h>using namespace std; // Function to sort the elements of the array// from index a to index bvoid partSort(int arr[], int N, int a, int b){ // Variables to store start and // end of the index range int l = min(a, b); int r = max(a, b); // Temporary array int temp[r - l + 1]; int j = 0; for (int i = l; i <= r; i++) { temp[j] = arr[i]; j++; } // Sort the temporary array sort(temp, temp + r - l + 1); // Modifying original array with // temporary array elements j = 0; for (int i = l; i <= r; i++) { arr[i] = temp[j]; j++; } // Print the modified array for (int i = 0; i < N; i++) { cout << arr[i] << \" \" ; } } // Driver codeint main(){ int arr[] = { 7, 8, 4, 5, 2 } ; int a = 1 ; int b = 4; // length of the array int N = sizeof(arr) / sizeof(arr[0]); partSort(arr, N, a, b); return 0;}// This code is contributed by Ryuga",
"e": 2283,
"s": 1234,
"text": null
},
{
"code": "// Java program to sort the array in a given index rangeimport java.io.*;import java.util.*;import java.lang.*; class GFG { // Function to sort the elements of the array // from index a to index b static void partSort(int[] arr, int N, int a, int b) { // Variables to store start and end of the index range int l = Math.min(a, b); int r = Math.max(a, b); // Temporary array int[] temp = new int[r - l + 1]; int j = 0; for (int i = l; i <= r; i++) { temp[j] = arr[i]; j++; } // Sort the temporary array Arrays.sort(temp); // Modifying original array with temporary array elements j = 0; for (int i = l; i <= r; i++) { arr[i] = temp[j]; j++; } // Print the modified array for (int i = 0; i < N; i++) { System.out.print(arr[i] + \" \"); } } // Driver code public static void main(String args[]) { int[] arr = { 7, 8, 4, 5, 2 }; int a = 1, b = 4; // length of the array int N = arr.length; partSort(arr, N, a, b); }}",
"e": 3438,
"s": 2283,
"text": null
},
{
"code": "# Python 3 program to sort the# array in a given index range # Function to sort the elements of# the array from index a to index bdef partSort(arr, N, a, b): # Variables to store start and # end of the index range l = min(a, b) r = max(a, b) # Temporary array temp = [0 for i in range(r - l + 1)] j = 0 for i in range(l, r + 1, 1): temp[j] = arr[i] j += 1 # Sort the temporary array temp.sort(reverse = False) # Modifying original array with # temporary array elements j = 0 for i in range(l, r + 1, 1): arr[i] = temp[j] j += 1 # Print the modified array for i in range(0, N, 1): print(arr[i], end = \" \") # Driver codeif __name__ == '__main__': arr = [7, 8, 4, 5, 2] a = 1 b = 4 # length of the array N = len(arr) partSort(arr, N, a, b) # This code is contributed by# Surendra_Gangwar",
"e": 4351,
"s": 3438,
"text": null
},
{
"code": "// C# program to sort the array in a given index rangeusing System;class GFG { // Function to sort the elements of the array // from index a to index b static void partSort(int[] arr, int N, int a, int b) { // Variables to store start and end of the index range int l = Math.Min(a, b); int r = Math.Max(a, b); // Temporary array int[] temp = new int[r - l + 1]; int j = 0; for (int i = l; i <= r; i++) { temp[j] = arr[i]; j++; } // Sort the temporary array Array.Sort(temp); // Modifying original array with temporary array elements j = 0; for (int i = l; i <= r; i++) { arr[i] = temp[j]; j++; } // Print the modified array for (int i = 0; i < N; i++) { Console.Write(arr[i] + \" \"); } } // Driver code public static void Main() { int[] arr = { 7, 8, 4, 5, 2 }; int a = 1, b = 4; // length of the array int N = arr.Length; partSort(arr, N, a, b); }}// This code is contributed by anuj_67",
"e": 5482,
"s": 4351,
"text": null
},
{
"code": "<?php# PHP program to sort the# array in a given index range // Function to sort the elements of the array// from index a to index bfunction partSort( $arr, $N, $a, $b){ // Variables to store start and // end of the index range $l = min($a, $b); $r = max($a, $b); // Temporary array $temp = array(); $j = 0; for ($i = $l; $i <= $r; $i++) { $temp[$j] = $arr[$i]; $j++; } // Sort the temporary array sort($temp); // Modifying original array with // temporary array elements $j = 0; for ($i = $l; $i <= $r; $i++) { $arr[$i] = $temp[$j]; $j++; } // Print the modified array for ($i = 0; $i < $N; $i++) { echo $arr[$i].\" \" ; } } $arr = array( 7, 8, 4, 5, 2 ) ; $a = 1 ; $b = 4; // length of the array $N = count($arr); partSort($arr, $N, $a, $b); //This code is contributed by 29AjayKumar ?>",
"e": 6421,
"s": 5482,
"text": null
},
{
"code": "<script> // Javascript program to sort the array in a given index range // Function to sort the elements of the array // from index a to index b function partSort(arr, N, a, b) { // Variables to store start and end of the index range let l = Math.min(a, b); let r = Math.max(a, b); // Temporary array let temp = new Array(r - l + 1); temp.fill(0); let j = 0; for (let i = l; i <= r; i++) { temp[j] = arr[i]; j++; } // Sort the temporary array temp.sort(function(a, b){return a - b}); // Modifying original array with temporary array elements j = 0; for (let i = l; i <= r; i++) { arr[i] = temp[j]; j++; } // Print the modified array for (let i = 0; i < N; i++) { document.write(arr[i] + \" \"); } } let arr = [ 7, 8, 4, 5, 2 ]; let a = 1, b = 4; // length of the array let N = arr.length; partSort(arr, N, a, b); </script>",
"e": 7476,
"s": 6421,
"text": null
},
{
"code": null,
"e": 7486,
"s": 7476,
"text": "7 2 4 5 8"
},
{
"code": null,
"e": 7537,
"s": 7488,
"text": "Time Complexity: O(nlog(n))Auxiliary Space: O(n)"
},
{
"code": null,
"e": 7585,
"s": 7537,
"text": "Below is a direct solution using Arrays.sort() "
},
{
"code": null,
"e": 7589,
"s": 7585,
"text": "C++"
},
{
"code": null,
"e": 7594,
"s": 7589,
"text": "Java"
},
{
"code": null,
"e": 7602,
"s": 7594,
"text": "Python3"
},
{
"code": null,
"e": 7605,
"s": 7602,
"text": "C#"
},
{
"code": null,
"e": 7616,
"s": 7605,
"text": "Javascript"
},
{
"code": "// C++ program to sort the array in a given index range#include<bits/stdc++.h>using namespace std; // Function to sort the elements of the array // from index a to index b void partSort(int arr[], int N, int a, int b) { // Variables to store start and end // of the index range int l = min(a, b); int r = max(a, b); vector<int> v(arr, arr + N); // Sort the subarray from arr[l] to // arr[r] sort(v.begin() + l, v.begin() + r + 1); // Print the modified array for (int i = 0; i < N; i++) cout << v[i] << \" \"; } // Driver code int main() { int arr[] = { 7, 8, 4, 5, 2 }; int a = 1, b = 4; int N = sizeof(arr)/sizeof(arr[0]); partSort(arr, N, a, b); } // This code is contributed by// Sanjit_Prasad",
"e": 8465,
"s": 7616,
"text": null
},
{
"code": "// Java program to sort the array in a given index rangeimport java.io.*;import java.util.*;import java.lang.*; class GFG { // Function to sort the elements of the array // from index a to index b static void partSort(int[] arr, int N, int a, int b) { // Variables to store start and end // of the index range int l = Math.min(a, b); int r = Math.max(a, b); // Sort the subarray from arr[l] to // arr[r] Arrays.sort(arr, l, r + 1); // Print the modified array for (int i = 0; i < N; i++) System.out.print(arr[i] + \" \"); } // Driver code public static void main(String args[]) { int[] arr = { 7, 8, 4, 5, 2 }; int a = 1, b = 4; int N = arr.length; partSort(arr, N, a, b); }}",
"e": 9272,
"s": 8465,
"text": null
},
{
"code": "# Python3 program to sort the# array in a given index range # Function to sort the elements of# the array from index a to index bdef partSort(arr, N, a, b): # Variables to store start and # end of the index range l = min(a, b) r = max(a, b) arr = (arr[0 : l] + sorted(arr[l : r + 1]) + arr[r : N]) # Print the modified array for i in range(0, N, 1): print(arr[i], end = \" \") # Driver codeif __name__ == '__main__': arr = [ 7, 8, 4, 5, 2 ] a = 1 b = 4 # Length of the array N = len(arr) partSort(arr, N, a, b) # This code is contributed by grand_master",
"e": 9901,
"s": 9272,
"text": null
},
{
"code": "// C# program to sort the array in a given index rangeusing System; class GFG { // Function to sort the elements of the array // from index a to index b static void partSort(int[] arr, int N, int a, int b) { // Variables to store start and end // of the index range int l = Math.Min(a, b); int r = Math.Max(a, b); // Sort the subarray from arr[l] to // arr[r] Array.Sort(arr, l, r); // Print the modified array for (int i = 0; i < N; i++) Console.Write(arr[i] + \" \"); } // Driver code static void Main() { int[] arr = { 7, 8, 4, 5, 2 }; int a = 1, b = 4; int N = arr.Length; partSort(arr, N, a, b); }} // This code is contributed by mits",
"e": 10672,
"s": 9901,
"text": null
},
{
"code": "<script>// javascript program to sort the array in a given index range// Function to sort the elements of the array// from index a to index bfunction swap(arr, xp, yp){ var temp = arr[xp]; arr[xp] = arr[yp]; arr[yp] = temp;} function partSort(arr , N , a , b) { // Variables to store start and end // of the index range var l = Math.min(a, b); var r = Math.max(a, b); // Sort the subarray from arr[l] to // arr[r] //.sort(arr, l, r + 1); var i, j; for (i = l; i < r + 1 + 1; i++) { for (j = l; j < r - i + 1; j++) { if (arr[j] > arr[j + 1]) { swap(arr, j, j + 1); } } } // Print the modified array for (i = 0; i < N; i++) document.write(arr[i] + \" \"); } // Driver code var arr = [ 7, 8, 4, 5, 2 ]; var a = 1, b = 4; var N = arr.length; partSort(arr, N, a, b); // This code is contributed by gauravrajput1</script>",
"e": 11704,
"s": 10672,
"text": null
},
{
"code": null,
"e": 11714,
"s": 11704,
"text": "7 2 4 5 8"
},
{
"code": null,
"e": 11765,
"s": 11716,
"text": "Time Complexity: O(nlog(n))Auxiliary Space: O(n)"
},
{
"code": null,
"e": 11770,
"s": 11765,
"text": "vt_m"
},
{
"code": null,
"e": 11778,
"s": 11770,
"text": "ankthon"
},
{
"code": null,
"e": 11795,
"s": 11778,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 11807,
"s": 11795,
"text": "29AjayKumar"
},
{
"code": null,
"e": 11821,
"s": 11807,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 11834,
"s": 11821,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 11847,
"s": 11834,
"text": "grand_master"
},
{
"code": null,
"e": 11858,
"s": 11847,
"text": "decode2207"
},
{
"code": null,
"e": 11872,
"s": 11858,
"text": "GauravRajput1"
},
{
"code": null,
"e": 11888,
"s": 11872,
"text": "simranarora5sos"
},
{
"code": null,
"e": 11904,
"s": 11888,
"text": "pushpeshrajdx01"
},
{
"code": null,
"e": 11911,
"s": 11904,
"text": "Arrays"
},
{
"code": null,
"e": 11924,
"s": 11911,
"text": "Sorting Quiz"
},
{
"code": null,
"e": 11931,
"s": 11924,
"text": "Arrays"
},
{
"code": null,
"e": 11945,
"s": 11931,
"text": "Java Programs"
},
{
"code": null,
"e": 11953,
"s": 11945,
"text": "Sorting"
},
{
"code": null,
"e": 11972,
"s": 11953,
"text": "Technical Scripter"
},
{
"code": null,
"e": 11979,
"s": 11972,
"text": "Arrays"
},
{
"code": null,
"e": 11987,
"s": 11979,
"text": "Sorting"
},
{
"code": null,
"e": 12085,
"s": 11987,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12191,
"s": 12085,
"text": "Find the smallest positive integer value that cannot be represented as sum of any subset of a given array"
},
{
"code": null,
"e": 12232,
"s": 12191,
"text": "Find a triplet that sum to a given value"
},
{
"code": null,
"e": 12263,
"s": 12232,
"text": "Product of Array except itself"
},
{
"code": null,
"e": 12304,
"s": 12263,
"text": "Median of two sorted arrays of same size"
},
{
"code": null,
"e": 12358,
"s": 12304,
"text": "Smallest subarray with sum greater than a given value"
},
{
"code": null,
"e": 12386,
"s": 12358,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 12412,
"s": 12386,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 12456,
"s": 12412,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 12490,
"s": 12456,
"text": "Convert Double to Integer in Java"
}
]
|
Java Concurrency – yield(), sleep() and join() Methods | 16 Jan, 2022
In this article, we will learn what is yield(), join(), and sleep() methods in Java and what is the basic difference between these three. First, we will see the basic introduction of all these three methods, and then we compare these three.
We can prevent the execution of a thread by using one of the following methods of the Thread class. All three methods will be used to prevent the thread from execution.
Suppose there are three threads t1, t2, and t3. Thread t1 gets the processor and starts its execution and thread t2 and t3 are in Ready/Runnable state. The completion time for thread t1 is 5 hours and the completion time for t2 is 5 minutes. Since t1 will complete its execution after 5 hours, t2 has to wait for 5 hours to just finish 5 minutes job. In such scenarios where one thread is taking too much time to complete its execution, we need a way to prevent the execution of a thread in between if something important is pending. yield() helps us in doing so.
The yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should run. Otherwise, the current thread will continue to run.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Use of yield method:
Whenever a thread calls java.lang.Thread.yield method gives hint to the thread scheduler that it is ready to pause its execution. The thread scheduler is free to ignore this hint.
If any thread executes the yield method, the thread scheduler checks if there is any thread with the same or high priority as this thread. If the processor finds any thread with higher or same priority then it will move the current thread to Ready/Runnable state and give the processor to another thread and if not – the current thread will keep executing.
Once a thread has executed the yield method and there are many threads with the same priority is waiting for the processor, then we can’t specify which thread will get the execution chance first.
The thread which executes the yield method will enter in the Runnable state from Running state.
Once a thread pauses its execution, we can’t specify when it will get a chance again it depends on the thread scheduler.
The underlying platform must provide support for preemptive scheduling if we are using the yield method.
This method causes the currently executing thread to sleep for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
Syntax:
// sleep for the specified number of milliseconds
public static void sleep(long millis) throws InterruptedException
//sleep for the specified number of milliseconds plus nano seconds
public static void sleep(long millis, int nanos)
throws InterruptedException
Java
// Java program to illustrate// sleep() method in Java import java.lang.*; public class SleepDemo implements Runnable { Thread t; public void run() { for (int i = 0; i < 4; i++) { System.out.println( Thread.currentThread().getName() + " " + i); try { // thread to sleep for 1000 milliseconds Thread.sleep(1000); } catch (Exception e) { System.out.println(e); } } } public static void main(String[] args) throws Exception { Thread t = new Thread(new SleepDemo()); // call run() function t.start(); Thread t2 = new Thread(new SleepDemo()); // call run() function t2.start(); }}
Thread-1 0
Thread-0 0
Thread-0 1
Thread-1 1
Thread-0 2
Thread-1 2
Thread-1 3
Thread-0 3
Note:
Based on the requirement we can make a thread to be in a sleeping state for a specified period of time
Sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power-saving mode).
The join() method of a Thread instance is used to join the start of a thread’s execution to the end of another thread’s execution such that a thread does not start running until another thread ends. If join() is called on a Thread instance, the currently running thread will block until the Thread instance has finished executing. The join() method waits at most this many milliseconds for this thread to die. A timeout of 0 means to wait forever
Syntax:
// waits for this thread to die.
public final void join() throws InterruptedException
// waits at most this much milliseconds for this thread to die
public final void join(long millis)
throws InterruptedException
// waits at most milliseconds plus nanoseconds for this thread to die.
The java.lang.Thread.join(long millis, int nanos)
Java
// Java program to illustrate join() method in Java import java.lang.*; public class JoinDemo implements Runnable { public void run() { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t.getName()); // checks if current thread is alive System.out.println("Is Alive? " + t.isAlive()); } public static void main(String args[]) throws Exception { Thread t = new Thread(new JoinDemo()); t.start(); // Waits for 1000ms this thread to die. t.join(1000); System.out.println("\nJoining after 1000" + " milliseconds: \n"); System.out.println("Current thread: " + t.getName()); // Checks if this thread is alive System.out.println("Is alive? " + t.isAlive()); }}
Current thread: Thread-0
Is Alive? true
Joining after 1000 milliseconds:
Current thread: Thread-0
Is alive? false
Note:
If any executing thread t1 calls join() on t2 i.e; t2.join() immediately t1 will enter into waiting state until t2 completes its execution.
Giving a timeout within join(), will make the join() effect to be nullified after the specific timeout.
This article is contributed by Dharmesh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sooda367
arorakashish0911
nishkarshgandhi
Java-Multithreading
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Jan, 2022"
},
{
"code": null,
"e": 295,
"s": 54,
"text": "In this article, we will learn what is yield(), join(), and sleep() methods in Java and what is the basic difference between these three. First, we will see the basic introduction of all these three methods, and then we compare these three."
},
{
"code": null,
"e": 464,
"s": 295,
"text": "We can prevent the execution of a thread by using one of the following methods of the Thread class. All three methods will be used to prevent the thread from execution."
},
{
"code": null,
"e": 1029,
"s": 464,
"text": "Suppose there are three threads t1, t2, and t3. Thread t1 gets the processor and starts its execution and thread t2 and t3 are in Ready/Runnable state. The completion time for thread t1 is 5 hours and the completion time for t2 is 5 minutes. Since t1 will complete its execution after 5 hours, t2 has to wait for 5 hours to just finish 5 minutes job. In such scenarios where one thread is taking too much time to complete its execution, we need a way to prevent the execution of a thread in between if something important is pending. yield() helps us in doing so. "
},
{
"code": null,
"e": 1241,
"s": 1029,
"text": "The yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should run. Otherwise, the current thread will continue to run."
},
{
"code": null,
"e": 1250,
"s": 1241,
"text": "Chapters"
},
{
"code": null,
"e": 1277,
"s": 1250,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1327,
"s": 1277,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1350,
"s": 1327,
"text": "captions off, selected"
},
{
"code": null,
"e": 1358,
"s": 1350,
"text": "English"
},
{
"code": null,
"e": 1382,
"s": 1358,
"text": "This is a modal window."
},
{
"code": null,
"e": 1451,
"s": 1382,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1473,
"s": 1451,
"text": "End of dialog window."
},
{
"code": null,
"e": 1495,
"s": 1473,
"text": "Use of yield method: "
},
{
"code": null,
"e": 1675,
"s": 1495,
"text": "Whenever a thread calls java.lang.Thread.yield method gives hint to the thread scheduler that it is ready to pause its execution. The thread scheduler is free to ignore this hint."
},
{
"code": null,
"e": 2032,
"s": 1675,
"text": "If any thread executes the yield method, the thread scheduler checks if there is any thread with the same or high priority as this thread. If the processor finds any thread with higher or same priority then it will move the current thread to Ready/Runnable state and give the processor to another thread and if not – the current thread will keep executing."
},
{
"code": null,
"e": 2228,
"s": 2032,
"text": "Once a thread has executed the yield method and there are many threads with the same priority is waiting for the processor, then we can’t specify which thread will get the execution chance first."
},
{
"code": null,
"e": 2324,
"s": 2228,
"text": "The thread which executes the yield method will enter in the Runnable state from Running state."
},
{
"code": null,
"e": 2445,
"s": 2324,
"text": "Once a thread pauses its execution, we can’t specify when it will get a chance again it depends on the thread scheduler."
},
{
"code": null,
"e": 2550,
"s": 2445,
"text": "The underlying platform must provide support for preemptive scheduling if we are using the yield method."
},
{
"code": null,
"e": 2723,
"s": 2550,
"text": "This method causes the currently executing thread to sleep for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. "
},
{
"code": null,
"e": 2732,
"s": 2723,
"text": " Syntax:"
},
{
"code": null,
"e": 3020,
"s": 2732,
"text": "// sleep for the specified number of milliseconds\npublic static void sleep(long millis) throws InterruptedException\n\n//sleep for the specified number of milliseconds plus nano seconds\npublic static void sleep(long millis, int nanos) \n throws InterruptedException"
},
{
"code": null,
"e": 3025,
"s": 3020,
"text": "Java"
},
{
"code": "// Java program to illustrate// sleep() method in Java import java.lang.*; public class SleepDemo implements Runnable { Thread t; public void run() { for (int i = 0; i < 4; i++) { System.out.println( Thread.currentThread().getName() + \" \" + i); try { // thread to sleep for 1000 milliseconds Thread.sleep(1000); } catch (Exception e) { System.out.println(e); } } } public static void main(String[] args) throws Exception { Thread t = new Thread(new SleepDemo()); // call run() function t.start(); Thread t2 = new Thread(new SleepDemo()); // call run() function t2.start(); }}",
"e": 3821,
"s": 3025,
"text": null
},
{
"code": null,
"e": 3917,
"s": 3821,
"text": "Thread-1 0\nThread-0 0\nThread-0 1\nThread-1 1\nThread-0 2\nThread-1 2\nThread-1 3\nThread-0 3"
},
{
"code": null,
"e": 3924,
"s": 3917,
"text": "Note: "
},
{
"code": null,
"e": 4027,
"s": 3924,
"text": "Based on the requirement we can make a thread to be in a sleeping state for a specified period of time"
},
{
"code": null,
"e": 4220,
"s": 4027,
"text": "Sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power-saving mode)."
},
{
"code": null,
"e": 4668,
"s": 4220,
"text": "The join() method of a Thread instance is used to join the start of a thread’s execution to the end of another thread’s execution such that a thread does not start running until another thread ends. If join() is called on a Thread instance, the currently running thread will block until the Thread instance has finished executing. The join() method waits at most this many milliseconds for this thread to die. A timeout of 0 means to wait forever "
},
{
"code": null,
"e": 4676,
"s": 4668,
"text": "Syntax:"
},
{
"code": null,
"e": 5027,
"s": 4676,
"text": "// waits for this thread to die.\npublic final void join() throws InterruptedException\n\n// waits at most this much milliseconds for this thread to die\npublic final void join(long millis) \n throws InterruptedException\n\n// waits at most milliseconds plus nanoseconds for this thread to die.\nThe java.lang.Thread.join(long millis, int nanos)"
},
{
"code": null,
"e": 5032,
"s": 5027,
"text": "Java"
},
{
"code": "// Java program to illustrate join() method in Java import java.lang.*; public class JoinDemo implements Runnable { public void run() { Thread t = Thread.currentThread(); System.out.println(\"Current thread: \" + t.getName()); // checks if current thread is alive System.out.println(\"Is Alive? \" + t.isAlive()); } public static void main(String args[]) throws Exception { Thread t = new Thread(new JoinDemo()); t.start(); // Waits for 1000ms this thread to die. t.join(1000); System.out.println(\"\\nJoining after 1000\" + \" milliseconds: \\n\"); System.out.println(\"Current thread: \" + t.getName()); // Checks if this thread is alive System.out.println(\"Is alive? \" + t.isAlive()); }}",
"e": 5903,
"s": 5032,
"text": null
},
{
"code": null,
"e": 6020,
"s": 5903,
"text": "Current thread: Thread-0\nIs Alive? true\n\nJoining after 1000 milliseconds: \n\nCurrent thread: Thread-0\nIs alive? false"
},
{
"code": null,
"e": 6026,
"s": 6020,
"text": "Note:"
},
{
"code": null,
"e": 6166,
"s": 6026,
"text": "If any executing thread t1 calls join() on t2 i.e; t2.join() immediately t1 will enter into waiting state until t2 completes its execution."
},
{
"code": null,
"e": 6270,
"s": 6166,
"text": "Giving a timeout within join(), will make the join() effect to be nullified after the specific timeout."
},
{
"code": null,
"e": 6687,
"s": 6270,
"text": "This article is contributed by Dharmesh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6696,
"s": 6687,
"text": "sooda367"
},
{
"code": null,
"e": 6713,
"s": 6696,
"text": "arorakashish0911"
},
{
"code": null,
"e": 6729,
"s": 6713,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 6749,
"s": 6729,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 6754,
"s": 6749,
"text": "Java"
},
{
"code": null,
"e": 6759,
"s": 6754,
"text": "Java"
},
{
"code": null,
"e": 6857,
"s": 6759,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6872,
"s": 6857,
"text": "Arrays in Java"
},
{
"code": null,
"e": 6908,
"s": 6872,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 6952,
"s": 6908,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 6977,
"s": 6952,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 7028,
"s": 6977,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 7050,
"s": 7028,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 7081,
"s": 7050,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 7100,
"s": 7081,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 7130,
"s": 7100,
"text": "HashMap in Java with Examples"
}
]
|
Acronym in Python | Suppose we have a string s that is representing a phrase, we have to find its acronym. The acronyms should be capitalized and should not include the word "and".
So, if the input is like "Indian Space Research Organisation", then the output will be ISRO
To solve this, we will follow these steps −
tokens:= each word of s as an array
tokens:= each word of s as an array
string:= blank string
string:= blank string
for each word in tokens, doif word is not "and", thenstring := string concatenate first letter of word
for each word in tokens, do
if word is not "and", thenstring := string concatenate first letter of word
if word is not "and", then
string := string concatenate first letter of word
string := string concatenate first letter of word
return convert string into uppercase string
return convert string into uppercase string
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, s):
tokens=s.split()
string=""
for word in tokens:
if word != "and":
string += str(word[0])
return string.upper()
ob = Solution()
print(ob.solve("Indian Space Research Organisation"))
"Indian Space Research Organisation"
ISRO | [
{
"code": null,
"e": 1223,
"s": 1062,
"text": "Suppose we have a string s that is representing a phrase, we have to find its acronym. The acronyms should be capitalized and should not include the word \"and\"."
},
{
"code": null,
"e": 1315,
"s": 1223,
"text": "So, if the input is like \"Indian Space Research Organisation\", then the output will be ISRO"
},
{
"code": null,
"e": 1359,
"s": 1315,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1395,
"s": 1359,
"text": "tokens:= each word of s as an array"
},
{
"code": null,
"e": 1431,
"s": 1395,
"text": "tokens:= each word of s as an array"
},
{
"code": null,
"e": 1453,
"s": 1431,
"text": "string:= blank string"
},
{
"code": null,
"e": 1475,
"s": 1453,
"text": "string:= blank string"
},
{
"code": null,
"e": 1578,
"s": 1475,
"text": "for each word in tokens, doif word is not \"and\", thenstring := string concatenate first letter of word"
},
{
"code": null,
"e": 1606,
"s": 1578,
"text": "for each word in tokens, do"
},
{
"code": null,
"e": 1682,
"s": 1606,
"text": "if word is not \"and\", thenstring := string concatenate first letter of word"
},
{
"code": null,
"e": 1709,
"s": 1682,
"text": "if word is not \"and\", then"
},
{
"code": null,
"e": 1759,
"s": 1709,
"text": "string := string concatenate first letter of word"
},
{
"code": null,
"e": 1809,
"s": 1759,
"text": "string := string concatenate first letter of word"
},
{
"code": null,
"e": 1853,
"s": 1809,
"text": "return convert string into uppercase string"
},
{
"code": null,
"e": 1897,
"s": 1853,
"text": "return convert string into uppercase string"
},
{
"code": null,
"e": 1967,
"s": 1897,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1978,
"s": 1967,
"text": " Live Demo"
},
{
"code": null,
"e": 2242,
"s": 1978,
"text": "class Solution:\n def solve(self, s):\n tokens=s.split()\n string=\"\"\n for word in tokens:\n if word != \"and\":\n string += str(word[0])\n return string.upper()\nob = Solution()\nprint(ob.solve(\"Indian Space Research Organisation\"))"
},
{
"code": null,
"e": 2279,
"s": 2242,
"text": "\"Indian Space Research Organisation\""
},
{
"code": null,
"e": 2284,
"s": 2279,
"text": "ISRO"
}
]
|
How do I specify different layouts for portrait and landscape orientations in Android? | This example demonstrates how do I specify different layouts for portrait and landscape orientations in android
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.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f6f4"
android:padding="10dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/button"
android:layout_centerInParent="true"
android:layout_marginTop="16sp"
android:text="Portrait Mode"
android:textSize="24sp"
android:textStyle="bold" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Show Orientation mode" />
</RelativeLayout>
Step 3 – Create a layout file by right-clicking on the resources, name the file, from the ‘Available qualifiers, select Orientation.
Click >> option.
Select Landscape from UI mode.
Add the following code in the res/layout/land/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginStart="64dp"
android:layout_toEndOf="@id/button"
android:text="Landscape Mode"
android:textSize="24sp"
android:textStyle="bold" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginStart="128sp"
android:text="Show Orientation mode" />
</RelativeLayout>
Step 4 − Add the following code to src/MainActivity.java
import android.content.res.Configuration
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var textView: TextView
lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.tvLayout)
button = findViewById(R.id.button)
button.setOnClickListener {
if (button.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(this@MainActivity, " We are in portrait mode",
Toast.LENGTH_SHORT).show()
}
else {
Toast.makeText(this@MainActivity, "We are in Landscape mode",
Toast.LENGTH_SHORT).show()
}
}
}
}
Step 5 - 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="com.example.q11">
<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 – | [
{
"code": null,
"e": 1174,
"s": 1062,
"text": "This example demonstrates how do I specify different layouts for portrait and landscape orientations in android"
},
{
"code": null,
"e": 1303,
"s": 1174,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1368,
"s": 1303,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2312,
"s": 1368,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/rl\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:background=\"#f2f6f4\"\n android:padding=\"10dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/tvLayout\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/button\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"16sp\"\n android:text=\"Portrait Mode\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Show Orientation mode\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2445,
"s": 2312,
"text": "Step 3 – Create a layout file by right-clicking on the resources, name the file, from the ‘Available qualifiers, select Orientation."
},
{
"code": null,
"e": 2462,
"s": 2445,
"text": "Click >> option."
},
{
"code": null,
"e": 2493,
"s": 2462,
"text": "Select Landscape from UI mode."
},
{
"code": null,
"e": 2557,
"s": 2493,
"text": "Add the following code in the res/layout/land/activity_main.xml"
},
{
"code": null,
"e": 3465,
"s": 2557,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/tvLayout\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:layout_marginStart=\"64dp\"\n android:layout_toEndOf=\"@id/button\"\n android:text=\"Landscape Mode\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerVertical=\"true\"\n android:layout_marginStart=\"128sp\"\n android:text=\"Show Orientation mode\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 3522,
"s": 3465,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4497,
"s": 3522,
"text": "import android.content.res.Configuration\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.TextView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var textView: TextView\n lateinit var button: Button\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.tvLayout)\n button = findViewById(R.id.button)\n button.setOnClickListener {\n if (button.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {\n Toast.makeText(this@MainActivity, \" We are in portrait mode\",\n Toast.LENGTH_SHORT).show()\n }\n else {\n Toast.makeText(this@MainActivity, \"We are in Landscape mode\",\n Toast.LENGTH_SHORT).show()\n }\n }\n }\n}"
},
{
"code": null,
"e": 4552,
"s": 4497,
"text": "Step 5 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5226,
"s": 4552,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5573,
"s": 5226,
"text": "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 –"
}
]
|
3 Approaches To Building A Recommendation System | by Kurtis Pykes | Towards Data Science | It’s no doubt that Recommendation systems are one of the most obvious ways to enhance user experience on various platforms, as well as introduce Machine Learning into a company. Hence, many companies have been adopting the “Recommended For You” mantra that has been popularized by the likes of Amazon, Netflix and Youtube by implementing there own version of recommendations to suit their customer needs.
Before heading on to the various approaches of implementation, we first define a recommendation system as a method of discarding redundant or useless information from an information stream before presenting the information to a human user, or more specifically, as a subclass of an information filtering system that seeks to predict the “rating” or “preference” a user will give to an item (Source: Wikipedia).
With this knowledge we may begin to look at some approaches to this problem — for the full code generated in this post visit my Github.
github.com
For the following demonstrations, we will be using the MovieLens 100k Dataset.
Collaborative filtering is one of the most popular implementations for Recommendation engines and is based on the assumption that people that were in agreement in the past will be in agreement in the future, and as a result they will like similar kinds of items as they liked in the past.
An example of Collaborative filtering may be that a friend and myself liked an identical range of books in the past and he/she goes on to like a book that I have not read, but because we agreed in the past and he/she liked the new book of which I have not read, it is highly likely I will also like that book so that book would recommended to me. The logic describes what is known as user-based collaborative filtering.
Taking from the previous example, instead of focusing solely on what my friend likes, we may decide to focus on the range of items liked previously and ensure I am recommended a new item based on the similarity between the items that have been liked in the past of which the similarity is calculated by using the ratings of the items — “users that like this item also liked”. The logic behind this algorithm is known as item-based collaborative filtering.
In all, these two methods fall under a heading of collaborative filtering known as memory based methods. Let’s see an example of a memory based method in Python.
import numpy as npimport pandas as pdfrom sklearn.metrics import mean_squared_error, pairwise# creating n x m matrix where n is user_id and m is item_id user_ratings = pd.pivot_table(rating, index="user_id", columns="item_id", values="rating").fillna(0)# user and item counts n_users = len(user_ratings.index)n_items = len(user_ratings.columns)print(f"Users: {n_users}\nItems: {n_items}")user_ratings.head()Users: 943Items: 1682
Now we have our data in the format we need, I will randomly generate a train and test set that we can use to test how well our approach is doing.
# https://www.ethanrosenthal.com/2015/11/02/intro-to-collaborative-filtering/ def train_test_split(data: np.array, n_users: int, n_items:int): # create a empty array of shape n x m for test test = np.zeros((n_users, n_items)) train = data.copy() # for each user, we generate a random sample of 5 from movies they've watched for user in range(n_users): random_sample = np.random.choice(data[user, :].nonzero()[0], size=5, replace=False) # set the train to zero to represent no rating and the test will be the original rating train[user, random_sample] = 0. test[user, random_sample] = data[user, random_sample] return train, testtrain, test = train_test_split(data=user_ratings.to_numpy(), n_users=n_users, n_items=n_items)
The first step of building a Collaborative filtering system is to calculate the similarity between users (for user based) or items (for item based).
user_similarity = pairwise.cosine_similarity(train + 1e-9)item_similarity = pairwise.cosine_similarity(train.T + 1e-9)print(user_similarity.shape, item_similarity.shape)(943, 943) (1682, 1682)
The next step is to predict the ratings that were not included in the data. Once we have made our predictions, we can compare our results with that of the actual test data to evaluate the quality of our model — evaluation metrics are beyond the scope of this tutorial.
# predict user ratings not included in datauser_preds = user_similarity.dot(train) / np.array([np.abs(user_similarity).sum(axis=1)]).T# # get the nonzero elementsnonzero_test = test[test.nonzero()]nonzero_user_preds = user_preds[test.nonzero()]user_rating_preds = mean_squared_error(nonzero_test, nonzero_user_preds)print(f"UBCF Mean Squared Error: {user_rating_preds}")UBCF Mean Squared Error: 8.250006012927786
The above code is an example of User-Based collaborative filtering. We can also do Item-based collaborative filtering.
# predict item ratings not included in dataitem_preds = train.dot(item_similarity) / np.array([np.abs(item_similarity).sum(axis=1)])# get the nonzero elementsnonzero_item_preds = item_preds[test.nonzero()]item_rating_preds = mean_squared_error(nonzero_test, nonzero_item_preds)print(f"IBCF Mean Squared Error: {item_rating_preds}")IBCF Mean Squared Error: 11.361431844412557
Our algorithm isn’t that great, but hopefully you get the gist!
We now know that Collaborative based approaches may be classified is memory-based and we’ve seen a Python implementation of this above. Another way we may classify a collaborative filtering method is as a model based approach.
In this approach, models are developed using different data mining, machine learning algorithms to predict users’ rating of unrated items (Source: Wikipedia).
Another popular way to recommend useful information to users is via Content-based filtering. This technique is based on the description of the item and a profile of the users preferences. It’s best suited in situations where there is known information on an item, but not much known information of the user. That being so, the Content-based filtering approach teats recommendations as a user specific classification problem.
An example of content-based filtering could be explained by using a movie recommendation scenario. Imagine we have built a fairly new site and we don’t currently have much user information, but what we do have is details about the movies in our backlog. What we’d do is take the meta-data/characteristics of the movie such as genre, actors, directors, length of the movie, etc and use them as inputs to predict whether a user would like a movie.
The scenario above would also suggest we have a user profile of preferences. This data may be collected via user interrogation — meaning that the user would set his or her preferences for filtering — or by recording user behavior as an implicit approach.
Note: You may also use a hybrid method for an optimal data collection strategy.
Let’s see how to do this in Python...
# merge data so we know the features of each moviemovies = pd.merge(item, rating, right_on="item_id", left_on="movie_id")# create a pivot tablemovies_pivot = pd.pivot_table(movies, index="user_id", columns="movie_title", values="rating")# Transpose only so it fit's in the screenmovies_pivot.T.head()
# avg ratings and rating countsavg_rating = movies.groupby("movie_title")["rating"].mean()num_ratings = movies.groupby("movie_title")["rating"].count()# getting counts and average ratingsratings_counts = pd.DataFrame({"avg_rating": avg_rating, "num_of_ratings": num_ratings})# joining the new values to movie datafull_movie_data = pd.merge(movies, ratings_counts, left_on="movie_title", right_index=True)# https://towardsdatascience.com/recommender-system-in-python-part-2-content-based-system-693a0e4bb306def get_similar_movies(full_movie_data: pd.DataFrame, movie_matrix: pd.DataFrame, movie_title: str, min_num_of_ratings: int = 100, n_recommendations: int = 5 ): """ Get similar movies based on correlation with other movies """ # get most correlated movies similar_movies = movie_matrix.corrwith(movie_matrix[movie_title]) # converting to a dataframe and dropping NaN's similar_corr_df = pd.DataFrame({"correlation":similar_movies}) similar_corr_df.dropna(inplace=True) # store the oringinal dataframe orig = full_movie_data.copy() # merge with correlated dataframe but only keep specified columns corr_with_movie = pd.merge(left=similar_corr_df, right=orig, on="movie_title")[ ["movie_title", "correlation", "avg_rating", "num_of_ratings"]].drop_duplicates().reset_index(drop=True) # filter movies with less than min_num_of_ratings result = corr_with_movie[corr_with_movie['num_of_ratings'] > min_num_of_ratings].sort_values( by='correlation', ascending=False) return result.iloc[1:, :].head()# test function on Toy Storyget_similar_movies(full_movie_data, movies_pivot, "Toy Story (1995)")
A hybrid system is much more common in the real world as a combining components from various approaches can overcome various traditional shortcomings; In this example we talk more specifically of hybrid components from Collaborative-Filtering and Content-based filtering.
The paper by Jung KY, Park DH, Lee JH (2004) [1] states “To be effective, a recommender system must deal with well with two fundamental problems. First, the sparse rating problem; the number of ratings already obtained is very small compared to the number of ratings that need to be predicted. Effective generation from a small number of examples is thus important. This problem is particularly severe during the startup phase of the system when the number of users is small. Second, the first-rater problem; an item cannot be recommended unless a user has rated it before.”
This approach can significantly improve predictions of a recommender system.
As a task to the reader, build your own hybrid recommender system! (Share with me when you’ve done it)
[1] Jung KY., Park DH., Lee JH. (2004) Hybrid Collaborative Filtering and Content-Based Filtering for Improved Recommender System. In: Bubak M., van Albada G.D., Sloot P.M.A., Dongarra J. (eds) Computational Science — ICCS 2004. ICCS 2004. Lecture Notes in Computer Science, vol 3036. Springer, Berlin, Heidelberg. https://doi.org/10.1007/978-3-540-24685-5_37
In this post we covered 3 practical ways of approaching recommendation systems and how to implement 2 of them (Collaborative Filtering and Content Based) using Python. I am aware that I did not go into much details regarding the theory behind the algorithms or performance metrics to evaluate them, but if you’d like a more in-depth insight to these feats then I highly recommend the Andrew Ng Recommender Systems playlist on Youtube.
Let’s continue the conversation on LinkedIn... | [
{
"code": null,
"e": 577,
"s": 172,
"text": "It’s no doubt that Recommendation systems are one of the most obvious ways to enhance user experience on various platforms, as well as introduce Machine Learning into a company. Hence, many companies have been adopting the “Recommended For You” mantra that has been popularized by the likes of Amazon, Netflix and Youtube by implementing there own version of recommendations to suit their customer needs."
},
{
"code": null,
"e": 988,
"s": 577,
"text": "Before heading on to the various approaches of implementation, we first define a recommendation system as a method of discarding redundant or useless information from an information stream before presenting the information to a human user, or more specifically, as a subclass of an information filtering system that seeks to predict the “rating” or “preference” a user will give to an item (Source: Wikipedia)."
},
{
"code": null,
"e": 1124,
"s": 988,
"text": "With this knowledge we may begin to look at some approaches to this problem — for the full code generated in this post visit my Github."
},
{
"code": null,
"e": 1135,
"s": 1124,
"text": "github.com"
},
{
"code": null,
"e": 1214,
"s": 1135,
"text": "For the following demonstrations, we will be using the MovieLens 100k Dataset."
},
{
"code": null,
"e": 1503,
"s": 1214,
"text": "Collaborative filtering is one of the most popular implementations for Recommendation engines and is based on the assumption that people that were in agreement in the past will be in agreement in the future, and as a result they will like similar kinds of items as they liked in the past."
},
{
"code": null,
"e": 1923,
"s": 1503,
"text": "An example of Collaborative filtering may be that a friend and myself liked an identical range of books in the past and he/she goes on to like a book that I have not read, but because we agreed in the past and he/she liked the new book of which I have not read, it is highly likely I will also like that book so that book would recommended to me. The logic describes what is known as user-based collaborative filtering."
},
{
"code": null,
"e": 2379,
"s": 1923,
"text": "Taking from the previous example, instead of focusing solely on what my friend likes, we may decide to focus on the range of items liked previously and ensure I am recommended a new item based on the similarity between the items that have been liked in the past of which the similarity is calculated by using the ratings of the items — “users that like this item also liked”. The logic behind this algorithm is known as item-based collaborative filtering."
},
{
"code": null,
"e": 2541,
"s": 2379,
"text": "In all, these two methods fall under a heading of collaborative filtering known as memory based methods. Let’s see an example of a memory based method in Python."
},
{
"code": null,
"e": 2970,
"s": 2541,
"text": "import numpy as npimport pandas as pdfrom sklearn.metrics import mean_squared_error, pairwise# creating n x m matrix where n is user_id and m is item_id user_ratings = pd.pivot_table(rating, index=\"user_id\", columns=\"item_id\", values=\"rating\").fillna(0)# user and item counts n_users = len(user_ratings.index)n_items = len(user_ratings.columns)print(f\"Users: {n_users}\\nItems: {n_items}\")user_ratings.head()Users: 943Items: 1682"
},
{
"code": null,
"e": 3116,
"s": 2970,
"text": "Now we have our data in the format we need, I will randomly generate a train and test set that we can use to test how well our approach is doing."
},
{
"code": null,
"e": 3981,
"s": 3116,
"text": "# https://www.ethanrosenthal.com/2015/11/02/intro-to-collaborative-filtering/ def train_test_split(data: np.array, n_users: int, n_items:int): # create a empty array of shape n x m for test test = np.zeros((n_users, n_items)) train = data.copy() # for each user, we generate a random sample of 5 from movies they've watched for user in range(n_users): random_sample = np.random.choice(data[user, :].nonzero()[0], size=5, replace=False) # set the train to zero to represent no rating and the test will be the original rating train[user, random_sample] = 0. test[user, random_sample] = data[user, random_sample] return train, testtrain, test = train_test_split(data=user_ratings.to_numpy(), n_users=n_users, n_items=n_items)"
},
{
"code": null,
"e": 4130,
"s": 3981,
"text": "The first step of building a Collaborative filtering system is to calculate the similarity between users (for user based) or items (for item based)."
},
{
"code": null,
"e": 4323,
"s": 4130,
"text": "user_similarity = pairwise.cosine_similarity(train + 1e-9)item_similarity = pairwise.cosine_similarity(train.T + 1e-9)print(user_similarity.shape, item_similarity.shape)(943, 943) (1682, 1682)"
},
{
"code": null,
"e": 4592,
"s": 4323,
"text": "The next step is to predict the ratings that were not included in the data. Once we have made our predictions, we can compare our results with that of the actual test data to evaluate the quality of our model — evaluation metrics are beyond the scope of this tutorial."
},
{
"code": null,
"e": 5005,
"s": 4592,
"text": "# predict user ratings not included in datauser_preds = user_similarity.dot(train) / np.array([np.abs(user_similarity).sum(axis=1)]).T# # get the nonzero elementsnonzero_test = test[test.nonzero()]nonzero_user_preds = user_preds[test.nonzero()]user_rating_preds = mean_squared_error(nonzero_test, nonzero_user_preds)print(f\"UBCF Mean Squared Error: {user_rating_preds}\")UBCF Mean Squared Error: 8.250006012927786"
},
{
"code": null,
"e": 5124,
"s": 5005,
"text": "The above code is an example of User-Based collaborative filtering. We can also do Item-based collaborative filtering."
},
{
"code": null,
"e": 5499,
"s": 5124,
"text": "# predict item ratings not included in dataitem_preds = train.dot(item_similarity) / np.array([np.abs(item_similarity).sum(axis=1)])# get the nonzero elementsnonzero_item_preds = item_preds[test.nonzero()]item_rating_preds = mean_squared_error(nonzero_test, nonzero_item_preds)print(f\"IBCF Mean Squared Error: {item_rating_preds}\")IBCF Mean Squared Error: 11.361431844412557"
},
{
"code": null,
"e": 5563,
"s": 5499,
"text": "Our algorithm isn’t that great, but hopefully you get the gist!"
},
{
"code": null,
"e": 5790,
"s": 5563,
"text": "We now know that Collaborative based approaches may be classified is memory-based and we’ve seen a Python implementation of this above. Another way we may classify a collaborative filtering method is as a model based approach."
},
{
"code": null,
"e": 5949,
"s": 5790,
"text": "In this approach, models are developed using different data mining, machine learning algorithms to predict users’ rating of unrated items (Source: Wikipedia)."
},
{
"code": null,
"e": 6374,
"s": 5949,
"text": "Another popular way to recommend useful information to users is via Content-based filtering. This technique is based on the description of the item and a profile of the users preferences. It’s best suited in situations where there is known information on an item, but not much known information of the user. That being so, the Content-based filtering approach teats recommendations as a user specific classification problem."
},
{
"code": null,
"e": 6820,
"s": 6374,
"text": "An example of content-based filtering could be explained by using a movie recommendation scenario. Imagine we have built a fairly new site and we don’t currently have much user information, but what we do have is details about the movies in our backlog. What we’d do is take the meta-data/characteristics of the movie such as genre, actors, directors, length of the movie, etc and use them as inputs to predict whether a user would like a movie."
},
{
"code": null,
"e": 7075,
"s": 6820,
"text": "The scenario above would also suggest we have a user profile of preferences. This data may be collected via user interrogation — meaning that the user would set his or her preferences for filtering — or by recording user behavior as an implicit approach."
},
{
"code": null,
"e": 7155,
"s": 7075,
"text": "Note: You may also use a hybrid method for an optimal data collection strategy."
},
{
"code": null,
"e": 7193,
"s": 7155,
"text": "Let’s see how to do this in Python..."
},
{
"code": null,
"e": 7494,
"s": 7193,
"text": "# merge data so we know the features of each moviemovies = pd.merge(item, rating, right_on=\"item_id\", left_on=\"movie_id\")# create a pivot tablemovies_pivot = pd.pivot_table(movies, index=\"user_id\", columns=\"movie_title\", values=\"rating\")# Transpose only so it fit's in the screenmovies_pivot.T.head()"
},
{
"code": null,
"e": 9525,
"s": 7494,
"text": "# avg ratings and rating countsavg_rating = movies.groupby(\"movie_title\")[\"rating\"].mean()num_ratings = movies.groupby(\"movie_title\")[\"rating\"].count()# getting counts and average ratingsratings_counts = pd.DataFrame({\"avg_rating\": avg_rating, \"num_of_ratings\": num_ratings})# joining the new values to movie datafull_movie_data = pd.merge(movies, ratings_counts, left_on=\"movie_title\", right_index=True)# https://towardsdatascience.com/recommender-system-in-python-part-2-content-based-system-693a0e4bb306def get_similar_movies(full_movie_data: pd.DataFrame, movie_matrix: pd.DataFrame, movie_title: str, min_num_of_ratings: int = 100, n_recommendations: int = 5 ): \"\"\" Get similar movies based on correlation with other movies \"\"\" # get most correlated movies similar_movies = movie_matrix.corrwith(movie_matrix[movie_title]) # converting to a dataframe and dropping NaN's similar_corr_df = pd.DataFrame({\"correlation\":similar_movies}) similar_corr_df.dropna(inplace=True) # store the oringinal dataframe orig = full_movie_data.copy() # merge with correlated dataframe but only keep specified columns corr_with_movie = pd.merge(left=similar_corr_df, right=orig, on=\"movie_title\")[ [\"movie_title\", \"correlation\", \"avg_rating\", \"num_of_ratings\"]].drop_duplicates().reset_index(drop=True) # filter movies with less than min_num_of_ratings result = corr_with_movie[corr_with_movie['num_of_ratings'] > min_num_of_ratings].sort_values( by='correlation', ascending=False) return result.iloc[1:, :].head()# test function on Toy Storyget_similar_movies(full_movie_data, movies_pivot, \"Toy Story (1995)\")"
},
{
"code": null,
"e": 9797,
"s": 9525,
"text": "A hybrid system is much more common in the real world as a combining components from various approaches can overcome various traditional shortcomings; In this example we talk more specifically of hybrid components from Collaborative-Filtering and Content-based filtering."
},
{
"code": null,
"e": 10372,
"s": 9797,
"text": "The paper by Jung KY, Park DH, Lee JH (2004) [1] states “To be effective, a recommender system must deal with well with two fundamental problems. First, the sparse rating problem; the number of ratings already obtained is very small compared to the number of ratings that need to be predicted. Effective generation from a small number of examples is thus important. This problem is particularly severe during the startup phase of the system when the number of users is small. Second, the first-rater problem; an item cannot be recommended unless a user has rated it before.”"
},
{
"code": null,
"e": 10449,
"s": 10372,
"text": "This approach can significantly improve predictions of a recommender system."
},
{
"code": null,
"e": 10552,
"s": 10449,
"text": "As a task to the reader, build your own hybrid recommender system! (Share with me when you’ve done it)"
},
{
"code": null,
"e": 10912,
"s": 10552,
"text": "[1] Jung KY., Park DH., Lee JH. (2004) Hybrid Collaborative Filtering and Content-Based Filtering for Improved Recommender System. In: Bubak M., van Albada G.D., Sloot P.M.A., Dongarra J. (eds) Computational Science — ICCS 2004. ICCS 2004. Lecture Notes in Computer Science, vol 3036. Springer, Berlin, Heidelberg. https://doi.org/10.1007/978-3-540-24685-5_37"
},
{
"code": null,
"e": 11347,
"s": 10912,
"text": "In this post we covered 3 practical ways of approaching recommendation systems and how to implement 2 of them (Collaborative Filtering and Content Based) using Python. I am aware that I did not go into much details regarding the theory behind the algorithms or performance metrics to evaluate them, but if you’d like a more in-depth insight to these feats then I highly recommend the Andrew Ng Recommender Systems playlist on Youtube."
}
]
|
Programmatically Build REGEX (Regular Expression) in Python for Pattern Matching | by AbdulMajedRaja RS | Towards Data Science | Regular Expression (Regex — often pronounced as ri-je-x or reg-x) is extremely useful while you are about to do Text Analytics or Natural Language Processing. But as much as Regex is useful, it’s also extremely confusing and hard to understand and always require (at least for me) multiple DDGing with click and back to multiple Stack Overflow links.
For starters:
According to Wikipedia, A regular expression, regex or regexp is a sequence of characters that define a search pattern.
This is the REGEX pattern to test the validity of a URL:
^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$
A typical regular expression contains — Characters ( http ) and Meta Characters ([]). The combination of these two form a meaningful regular expression for a particular task.
Remembering the way in which characters and meta-characters are combined to create a meaningful regex is itself a tedious task which sometimes becomes a bigger task than the actual problem of NLP which is the larger goal. This in fact has driven the meme world and programming cartoons all over the internet. Like this:
Some good soul on this planet has created an open-source Javascript library JSVerbalExpressions to make Regex creation easy. Then some other good soul ported the javascript library to Python — PythonVerbalExpressions. This is the beauty of the open source world. Sorry I digressed, but wanted to make a point.
Based on the version of Python you’ve got, You can install PythonVerbalExpressions using pip.
pip3 install VerbalExpressions
Much like how the ML library scikit-learn works with a basic constructor and building on top of it, VerbalExpressions follows a similar API syntax.
from verbalexpressions import VerExverEx = VerEx()
Let’s create a pseudo-problem that we’d like to solve with regex through which we can understand this package to programmatically create regex.
A simpler one perhaps, We’ve got multiple text like this:
strings = ['123Abdul233', '233Raja434', '223Ethan Hunt444']
and we’d like to extract the names from it. So our result should be:
Abdul, Raja, Ethan Hunt
Before we code, it’s always good to write-out a pseudo-code on a napkin or even a paper if you’ve got. That is, We want to extract names (which is composition of alphabets) except numbers (which is digits). We build a regex for one-line and then we iterate it for all the elements in our list.
We use the range() function that says anything in the given range.
expression = verEx.range('a','z','A','Z',' ')
In this expression, anything from a-z or A-Z or a whitespace (whitespace: because of Ethan Hunt ).
To see how this python code actually translates to a regex pattern:
expression.source()#output: '([a-zA-Z\\ ])'
Now that the expression is ready, we can use it to find the required substrings in multiple ways. Here, we’ll turn to the go-to Python library for anything regex re . Because we’re going to deal with re, we’ll compile the expression that we built for re .
import rere_exp = expression.compile()
Now, that the re compilation has been done. We’ll use that re_exp to test this regex on one-line (one element of the input list).
re.findall(re_exp,strings[0])#output: ['A', 'b', 'd', 'u', 'l']
That’s promising! Let’s use our string joining and for-loop skills to finish off our pseudo-problem!
[''.join(re.findall(re_exp,line)) for line in strings]#output: ['Abdul', 'Raja', 'Ethan Hunt']
Thus, we managed to build a regex pattern without knowing regex. Simply put, we programmatically generated a regex pattern using Python (that doesn’t require the high-level knowledge of regex patterns) and accomplished a tiny task that we took up to demonstrate the potential. The caveat here is though, this Python package VerbalExpressions doesn’t have all the functions from its parent javascript library, so the functionalities are limited. For more of Regex using Python, Check out this Datacamp course. The entire code is available here. | [
{
"code": null,
"e": 523,
"s": 172,
"text": "Regular Expression (Regex — often pronounced as ri-je-x or reg-x) is extremely useful while you are about to do Text Analytics or Natural Language Processing. But as much as Regex is useful, it’s also extremely confusing and hard to understand and always require (at least for me) multiple DDGing with click and back to multiple Stack Overflow links."
},
{
"code": null,
"e": 537,
"s": 523,
"text": "For starters:"
},
{
"code": null,
"e": 657,
"s": 537,
"text": "According to Wikipedia, A regular expression, regex or regexp is a sequence of characters that define a search pattern."
},
{
"code": null,
"e": 714,
"s": 657,
"text": "This is the REGEX pattern to test the validity of a URL:"
},
{
"code": null,
"e": 751,
"s": 714,
"text": "^(http)(s)?(\\:\\/\\/)(www\\.)?([^\\ ]*)$"
},
{
"code": null,
"e": 926,
"s": 751,
"text": "A typical regular expression contains — Characters ( http ) and Meta Characters ([]). The combination of these two form a meaningful regular expression for a particular task."
},
{
"code": null,
"e": 1246,
"s": 926,
"text": "Remembering the way in which characters and meta-characters are combined to create a meaningful regex is itself a tedious task which sometimes becomes a bigger task than the actual problem of NLP which is the larger goal. This in fact has driven the meme world and programming cartoons all over the internet. Like this:"
},
{
"code": null,
"e": 1556,
"s": 1246,
"text": "Some good soul on this planet has created an open-source Javascript library JSVerbalExpressions to make Regex creation easy. Then some other good soul ported the javascript library to Python — PythonVerbalExpressions. This is the beauty of the open source world. Sorry I digressed, but wanted to make a point."
},
{
"code": null,
"e": 1650,
"s": 1556,
"text": "Based on the version of Python you’ve got, You can install PythonVerbalExpressions using pip."
},
{
"code": null,
"e": 1681,
"s": 1650,
"text": "pip3 install VerbalExpressions"
},
{
"code": null,
"e": 1829,
"s": 1681,
"text": "Much like how the ML library scikit-learn works with a basic constructor and building on top of it, VerbalExpressions follows a similar API syntax."
},
{
"code": null,
"e": 1880,
"s": 1829,
"text": "from verbalexpressions import VerExverEx = VerEx()"
},
{
"code": null,
"e": 2024,
"s": 1880,
"text": "Let’s create a pseudo-problem that we’d like to solve with regex through which we can understand this package to programmatically create regex."
},
{
"code": null,
"e": 2082,
"s": 2024,
"text": "A simpler one perhaps, We’ve got multiple text like this:"
},
{
"code": null,
"e": 2162,
"s": 2082,
"text": "strings = ['123Abdul233', '233Raja434', '223Ethan Hunt444']"
},
{
"code": null,
"e": 2231,
"s": 2162,
"text": "and we’d like to extract the names from it. So our result should be:"
},
{
"code": null,
"e": 2255,
"s": 2231,
"text": "Abdul, Raja, Ethan Hunt"
},
{
"code": null,
"e": 2549,
"s": 2255,
"text": "Before we code, it’s always good to write-out a pseudo-code on a napkin or even a paper if you’ve got. That is, We want to extract names (which is composition of alphabets) except numbers (which is digits). We build a regex for one-line and then we iterate it for all the elements in our list."
},
{
"code": null,
"e": 2616,
"s": 2549,
"text": "We use the range() function that says anything in the given range."
},
{
"code": null,
"e": 2662,
"s": 2616,
"text": "expression = verEx.range('a','z','A','Z',' ')"
},
{
"code": null,
"e": 2761,
"s": 2662,
"text": "In this expression, anything from a-z or A-Z or a whitespace (whitespace: because of Ethan Hunt )."
},
{
"code": null,
"e": 2829,
"s": 2761,
"text": "To see how this python code actually translates to a regex pattern:"
},
{
"code": null,
"e": 2873,
"s": 2829,
"text": "expression.source()#output: '([a-zA-Z\\\\ ])'"
},
{
"code": null,
"e": 3129,
"s": 2873,
"text": "Now that the expression is ready, we can use it to find the required substrings in multiple ways. Here, we’ll turn to the go-to Python library for anything regex re . Because we’re going to deal with re, we’ll compile the expression that we built for re ."
},
{
"code": null,
"e": 3168,
"s": 3129,
"text": "import rere_exp = expression.compile()"
},
{
"code": null,
"e": 3298,
"s": 3168,
"text": "Now, that the re compilation has been done. We’ll use that re_exp to test this regex on one-line (one element of the input list)."
},
{
"code": null,
"e": 3362,
"s": 3298,
"text": "re.findall(re_exp,strings[0])#output: ['A', 'b', 'd', 'u', 'l']"
},
{
"code": null,
"e": 3463,
"s": 3362,
"text": "That’s promising! Let’s use our string joining and for-loop skills to finish off our pseudo-problem!"
},
{
"code": null,
"e": 3558,
"s": 3463,
"text": "[''.join(re.findall(re_exp,line)) for line in strings]#output: ['Abdul', 'Raja', 'Ethan Hunt']"
}
]
|
Apache Spark on Windows: A Docker approach | by Israel Siqueira | Towards Data Science | Recently I was allocated to a project where the entire customer database is in Apache Spark / Hadoop. As a standard in all my projects, I first went to prepare the development environment on the corporate laptop, which comes with Windows as standard OS. As many already know, preparing a development environment on a Windows laptop can sometimes be painful and if the laptop is a corporate one it can be even more painful (due to restrictions imposed by the system administrator, corporate VPN, etc.).
Creating a development environment for Apache Spark / Hadoop is no different. Installing Spark on Windows is extremely complicated. Several dependencies need to be installed (Java SDK, Python, Winutils, Log4j), services need to be configured, and environment variables need to be properly set. Given that, I decided to use Docker as the first option for all my development environments.
Now, Docker is my “one ring / one tool”, (a reference to Lord of the Rings):
“In the Land of Mordor (Windows) where the shadows lie. One ring to rule them all, One ring to find them, One ring to bring them all, and in the darkness bind them; In the Land of Mordor where the shadows lie.” (Tolkien)
If Docker isn’t an option for you, there are several articles to shed light on the subject:
Installing Apache PySpark on Windows 10
Apache Spark Installation on Windows
Getting Started with PySpark on Windows
Why Docker?
There is no need to install any library or application on Windows, only Docker. No need to ask Technical Support for permission to install software and libraries every week. (They will love you, trust me)Windows will always run at maximum potential (without having countless services starting on login)Have different environments for projects, including software versions. Ex: a project can use Apache Spark 2 with Scala and another Apache Spark 3 project with pyspark without any conflict.There are several ready-made images made by the community (postgres, spark, jupyters, etc.), making the development set-up much faster.
There is no need to install any library or application on Windows, only Docker. No need to ask Technical Support for permission to install software and libraries every week. (They will love you, trust me)
Windows will always run at maximum potential (without having countless services starting on login)
Have different environments for projects, including software versions. Ex: a project can use Apache Spark 2 with Scala and another Apache Spark 3 project with pyspark without any conflict.
There are several ready-made images made by the community (postgres, spark, jupyters, etc.), making the development set-up much faster.
These are just some of the advantages of Docker, there are others which you can read more about on the Docker official page.
With all that said, let’s get down to business and set up our Apache Spark environment.
You can follow the start guide to download Docker for Windows and go for instructions to install Docker on your machine. If your Windows is the Home Edition, you can follow Install Docker Desktop on Windows Home instructions.
When the installation finishes you can restart your machine (remember to save this article in favorites to back from restart).
If you run any error at this point or later, check Microsoft Troubleshoot guide.
You can start Docker from the start menu, after a while you will see this icon on the system tray:
you can right-click on the icon and select Dashboard. On the dashboard, you can click on the configurations button (engine icon on the top right). You will see this screen:
One thing I like to do is unselect the option:
Start docker desktop on your login.
This way docker will not start with windows and I can start it only when I need by the start menu. But it’s a personal choice.
Check Docker Installation
First of all, we need to ensure that our docker installation is working properly. Open a Powershell (or a WSL terminal), I strongly recommend the amazing Windows Terminal, a Windows (Unix-like) terminal that has a lot of features that help us as developers (tabs, auto-complete, themes, and other cool features) and type the following:
~$ docker run hello world
If you see something like this:
Your docker installation is ok.
As I said earlier, one of the coolest features of docker relies on the community images. There’s a lot of pre-made images for almost all needs available to download and use with minimum or no configuration. Take some time to explore the Docker Hub, and see by yourself.
The Jupyter developers have been doing an amazing job actively maintaining some images for Data Scientists and Researchers, the project page can be found here. Some of the images are:
jupyter/r-notebook includes popular packages from the R ecosystem.jupyter/scipy-notebook includes popular packages from the scientific Python ecosystem.jupyter/tensorflow-notebook includes popular Python deep learning libraries.jupyter/pyspark-notebook includes Python support for Apache Spark.jupyter/all-spark-notebook includes Python, R, and Scala support for Apache Spark.
jupyter/r-notebook includes popular packages from the R ecosystem.
jupyter/scipy-notebook includes popular packages from the scientific Python ecosystem.
jupyter/tensorflow-notebook includes popular Python deep learning libraries.
jupyter/pyspark-notebook includes Python support for Apache Spark.
jupyter/all-spark-notebook includes Python, R, and Scala support for Apache Spark.
and many others.
For our Apache Spark environment, we choose the jupyter/pyspark-notebook, as we don’t need the R and Scala support.
To create a new container you can go to a terminal and type the following:
~$ docker run -p 8888:8888 -e JUPYTER_ENABLE_LAB=yes --name pyspark jupyter/pyspark-notebook
This command pulls the jupyter/pyspark-notebook image from Docker Hub if it is not already present on the localhost.
It then starts a container with name=pyspark running a Jupyter Notebook server and exposes the server on host port 8888.
You may instruct the start script to customize the container environment before launching the notebook server. You do so by passing arguments (-e flag) to the docker run command. The list of all available variables can be found in docker-stacks docs.
The server logs appear in the terminal and include a URL to the notebook server. You can navigate to the URL, create a new python notebook and paste the following code:
#create a spark session
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("local[*]").appName("spark_on_docker").getOrCreate()
#Download a README.md file from docker-stacks to test Spark
!wget -q https://github.com/jupyter/docker-stacks/blob/d990a62010aededcda836196c4b04efece7f838f/README.md
#read the file and count how many rows have the word Jupyter
textFile = spark.read.text("README.md")
rows_with_jupyter = textFile.filter(textFile.value.contains("Jupyter")).count()
print("There's %d rows with the word Jupyter."%rows_with_jupyter)
There's 21 rows with the word Jupyter.
#print the session status
spark
SparkSession - in-memory
SparkContext
Spark UI
Voilá! We have our Apache Spark environment with minnimum effort. You can open a terminal and install packages using conda or pip and manage your packages and dependecies as you wish. Once you have finished you can press ctrl+C and stop the container.
If you want to start your container and have your data persisted you cannot run the “docker run” command again, this will create a new default container, so what we need to do?
You can type in a terminal:
~$ docker ps -a
this will list all containers available, to start the same container that you create previously, type:
~$ docker start -a pyspark
where -a is a flag that tells docker to bind the console output to the terminal and pyspark is the name of the container. To learn more about docker start options you can visit Docker docs.
In this article, we can see how docker can speed-up the development lifecycle and help us mitigate some of the drawbacks of using Windows as the main OS for development. Microsoft is doing a great job with WSL, Docker, and other tools for developers and engineers even supporting GPU processing through docker and WSL. The future is promising.
Thanks for reading this article, I hope that this small guide can help you and give valuable insights to anyone who decides to use Docker for Windows as your “One ring”.
Please feel free to ask or provide feedback in the comments section. | [
{
"code": null,
"e": 674,
"s": 172,
"text": "Recently I was allocated to a project where the entire customer database is in Apache Spark / Hadoop. As a standard in all my projects, I first went to prepare the development environment on the corporate laptop, which comes with Windows as standard OS. As many already know, preparing a development environment on a Windows laptop can sometimes be painful and if the laptop is a corporate one it can be even more painful (due to restrictions imposed by the system administrator, corporate VPN, etc.)."
},
{
"code": null,
"e": 1061,
"s": 674,
"text": "Creating a development environment for Apache Spark / Hadoop is no different. Installing Spark on Windows is extremely complicated. Several dependencies need to be installed (Java SDK, Python, Winutils, Log4j), services need to be configured, and environment variables need to be properly set. Given that, I decided to use Docker as the first option for all my development environments."
},
{
"code": null,
"e": 1138,
"s": 1061,
"text": "Now, Docker is my “one ring / one tool”, (a reference to Lord of the Rings):"
},
{
"code": null,
"e": 1359,
"s": 1138,
"text": "“In the Land of Mordor (Windows) where the shadows lie. One ring to rule them all, One ring to find them, One ring to bring them all, and in the darkness bind them; In the Land of Mordor where the shadows lie.” (Tolkien)"
},
{
"code": null,
"e": 1451,
"s": 1359,
"text": "If Docker isn’t an option for you, there are several articles to shed light on the subject:"
},
{
"code": null,
"e": 1491,
"s": 1451,
"text": "Installing Apache PySpark on Windows 10"
},
{
"code": null,
"e": 1528,
"s": 1491,
"text": "Apache Spark Installation on Windows"
},
{
"code": null,
"e": 1568,
"s": 1528,
"text": "Getting Started with PySpark on Windows"
},
{
"code": null,
"e": 1580,
"s": 1568,
"text": "Why Docker?"
},
{
"code": null,
"e": 2206,
"s": 1580,
"text": "There is no need to install any library or application on Windows, only Docker. No need to ask Technical Support for permission to install software and libraries every week. (They will love you, trust me)Windows will always run at maximum potential (without having countless services starting on login)Have different environments for projects, including software versions. Ex: a project can use Apache Spark 2 with Scala and another Apache Spark 3 project with pyspark without any conflict.There are several ready-made images made by the community (postgres, spark, jupyters, etc.), making the development set-up much faster."
},
{
"code": null,
"e": 2411,
"s": 2206,
"text": "There is no need to install any library or application on Windows, only Docker. No need to ask Technical Support for permission to install software and libraries every week. (They will love you, trust me)"
},
{
"code": null,
"e": 2510,
"s": 2411,
"text": "Windows will always run at maximum potential (without having countless services starting on login)"
},
{
"code": null,
"e": 2699,
"s": 2510,
"text": "Have different environments for projects, including software versions. Ex: a project can use Apache Spark 2 with Scala and another Apache Spark 3 project with pyspark without any conflict."
},
{
"code": null,
"e": 2835,
"s": 2699,
"text": "There are several ready-made images made by the community (postgres, spark, jupyters, etc.), making the development set-up much faster."
},
{
"code": null,
"e": 2960,
"s": 2835,
"text": "These are just some of the advantages of Docker, there are others which you can read more about on the Docker official page."
},
{
"code": null,
"e": 3048,
"s": 2960,
"text": "With all that said, let’s get down to business and set up our Apache Spark environment."
},
{
"code": null,
"e": 3274,
"s": 3048,
"text": "You can follow the start guide to download Docker for Windows and go for instructions to install Docker on your machine. If your Windows is the Home Edition, you can follow Install Docker Desktop on Windows Home instructions."
},
{
"code": null,
"e": 3401,
"s": 3274,
"text": "When the installation finishes you can restart your machine (remember to save this article in favorites to back from restart)."
},
{
"code": null,
"e": 3482,
"s": 3401,
"text": "If you run any error at this point or later, check Microsoft Troubleshoot guide."
},
{
"code": null,
"e": 3581,
"s": 3482,
"text": "You can start Docker from the start menu, after a while you will see this icon on the system tray:"
},
{
"code": null,
"e": 3754,
"s": 3581,
"text": "you can right-click on the icon and select Dashboard. On the dashboard, you can click on the configurations button (engine icon on the top right). You will see this screen:"
},
{
"code": null,
"e": 3801,
"s": 3754,
"text": "One thing I like to do is unselect the option:"
},
{
"code": null,
"e": 3837,
"s": 3801,
"text": "Start docker desktop on your login."
},
{
"code": null,
"e": 3964,
"s": 3837,
"text": "This way docker will not start with windows and I can start it only when I need by the start menu. But it’s a personal choice."
},
{
"code": null,
"e": 3990,
"s": 3964,
"text": "Check Docker Installation"
},
{
"code": null,
"e": 4326,
"s": 3990,
"text": "First of all, we need to ensure that our docker installation is working properly. Open a Powershell (or a WSL terminal), I strongly recommend the amazing Windows Terminal, a Windows (Unix-like) terminal that has a lot of features that help us as developers (tabs, auto-complete, themes, and other cool features) and type the following:"
},
{
"code": null,
"e": 4352,
"s": 4326,
"text": "~$ docker run hello world"
},
{
"code": null,
"e": 4384,
"s": 4352,
"text": "If you see something like this:"
},
{
"code": null,
"e": 4416,
"s": 4384,
"text": "Your docker installation is ok."
},
{
"code": null,
"e": 4686,
"s": 4416,
"text": "As I said earlier, one of the coolest features of docker relies on the community images. There’s a lot of pre-made images for almost all needs available to download and use with minimum or no configuration. Take some time to explore the Docker Hub, and see by yourself."
},
{
"code": null,
"e": 4870,
"s": 4686,
"text": "The Jupyter developers have been doing an amazing job actively maintaining some images for Data Scientists and Researchers, the project page can be found here. Some of the images are:"
},
{
"code": null,
"e": 5247,
"s": 4870,
"text": "jupyter/r-notebook includes popular packages from the R ecosystem.jupyter/scipy-notebook includes popular packages from the scientific Python ecosystem.jupyter/tensorflow-notebook includes popular Python deep learning libraries.jupyter/pyspark-notebook includes Python support for Apache Spark.jupyter/all-spark-notebook includes Python, R, and Scala support for Apache Spark."
},
{
"code": null,
"e": 5314,
"s": 5247,
"text": "jupyter/r-notebook includes popular packages from the R ecosystem."
},
{
"code": null,
"e": 5401,
"s": 5314,
"text": "jupyter/scipy-notebook includes popular packages from the scientific Python ecosystem."
},
{
"code": null,
"e": 5478,
"s": 5401,
"text": "jupyter/tensorflow-notebook includes popular Python deep learning libraries."
},
{
"code": null,
"e": 5545,
"s": 5478,
"text": "jupyter/pyspark-notebook includes Python support for Apache Spark."
},
{
"code": null,
"e": 5628,
"s": 5545,
"text": "jupyter/all-spark-notebook includes Python, R, and Scala support for Apache Spark."
},
{
"code": null,
"e": 5645,
"s": 5628,
"text": "and many others."
},
{
"code": null,
"e": 5761,
"s": 5645,
"text": "For our Apache Spark environment, we choose the jupyter/pyspark-notebook, as we don’t need the R and Scala support."
},
{
"code": null,
"e": 5836,
"s": 5761,
"text": "To create a new container you can go to a terminal and type the following:"
},
{
"code": null,
"e": 5929,
"s": 5836,
"text": "~$ docker run -p 8888:8888 -e JUPYTER_ENABLE_LAB=yes --name pyspark jupyter/pyspark-notebook"
},
{
"code": null,
"e": 6046,
"s": 5929,
"text": "This command pulls the jupyter/pyspark-notebook image from Docker Hub if it is not already present on the localhost."
},
{
"code": null,
"e": 6167,
"s": 6046,
"text": "It then starts a container with name=pyspark running a Jupyter Notebook server and exposes the server on host port 8888."
},
{
"code": null,
"e": 6418,
"s": 6167,
"text": "You may instruct the start script to customize the container environment before launching the notebook server. You do so by passing arguments (-e flag) to the docker run command. The list of all available variables can be found in docker-stacks docs."
},
{
"code": null,
"e": 6587,
"s": 6418,
"text": "The server logs appear in the terminal and include a URL to the notebook server. You can navigate to the URL, create a new python notebook and paste the following code:"
},
{
"code": null,
"e": 6738,
"s": 6587,
"text": "#create a spark session\nfrom pyspark.sql import SparkSession\nspark = SparkSession.builder.master(\"local[*]\").appName(\"spark_on_docker\").getOrCreate()\n"
},
{
"code": null,
"e": 6906,
"s": 6738,
"text": "#Download a README.md file from docker-stacks to test Spark\n!wget -q https://github.com/jupyter/docker-stacks/blob/d990a62010aededcda836196c4b04efece7f838f/README.md \n"
},
{
"code": null,
"e": 7155,
"s": 6906,
"text": "#read the file and count how many rows have the word Jupyter\ntextFile = spark.read.text(\"README.md\")\nrows_with_jupyter = textFile.filter(textFile.value.contains(\"Jupyter\")).count()\n\nprint(\"There's %d rows with the word Jupyter.\"%rows_with_jupyter)\n"
},
{
"code": null,
"e": 7195,
"s": 7155,
"text": "There's 21 rows with the word Jupyter.\n"
},
{
"code": null,
"e": 7228,
"s": 7195,
"text": "#print the session status\nspark\n"
},
{
"code": null,
"e": 7253,
"s": 7228,
"text": "SparkSession - in-memory"
},
{
"code": null,
"e": 7266,
"s": 7253,
"text": "SparkContext"
},
{
"code": null,
"e": 7275,
"s": 7266,
"text": "Spark UI"
},
{
"code": null,
"e": 7531,
"s": 7278,
"text": "Voilá! We have our Apache Spark environment with minnimum effort. You can open a terminal and install packages using conda or pip and manage your packages and dependecies as you wish. Once you have finished you can press ctrl+C and stop the container."
},
{
"code": null,
"e": 7708,
"s": 7531,
"text": "If you want to start your container and have your data persisted you cannot run the “docker run” command again, this will create a new default container, so what we need to do?"
},
{
"code": null,
"e": 7736,
"s": 7708,
"text": "You can type in a terminal:"
},
{
"code": null,
"e": 7752,
"s": 7736,
"text": "~$ docker ps -a"
},
{
"code": null,
"e": 7855,
"s": 7752,
"text": "this will list all containers available, to start the same container that you create previously, type:"
},
{
"code": null,
"e": 7882,
"s": 7855,
"text": "~$ docker start -a pyspark"
},
{
"code": null,
"e": 8072,
"s": 7882,
"text": "where -a is a flag that tells docker to bind the console output to the terminal and pyspark is the name of the container. To learn more about docker start options you can visit Docker docs."
},
{
"code": null,
"e": 8416,
"s": 8072,
"text": "In this article, we can see how docker can speed-up the development lifecycle and help us mitigate some of the drawbacks of using Windows as the main OS for development. Microsoft is doing a great job with WSL, Docker, and other tools for developers and engineers even supporting GPU processing through docker and WSL. The future is promising."
},
{
"code": null,
"e": 8586,
"s": 8416,
"text": "Thanks for reading this article, I hope that this small guide can help you and give valuable insights to anyone who decides to use Docker for Windows as your “One ring”."
}
]
|
Binary Tree and Lowest Common Ancestor | by Shuo Wang | Towards Data Science | It is the lowest level parent shared by two nodes within a tree.
Let’s take a look at an example:
Within the above binary tree, nodes 8 and 10 are highlighted. What are their shared parents?
It’s quite obvious that the shared parents are 5, 7, and 9.
But the shared parent at the lowest level is 9, and it is referred to as the lowest common ancestor(LCA).
Let’s warm up with a binary search tree.
A binary search tree is a special case of a binary tree, where the left subtree only contains smaller nodes and right subtree only contains bigger nodes.
Our example above is a binary search tree. As you can see, at node 3, all nodes in the left subtree(0, 1, 2) are smaller than 3 and all nodes on in the right subtree are bigger (4).
So, how do we go about looking for the LCA in a binary search tree for, say, node 8 and 10?
Actually binary search tree makes the search quite simple. Take a close look at node 9, what makes it different from node 7? I can think one thing:
Node 9 is between 8 and 10, whereas for node 7, both nodes 8 and 10 are bigger.
This is actually enough information to determine that node 9 is the LCA for node 8 and 10 in a binary search tree, thanks to its great property.
Below is an implementation of it:
from collections import dequeclass Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = rightdef create_bt(value_queue): """create binary tree""" if len(value_queue) <= 0: return None, None root = Node(value_queue.popleft()) current_queue = deque() current_queue.append(root) while len(current_queue) > 0 and len(value_queue) > 0: current_node = current_queue.popleft() left = value_queue.popleft() if left is not None: current_node.left = Node(left) current_queue.append(current_node.left) right = value_queue.popleft() if right is not None: current_node.right = Node(right) current_queue.append(current_node.right) return rootdef create_bt_fls(value_list): """create binary create from list""" return create_bt(deque(value_list))def lca_bst(bst, v1, v2): """lowest common ancestor of two nodes in a binary search tree""" if v1 <= bst.value <= v2 or v1 >= bst.value >= v2: return bst elif bst.value > v1 and bst.value > v2: return lca_bst(bst.left, v1, v2) else: return lca_bst(bst.right, v1, v2)bt1 = create_bt_fls([5, 3, 7, 1, 4, 6, 9, 0, 2, None, None, None, None, 8, 10])lca = lca_bst(bt1, 8, 10)print(lca.value)'''output:9'''
In this implementation, we first create a binary tree data structure from a list of values, and then call the LCA algorithm to find the LCA of node 8 and 10, which returns the correct value of 9.
Let’s take a pause and think about the complexity of this algorithm a little. The algorithm starts at the root, at each node it compares the node’s value against the two input nodes, if the value is between the two nodes return the node as the answer, otherwise move on to the left if the value is greater than both input nodes, or right if the value is smaller than both input nodes.
So during each recursion iteration, the search space is cut in half (half of the tree), this means that if the total number of nodes in the tree is n, the number of iterations needed is log(n) (of base 2), so the complexity is O(log(n)). Not too bad.
That was a nice warm up, now let’s make things slightly more complicated.
Suppose now that the tree is not a binary search tree, but a tree with random node values of no particular structure. How do we find the LCA of two nodes in the tree?
If you try to run the binary search tree LCA algorithm on the above tree, it will fail miserably:
ls1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, None, None, None, None, 9, 10]bt1, node_dict = create_bt_fls(ls1)lca = lca_bst(bt1, 9, 10)print(lca.value)'''output:10 WRONG!!'''
We have to think of another way.
One intuitive way is from the following observation:
As you can see from the graphs above, the path to node 9 is 0, 2, 6, 9, and the path to node 10, is 0, 2, 6, 10. Once we have the paths to each node, all we need to do is find the last matching node in the two paths, which would also be our LCA!
Below is an implementation:
def find_path(tree, value): """find path from root to value""" if tree is None: return None elif tree.value == value: return [tree] res = find_path(tree.left, value) if res is not None: return [tree] + res res = find_path(tree.right, value) if res is not None: return [tree] + res return Nonedef lca_fp(tree, v1, v2): """find lca of two nodes using find_path""" path1 = find_path(tree, v1) path2 = find_path(tree, v2) cur_idx = 0 while len(path1) > cur_idx and \ len(path2) > cur_idx and \ path1[cur_idx].value == path2[cur_idx].value: cur_idx = cur_idx + 1 return path1[cur_idx - 1]lca = lca_fp(bt1, 9, 10)print(lca.value)'''output:6'''
Works.
The above algorithm is simple enough, just one thing to notice, the Find Path algorithm searches the entire tree for a path to a target node, so its complexity is O(n), therefore the LCA algorithm using find_path is also O(n). A sacrifice of performance for not constructing the tree as a binary search tree.
The complexity of the Find Path algorithm is not terribly worrying, but what if you need to perform the search repeatedly? Remember there are n choose 2 number of unique pairs of nodes in a tree of size n. that’s:
number of node pairs, if we get the LCA for all of them using Find Path algorithm, that would be O(n2n) or O(n3). Maybe we should try to speed it up a bit.
One way to speed up the calculation of the find path is to store a parent pointer in the node, so that when we try to find the path to a node, all we need to do is follow the parents all the way to the root instead of searching the entire tree for a path.
Below is an implementation of this enhancement to the tree:
class Node: def __init__(self, value, parent=None, left=None, right=None): self.value = value self.parent = parent self.left = left self.right = right def add_to_dict(self, node_dict): node_dict[self.value] = selfdef create_bt(value_queue): """create binary tree""" if len(value_queue) <= 0: return None, None node_dict = {} root = Node(value_queue.popleft()) root.add_to_dict(node_dict) current_queue = deque() current_queue.append(root) while len(current_queue) > 0 and len(value_queue) > 0: current_node = current_queue.popleft() left = value_queue.popleft() if left is not None: current_node.left = Node(left, parent=current_node) current_node.left.add_to_dict(node_dict) current_queue.append(current_node.left) right = value_queue.popleft() if right is not None: current_node.right = Node(right, parent=current_node) current_node.right.add_to_dict(node_dict) current_queue.append(current_node.right) return root, node_dictdef create_bt_fls(value_list): """create binary create from list""" return create_bt(deque(value_list))
In this new implementation of the tree, we have stored an additional field, parent, in the node to store the parent node.
We have also created a dictionary of value to nodes so that we can find the nodes corresponding to a value easily.
With these two enhancement, we can implement a new LCA algorithm:
def lca(node1, node2): parents = set() cur_parent = node1 while cur_parent is not None: parents.add(cur_parent) cur_parent = cur_parent.parent cur_parent = node2 while cur_parent is not None: if cur_parent in parents: return cur_parent cur_parent = cur_parent.parent return Nonels1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, None, None, None, None, 9, 10]bt1, node_dict = create_bt_fls(ls1)lca1 = lca(node_dict[9], node_dict[10])print(lca1.value)'''output:6'''
Works again.
With this enhancement, we sacrificed a bit more memory space, O(n), to store the parent pointer, but since tracing from node to root parent is O(log(n)), the complexity of the algorithm reduces to O(log(n)). Running on all node pairs now takes O(n2log(n)), memory for speed.
To be Continued...
Is this the best we can do? Absolutely not, there are many ways to optimize the algorithm. Tarjan’s Off-Line Lowest Common Ancestor algorithm, in particular, can reduce the performance complexity to constant! But since it involves a completely new data structure (disjoint-set), we’ll discuss it in another story. | [
{
"code": null,
"e": 237,
"s": 172,
"text": "It is the lowest level parent shared by two nodes within a tree."
},
{
"code": null,
"e": 270,
"s": 237,
"text": "Let’s take a look at an example:"
},
{
"code": null,
"e": 363,
"s": 270,
"text": "Within the above binary tree, nodes 8 and 10 are highlighted. What are their shared parents?"
},
{
"code": null,
"e": 423,
"s": 363,
"text": "It’s quite obvious that the shared parents are 5, 7, and 9."
},
{
"code": null,
"e": 529,
"s": 423,
"text": "But the shared parent at the lowest level is 9, and it is referred to as the lowest common ancestor(LCA)."
},
{
"code": null,
"e": 570,
"s": 529,
"text": "Let’s warm up with a binary search tree."
},
{
"code": null,
"e": 724,
"s": 570,
"text": "A binary search tree is a special case of a binary tree, where the left subtree only contains smaller nodes and right subtree only contains bigger nodes."
},
{
"code": null,
"e": 906,
"s": 724,
"text": "Our example above is a binary search tree. As you can see, at node 3, all nodes in the left subtree(0, 1, 2) are smaller than 3 and all nodes on in the right subtree are bigger (4)."
},
{
"code": null,
"e": 998,
"s": 906,
"text": "So, how do we go about looking for the LCA in a binary search tree for, say, node 8 and 10?"
},
{
"code": null,
"e": 1146,
"s": 998,
"text": "Actually binary search tree makes the search quite simple. Take a close look at node 9, what makes it different from node 7? I can think one thing:"
},
{
"code": null,
"e": 1226,
"s": 1146,
"text": "Node 9 is between 8 and 10, whereas for node 7, both nodes 8 and 10 are bigger."
},
{
"code": null,
"e": 1371,
"s": 1226,
"text": "This is actually enough information to determine that node 9 is the LCA for node 8 and 10 in a binary search tree, thanks to its great property."
},
{
"code": null,
"e": 1405,
"s": 1371,
"text": "Below is an implementation of it:"
},
{
"code": null,
"e": 2765,
"s": 1405,
"text": "from collections import dequeclass Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = rightdef create_bt(value_queue): \"\"\"create binary tree\"\"\" if len(value_queue) <= 0: return None, None root = Node(value_queue.popleft()) current_queue = deque() current_queue.append(root) while len(current_queue) > 0 and len(value_queue) > 0: current_node = current_queue.popleft() left = value_queue.popleft() if left is not None: current_node.left = Node(left) current_queue.append(current_node.left) right = value_queue.popleft() if right is not None: current_node.right = Node(right) current_queue.append(current_node.right) return rootdef create_bt_fls(value_list): \"\"\"create binary create from list\"\"\" return create_bt(deque(value_list))def lca_bst(bst, v1, v2): \"\"\"lowest common ancestor of two nodes in a binary search tree\"\"\" if v1 <= bst.value <= v2 or v1 >= bst.value >= v2: return bst elif bst.value > v1 and bst.value > v2: return lca_bst(bst.left, v1, v2) else: return lca_bst(bst.right, v1, v2)bt1 = create_bt_fls([5, 3, 7, 1, 4, 6, 9, 0, 2, None, None, None, None, 8, 10])lca = lca_bst(bt1, 8, 10)print(lca.value)'''output:9'''"
},
{
"code": null,
"e": 2961,
"s": 2765,
"text": "In this implementation, we first create a binary tree data structure from a list of values, and then call the LCA algorithm to find the LCA of node 8 and 10, which returns the correct value of 9."
},
{
"code": null,
"e": 3346,
"s": 2961,
"text": "Let’s take a pause and think about the complexity of this algorithm a little. The algorithm starts at the root, at each node it compares the node’s value against the two input nodes, if the value is between the two nodes return the node as the answer, otherwise move on to the left if the value is greater than both input nodes, or right if the value is smaller than both input nodes."
},
{
"code": null,
"e": 3597,
"s": 3346,
"text": "So during each recursion iteration, the search space is cut in half (half of the tree), this means that if the total number of nodes in the tree is n, the number of iterations needed is log(n) (of base 2), so the complexity is O(log(n)). Not too bad."
},
{
"code": null,
"e": 3671,
"s": 3597,
"text": "That was a nice warm up, now let’s make things slightly more complicated."
},
{
"code": null,
"e": 3838,
"s": 3671,
"text": "Suppose now that the tree is not a binary search tree, but a tree with random node values of no particular structure. How do we find the LCA of two nodes in the tree?"
},
{
"code": null,
"e": 3936,
"s": 3838,
"text": "If you try to run the binary search tree LCA algorithm on the above tree, it will fail miserably:"
},
{
"code": null,
"e": 4100,
"s": 3936,
"text": "ls1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, None, None, None, None, 9, 10]bt1, node_dict = create_bt_fls(ls1)lca = lca_bst(bt1, 9, 10)print(lca.value)'''output:10 WRONG!!'''"
},
{
"code": null,
"e": 4133,
"s": 4100,
"text": "We have to think of another way."
},
{
"code": null,
"e": 4186,
"s": 4133,
"text": "One intuitive way is from the following observation:"
},
{
"code": null,
"e": 4432,
"s": 4186,
"text": "As you can see from the graphs above, the path to node 9 is 0, 2, 6, 9, and the path to node 10, is 0, 2, 6, 10. Once we have the paths to each node, all we need to do is find the last matching node in the two paths, which would also be our LCA!"
},
{
"code": null,
"e": 4460,
"s": 4432,
"text": "Below is an implementation:"
},
{
"code": null,
"e": 5193,
"s": 4460,
"text": "def find_path(tree, value): \"\"\"find path from root to value\"\"\" if tree is None: return None elif tree.value == value: return [tree] res = find_path(tree.left, value) if res is not None: return [tree] + res res = find_path(tree.right, value) if res is not None: return [tree] + res return Nonedef lca_fp(tree, v1, v2): \"\"\"find lca of two nodes using find_path\"\"\" path1 = find_path(tree, v1) path2 = find_path(tree, v2) cur_idx = 0 while len(path1) > cur_idx and \\ len(path2) > cur_idx and \\ path1[cur_idx].value == path2[cur_idx].value: cur_idx = cur_idx + 1 return path1[cur_idx - 1]lca = lca_fp(bt1, 9, 10)print(lca.value)'''output:6'''"
},
{
"code": null,
"e": 5200,
"s": 5193,
"text": "Works."
},
{
"code": null,
"e": 5509,
"s": 5200,
"text": "The above algorithm is simple enough, just one thing to notice, the Find Path algorithm searches the entire tree for a path to a target node, so its complexity is O(n), therefore the LCA algorithm using find_path is also O(n). A sacrifice of performance for not constructing the tree as a binary search tree."
},
{
"code": null,
"e": 5723,
"s": 5509,
"text": "The complexity of the Find Path algorithm is not terribly worrying, but what if you need to perform the search repeatedly? Remember there are n choose 2 number of unique pairs of nodes in a tree of size n. that’s:"
},
{
"code": null,
"e": 5879,
"s": 5723,
"text": "number of node pairs, if we get the LCA for all of them using Find Path algorithm, that would be O(n2n) or O(n3). Maybe we should try to speed it up a bit."
},
{
"code": null,
"e": 6135,
"s": 5879,
"text": "One way to speed up the calculation of the find path is to store a parent pointer in the node, so that when we try to find the path to a node, all we need to do is follow the parents all the way to the root instead of searching the entire tree for a path."
},
{
"code": null,
"e": 6195,
"s": 6135,
"text": "Below is an implementation of this enhancement to the tree:"
},
{
"code": null,
"e": 7408,
"s": 6195,
"text": "class Node: def __init__(self, value, parent=None, left=None, right=None): self.value = value self.parent = parent self.left = left self.right = right def add_to_dict(self, node_dict): node_dict[self.value] = selfdef create_bt(value_queue): \"\"\"create binary tree\"\"\" if len(value_queue) <= 0: return None, None node_dict = {} root = Node(value_queue.popleft()) root.add_to_dict(node_dict) current_queue = deque() current_queue.append(root) while len(current_queue) > 0 and len(value_queue) > 0: current_node = current_queue.popleft() left = value_queue.popleft() if left is not None: current_node.left = Node(left, parent=current_node) current_node.left.add_to_dict(node_dict) current_queue.append(current_node.left) right = value_queue.popleft() if right is not None: current_node.right = Node(right, parent=current_node) current_node.right.add_to_dict(node_dict) current_queue.append(current_node.right) return root, node_dictdef create_bt_fls(value_list): \"\"\"create binary create from list\"\"\" return create_bt(deque(value_list))"
},
{
"code": null,
"e": 7530,
"s": 7408,
"text": "In this new implementation of the tree, we have stored an additional field, parent, in the node to store the parent node."
},
{
"code": null,
"e": 7645,
"s": 7530,
"text": "We have also created a dictionary of value to nodes so that we can find the nodes corresponding to a value easily."
},
{
"code": null,
"e": 7711,
"s": 7645,
"text": "With these two enhancement, we can implement a new LCA algorithm:"
},
{
"code": null,
"e": 8216,
"s": 7711,
"text": "def lca(node1, node2): parents = set() cur_parent = node1 while cur_parent is not None: parents.add(cur_parent) cur_parent = cur_parent.parent cur_parent = node2 while cur_parent is not None: if cur_parent in parents: return cur_parent cur_parent = cur_parent.parent return Nonels1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, None, None, None, None, 9, 10]bt1, node_dict = create_bt_fls(ls1)lca1 = lca(node_dict[9], node_dict[10])print(lca1.value)'''output:6'''"
},
{
"code": null,
"e": 8229,
"s": 8216,
"text": "Works again."
},
{
"code": null,
"e": 8504,
"s": 8229,
"text": "With this enhancement, we sacrificed a bit more memory space, O(n), to store the parent pointer, but since tracing from node to root parent is O(log(n)), the complexity of the algorithm reduces to O(log(n)). Running on all node pairs now takes O(n2log(n)), memory for speed."
},
{
"code": null,
"e": 8523,
"s": 8504,
"text": "To be Continued..."
}
]
|
C Program to check if an Array is Palindrome or not | Given an array arr[] of any size n, our task is to find out that the array is palindrome or not. Palindrome is a sequence which can be read backwards and forward as same, like: MADAM, NAMAN, etc.
So to check an array is palindrome or not so we can traverse an array from back and forward like −
Input: arr[] = {1, 0, 0, 1}
Output: Array is palindrome
Input: arr[] = {1, 2, 3, 4, 5}
Output: Array is not palindrome
Approach used below is as follows −
We will traverse the array from starting as well as from the end until they both are equal and check whether the element from starting is same as the element from the end, then the array is palindrome else the array is not a palindrome.
Start
In function int pallindrome(int arr[], int n)
Step 1-> initialize i, j, flag and assign flag as 0
Step 2-> Loop For i = 0, j=n-1 and i< n/2, j>=n/2 and i++, j--
If arr[i]!=arr[j] then,
Set flag as 1
Break
End If
End Loop
Step 3-> If flag == 1 then,
Return 0
Step 4-> Else
Return 1
End function
In function int main(int argc, char const *argv[])
Step 1-> Declare and initialize arr[] as {1, 0, 2, 3, 2, 2, 1}
Step 2-> Declare and initialize n as sizeof(arr)/sizeof(arr[0])
Step 3-> If pallindrome(arr, n) then,
Print "Array is pallindrome "
End if
Step 4-> Else
Print "Array is not pallindrome "
Return 0
End main
Stop
Live Demo
#include <stdio.h>
int pallindrome(int arr[], int n) {
int i, j, flag = 0;
for(i = 0, j=n-1; i< n/2, j>=n/2; i++, j--) {
if(arr[i]!=arr[j]) {
flag = 1;
break;
}
}
if (flag == 1)
return 0;
else
return 1;
}
int main(int argc, char const *argv[]) {
int arr[] = {1, 0, 2, 3, 2, 2, 1};
int n = sizeof(arr)/sizeof(arr[0]);
if(pallindrome(arr, n)) {
printf("Array is pallindrome\n");
}
else
printf("Array is not pallindrome\n");
return 0;
}
If run the above code it will generate the following output −
Array is not palindrome | [
{
"code": null,
"e": 1258,
"s": 1062,
"text": "Given an array arr[] of any size n, our task is to find out that the array is palindrome or not. Palindrome is a sequence which can be read backwards and forward as same, like: MADAM, NAMAN, etc."
},
{
"code": null,
"e": 1357,
"s": 1258,
"text": "So to check an array is palindrome or not so we can traverse an array from back and forward like −"
},
{
"code": null,
"e": 1476,
"s": 1357,
"text": "Input: arr[] = {1, 0, 0, 1}\nOutput: Array is palindrome\nInput: arr[] = {1, 2, 3, 4, 5}\nOutput: Array is not palindrome"
},
{
"code": null,
"e": 1512,
"s": 1476,
"text": "Approach used below is as follows −"
},
{
"code": null,
"e": 1749,
"s": 1512,
"text": "We will traverse the array from starting as well as from the end until they both are equal and check whether the element from starting is same as the element from the end, then the array is palindrome else the array is not a palindrome."
},
{
"code": null,
"e": 2463,
"s": 1749,
"text": "Start\nIn function int pallindrome(int arr[], int n)\n Step 1-> initialize i, j, flag and assign flag as 0\n Step 2-> Loop For i = 0, j=n-1 and i< n/2, j>=n/2 and i++, j--\n If arr[i]!=arr[j] then,\n Set flag as 1\n Break\n End If\n End Loop\n Step 3-> If flag == 1 then,\n Return 0\n Step 4-> Else\n Return 1\nEnd function\nIn function int main(int argc, char const *argv[])\n Step 1-> Declare and initialize arr[] as {1, 0, 2, 3, 2, 2, 1}\n Step 2-> Declare and initialize n as sizeof(arr)/sizeof(arr[0])\n Step 3-> If pallindrome(arr, n) then,\n Print \"Array is pallindrome \"\n End if\n Step 4-> Else\n Print \"Array is not pallindrome \"\n Return 0\nEnd main\nStop"
},
{
"code": null,
"e": 2474,
"s": 2463,
"text": " Live Demo"
},
{
"code": null,
"e": 2989,
"s": 2474,
"text": "#include <stdio.h>\nint pallindrome(int arr[], int n) {\n int i, j, flag = 0;\n for(i = 0, j=n-1; i< n/2, j>=n/2; i++, j--) {\n if(arr[i]!=arr[j]) {\n flag = 1;\n break;\n }\n }\n if (flag == 1)\n return 0;\n else\n return 1;\n}\nint main(int argc, char const *argv[]) {\n int arr[] = {1, 0, 2, 3, 2, 2, 1};\n int n = sizeof(arr)/sizeof(arr[0]);\n if(pallindrome(arr, n)) {\n printf(\"Array is pallindrome\\n\");\n }\n else\n printf(\"Array is not pallindrome\\n\");\n return 0;\n}"
},
{
"code": null,
"e": 3051,
"s": 2989,
"text": "If run the above code it will generate the following output −"
},
{
"code": null,
"e": 3075,
"s": 3051,
"text": "Array is not palindrome"
}
]
|
Shearing in 2D Graphics | 01 Jul, 2020
Shearing deals with changing the shape and size of the 2D object along x-axis and y-axis. It is similar to sliding the layers in one direction to change the shape of the 2D object.It is an ideal technique to change the shape of an existing object in a two dimensional plane. In a two dimensional plane, the object size can be changed along X direction as well as Y direction.
x-Shear :In x shear, the y co-ordinates remain the same but the x co-ordinates changes. If P(x, y) is the point then the new points will be P’(x’, y’) given as –
Matrix Form:y-Shear :In y shear, the x co-ordinates remain the same but the y co-ordinates changes. If P(x, y) is the point then the new points will be P’(x’, y’) given as –
Matrix Form:
x-y Shear :In x-y shear, both the x and y co-ordinates changes. If P(x, y) is the point then the new points will be P’(x’, y’) given as –
Matrix Form:
Example :Given a triangle with points (1, 1), (0, 0) and (1, 0).Find out the new coordinates of the object along x-axis, y-axis, xy-axis.(Applying shear parameter 4 on X-axis and 1 on Y-axis.).
Explanation –
Given,
Old corner coordinates of the triangle = A (1, 1), B(0, 0), C(1, 0)
Shearing parameter along X-axis (Shx) = 4
Shearing parameter along Y-axis (Shy) = 1
Along x-axis:
A'=(1+4*1, 1)=(5, 1)
B'=(0+4*0, 0)=(0, 0)
C'=(1+4*0, 0)=(1, 0)
Along y-axis:
A''=(1, 1+1*1)=(1, 2)
B''=(0, 0+1*0)=(0, 0)
C''=(1, 0+1*1)=(1, 1)
Along xy-axis:
A'''=(1+4*1, 1+1*1)=(5, 2)
B'''=(0+4*0, 0+1*0)=(0, 0)
C'''=(1+4*0, 0+1*1)=(1, 1)
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Propositional Logic and Predicate Logic
Arrow Symbols in LaTeX
Set Notations in LaTeX
Activation Functions
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph
Univariate, Bivariate and Multivariate data and its analysis
Properties of Boolean Algebra
Discrete Mathematics | Hasse Diagrams
Newton's Divided Difference Interpolation Formula
Representation of Boolean Functions | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Jul, 2020"
},
{
"code": null,
"e": 430,
"s": 54,
"text": "Shearing deals with changing the shape and size of the 2D object along x-axis and y-axis. It is similar to sliding the layers in one direction to change the shape of the 2D object.It is an ideal technique to change the shape of an existing object in a two dimensional plane. In a two dimensional plane, the object size can be changed along X direction as well as Y direction."
},
{
"code": null,
"e": 592,
"s": 430,
"text": "x-Shear :In x shear, the y co-ordinates remain the same but the x co-ordinates changes. If P(x, y) is the point then the new points will be P’(x’, y’) given as –"
},
{
"code": null,
"e": 766,
"s": 592,
"text": "Matrix Form:y-Shear :In y shear, the x co-ordinates remain the same but the y co-ordinates changes. If P(x, y) is the point then the new points will be P’(x’, y’) given as –"
},
{
"code": null,
"e": 779,
"s": 766,
"text": "Matrix Form:"
},
{
"code": null,
"e": 917,
"s": 779,
"text": "x-y Shear :In x-y shear, both the x and y co-ordinates changes. If P(x, y) is the point then the new points will be P’(x’, y’) given as –"
},
{
"code": null,
"e": 930,
"s": 917,
"text": "Matrix Form:"
},
{
"code": null,
"e": 1124,
"s": 930,
"text": "Example :Given a triangle with points (1, 1), (0, 0) and (1, 0).Find out the new coordinates of the object along x-axis, y-axis, xy-axis.(Applying shear parameter 4 on X-axis and 1 on Y-axis.)."
},
{
"code": null,
"e": 1138,
"s": 1124,
"text": "Explanation –"
},
{
"code": null,
"e": 1554,
"s": 1138,
"text": "Given,\nOld corner coordinates of the triangle = A (1, 1), B(0, 0), C(1, 0)\nShearing parameter along X-axis (Shx) = 4\nShearing parameter along Y-axis (Shy) = 1\n\nAlong x-axis:\nA'=(1+4*1, 1)=(5, 1)\nB'=(0+4*0, 0)=(0, 0)\nC'=(1+4*0, 0)=(1, 0)\n\nAlong y-axis:\nA''=(1, 1+1*1)=(1, 2)\nB''=(0, 0+1*0)=(0, 0)\nC''=(1, 0+1*1)=(1, 1)\n\nAlong xy-axis:\nA'''=(1+4*1, 1+1*1)=(5, 2)\nB'''=(0+4*0, 0+1*0)=(0, 0)\nC'''=(1+4*0, 0+1*1)=(1, 1) "
},
{
"code": null,
"e": 1578,
"s": 1554,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 1676,
"s": 1578,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1735,
"s": 1676,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 1758,
"s": 1735,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 1781,
"s": 1758,
"text": "Set Notations in LaTeX"
},
{
"code": null,
"e": 1802,
"s": 1781,
"text": "Activation Functions"
},
{
"code": null,
"e": 1867,
"s": 1802,
"text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph"
},
{
"code": null,
"e": 1928,
"s": 1867,
"text": "Univariate, Bivariate and Multivariate data and its analysis"
},
{
"code": null,
"e": 1958,
"s": 1928,
"text": "Properties of Boolean Algebra"
},
{
"code": null,
"e": 1996,
"s": 1958,
"text": "Discrete Mathematics | Hasse Diagrams"
},
{
"code": null,
"e": 2046,
"s": 1996,
"text": "Newton's Divided Difference Interpolation Formula"
}
]
|
p5.js | createVideo() Function | 26 Feb, 2020
The createVideo() function is used to create a video element in the DOM. The video is created as a p5.MediaElement, which has methods for controlling the media and its playback.
Syntax:
createVideo(src, callback)
Parameters: This function accepts two parameters as mentioned above and described below:
src: It is a string that specified path of the video file. An array of strings can also be used to specify multiple paths for the support of different browsers.
callback: It is a callback function that would be fired when the ‘canplaythrough’ event fires. This event is fired when the video has completed loading and does not require any additional buffering. It is an optional parameter.
Return Value: It returns a pointer to the p5.MediaElement with the video.
Below examples illustrate the createVideo() function in p5.js:
Example 1:
function setup() { createCanvas(300, 300); text("Click on the buttons below to"+ " play/pause the video", 20, 20); vidElement = createVideo("sample_video.mp4"); vidElement.position(20, 0); vidElement.size(300); playBtn = createButton("Play Video"); playBtn.position(30, 40); playBtn.mouseClicked(playVideo); pauseBtn = createButton("Pause Video"); pauseBtn.position(150, 40); pauseBtn.mouseClicked(pauseVideo);} function playVideo() { vidElement.play();} function pauseVideo() { vidElement.pause();}
Output:
Example 2:
function setup() { createCanvas(300, 300); text("Loading the video...", 20, 20); vidElement = createVideo("sample_video.mp4", afterLoad); vidElement.position(20, 20); vidElement.size(300);} function afterLoad() { text("The video has finished loading and will"+ " now play!", 20, 40); vidElement.play();}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/createVideo
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Feb, 2020"
},
{
"code": null,
"e": 206,
"s": 28,
"text": "The createVideo() function is used to create a video element in the DOM. The video is created as a p5.MediaElement, which has methods for controlling the media and its playback."
},
{
"code": null,
"e": 214,
"s": 206,
"text": "Syntax:"
},
{
"code": null,
"e": 241,
"s": 214,
"text": "createVideo(src, callback)"
},
{
"code": null,
"e": 330,
"s": 241,
"text": "Parameters: This function accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 491,
"s": 330,
"text": "src: It is a string that specified path of the video file. An array of strings can also be used to specify multiple paths for the support of different browsers."
},
{
"code": null,
"e": 719,
"s": 491,
"text": "callback: It is a callback function that would be fired when the ‘canplaythrough’ event fires. This event is fired when the video has completed loading and does not require any additional buffering. It is an optional parameter."
},
{
"code": null,
"e": 793,
"s": 719,
"text": "Return Value: It returns a pointer to the p5.MediaElement with the video."
},
{
"code": null,
"e": 856,
"s": 793,
"text": "Below examples illustrate the createVideo() function in p5.js:"
},
{
"code": null,
"e": 867,
"s": 856,
"text": "Example 1:"
},
{
"code": "function setup() { createCanvas(300, 300); text(\"Click on the buttons below to\"+ \" play/pause the video\", 20, 20); vidElement = createVideo(\"sample_video.mp4\"); vidElement.position(20, 0); vidElement.size(300); playBtn = createButton(\"Play Video\"); playBtn.position(30, 40); playBtn.mouseClicked(playVideo); pauseBtn = createButton(\"Pause Video\"); pauseBtn.position(150, 40); pauseBtn.mouseClicked(pauseVideo);} function playVideo() { vidElement.play();} function pauseVideo() { vidElement.pause();}",
"e": 1394,
"s": 867,
"text": null
},
{
"code": null,
"e": 1402,
"s": 1394,
"text": "Output:"
},
{
"code": null,
"e": 1413,
"s": 1402,
"text": "Example 2:"
},
{
"code": "function setup() { createCanvas(300, 300); text(\"Loading the video...\", 20, 20); vidElement = createVideo(\"sample_video.mp4\", afterLoad); vidElement.position(20, 20); vidElement.size(300);} function afterLoad() { text(\"The video has finished loading and will\"+ \" now play!\", 20, 40); vidElement.play();}",
"e": 1753,
"s": 1413,
"text": null
},
{
"code": null,
"e": 1761,
"s": 1753,
"text": "Output:"
},
{
"code": null,
"e": 1801,
"s": 1761,
"text": "Online editor: https://editor.p5js.org/"
},
{
"code": null,
"e": 1899,
"s": 1801,
"text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/"
},
{
"code": null,
"e": 1954,
"s": 1899,
"text": "Reference: https://p5js.org/reference/#/p5/createVideo"
},
{
"code": null,
"e": 1971,
"s": 1954,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 1982,
"s": 1971,
"text": "JavaScript"
},
{
"code": null,
"e": 1999,
"s": 1982,
"text": "Web Technologies"
}
]
|
Read SQL database table into a Pandas DataFrame using SQLAlchemy | 17 Aug, 2020
To read sql table into a DataFrame using only the table name, without executing any query we use read_sql_table() method in Pandas. This function does not support DBAPI connections.
Syntax : pandas.read_sql_table(table_name, con, schema=None, index_col=None, coerce_float=True, parse_dates=None, columns=None, chunksize=None)
Parameters :
table_name : (str) Name of SQL table in database.
con : SQLAlchemy connectable or str.
schema : (str) Name of SQL schema in database to query (if database flavor supports this). Default is None
index_col : List of string or string. Column(s) to set as index(MultiIndex). Default is None.
coerce_float : (bool) Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point. Default is True
parse_dates : (list or dict)
List of column names to parse as dates.
Dict of {column_name: format string} where format string is strftime compatible in case of parsing string times or is one of (D, s, ns, ms, us) in case of parsing integer timestamps.
Dict of {column_name: arg dict}, where the arg dict corresponds to the keyword arguments of pandas.to_datetime() Especially useful with databases without native Datetime support, such as SQLite.
columns : List of column names to select from SQL table. Default is None
chunksize : (int) If specified, returns an iterator where chunksize is the number of rows to include in each chunk. Default is None.
Return type : DataFrame
Example 1 :
# import the modulesimport pandas as pd from sqlalchemy import create_engine # SQLAlchemy connectablecnx = create_engine('sqlite:///contacts.db').connect() # table named 'contacts' will be returned as a dataframe.df = pd.read_sql_table('contacts', cnx)print(df)
Output :
Example 2 :
# import the modulesimport pandas as pd from sqlalchemy import create_engine # SQLAlchemy connectablecnx = create_engine('sqlite:///students.db').connect() # table named 'students' will be returned as a dataframe.df = pd.read_sql_table('students', cnx)print(df)
Output :
Example 3 :
# import the modulesimport pandas as pd from sqlalchemy import create_engine # SQLAlchemy connectablecnx = create_engine('sqlite:///students.db').connect() # table named 'employee' will be returned as a dataframe.df = pd.read_sql_table('employee', cnx)print(df)
Output :
Python-pandas
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 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 210,
"s": 28,
"text": "To read sql table into a DataFrame using only the table name, without executing any query we use read_sql_table() method in Pandas. This function does not support DBAPI connections."
},
{
"code": null,
"e": 354,
"s": 210,
"text": "Syntax : pandas.read_sql_table(table_name, con, schema=None, index_col=None, coerce_float=True, parse_dates=None, columns=None, chunksize=None)"
},
{
"code": null,
"e": 368,
"s": 354,
"text": "Parameters : "
},
{
"code": null,
"e": 418,
"s": 368,
"text": "table_name : (str) Name of SQL table in database."
},
{
"code": null,
"e": 456,
"s": 418,
"text": "con : SQLAlchemy connectable or str. "
},
{
"code": null,
"e": 564,
"s": 456,
"text": "schema : (str) Name of SQL schema in database to query (if database flavor supports this). Default is None"
},
{
"code": null,
"e": 658,
"s": 564,
"text": "index_col : List of string or string. Column(s) to set as index(MultiIndex). Default is None."
},
{
"code": null,
"e": 801,
"s": 658,
"text": "coerce_float : (bool) Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point. Default is True"
},
{
"code": null,
"e": 831,
"s": 801,
"text": "parse_dates : (list or dict) "
},
{
"code": null,
"e": 871,
"s": 831,
"text": "List of column names to parse as dates."
},
{
"code": null,
"e": 1054,
"s": 871,
"text": "Dict of {column_name: format string} where format string is strftime compatible in case of parsing string times or is one of (D, s, ns, ms, us) in case of parsing integer timestamps."
},
{
"code": null,
"e": 1249,
"s": 1054,
"text": "Dict of {column_name: arg dict}, where the arg dict corresponds to the keyword arguments of pandas.to_datetime() Especially useful with databases without native Datetime support, such as SQLite."
},
{
"code": null,
"e": 1322,
"s": 1249,
"text": "columns : List of column names to select from SQL table. Default is None"
},
{
"code": null,
"e": 1456,
"s": 1322,
"text": "chunksize : (int) If specified, returns an iterator where chunksize is the number of rows to include in each chunk. Default is None. "
},
{
"code": null,
"e": 1480,
"s": 1456,
"text": "Return type : DataFrame"
},
{
"code": null,
"e": 1492,
"s": 1480,
"text": "Example 1 :"
},
{
"code": "# import the modulesimport pandas as pd from sqlalchemy import create_engine # SQLAlchemy connectablecnx = create_engine('sqlite:///contacts.db').connect() # table named 'contacts' will be returned as a dataframe.df = pd.read_sql_table('contacts', cnx)print(df)",
"e": 1756,
"s": 1492,
"text": null
},
{
"code": null,
"e": 1765,
"s": 1756,
"text": "Output :"
},
{
"code": null,
"e": 1777,
"s": 1765,
"text": "Example 2 :"
},
{
"code": "# import the modulesimport pandas as pd from sqlalchemy import create_engine # SQLAlchemy connectablecnx = create_engine('sqlite:///students.db').connect() # table named 'students' will be returned as a dataframe.df = pd.read_sql_table('students', cnx)print(df)",
"e": 2041,
"s": 1777,
"text": null
},
{
"code": null,
"e": 2050,
"s": 2041,
"text": "Output :"
},
{
"code": null,
"e": 2062,
"s": 2050,
"text": "Example 3 :"
},
{
"code": "# import the modulesimport pandas as pd from sqlalchemy import create_engine # SQLAlchemy connectablecnx = create_engine('sqlite:///students.db').connect() # table named 'employee' will be returned as a dataframe.df = pd.read_sql_table('employee', cnx)print(df)",
"e": 2326,
"s": 2062,
"text": null
},
{
"code": null,
"e": 2335,
"s": 2326,
"text": "Output :"
},
{
"code": null,
"e": 2349,
"s": 2335,
"text": "Python-pandas"
},
{
"code": null,
"e": 2356,
"s": 2349,
"text": "Python"
},
{
"code": null,
"e": 2454,
"s": 2356,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2472,
"s": 2454,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2514,
"s": 2472,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2536,
"s": 2514,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2571,
"s": 2536,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2597,
"s": 2571,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2629,
"s": 2597,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2658,
"s": 2629,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2685,
"s": 2658,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2715,
"s": 2685,
"text": "Iterate over a list in Python"
}
]
|
Matplotlib.pyplot.contour() in Python | 21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The contour() function in pyplot module of matplotlib library is used to plot contours.
Syntax: matplotlib.pyplot.contour(\*args, data=None, \*\*kwargs)
Parameters: This method accept the following parameters that are described below:
X, Y: These parameter are the coordinates of the values in Z.
Z : This parameter is the height values over which the contour is drawn.
levels : This parameter is used to determine the numbers and positions of the contour lines / regions.
Returns: This returns the following:
c :This returns the QuadContourSet.
Below examples illustrate the matplotlib.pyplot.contour() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerimport matplotlib delta = 0.15x = np.arange(1.5, 2.5, delta)y = np.arange(1.0, 3.0, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(X - Y)) CS1 = plt.contour(X, Y, Z) fmt = {}strs = ['1', '2', '3', '4', '5', '6', '7']for l, s in zip(CS1.levels, strs): fmt[l] = splt.clabel(CS1, CS1.levels, inline = True, fmt = fmt, fontsize = 10) plt.title('matplotlib.pyplot.contour() Example')plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.cm as cmimport matplotlib.pyplot as plt delta = 0.25x = np.arange(-3.0, 5.0, delta)y = np.arange(-1.3, 2.5, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(-X**2 - Y**2) - np.exp(-(X - 1)**2 - (Y - 1)**2)) fig, ax = plt.subplots()im = ax.imshow(Z, interpolation ='bilinear', origin ='lower', cmap ="bone", extent =(-3, 3, -2, 2)) levels = np.arange(-1.2, 1.6, 0.2)CS = ax.contour(Z, levels, origin ='lower', cmap ='Greens', linewidths = 2, extent =(-3, 3, -2, 2)) zc = CS.collections[6]plt.setp(zc, linewidth = 2) ax.clabel(CS, levels, inline = 1, fmt ='% 1.1f', fontsize = 14) plt.title('matplotlib.pyplot.contour() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 223,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface."
},
{
"code": null,
"e": 311,
"s": 223,
"text": "The contour() function in pyplot module of matplotlib library is used to plot contours."
},
{
"code": null,
"e": 376,
"s": 311,
"text": "Syntax: matplotlib.pyplot.contour(\\*args, data=None, \\*\\*kwargs)"
},
{
"code": null,
"e": 458,
"s": 376,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 520,
"s": 458,
"text": "X, Y: These parameter are the coordinates of the values in Z."
},
{
"code": null,
"e": 593,
"s": 520,
"text": "Z : This parameter is the height values over which the contour is drawn."
},
{
"code": null,
"e": 696,
"s": 593,
"text": "levels : This parameter is used to determine the numbers and positions of the contour lines / regions."
},
{
"code": null,
"e": 733,
"s": 696,
"text": "Returns: This returns the following:"
},
{
"code": null,
"e": 769,
"s": 733,
"text": "c :This returns the QuadContourSet."
},
{
"code": null,
"e": 858,
"s": 769,
"text": "Below examples illustrate the matplotlib.pyplot.contour() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 870,
"s": 858,
"text": "Example #1:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerimport matplotlib delta = 0.15x = np.arange(1.5, 2.5, delta)y = np.arange(1.0, 3.0, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(X - Y)) CS1 = plt.contour(X, Y, Z) fmt = {}strs = ['1', '2', '3', '4', '5', '6', '7']for l, s in zip(CS1.levels, strs): fmt[l] = splt.clabel(CS1, CS1.levels, inline = True, fmt = fmt, fontsize = 10) plt.title('matplotlib.pyplot.contour() Example')plt.show()",
"e": 1397,
"s": 870,
"text": null
},
{
"code": null,
"e": 1405,
"s": 1397,
"text": "Output:"
},
{
"code": null,
"e": 1417,
"s": 1405,
"text": "Example #2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.cm as cmimport matplotlib.pyplot as plt delta = 0.25x = np.arange(-3.0, 5.0, delta)y = np.arange(-1.3, 2.5, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(-X**2 - Y**2) - np.exp(-(X - 1)**2 - (Y - 1)**2)) fig, ax = plt.subplots()im = ax.imshow(Z, interpolation ='bilinear', origin ='lower', cmap =\"bone\", extent =(-3, 3, -2, 2)) levels = np.arange(-1.2, 1.6, 0.2)CS = ax.contour(Z, levels, origin ='lower', cmap ='Greens', linewidths = 2, extent =(-3, 3, -2, 2)) zc = CS.collections[6]plt.setp(zc, linewidth = 2) ax.clabel(CS, levels, inline = 1, fmt ='% 1.1f', fontsize = 14) plt.title('matplotlib.pyplot.contour() Example')plt.show()",
"e": 2281,
"s": 1417,
"text": null
},
{
"code": null,
"e": 2289,
"s": 2281,
"text": "Output:"
},
{
"code": null,
"e": 2307,
"s": 2289,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2314,
"s": 2307,
"text": "Python"
},
{
"code": null,
"e": 2412,
"s": 2314,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2457,
"s": 2412,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 2507,
"s": 2457,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 2523,
"s": 2507,
"text": "Deque in Python"
},
{
"code": null,
"e": 2539,
"s": 2523,
"text": "Queue in Python"
},
{
"code": null,
"e": 2561,
"s": 2539,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2603,
"s": 2561,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2630,
"s": 2603,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2653,
"s": 2630,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 2672,
"s": 2653,
"text": "reduce() in Python"
}
]
|
UDP Server-Client implementation in C | 04 May, 2022
There are two major transport layer protocols to communicate between hosts: TCP and UDP. Creating TCP Server/Client was discussed in a previous post.
Prerequisite: Creating TCP Server/Client
Theory In UDP, the client does not form a connection with the server like in TCP and instead just sends a datagram. Similarly, the server need not accept a connection and just waits for datagrams to arrive. Datagrams upon arrival contain the address of the sender which the server uses to send data to the correct client.
The entire process can be broken down into the following steps :
UDP Server :
Create a UDP socket.Bind the socket to the server address.Wait until the datagram packet arrives from the client.Process the datagram packet and send a reply to the client.Go back to Step 3.
Create a UDP socket.
Bind the socket to the server address.
Wait until the datagram packet arrives from the client.
Process the datagram packet and send a reply to the client.
Go back to Step 3.
UDP Client :
Create a UDP socket.Send a message to the server.Wait until response from the server is received.Process reply and go back to step 2, if necessary.Close socket descriptor and exit.
Create a UDP socket.
Send a message to the server.
Wait until response from the server is received.
Process reply and go back to step 2, if necessary.
Close socket descriptor and exit.
Necessary Functions :
int socket(int domain, int type, int protocol)
Creates an unbound socket in the specified domain.
Returns socket file descriptor.
Arguments : domain – Specifies the communication domain ( AF_INET for IPv4/ AF_INET6 for IPv6 ) type – Type of socket to be created ( SOCK_STREAM for TCP / SOCK_DGRAM for UDP ) protocol – Protocol to be used by the socket. 0 means use default protocol for the address family.
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
Assigns address to the unbound socket.
Arguments : sockfd – File descriptor of a socket to be bonded addr – Structure in which address to be bound to is specified addrlen – Size of addr structure
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen)
Send a message on the socket
Arguments : sockfd – File descriptor of the socket buf – Application buffer containing the data to be sent len – Size of buf application buffer flags – Bitwise OR of flags to modify socket behavior dest_addr – Structure containing the address of the destination addrlen – Size of dest_addr structure
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen)
Receive a message from the socket.
Arguments : sockfd – File descriptor of the socket buf – Application buffer in which to receive data len – Size of buf application buffer flags – Bitwise OR of flags to modify socket behavior src_addr – Structure containing source address is returned addrlen – Variable in which size of src_addr structure is returned
int close(int fd)
Close a file descriptor
Arguments:
fd – File descriptor
In the below code, the exchange of one hello message between server and client is shown to demonstrate the model.
Filename: UDPServer.c
C
// Server side implementation of UDP client-server model #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #define PORT 8080 #define MAXLINE 1024 // Driver code int main() { int sockfd; char buffer[MAXLINE]; char *hello = "Hello from server"; struct sockaddr_in servaddr, cliaddr; // Creating socket file descriptor if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { perror("socket creation failed"); exit(EXIT_FAILURE); } memset(&servaddr, 0, sizeof(servaddr)); memset(&cliaddr, 0, sizeof(cliaddr)); // Filling server information servaddr.sin_family = AF_INET; // IPv4 servaddr.sin_addr.s_addr = INADDR_ANY; servaddr.sin_port = htons(PORT); // Bind the socket with the server address if ( bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0 ) { perror("bind failed"); exit(EXIT_FAILURE); } int len, n; len = sizeof(cliaddr); //len is value/result n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL, ( struct sockaddr *) &cliaddr, &len); buffer[n] = '\0'; printf("Client : %s\n", buffer); sendto(sockfd, (const char *)hello, strlen(hello), MSG_CONFIRM, (const struct sockaddr *) &cliaddr, len); printf("Hello message sent.\n"); return 0; }
Filename: UDPClient.c
C
// Client side implementation of UDP client-server model #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #define PORT 8080 #define MAXLINE 1024 // Driver code int main() { int sockfd; char buffer[MAXLINE]; char *hello = "Hello from client"; struct sockaddr_in servaddr; // Creating socket file descriptor if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { perror("socket creation failed"); exit(EXIT_FAILURE); } memset(&servaddr, 0, sizeof(servaddr)); // Filling server information servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); servaddr.sin_addr.s_addr = INADDR_ANY; int n, len; sendto(sockfd, (const char *)hello, strlen(hello), MSG_CONFIRM, (const struct sockaddr *) &servaddr, sizeof(servaddr)); printf("Hello message sent.\n"); n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL, (struct sockaddr *) &servaddr, &len); buffer[n] = '\0'; printf("Server : %s\n", buffer); close(sockfd); return 0; }
Output :
$ ./server
Client : Hello from client
Hello message sent.
$ ./client
Hello message sent.
Server : Hello from server
muazzamali
anikakapoor
marcosarcticseal
GabrielStaples
sumitgumber28
C Language
C Programs
Computer Networks
Linux-Unix
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
Header files in C/C++ and its uses
C Program to read contents of Whole File | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 May, 2022"
},
{
"code": null,
"e": 205,
"s": 54,
"text": "There are two major transport layer protocols to communicate between hosts: TCP and UDP. Creating TCP Server/Client was discussed in a previous post. "
},
{
"code": null,
"e": 246,
"s": 205,
"text": "Prerequisite: Creating TCP Server/Client"
},
{
"code": null,
"e": 569,
"s": 246,
"text": "Theory In UDP, the client does not form a connection with the server like in TCP and instead just sends a datagram. Similarly, the server need not accept a connection and just waits for datagrams to arrive. Datagrams upon arrival contain the address of the sender which the server uses to send data to the correct client. "
},
{
"code": null,
"e": 635,
"s": 569,
"text": "The entire process can be broken down into the following steps : "
},
{
"code": null,
"e": 650,
"s": 635,
"text": "UDP Server : "
},
{
"code": null,
"e": 841,
"s": 650,
"text": "Create a UDP socket.Bind the socket to the server address.Wait until the datagram packet arrives from the client.Process the datagram packet and send a reply to the client.Go back to Step 3."
},
{
"code": null,
"e": 862,
"s": 841,
"text": "Create a UDP socket."
},
{
"code": null,
"e": 901,
"s": 862,
"text": "Bind the socket to the server address."
},
{
"code": null,
"e": 957,
"s": 901,
"text": "Wait until the datagram packet arrives from the client."
},
{
"code": null,
"e": 1017,
"s": 957,
"text": "Process the datagram packet and send a reply to the client."
},
{
"code": null,
"e": 1036,
"s": 1017,
"text": "Go back to Step 3."
},
{
"code": null,
"e": 1051,
"s": 1036,
"text": "UDP Client : "
},
{
"code": null,
"e": 1232,
"s": 1051,
"text": "Create a UDP socket.Send a message to the server.Wait until response from the server is received.Process reply and go back to step 2, if necessary.Close socket descriptor and exit."
},
{
"code": null,
"e": 1253,
"s": 1232,
"text": "Create a UDP socket."
},
{
"code": null,
"e": 1283,
"s": 1253,
"text": "Send a message to the server."
},
{
"code": null,
"e": 1332,
"s": 1283,
"text": "Wait until response from the server is received."
},
{
"code": null,
"e": 1383,
"s": 1332,
"text": "Process reply and go back to step 2, if necessary."
},
{
"code": null,
"e": 1417,
"s": 1383,
"text": "Close socket descriptor and exit."
},
{
"code": null,
"e": 1441,
"s": 1417,
"text": "Necessary Functions : "
},
{
"code": null,
"e": 1571,
"s": 1441,
"text": "int socket(int domain, int type, int protocol)\nCreates an unbound socket in the specified domain.\nReturns socket file descriptor."
},
{
"code": null,
"e": 1849,
"s": 1571,
"text": "Arguments : domain – Specifies the communication domain ( AF_INET for IPv4/ AF_INET6 for IPv6 ) type – Type of socket to be created ( SOCK_STREAM for TCP / SOCK_DGRAM for UDP ) protocol – Protocol to be used by the socket. 0 means use default protocol for the address family. "
},
{
"code": null,
"e": 1957,
"s": 1849,
"text": "int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen)\nAssigns address to the unbound socket."
},
{
"code": null,
"e": 2116,
"s": 1957,
"text": "Arguments : sockfd – File descriptor of a socket to be bonded addr – Structure in which address to be bound to is specified addrlen – Size of addr structure "
},
{
"code": null,
"e": 2280,
"s": 2116,
"text": "ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,\n const struct sockaddr *dest_addr, socklen_t addrlen)\nSend a message on the socket"
},
{
"code": null,
"e": 2582,
"s": 2280,
"text": "Arguments : sockfd – File descriptor of the socket buf – Application buffer containing the data to be sent len – Size of buf application buffer flags – Bitwise OR of flags to modify socket behavior dest_addr – Structure containing the address of the destination addrlen – Size of dest_addr structure "
},
{
"code": null,
"e": 2744,
"s": 2582,
"text": "ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,\n struct sockaddr *src_addr, socklen_t *addrlen)\nReceive a message from the socket."
},
{
"code": null,
"e": 3063,
"s": 2744,
"text": "Arguments : sockfd – File descriptor of the socket buf – Application buffer in which to receive data len – Size of buf application buffer flags – Bitwise OR of flags to modify socket behavior src_addr – Structure containing source address is returned addrlen – Variable in which size of src_addr structure is returned "
},
{
"code": null,
"e": 3105,
"s": 3063,
"text": "int close(int fd)\nClose a file descriptor"
},
{
"code": null,
"e": 3116,
"s": 3105,
"text": "Arguments:"
},
{
"code": null,
"e": 3138,
"s": 3116,
"text": " fd – File descriptor"
},
{
"code": null,
"e": 3252,
"s": 3138,
"text": "In the below code, the exchange of one hello message between server and client is shown to demonstrate the model."
},
{
"code": null,
"e": 3274,
"s": 3252,
"text": "Filename: UDPServer.c"
},
{
"code": null,
"e": 3276,
"s": 3274,
"text": "C"
},
{
"code": "// Server side implementation of UDP client-server model #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #define PORT 8080 #define MAXLINE 1024 // Driver code int main() { int sockfd; char buffer[MAXLINE]; char *hello = \"Hello from server\"; struct sockaddr_in servaddr, cliaddr; // Creating socket file descriptor if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { perror(\"socket creation failed\"); exit(EXIT_FAILURE); } memset(&servaddr, 0, sizeof(servaddr)); memset(&cliaddr, 0, sizeof(cliaddr)); // Filling server information servaddr.sin_family = AF_INET; // IPv4 servaddr.sin_addr.s_addr = INADDR_ANY; servaddr.sin_port = htons(PORT); // Bind the socket with the server address if ( bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0 ) { perror(\"bind failed\"); exit(EXIT_FAILURE); } int len, n; len = sizeof(cliaddr); //len is value/result n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL, ( struct sockaddr *) &cliaddr, &len); buffer[n] = '\\0'; printf(\"Client : %s\\n\", buffer); sendto(sockfd, (const char *)hello, strlen(hello), MSG_CONFIRM, (const struct sockaddr *) &cliaddr, len); printf(\"Hello message sent.\\n\"); return 0; }",
"e": 4841,
"s": 3276,
"text": null
},
{
"code": null,
"e": 4863,
"s": 4841,
"text": "Filename: UDPClient.c"
},
{
"code": null,
"e": 4865,
"s": 4863,
"text": "C"
},
{
"code": "// Client side implementation of UDP client-server model #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #define PORT 8080 #define MAXLINE 1024 // Driver code int main() { int sockfd; char buffer[MAXLINE]; char *hello = \"Hello from client\"; struct sockaddr_in servaddr; // Creating socket file descriptor if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { perror(\"socket creation failed\"); exit(EXIT_FAILURE); } memset(&servaddr, 0, sizeof(servaddr)); // Filling server information servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); servaddr.sin_addr.s_addr = INADDR_ANY; int n, len; sendto(sockfd, (const char *)hello, strlen(hello), MSG_CONFIRM, (const struct sockaddr *) &servaddr, sizeof(servaddr)); printf(\"Hello message sent.\\n\"); n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL, (struct sockaddr *) &servaddr, &len); buffer[n] = '\\0'; printf(\"Server : %s\\n\", buffer); close(sockfd); return 0; }",
"e": 6133,
"s": 4865,
"text": null
},
{
"code": null,
"e": 6143,
"s": 6133,
"text": "Output : "
},
{
"code": null,
"e": 6201,
"s": 6143,
"text": "$ ./server\nClient : Hello from client\nHello message sent."
},
{
"code": null,
"e": 6259,
"s": 6201,
"text": "$ ./client\nHello message sent.\nServer : Hello from server"
},
{
"code": null,
"e": 6270,
"s": 6259,
"text": "muazzamali"
},
{
"code": null,
"e": 6282,
"s": 6270,
"text": "anikakapoor"
},
{
"code": null,
"e": 6299,
"s": 6282,
"text": "marcosarcticseal"
},
{
"code": null,
"e": 6314,
"s": 6299,
"text": "GabrielStaples"
},
{
"code": null,
"e": 6328,
"s": 6314,
"text": "sumitgumber28"
},
{
"code": null,
"e": 6339,
"s": 6328,
"text": "C Language"
},
{
"code": null,
"e": 6350,
"s": 6339,
"text": "C Programs"
},
{
"code": null,
"e": 6368,
"s": 6350,
"text": "Computer Networks"
},
{
"code": null,
"e": 6379,
"s": 6368,
"text": "Linux-Unix"
},
{
"code": null,
"e": 6397,
"s": 6379,
"text": "Computer Networks"
},
{
"code": null,
"e": 6495,
"s": 6397,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6512,
"s": 6495,
"text": "Substring in C++"
},
{
"code": null,
"e": 6547,
"s": 6512,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 6569,
"s": 6547,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 6615,
"s": 6569,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 6660,
"s": 6615,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 6673,
"s": 6660,
"text": "Strings in C"
},
{
"code": null,
"e": 6714,
"s": 6673,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 6743,
"s": 6714,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 6778,
"s": 6743,
"text": "Header files in C/C++ and its uses"
}
]
|
p5.js | curveVertex() Function | 25 May, 2020
The curveVertex() function in p5.js is used to specify the vertex coordinates used to draw a curve. It expects 2 parameters for 2D curves and 3 parameters for 3D curves. Both the 2D and 3D modes can be used for drawing in the WebGL mode. This function can only be used between the beginShape() and endShape().
The first and last vertices are used to guide the beginning and end of a curve. A minimum of four points is required to draw a curve between the given second and third points. Additional vertices would be used to draw the curve between them.
Syntax:
curveVertex( x, y )
OR
curveVertex( x, y, [z] )
Parameters: This function accepts three parameters as mentioned above and described below:
x: It is a number that specifies the x-coordinate of the vertex.
y: It is a number that specifies the y-coordinate of the vertex.
z: It is a number that specifies the z-coordinate of the vertex. It is an optional parameter.
The examples below illustrates the curveVertex() function in p5.js:
Example 1:
function setup() { createCanvas(500, 300); textSize(16);} function draw() { background("green"); fill("black"); text("The curve below is made using curveVertex() function in Canvas", 10, 20); // Define the vertex points let p1 = { x: 150, y: 250 }; let p2 = { x: 100, y: 100 }; let p3 = { x: 400, y: 100 }; let p4 = { x: 350, y: 250 }; noFill(); // Start the curve beginShape(); // Specify other points in curveVertex() curveVertex(p1.x, p1.y); curveVertex(p2.x, p2.y); curveVertex(p3.x, p3.y); curveVertex(p4.x, p4.y); endShape(); // Draw circles for demonstration circle(p1.x, p1.y, 10); circle(p2.x, p2.y, 10); circle(p3.x, p3.y, 10); circle(p4.x, p4.y, 10);}
Output:
Example 2:
let newFont; function preload() { newFont = loadFont("fonts/Montserrat.otf");} function setup() { createCanvas(500, 200, WEBGL); textFont(newFont, 14);} function draw() { background("green"); fill("black"); text("The curve below is made using curveVertex() function in WebGL", -245, -75); // Define the vertex points let p1 = { x: -200, y: 175, z: 0 }; let p2 = { x: -200, y: 25, z: 0 }; let p3 = { x: 150, y: 25, z: 0 }; let p4 = { x: 275, y: 175, z: 0 }; noFill(); // Start the curve beginShape(); // Specify the points of the vertex curveVertex(p1.x, p1.y, p1.z); curveVertex(p2.x, p2.y, p2.z); curveVertex(p3.x, p3.y, p3.z); curveVertex(p4.x, p4.y, p4.z); endShape();}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/curveVertex
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 May, 2020"
},
{
"code": null,
"e": 338,
"s": 28,
"text": "The curveVertex() function in p5.js is used to specify the vertex coordinates used to draw a curve. It expects 2 parameters for 2D curves and 3 parameters for 3D curves. Both the 2D and 3D modes can be used for drawing in the WebGL mode. This function can only be used between the beginShape() and endShape()."
},
{
"code": null,
"e": 580,
"s": 338,
"text": "The first and last vertices are used to guide the beginning and end of a curve. A minimum of four points is required to draw a curve between the given second and third points. Additional vertices would be used to draw the curve between them."
},
{
"code": null,
"e": 588,
"s": 580,
"text": "Syntax:"
},
{
"code": null,
"e": 608,
"s": 588,
"text": "curveVertex( x, y )"
},
{
"code": null,
"e": 611,
"s": 608,
"text": "OR"
},
{
"code": null,
"e": 636,
"s": 611,
"text": "curveVertex( x, y, [z] )"
},
{
"code": null,
"e": 727,
"s": 636,
"text": "Parameters: This function accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 792,
"s": 727,
"text": "x: It is a number that specifies the x-coordinate of the vertex."
},
{
"code": null,
"e": 857,
"s": 792,
"text": "y: It is a number that specifies the y-coordinate of the vertex."
},
{
"code": null,
"e": 951,
"s": 857,
"text": "z: It is a number that specifies the z-coordinate of the vertex. It is an optional parameter."
},
{
"code": null,
"e": 1019,
"s": 951,
"text": "The examples below illustrates the curveVertex() function in p5.js:"
},
{
"code": null,
"e": 1030,
"s": 1019,
"text": "Example 1:"
},
{
"code": "function setup() { createCanvas(500, 300); textSize(16);} function draw() { background(\"green\"); fill(\"black\"); text(\"The curve below is made using curveVertex() function in Canvas\", 10, 20); // Define the vertex points let p1 = { x: 150, y: 250 }; let p2 = { x: 100, y: 100 }; let p3 = { x: 400, y: 100 }; let p4 = { x: 350, y: 250 }; noFill(); // Start the curve beginShape(); // Specify other points in curveVertex() curveVertex(p1.x, p1.y); curveVertex(p2.x, p2.y); curveVertex(p3.x, p3.y); curveVertex(p4.x, p4.y); endShape(); // Draw circles for demonstration circle(p1.x, p1.y, 10); circle(p2.x, p2.y, 10); circle(p3.x, p3.y, 10); circle(p4.x, p4.y, 10);}",
"e": 1728,
"s": 1030,
"text": null
},
{
"code": null,
"e": 1736,
"s": 1728,
"text": "Output:"
},
{
"code": null,
"e": 1747,
"s": 1736,
"text": "Example 2:"
},
{
"code": "let newFont; function preload() { newFont = loadFont(\"fonts/Montserrat.otf\");} function setup() { createCanvas(500, 200, WEBGL); textFont(newFont, 14);} function draw() { background(\"green\"); fill(\"black\"); text(\"The curve below is made using curveVertex() function in WebGL\", -245, -75); // Define the vertex points let p1 = { x: -200, y: 175, z: 0 }; let p2 = { x: -200, y: 25, z: 0 }; let p3 = { x: 150, y: 25, z: 0 }; let p4 = { x: 275, y: 175, z: 0 }; noFill(); // Start the curve beginShape(); // Specify the points of the vertex curveVertex(p1.x, p1.y, p1.z); curveVertex(p2.x, p2.y, p2.z); curveVertex(p3.x, p3.y, p3.z); curveVertex(p4.x, p4.y, p4.z); endShape();}",
"e": 2451,
"s": 1747,
"text": null
},
{
"code": null,
"e": 2459,
"s": 2451,
"text": "Output:"
},
{
"code": null,
"e": 2499,
"s": 2459,
"text": "Online editor: https://editor.p5js.org/"
},
{
"code": null,
"e": 2597,
"s": 2499,
"text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/"
},
{
"code": null,
"e": 2652,
"s": 2597,
"text": "Reference: https://p5js.org/reference/#/p5/curveVertex"
},
{
"code": null,
"e": 2669,
"s": 2652,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 2680,
"s": 2669,
"text": "JavaScript"
},
{
"code": null,
"e": 2697,
"s": 2680,
"text": "Web Technologies"
}
]
|
Python | Pandas Series.count() | 15 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.count() function return the count of non-NA/null observations in the given Series object.
Syntax: Series.count(level=None)
Parameter :level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a smaller Series
Returns : nobs : int or Series (if level specified)
Example #1: Use Series.count() function to find the count of non-missing values in the given series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([80, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
Now we will use Series.count() function to find the count of non-missing values in the given series object.
# find the count of non-missing values# in the given series objectresult = sr.count() # Print the resultprint(result)
Output :As we can see in the output, the Series.count() function has successfully returned the count of non-missing values in the given series object. Example #2 : Use Series.count() function to find the count of non-missing values in the given series object. The given series object contains some missing values.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, None, None, 18, 65, None, 32, 10, 5, 24, None]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
Now we will use Series.count() function to find the count of non-missing values in the given series object.
# find the count of non-missing values# in the given series objectresult = sr.count() # Print the resultprint(result)
Output :As we can see in the output, the Series.count() function has successfully returned the count of non-missing values in the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
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
Python OOPs Concepts | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Feb, 2019"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 389,
"s": 285,
"text": "Pandas Series.count() function return the count of non-NA/null observations in the given Series object."
},
{
"code": null,
"e": 422,
"s": 389,
"text": "Syntax: Series.count(level=None)"
},
{
"code": null,
"e": 550,
"s": 422,
"text": "Parameter :level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a smaller Series"
},
{
"code": null,
"e": 602,
"s": 550,
"text": "Returns : nobs : int or Series (if level specified)"
},
{
"code": null,
"e": 710,
"s": 602,
"text": "Example #1: Use Series.count() function to find the count of non-missing values in the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([80, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 966,
"s": 710,
"text": null
},
{
"code": null,
"e": 975,
"s": 966,
"text": "Output :"
},
{
"code": null,
"e": 1083,
"s": 975,
"text": "Now we will use Series.count() function to find the count of non-missing values in the given series object."
},
{
"code": "# find the count of non-missing values# in the given series objectresult = sr.count() # Print the resultprint(result)",
"e": 1202,
"s": 1083,
"text": null
},
{
"code": null,
"e": 1516,
"s": 1202,
"text": "Output :As we can see in the output, the Series.count() function has successfully returned the count of non-missing values in the given series object. Example #2 : Use Series.count() function to find the count of non-missing values in the given series object. The given series object contains some missing values."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, None, None, 18, 65, None, 32, 10, 5, 24, None]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 1795,
"s": 1516,
"text": null
},
{
"code": null,
"e": 1804,
"s": 1795,
"text": "Output :"
},
{
"code": null,
"e": 1912,
"s": 1804,
"text": "Now we will use Series.count() function to find the count of non-missing values in the given series object."
},
{
"code": "# find the count of non-missing values# in the given series objectresult = sr.count() # Print the resultprint(result)",
"e": 2031,
"s": 1912,
"text": null
},
{
"code": null,
"e": 2182,
"s": 2031,
"text": "Output :As we can see in the output, the Series.count() function has successfully returned the count of non-missing values in the given series object."
},
{
"code": null,
"e": 2203,
"s": 2182,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2232,
"s": 2203,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2246,
"s": 2232,
"text": "Python-pandas"
},
{
"code": null,
"e": 2253,
"s": 2246,
"text": "Python"
},
{
"code": null,
"e": 2351,
"s": 2253,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2369,
"s": 2351,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2411,
"s": 2369,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2433,
"s": 2411,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2468,
"s": 2433,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2500,
"s": 2468,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2529,
"s": 2500,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2556,
"s": 2529,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2586,
"s": 2556,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2622,
"s": 2586,
"text": "Convert integer to string in Python"
}
]
|
Count SQL Table Column Using Python | 23 Dec, 2020
Prerequisite: Python: MySQL Create Table
In this article, we are going to see how to count the table column of a MySQL Table Using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database.
We are going to use geeks(Database name) database and table describing the salary.
Approach:
Import module.
Make a connection request with the database.
Create an object for the database cursor.
Execute the following MySQL query:
SELECT count(*) AS New_column_name FROM information_schema.columns where table_name = ‘Table_name’;
Example 1:
In this example we are using this database with the following query;
Python3
# Establish connection to MySQL databaseimport mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="root123", database="geeks") # Create a cursor objectmycursor = mydb.cursor() # Execute the queryquery = "SELECT count(*) AS New_column_name FROM information_schema.columns where table_name = 'Persons';"mycursor.execute(query) myresult = mycursor.fetchall() print(myresult[-1][-1]) # Close database connectionmydb.close()
Output;
5
Example 2:
In this example we are using this database with the following query;
Python3
# Establish connection to MySQL databaseimport mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="root123", database="geeks") # Create a cursor objectmycursor = mydb.cursor() # Execute the queryquery = "SELECT count(*) AS New_column_name FROM information_schema.columns where table_name = 'Salary';"mycursor.execute(query) myresult = mycursor.fetchall() print(myresult[-1][-1]) # Close database connectionmydb.close()
Output:
2
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Dec, 2020"
},
{
"code": null,
"e": 69,
"s": 28,
"text": "Prerequisite: Python: MySQL Create Table"
},
{
"code": null,
"e": 411,
"s": 69,
"text": "In this article, we are going to see how to count the table column of a MySQL Table Using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. "
},
{
"code": null,
"e": 494,
"s": 411,
"text": "We are going to use geeks(Database name) database and table describing the salary."
},
{
"code": null,
"e": 504,
"s": 494,
"text": "Approach:"
},
{
"code": null,
"e": 519,
"s": 504,
"text": "Import module."
},
{
"code": null,
"e": 564,
"s": 519,
"text": "Make a connection request with the database."
},
{
"code": null,
"e": 606,
"s": 564,
"text": "Create an object for the database cursor."
},
{
"code": null,
"e": 641,
"s": 606,
"text": "Execute the following MySQL query:"
},
{
"code": null,
"e": 741,
"s": 641,
"text": "SELECT count(*) AS New_column_name FROM information_schema.columns where table_name = ‘Table_name’;"
},
{
"code": null,
"e": 752,
"s": 741,
"text": "Example 1:"
},
{
"code": null,
"e": 821,
"s": 752,
"text": "In this example we are using this database with the following query;"
},
{
"code": null,
"e": 829,
"s": 821,
"text": "Python3"
},
{
"code": "# Establish connection to MySQL databaseimport mysql.connector mydb = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"root123\", database=\"geeks\") # Create a cursor objectmycursor = mydb.cursor() # Execute the queryquery = \"SELECT count(*) AS New_column_name FROM information_schema.columns where table_name = 'Persons';\"mycursor.execute(query) myresult = mycursor.fetchall() print(myresult[-1][-1]) # Close database connectionmydb.close()",
"e": 1304,
"s": 829,
"text": null
},
{
"code": null,
"e": 1312,
"s": 1304,
"text": "Output;"
},
{
"code": null,
"e": 1314,
"s": 1312,
"text": "5"
},
{
"code": null,
"e": 1325,
"s": 1314,
"text": "Example 2:"
},
{
"code": null,
"e": 1394,
"s": 1325,
"text": "In this example we are using this database with the following query;"
},
{
"code": null,
"e": 1402,
"s": 1394,
"text": "Python3"
},
{
"code": "# Establish connection to MySQL databaseimport mysql.connector mydb = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"root123\", database=\"geeks\") # Create a cursor objectmycursor = mydb.cursor() # Execute the queryquery = \"SELECT count(*) AS New_column_name FROM information_schema.columns where table_name = 'Salary';\"mycursor.execute(query) myresult = mycursor.fetchall() print(myresult[-1][-1]) # Close database connectionmydb.close()",
"e": 1876,
"s": 1402,
"text": null
},
{
"code": null,
"e": 1884,
"s": 1876,
"text": "Output:"
},
{
"code": null,
"e": 1886,
"s": 1884,
"text": "2"
},
{
"code": null,
"e": 1899,
"s": 1886,
"text": "Python-mySQL"
},
{
"code": null,
"e": 1906,
"s": 1899,
"text": "Python"
}
]
|
Largest power of k in n! (factorial) where k may not be prime | 08 Jul, 2021
Given two numbers k and n, find the largest power of k that divides n! Constraints:
K > 1
Examples:
Input : n = 7, k = 2
Output : 4
Explanation : 7! = 5040
The largest power of 2 that
divides 5040 is 24.
Input : n = 10, k = 9
Output : 2
The largest power of 9 that
divides 10! is 92.
We have discussed a solution in below post when k is always prime.Legendre’s formula (Given p and n, find the largest x such that p^x divides n!)Now to find the power of any non-prime number k in n!, we first find all the prime factors of the number k along with the count of number of their occurrences. Then for each prime factor, we count occurrences using Legendre’s formula which states that the largest possible power of a prime number p in n is ⌊n/p⌋ + ⌊n/(p2)⌋ + ⌊n/(p3)⌋ + ......Over all the prime factors p of K, the one with the minimum value of findPowerOfK(n, p)/count will be our answer where count is number of occurrences of p in k.
C++
Java
Python3
C#
Javascript
// CPP program to find the largest power// of k that divides n!#include <bits/stdc++.h>using namespace std; // To find the power of a prime p in// factorial Nint findPowerOfP(int n, int p){ int count = 0; int r=p; while (r <= n) { // calculating floor(n/r) // and adding to the count count += (n / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kvector<pair<int, int> > primeFactorsofK(int k){ // vector to store all the prime factors // along with their number of occurrence // in factorization of k vector<pair<int, int> > ans; for (int i = 2; k != 1; i++) { if (k % i == 0) { int count = 0; while (k % i == 0) { k = k / i; count++; } ans.push_back(make_pair(i, count)); } } return ans;} // Returns largest power of k that// divides n!int largestPowerOfK(int n, int k){ vector<pair<int, int> > vec; vec = primeFactorsofK(k); int ans = INT_MAX; for (int i = 0; i < vec.size(); i++) // calculating minimum power of all // the prime factors of k ans = min(ans, findPowerOfP(n, vec[i].first) / vec[i].second); return ans;} // Driver codeint main(){ cout << largestPowerOfK(7, 2) << endl; cout << largestPowerOfK(10, 9) << endl; return 0;}
// JAVA program to find the largest power// of k that divides n!import java.util.*; class GFG{ static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }}// To find the power of a prime p in// factorial Nstatic int findPowerOfP(int n, int p){ int count = 0; int r = p; while (r <= n) { // calculating Math.floor(n/r) // and adding to the count count += (n / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kstatic Vector<pair > primeFactorsofK(int k){ // vector to store all the prime factors // along with their number of occurrence // in factorization of k Vector<pair> ans = new Vector<pair>(); for (int i = 2; k != 1; i++) { if (k % i == 0) { int count = 0; while (k % i == 0) { k = k / i; count++; } ans.add(new pair(i, count)); } } return ans;} // Returns largest power of k that// divides n!static int largestPowerOfK(int n, int k){ Vector<pair > vec = new Vector<pair>(); vec = primeFactorsofK(k); int ans = Integer.MAX_VALUE; for (int i = 0; i < vec.size(); i++) // calculating minimum power of all // the prime factors of k ans = Math.min(ans, findPowerOfP(n, vec.get(i).first) / vec.get(i).second); return ans;} // Driver codepublic static void main(String[] args){ System.out.print(largestPowerOfK(7, 2) +"\n"); System.out.print(largestPowerOfK(10, 9) +"\n");}} // This code is contributed by 29AjayKumar
# Python3 program to find the largest power# of k that divides n!import sys # To find the power of a prime p in# factorial Ndef findPowerOfP(n, p) : count = 0 r = p while (r <= n) : # calculating floor(n/r) # and adding to the count count += (n // r) # increasing the power of p # from 1 to 2 to 3 and so on r = r * p return count # returns all the prime factors of kdef primeFactorsofK(k) : # vector to store all the prime factors # along with their number of occurrence # in factorization of k ans = [] i = 2 while k != 1 : if k % i == 0 : count = 0 while k % i == 0 : k = k // i count += 1 ans.append([i , count]) i += 1 return ans # Returns largest power of k that# divides n!def largestPowerOfK(n, k) : vec = primeFactorsofK(k) ans = sys.maxsize for i in range(len(vec)) : # calculating minimum power of all # the prime factors of k ans = min(ans, findPowerOfP(n, vec[i][0]) // vec[i][1]) return ans print(largestPowerOfK(7, 2))print(largestPowerOfK(10, 9)) # This code is contributed by divyesh072019
// C# program to find the largest power// of k that divides n!using System;using System.Collections.Generic; class GFG{ class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // To find the power of a prime p in// factorial Nstatic int findPowerOfP(int n, int p){ int count = 0; int r = p; while (r <= n) { // calculating Math.Floor(n/r) // and adding to the count count += (n / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kstatic List<pair > primeFactorsofK(int k){ // vector to store all the prime factors // along with their number of occurrence // in factorization of k List<pair> ans = new List<pair>(); for (int i = 2; k != 1; i++) { if (k % i == 0) { int count = 0; while (k % i == 0) { k = k / i; count++; } ans.Add(new pair(i, count)); } } return ans;} // Returns largest power of k that// divides n!static int largestPowerOfK(int n, int k){ List<pair > vec = new List<pair>(); vec = primeFactorsofK(k); int ans = int.MaxValue; for (int i = 0; i < vec.Count; i++) // calculating minimum power of all // the prime factors of k ans = Math.Min(ans, findPowerOfP(n, vec[i].first) / vec[i].second); return ans;} // Driver codepublic static void Main(String[] args){ Console.Write(largestPowerOfK(7, 2) +"\n"); Console.Write(largestPowerOfK(10, 9) +"\n");}} // This code is contributed by 29AjayKumar
<script> // JavaScript program to find the largest power// of k that divides n! class pair{ constructor(first,second) { this.first = first; this.second = second; }} // To find the power of a prime p in// factorial Nfunction findPowerOfP(n,p){ let count = 0; let r = p; while (r <= n) { // calculating Math.floor(n/r) // and adding to the count count += Math.floor(n / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kfunction primeFactorsofK(k){ // vector to store all the prime factors // along with their number of occurrence // in factorization of k let ans = []; for (let i = 2; k != 1; i++) { if (k % i == 0) { let count = 0; while (k % i == 0) { k = Math.floor(k / i); count++; } ans.push(new pair(i, count)); } } return ans;} // Returns largest power of k that// divides n!function largestPowerOfK(n,k){ let vec = []; vec = primeFactorsofK(k); let ans = Number.MAX_VALUE; for (let i = 0; i < vec.length; i++) // calculating minimum power of all // the prime factors of k ans = Math.min(ans, findPowerOfP(n, vec[i].first) / vec[i].second); return ans;} // Driver codedocument.write(largestPowerOfK(7, 2) +"<br>");document.write(largestPowerOfK(10, 9) +"<br>"); // This code is contributed by rag2127 </script>
Output:
4
2
This article is contributed by ShivamKD. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
29AjayKumar
divyesh072019
rag2127
factorial
number-theory
prime-factor
Mathematical
number-theory
Mathematical
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 140,
"s": 54,
"text": "Given two numbers k and n, find the largest power of k that divides n! Constraints: "
},
{
"code": null,
"e": 147,
"s": 140,
"text": " K > 1"
},
{
"code": null,
"e": 159,
"s": 147,
"text": "Examples: "
},
{
"code": null,
"e": 345,
"s": 159,
"text": "Input : n = 7, k = 2\nOutput : 4\nExplanation : 7! = 5040\nThe largest power of 2 that\ndivides 5040 is 24.\n\nInput : n = 10, k = 9\nOutput : 2\nThe largest power of 9 that\ndivides 10! is 92."
},
{
"code": null,
"e": 997,
"s": 347,
"text": "We have discussed a solution in below post when k is always prime.Legendre’s formula (Given p and n, find the largest x such that p^x divides n!)Now to find the power of any non-prime number k in n!, we first find all the prime factors of the number k along with the count of number of their occurrences. Then for each prime factor, we count occurrences using Legendre’s formula which states that the largest possible power of a prime number p in n is ⌊n/p⌋ + ⌊n/(p2)⌋ + ⌊n/(p3)⌋ + ......Over all the prime factors p of K, the one with the minimum value of findPowerOfK(n, p)/count will be our answer where count is number of occurrences of p in k. "
},
{
"code": null,
"e": 1001,
"s": 997,
"text": "C++"
},
{
"code": null,
"e": 1006,
"s": 1001,
"text": "Java"
},
{
"code": null,
"e": 1014,
"s": 1006,
"text": "Python3"
},
{
"code": null,
"e": 1017,
"s": 1014,
"text": "C#"
},
{
"code": null,
"e": 1028,
"s": 1017,
"text": "Javascript"
},
{
"code": "// CPP program to find the largest power// of k that divides n!#include <bits/stdc++.h>using namespace std; // To find the power of a prime p in// factorial Nint findPowerOfP(int n, int p){ int count = 0; int r=p; while (r <= n) { // calculating floor(n/r) // and adding to the count count += (n / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kvector<pair<int, int> > primeFactorsofK(int k){ // vector to store all the prime factors // along with their number of occurrence // in factorization of k vector<pair<int, int> > ans; for (int i = 2; k != 1; i++) { if (k % i == 0) { int count = 0; while (k % i == 0) { k = k / i; count++; } ans.push_back(make_pair(i, count)); } } return ans;} // Returns largest power of k that// divides n!int largestPowerOfK(int n, int k){ vector<pair<int, int> > vec; vec = primeFactorsofK(k); int ans = INT_MAX; for (int i = 0; i < vec.size(); i++) // calculating minimum power of all // the prime factors of k ans = min(ans, findPowerOfP(n, vec[i].first) / vec[i].second); return ans;} // Driver codeint main(){ cout << largestPowerOfK(7, 2) << endl; cout << largestPowerOfK(10, 9) << endl; return 0;}",
"e": 2475,
"s": 1028,
"text": null
},
{
"code": "// JAVA program to find the largest power// of k that divides n!import java.util.*; class GFG{ static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }}// To find the power of a prime p in// factorial Nstatic int findPowerOfP(int n, int p){ int count = 0; int r = p; while (r <= n) { // calculating Math.floor(n/r) // and adding to the count count += (n / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kstatic Vector<pair > primeFactorsofK(int k){ // vector to store all the prime factors // along with their number of occurrence // in factorization of k Vector<pair> ans = new Vector<pair>(); for (int i = 2; k != 1; i++) { if (k % i == 0) { int count = 0; while (k % i == 0) { k = k / i; count++; } ans.add(new pair(i, count)); } } return ans;} // Returns largest power of k that// divides n!static int largestPowerOfK(int n, int k){ Vector<pair > vec = new Vector<pair>(); vec = primeFactorsofK(k); int ans = Integer.MAX_VALUE; for (int i = 0; i < vec.size(); i++) // calculating minimum power of all // the prime factors of k ans = Math.min(ans, findPowerOfP(n, vec.get(i).first) / vec.get(i).second); return ans;} // Driver codepublic static void main(String[] args){ System.out.print(largestPowerOfK(7, 2) +\"\\n\"); System.out.print(largestPowerOfK(10, 9) +\"\\n\");}} // This code is contributed by 29AjayKumar",
"e": 4210,
"s": 2475,
"text": null
},
{
"code": "# Python3 program to find the largest power# of k that divides n!import sys # To find the power of a prime p in# factorial Ndef findPowerOfP(n, p) : count = 0 r = p while (r <= n) : # calculating floor(n/r) # and adding to the count count += (n // r) # increasing the power of p # from 1 to 2 to 3 and so on r = r * p return count # returns all the prime factors of kdef primeFactorsofK(k) : # vector to store all the prime factors # along with their number of occurrence # in factorization of k ans = [] i = 2 while k != 1 : if k % i == 0 : count = 0 while k % i == 0 : k = k // i count += 1 ans.append([i , count]) i += 1 return ans # Returns largest power of k that# divides n!def largestPowerOfK(n, k) : vec = primeFactorsofK(k) ans = sys.maxsize for i in range(len(vec)) : # calculating minimum power of all # the prime factors of k ans = min(ans, findPowerOfP(n, vec[i][0]) // vec[i][1]) return ans print(largestPowerOfK(7, 2))print(largestPowerOfK(10, 9)) # This code is contributed by divyesh072019",
"e": 5416,
"s": 4210,
"text": null
},
{
"code": "// C# program to find the largest power// of k that divides n!using System;using System.Collections.Generic; class GFG{ class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // To find the power of a prime p in// factorial Nstatic int findPowerOfP(int n, int p){ int count = 0; int r = p; while (r <= n) { // calculating Math.Floor(n/r) // and adding to the count count += (n / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kstatic List<pair > primeFactorsofK(int k){ // vector to store all the prime factors // along with their number of occurrence // in factorization of k List<pair> ans = new List<pair>(); for (int i = 2; k != 1; i++) { if (k % i == 0) { int count = 0; while (k % i == 0) { k = k / i; count++; } ans.Add(new pair(i, count)); } } return ans;} // Returns largest power of k that// divides n!static int largestPowerOfK(int n, int k){ List<pair > vec = new List<pair>(); vec = primeFactorsofK(k); int ans = int.MaxValue; for (int i = 0; i < vec.Count; i++) // calculating minimum power of all // the prime factors of k ans = Math.Min(ans, findPowerOfP(n, vec[i].first) / vec[i].second); return ans;} // Driver codepublic static void Main(String[] args){ Console.Write(largestPowerOfK(7, 2) +\"\\n\"); Console.Write(largestPowerOfK(10, 9) +\"\\n\");}} // This code is contributed by 29AjayKumar",
"e": 7147,
"s": 5416,
"text": null
},
{
"code": "<script> // JavaScript program to find the largest power// of k that divides n! class pair{ constructor(first,second) { this.first = first; this.second = second; }} // To find the power of a prime p in// factorial Nfunction findPowerOfP(n,p){ let count = 0; let r = p; while (r <= n) { // calculating Math.floor(n/r) // and adding to the count count += Math.floor(n / r); // increasing the power of p // from 1 to 2 to 3 and so on r = r * p; } return count;} // returns all the prime factors of kfunction primeFactorsofK(k){ // vector to store all the prime factors // along with their number of occurrence // in factorization of k let ans = []; for (let i = 2; k != 1; i++) { if (k % i == 0) { let count = 0; while (k % i == 0) { k = Math.floor(k / i); count++; } ans.push(new pair(i, count)); } } return ans;} // Returns largest power of k that// divides n!function largestPowerOfK(n,k){ let vec = []; vec = primeFactorsofK(k); let ans = Number.MAX_VALUE; for (let i = 0; i < vec.length; i++) // calculating minimum power of all // the prime factors of k ans = Math.min(ans, findPowerOfP(n, vec[i].first) / vec[i].second); return ans;} // Driver codedocument.write(largestPowerOfK(7, 2) +\"<br>\");document.write(largestPowerOfK(10, 9) +\"<br>\"); // This code is contributed by rag2127 </script>",
"e": 8715,
"s": 7147,
"text": null
},
{
"code": null,
"e": 8725,
"s": 8715,
"text": "Output: "
},
{
"code": null,
"e": 8729,
"s": 8725,
"text": "4\n2"
},
{
"code": null,
"e": 9146,
"s": 8729,
"text": "This article is contributed by ShivamKD. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 9158,
"s": 9146,
"text": "29AjayKumar"
},
{
"code": null,
"e": 9172,
"s": 9158,
"text": "divyesh072019"
},
{
"code": null,
"e": 9180,
"s": 9172,
"text": "rag2127"
},
{
"code": null,
"e": 9190,
"s": 9180,
"text": "factorial"
},
{
"code": null,
"e": 9204,
"s": 9190,
"text": "number-theory"
},
{
"code": null,
"e": 9217,
"s": 9204,
"text": "prime-factor"
},
{
"code": null,
"e": 9230,
"s": 9217,
"text": "Mathematical"
},
{
"code": null,
"e": 9244,
"s": 9230,
"text": "number-theory"
},
{
"code": null,
"e": 9257,
"s": 9244,
"text": "Mathematical"
},
{
"code": null,
"e": 9267,
"s": 9257,
"text": "factorial"
}
]
|
Largest Number formed from an Array | Practice | GeeksforGeeks | Given a list of non negative integers, arrange them in such a manner that they form the largest number possible.The result is going to be very large, hence return the result in the form of a string.
Example 1:
Input:
N = 5
Arr[] = {3, 30, 34, 5, 9}
Output: 9534330
Explanation: Given numbers are {3, 30, 34,
5, 9}, the arrangement 9534330 gives the
largest value.
Example 2:
Input:
N = 4
Arr[] = {54, 546, 548, 60}
Output: 6054854654
Explanation: Given numbers are {54, 546,
548, 60}, the arrangement 6054854654
gives the largest value.
Your Task:
You don't need to read input or print anything. Your task is to complete the function printLargest() which takes the array of strings arr[] as parameter and returns a string denoting the answer.
Expected Time Complexity: O(NlogN)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 105
0 ≤ Arr[i] ≤ 1018
Sum of all the elements of the array is greater than 0.
+1
prateeklucifer262 days ago
EASIEST AND SHORT JAVA CODE.
class Solution { String printLargest(String[] arr) { // code here Arrays.sort(arr, (s1,s2)->(s2+s1).compareTo(s1+s2)); String res = String.join("", arr); return res; }}
0
abhishek0908021 week ago
static bool comp(string &a,string &b)
{
if(a+b>b+a)
return 1;
else return 0;
}
string printLargest(vector<string> &arr) {
vector<int>temp;
string ans;
sort(arr.begin(),arr.end(),comp);
for(auto it:arr)
ans+=it;
return ans;
}
0
gaganwalhdzq1 week ago
string printLargest(vector<string> &arr) {
function<bool(string,string)> sort_fun= [](string a, string b)->bool{
return (a+b)>(b+a);
};
sort(arr.begin(),arr.end(),sort_fun);
string ans="";
for(int i=0;i<arr.size();i++)
ans+=arr[i];
return ans;
}
very easy approach
0
kamresh4852 weeks ago
string printLargest(vector<string> &arr) {
function<bool(string,string)> sort_fun= [](string a, string b)->bool{
return (a+b)>(b+a);
};
sort(arr.begin(),arr.end(),sort_fun);
string ans="";
for(int i=0;i<arr.size();i++)
ans+=arr[i];
return ans;
}
+5
prakashish3 weeks ago
Java Solution
class Solution {
String printLargest(String[] arr) {
// code here
String str[] = new String[arr.length];
for(int i=0;i<str.length;i++){
str[i] = String.valueOf(arr[i]);
}
Arrays.sort(str, new comp());
StringBuilder sb = new StringBuilder();
for(String s : str){
sb.append(s);
}
return sb.toString();
}
class comp implements Comparator<String> {
public int compare(String a, String b){
return (b+a).compareTo(a+b);
}
}
}
+1
surajgorai20023 weeks ago
class Solution{
public:
static bool cmp(string& a, string& b )
{
return a+b<b+a;
}
// The main function that returns the arrangement with the largest value as
// string.
// The function accepts a vector of strings
string printLargest(vector<string> &arr) {
string ans ="";
sort(arr.begin(),arr.end(),cmp);
for(int i=arr.size()-1;i>=0;i--)
{
ans+=arr[i];
}
return ans ;// code here
}
};
+1
vishaljaiswal261020003 weeks ago
C++ solution
string printLargest(vector<string> &arr) {
// code here
sort(arr.begin(),arr.end(),[](string a,string b){
return a+b>b+a;});// this gives maximum to minimum comparison using lambda expression
string ans;
for(string s:arr){
ans+=s;
}
return ans;
}
0
mrutyunjaykumarmkd3 weeks ago
//java code in few lines
class Solution { String printLargest(String[] arr) { // code h String s=""; Arrays.sort(arr,(a,b)->(b+a).compareTo(a+b)); for(int i=0;i<arr.length;i++){ s+=arr[i]; } return s; }}
+1
sanketsupekar4 weeks ago
Java Solution 7.71 Sec
class Solution {
class sortByChar implements java.util.Comparator<String>
{
public int compare(String a, String b)
{
String x = a+b;
String y = b+a;
return y.compareTo(x);
}
}
String printLargest(String[] arr)
{
Arrays.sort(arr, new sortByChar());
String res = "";
for(int i=0;i<arr.length;i++)
res += arr[i];
return res;
}
}
0
premkodavath984 weeks ago
/*step-1
convert the arrays in to String
step-2
Sort the arrays and then pass two custom strings to compare
step-3
using string builder
simple JAVA CODE*/
int n=arr.length;
String[] s=new String[n];
for(int i=0; i<n; i++)
s[i]=String.valueOf(arr[i]);
Arrays.sort(s, (a,b)→(b+a).compareTo(a+b));
StrungBuilder sb= new StringBuilder();
for(String str : s)
sb.append(str);
String result= sb.toString();
return result;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints. | [
{
"code": null,
"e": 437,
"s": 238,
"text": "Given a list of non negative integers, arrange them in such a manner that they form the largest number possible.The result is going to be very large, hence return the result in the form of a string."
},
{
"code": null,
"e": 449,
"s": 437,
"text": "\nExample 1:"
},
{
"code": null,
"e": 604,
"s": 449,
"text": "Input: \nN = 5\nArr[] = {3, 30, 34, 5, 9}\nOutput: 9534330\nExplanation: Given numbers are {3, 30, 34,\n5, 9}, the arrangement 9534330 gives the\nlargest value."
},
{
"code": null,
"e": 615,
"s": 604,
"text": "Example 2:"
},
{
"code": null,
"e": 779,
"s": 615,
"text": "Input: \nN = 4\nArr[] = {54, 546, 548, 60}\nOutput: 6054854654\nExplanation: Given numbers are {54, 546,\n548, 60}, the arrangement 6054854654 \ngives the largest value."
},
{
"code": null,
"e": 1055,
"s": 779,
"text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function printLargest() which takes the array of strings arr[] as parameter and returns a string denoting the answer.\n\nExpected Time Complexity: O(NlogN)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1155,
"s": 1055,
"text": "\nConstraints:\n1 ≤ N ≤ 105\n0 ≤ Arr[i] ≤ 1018\nSum of all the elements of the array is greater than 0."
},
{
"code": null,
"e": 1158,
"s": 1155,
"text": "+1"
},
{
"code": null,
"e": 1185,
"s": 1158,
"text": "prateeklucifer262 days ago"
},
{
"code": null,
"e": 1214,
"s": 1185,
"text": "EASIEST AND SHORT JAVA CODE."
},
{
"code": null,
"e": 1411,
"s": 1214,
"text": "class Solution { String printLargest(String[] arr) { // code here Arrays.sort(arr, (s1,s2)->(s2+s1).compareTo(s1+s2)); String res = String.join(\"\", arr); return res; }}"
},
{
"code": null,
"e": 1413,
"s": 1411,
"text": "0"
},
{
"code": null,
"e": 1438,
"s": 1413,
"text": "abhishek0908021 week ago"
},
{
"code": null,
"e": 1476,
"s": 1438,
"text": "static bool comp(string &a,string &b)"
},
{
"code": null,
"e": 1482,
"s": 1476,
"text": " {"
},
{
"code": null,
"e": 1502,
"s": 1482,
"text": " if(a+b>b+a)"
},
{
"code": null,
"e": 1521,
"s": 1502,
"text": " return 1; "
},
{
"code": null,
"e": 1544,
"s": 1521,
"text": " else return 0;"
},
{
"code": null,
"e": 1550,
"s": 1544,
"text": " }"
},
{
"code": null,
"e": 1597,
"s": 1550,
"text": " string printLargest(vector<string> &arr) {"
},
{
"code": null,
"e": 1622,
"s": 1597,
"text": " vector<int>temp;"
},
{
"code": null,
"e": 1643,
"s": 1622,
"text": " string ans; "
},
{
"code": null,
"e": 1685,
"s": 1643,
"text": " sort(arr.begin(),arr.end(),comp);"
},
{
"code": null,
"e": 1710,
"s": 1685,
"text": " for(auto it:arr)"
},
{
"code": null,
"e": 1728,
"s": 1710,
"text": " ans+=it; "
},
{
"code": null,
"e": 1748,
"s": 1728,
"text": " return ans;"
},
{
"code": null,
"e": 1754,
"s": 1748,
"text": " }"
},
{
"code": null,
"e": 1756,
"s": 1754,
"text": "0"
},
{
"code": null,
"e": 1779,
"s": 1756,
"text": "gaganwalhdzq1 week ago"
},
{
"code": null,
"e": 2088,
"s": 1779,
"text": "string printLargest(vector<string> &arr) {\n\t function<bool(string,string)> sort_fun= [](string a, string b)->bool{\n\t return (a+b)>(b+a);\n\t };\n\t sort(arr.begin(),arr.end(),sort_fun);\n\t string ans=\"\";\n\t for(int i=0;i<arr.size();i++)\n\t ans+=arr[i];\n\t return ans; \n\t}\n\tvery easy approach"
},
{
"code": null,
"e": 2090,
"s": 2088,
"text": "0"
},
{
"code": null,
"e": 2112,
"s": 2090,
"text": "kamresh4852 weeks ago"
},
{
"code": null,
"e": 2401,
"s": 2112,
"text": "string printLargest(vector<string> &arr) {\n\t function<bool(string,string)> sort_fun= [](string a, string b)->bool{\n\t return (a+b)>(b+a);\n\t };\n\t sort(arr.begin(),arr.end(),sort_fun);\n\t string ans=\"\";\n\t for(int i=0;i<arr.size();i++)\n\t ans+=arr[i];\n\t return ans; \n\t}"
},
{
"code": null,
"e": 2404,
"s": 2401,
"text": "+5"
},
{
"code": null,
"e": 2426,
"s": 2404,
"text": "prakashish3 weeks ago"
},
{
"code": null,
"e": 2440,
"s": 2426,
"text": "Java Solution"
},
{
"code": null,
"e": 3002,
"s": 2442,
"text": "class Solution {\n String printLargest(String[] arr) {\n // code here\n String str[] = new String[arr.length];\n for(int i=0;i<str.length;i++){\n str[i] = String.valueOf(arr[i]);\n }\n Arrays.sort(str, new comp());\n StringBuilder sb = new StringBuilder();\n for(String s : str){\n sb.append(s);\n }\n return sb.toString();\n }\n class comp implements Comparator<String> {\n public int compare(String a, String b){\n return (b+a).compareTo(a+b);\n }\n }\n}"
},
{
"code": null,
"e": 3005,
"s": 3002,
"text": "+1"
},
{
"code": null,
"e": 3031,
"s": 3005,
"text": "surajgorai20023 weeks ago"
},
{
"code": null,
"e": 3450,
"s": 3031,
"text": "class Solution{\npublic:\nstatic bool cmp(string& a, string& b )\n{\n return a+b<b+a;\n}\n\t// The main function that returns the arrangement with the largest value as\n\t// string.\n\t// The function accepts a vector of strings\n\tstring printLargest(vector<string> &arr) {\n\t string ans =\"\";\n\t sort(arr.begin(),arr.end(),cmp);\n\t for(int i=arr.size()-1;i>=0;i--)\n\t {\n\t ans+=arr[i];\n\t }\n\t return ans ;// code here\n\t}\n};"
},
{
"code": null,
"e": 3453,
"s": 3450,
"text": "+1"
},
{
"code": null,
"e": 3486,
"s": 3453,
"text": "vishaljaiswal261020003 weeks ago"
},
{
"code": null,
"e": 3499,
"s": 3486,
"text": "C++ solution"
},
{
"code": null,
"e": 3825,
"s": 3499,
"text": "string printLargest(vector<string> &arr) {\n\t // code here\n\t sort(arr.begin(),arr.end(),[](string a,string b){\n\t return a+b>b+a;});// this gives maximum to minimum comparison using lambda expression\n\t string ans;\n\t \n\t for(string s:arr){\n\t ans+=s;\n\t }\n\t return ans;\n\t}"
},
{
"code": null,
"e": 3827,
"s": 3825,
"text": "0"
},
{
"code": null,
"e": 3857,
"s": 3827,
"text": "mrutyunjaykumarmkd3 weeks ago"
},
{
"code": null,
"e": 3882,
"s": 3857,
"text": "//java code in few lines"
},
{
"code": null,
"e": 4111,
"s": 3882,
"text": "class Solution { String printLargest(String[] arr) { // code h String s=\"\"; Arrays.sort(arr,(a,b)->(b+a).compareTo(a+b)); for(int i=0;i<arr.length;i++){ s+=arr[i]; } return s; }}"
},
{
"code": null,
"e": 4114,
"s": 4111,
"text": "+1"
},
{
"code": null,
"e": 4139,
"s": 4114,
"text": "sanketsupekar4 weeks ago"
},
{
"code": null,
"e": 4162,
"s": 4139,
"text": "Java Solution 7.71 Sec"
},
{
"code": null,
"e": 4628,
"s": 4162,
"text": "class Solution {\n \n class sortByChar implements java.util.Comparator<String>\n {\n public int compare(String a, String b)\n {\n String x = a+b; \n String y = b+a;\n return y.compareTo(x);\n }\n }\n \n String printLargest(String[] arr) \n {\n Arrays.sort(arr, new sortByChar());\n String res = \"\";\n for(int i=0;i<arr.length;i++)\n res += arr[i];\n return res;\n }\n \n}"
},
{
"code": null,
"e": 4630,
"s": 4628,
"text": "0"
},
{
"code": null,
"e": 4656,
"s": 4630,
"text": "premkodavath984 weeks ago"
},
{
"code": null,
"e": 4665,
"s": 4656,
"text": "/*step-1"
},
{
"code": null,
"e": 4697,
"s": 4665,
"text": "convert the arrays in to String"
},
{
"code": null,
"e": 4704,
"s": 4697,
"text": "step-2"
},
{
"code": null,
"e": 4764,
"s": 4704,
"text": "Sort the arrays and then pass two custom strings to compare"
},
{
"code": null,
"e": 4771,
"s": 4764,
"text": "step-3"
},
{
"code": null,
"e": 4793,
"s": 4771,
"text": "using string builder "
},
{
"code": null,
"e": 4813,
"s": 4793,
"text": " simple JAVA CODE*/"
},
{
"code": null,
"e": 4843,
"s": 4813,
"text": " int n=arr.length;"
},
{
"code": null,
"e": 4881,
"s": 4843,
"text": " String[] s=new String[n];"
},
{
"code": null,
"e": 4916,
"s": 4881,
"text": " for(int i=0; i<n; i++)"
},
{
"code": null,
"e": 4962,
"s": 4916,
"text": " s[i]=String.valueOf(arr[i]);"
},
{
"code": null,
"e": 5024,
"s": 4962,
"text": " Arrays.sort(s, (a,b)→(b+a).compareTo(a+b));"
},
{
"code": null,
"e": 5105,
"s": 5046,
"text": " StrungBuilder sb= new StringBuilder();"
},
{
"code": null,
"e": 5153,
"s": 5105,
"text": " for(String str : s)"
},
{
"code": null,
"e": 5198,
"s": 5153,
"text": " sb.append(str);"
},
{
"code": null,
"e": 5255,
"s": 5206,
"text": " String result= sb.toString();"
},
{
"code": null,
"e": 5290,
"s": 5255,
"text": " return result;"
},
{
"code": null,
"e": 5438,
"s": 5292,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5474,
"s": 5438,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5484,
"s": 5474,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5494,
"s": 5484,
"text": "\nContest\n"
},
{
"code": null,
"e": 5557,
"s": 5494,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5742,
"s": 5557,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6026,
"s": 5742,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 6172,
"s": 6026,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 6249,
"s": 6172,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 6290,
"s": 6249,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 6318,
"s": 6290,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 6389,
"s": 6318,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 6576,
"s": 6389,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
]
|
Get contents of entire page using Selenium | 25 Feb, 2021
In this article, we will discuss ways to get the contents of the entire page using Selenium. There can broadly be two methods for the same. Let’s discuss them in detail.
For extracting the visible text from the entire page, we can use the find_element_by_* methods which help us find or locate the elements on the page. Then, We will use the text method which helps to retrieve the text from a specific web element.
Approach
Import module
Instantiate driver
Get content of the page
Display contents scraped
Close driver
Syntax:
driver.find_element_by_class_xpath(“/html/body”).text
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_xpath
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector
find_element_by_id
find_element_by_name
We can use these above methods for finding or locating elements on a entire page. Most commonly used method is find_element_by_xpath which helps us to easily locate any elements. We will use appropriate methods as per our requirement.
Program:
Python3
# importing the modulesfrom selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager # using webdriver for chrome browserdriver = webdriver.Chrome(ChromeDriverManager().install()) # using target urldriver.get( "https://www.geeksforgeeks.org/competitive-programming-a-complete-guide/") # printing the content of entire pageprint(driver.find_element_by_xpath("/html/body").text) # closing the driverdriver.close()
Output:
There is one another method available for achieving our desired output. This one line will retrieve the entire text of the web page. Once we get the extracted data, with the help of file system, we will store the result inside the result.html file.
Approach:
Import module
Instantiate webdriver
Get contents from the URL
Open a file
Save contents to a file
Close file
Close driver
Syntax:
driver.page_source
Program:
Python3
# Importing important libraryfrom selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager # using chrome browserdriver = webdriver.Chrome(ChromeDriverManager().install()) # Target urldriver.get( "https://www.geeksforgeeks.org/competitive-programming-a-complete-guide/") # Storing the page source in page variablepage = driver.page_source.encode('utf-8')# print(page) # open result.htmlfile_ = open('result.html', 'wb') # Write the entire page content in result.htmlfile_.write(page) # Closing the filefile_.close() # Closing the driverdriver.close()
Output:
Click here to download the output file of above program.
Picked
Python Selenium-Exercises
Python-selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 198,
"s": 28,
"text": "In this article, we will discuss ways to get the contents of the entire page using Selenium. There can broadly be two methods for the same. Let’s discuss them in detail."
},
{
"code": null,
"e": 444,
"s": 198,
"text": "For extracting the visible text from the entire page, we can use the find_element_by_* methods which help us find or locate the elements on the page. Then, We will use the text method which helps to retrieve the text from a specific web element."
},
{
"code": null,
"e": 453,
"s": 444,
"text": "Approach"
},
{
"code": null,
"e": 467,
"s": 453,
"text": "Import module"
},
{
"code": null,
"e": 486,
"s": 467,
"text": "Instantiate driver"
},
{
"code": null,
"e": 510,
"s": 486,
"text": "Get content of the page"
},
{
"code": null,
"e": 535,
"s": 510,
"text": "Display contents scraped"
},
{
"code": null,
"e": 548,
"s": 535,
"text": "Close driver"
},
{
"code": null,
"e": 556,
"s": 548,
"text": "Syntax:"
},
{
"code": null,
"e": 610,
"s": 556,
"text": "driver.find_element_by_class_xpath(“/html/body”).text"
},
{
"code": null,
"e": 636,
"s": 610,
"text": "find_element_by_link_text"
},
{
"code": null,
"e": 670,
"s": 636,
"text": "find_element_by_partial_link_text"
},
{
"code": null,
"e": 692,
"s": 670,
"text": "find_element_by_xpath"
},
{
"code": null,
"e": 717,
"s": 692,
"text": "find_element_by_tag_name"
},
{
"code": null,
"e": 744,
"s": 717,
"text": "find_element_by_class_name"
},
{
"code": null,
"e": 773,
"s": 744,
"text": "find_element_by_css_selector"
},
{
"code": null,
"e": 792,
"s": 773,
"text": "find_element_by_id"
},
{
"code": null,
"e": 813,
"s": 792,
"text": "find_element_by_name"
},
{
"code": null,
"e": 1048,
"s": 813,
"text": "We can use these above methods for finding or locating elements on a entire page. Most commonly used method is find_element_by_xpath which helps us to easily locate any elements. We will use appropriate methods as per our requirement."
},
{
"code": null,
"e": 1057,
"s": 1048,
"text": "Program:"
},
{
"code": null,
"e": 1065,
"s": 1057,
"text": "Python3"
},
{
"code": "# importing the modulesfrom selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager # using webdriver for chrome browserdriver = webdriver.Chrome(ChromeDriverManager().install()) # using target urldriver.get( \"https://www.geeksforgeeks.org/competitive-programming-a-complete-guide/\") # printing the content of entire pageprint(driver.find_element_by_xpath(\"/html/body\").text) # closing the driverdriver.close()",
"e": 1509,
"s": 1065,
"text": null
},
{
"code": null,
"e": 1517,
"s": 1509,
"text": "Output:"
},
{
"code": null,
"e": 1766,
"s": 1517,
"text": "There is one another method available for achieving our desired output. This one line will retrieve the entire text of the web page. Once we get the extracted data, with the help of file system, we will store the result inside the result.html file."
},
{
"code": null,
"e": 1776,
"s": 1766,
"text": "Approach:"
},
{
"code": null,
"e": 1790,
"s": 1776,
"text": "Import module"
},
{
"code": null,
"e": 1812,
"s": 1790,
"text": "Instantiate webdriver"
},
{
"code": null,
"e": 1838,
"s": 1812,
"text": "Get contents from the URL"
},
{
"code": null,
"e": 1850,
"s": 1838,
"text": "Open a file"
},
{
"code": null,
"e": 1874,
"s": 1850,
"text": "Save contents to a file"
},
{
"code": null,
"e": 1885,
"s": 1874,
"text": "Close file"
},
{
"code": null,
"e": 1898,
"s": 1885,
"text": "Close driver"
},
{
"code": null,
"e": 1906,
"s": 1898,
"text": "Syntax:"
},
{
"code": null,
"e": 1925,
"s": 1906,
"text": "driver.page_source"
},
{
"code": null,
"e": 1934,
"s": 1925,
"text": "Program:"
},
{
"code": null,
"e": 1942,
"s": 1934,
"text": "Python3"
},
{
"code": "# Importing important libraryfrom selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager # using chrome browserdriver = webdriver.Chrome(ChromeDriverManager().install()) # Target urldriver.get( \"https://www.geeksforgeeks.org/competitive-programming-a-complete-guide/\") # Storing the page source in page variablepage = driver.page_source.encode('utf-8')# print(page) # open result.htmlfile_ = open('result.html', 'wb') # Write the entire page content in result.htmlfile_.write(page) # Closing the filefile_.close() # Closing the driverdriver.close()",
"e": 2528,
"s": 1942,
"text": null
},
{
"code": null,
"e": 2536,
"s": 2528,
"text": "Output:"
},
{
"code": null,
"e": 2593,
"s": 2536,
"text": "Click here to download the output file of above program."
},
{
"code": null,
"e": 2600,
"s": 2593,
"text": "Picked"
},
{
"code": null,
"e": 2626,
"s": 2600,
"text": "Python Selenium-Exercises"
},
{
"code": null,
"e": 2642,
"s": 2626,
"text": "Python-selenium"
},
{
"code": null,
"e": 2649,
"s": 2642,
"text": "Python"
},
{
"code": null,
"e": 2747,
"s": 2649,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2779,
"s": 2747,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2806,
"s": 2779,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2827,
"s": 2806,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2850,
"s": 2827,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2906,
"s": 2850,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2937,
"s": 2906,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2979,
"s": 2937,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3021,
"s": 2979,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3060,
"s": 3021,
"text": "Python | Get unique values from a list"
}
]
|
Johnson’s algorithm for All-pairs shortest paths | Implementation | 12 Oct, 2018
Given a weighted Directed Graph where the weights may be negative, find the shortest path between every pair of vertices in the Graph using Johnson’s Algorithm.
The detailed explanation of Johnson’s algorithm has already been discussed in the previous post.
Refer: Johnson’s algorithm for All-pairs shortest paths.
This post focusses on the implementation of Johnson’s Algorithm.
Algorithm:
Let the given graph be G. Add a new vertex s to the graph, add edges from new vertex to all vertices of G. Let the modified graph be G’.Run Bellman-Ford algorithm on G’ with s as source. Let the distances calculated by Bellman-Ford be h[0], h[1], .. h[V-1]. If we find a negative weight cycle, then return. Note that the negative weight cycle cannot be created by new vertex s as there is no edge to s. All edges are from s.Reweight the edges of original graph. For each edge (u, v), assign the new weight as “original weight + h[u] – h[v]”.Remove the added vertex s and run Dijkstra’s algorithm for every vertex.
Let the given graph be G. Add a new vertex s to the graph, add edges from new vertex to all vertices of G. Let the modified graph be G’.
Run Bellman-Ford algorithm on G’ with s as source. Let the distances calculated by Bellman-Ford be h[0], h[1], .. h[V-1]. If we find a negative weight cycle, then return. Note that the negative weight cycle cannot be created by new vertex s as there is no edge to s. All edges are from s.
Reweight the edges of original graph. For each edge (u, v), assign the new weight as “original weight + h[u] – h[v]”.
Remove the added vertex s and run Dijkstra’s algorithm for every vertex.
Example:Let us consider the following graph.
We add a source s and add edges from s to all vertices of the original graph. In the following diagram s is 4.
We calculate the shortest distances from 4 to all other vertices using Bellman-Ford algorithm. The shortest distances from 4 to 0, 1, 2 and 3 are 0, -5, -1 and 0 respectively, i.e., h[] = {0, -5, -1, 0}. Once we get these distances, we remove the source vertex 4 and reweight the edges using following formula. w(u, v) = w(u, v) + h[u] – h[v].
Since all weights are positive now, we can run Dijkstra’s shortest path algorithm for every vertex as source.
Below is the implementation of the above approach
# Implementation of Johnson's algorithm in Python3 # Import function to initialize the dictionaryfrom collections import defaultdictMAX_INT = float('Inf') # Returns the vertex with minimum # distance from the sourcedef minDistance(dist, visited): (minimum, minVertex) = (MAX_INT, 0) for vertex in range(len(dist)): if minimum > dist[vertex] and visited[vertex] == False: (minimum, minVertex) = (dist[vertex], vertex) return minVertex # Dijkstra Algorithm for Modified # Graph (removing negative weights)def Dijkstra(graph, modifiedGraph, src): # Number of vertices in the graph num_vertices = len(graph) # Dictionary to check if given vertex is # already included in the shortest path tree sptSet = defaultdict(lambda : False) # Shortest distance of all vertices from the source dist = [MAX_INT] * num_vertices dist[src] = 0 for count in range(num_vertices): # The current vertex which is at min Distance # from the source and not yet included in the # shortest path tree curVertex = minDistance(dist, sptSet) sptSet[curVertex] = True for vertex in range(num_vertices): if ((sptSet[vertex] == False) and (dist[vertex] > (dist[curVertex] + modifiedGraph[curVertex][vertex])) and (graph[curVertex][vertex] != 0)): dist[vertex] = (dist[curVertex] + modifiedGraph[curVertex][vertex]); # Print the Shortest distance from the source for vertex in range(num_vertices): print ('Vertex ' + str(vertex) + ': ' + str(dist[vertex])) # Function to calculate shortest distances from source# to all other vertices using Bellman-Ford algorithmdef BellmanFord(edges, graph, num_vertices): # Add a source s and calculate its min # distance from every other node dist = [MAX_INT] * (num_vertices + 1) dist[num_vertices] = 0 for i in range(num_vertices): edges.append([num_vertices, i, 0]) for i in range(num_vertices): for (src, des, weight) in edges: if((dist[src] != MAX_INT) and (dist[src] + weight < dist[des])): dist[des] = dist[src] + weight # Don't send the value for the source added return dist[0:num_vertices] # Function to implement Johnson Algorithmdef JohnsonAlgorithm(graph): edges = [] # Create a list of edges for Bellman-Ford Algorithm for i in range(len(graph)): for j in range(len(graph[i])): if graph[i][j] != 0: edges.append([i, j, graph[i][j]]) # Weights used to modify the original weights modifyWeights = BellmanFord(edges, graph, len(graph)) modifiedGraph = [[0 for x in range(len(graph))] for y in range(len(graph))] # Modify the weights to get rid of negative weights for i in range(len(graph)): for j in range(len(graph[i])): if graph[i][j] != 0: modifiedGraph[i][j] = (graph[i][j] + modifyWeights[i] - modifyWeights[j]); print ('Modified Graph: ' + str(modifiedGraph)) # Run Dijkstra for every vertex as source one by one for src in range(len(graph)): print ('\nShortest Distance with vertex ' + str(src) + ' as the source:\n') Dijkstra(graph, modifiedGraph, src) # Driver Codegraph = [[0, -5, 2, 3], [0, 0, 4, 0], [0, 0, 0, 1], [0, 0, 0, 0]] JohnsonAlgorithm(graph)
Modified Graph: [[0, 0, 3, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Shortest Distance with vertex 0 as the source:
Vertex 0: 0
Vertex 1: 0
Vertex 2: 0
Vertex 3: 0
Shortest Distance with vertex 1 as the source:
Vertex 0: inf
Vertex 1: 0
Vertex 2: 0
Vertex 3: 0
Shortest Distance with vertex 2 as the source:
Vertex 0: inf
Vertex 1: inf
Vertex 2: 0
Vertex 3: 0
Shortest Distance with vertex 3 as the source:
Vertex 0: inf
Vertex 1: inf
Vertex 2: inf
Vertex 3: 0
Time Complexity: The time complexity of the above algorithm is as Dijkstra’s Algorithm takes for adjacency matrix. Note that the above algorithm can be made more efficient by using adjacency list instead of the adjacency matrix to represent the Graph.
Algorithms-Graph Shortest Paths Quiz
Graph Shortest Paths Quiz
Picked
Technical Scripter 2018
Data Structures
Graph
Technical Scripter
Data Structures
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advantages and Disadvantages of Linked List
Data Structures | Array | Question 2
Amazon Interview Experience for SDE-II
Data Structures | Queue | Question 2
Data Structures | Hash | Question 5
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Find if there is a path between two vertices in a directed graph | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Oct, 2018"
},
{
"code": null,
"e": 215,
"s": 54,
"text": "Given a weighted Directed Graph where the weights may be negative, find the shortest path between every pair of vertices in the Graph using Johnson’s Algorithm."
},
{
"code": null,
"e": 312,
"s": 215,
"text": "The detailed explanation of Johnson’s algorithm has already been discussed in the previous post."
},
{
"code": null,
"e": 369,
"s": 312,
"text": "Refer: Johnson’s algorithm for All-pairs shortest paths."
},
{
"code": null,
"e": 434,
"s": 369,
"text": "This post focusses on the implementation of Johnson’s Algorithm."
},
{
"code": null,
"e": 445,
"s": 434,
"text": "Algorithm:"
},
{
"code": null,
"e": 1059,
"s": 445,
"text": "Let the given graph be G. Add a new vertex s to the graph, add edges from new vertex to all vertices of G. Let the modified graph be G’.Run Bellman-Ford algorithm on G’ with s as source. Let the distances calculated by Bellman-Ford be h[0], h[1], .. h[V-1]. If we find a negative weight cycle, then return. Note that the negative weight cycle cannot be created by new vertex s as there is no edge to s. All edges are from s.Reweight the edges of original graph. For each edge (u, v), assign the new weight as “original weight + h[u] – h[v]”.Remove the added vertex s and run Dijkstra’s algorithm for every vertex."
},
{
"code": null,
"e": 1196,
"s": 1059,
"text": "Let the given graph be G. Add a new vertex s to the graph, add edges from new vertex to all vertices of G. Let the modified graph be G’."
},
{
"code": null,
"e": 1485,
"s": 1196,
"text": "Run Bellman-Ford algorithm on G’ with s as source. Let the distances calculated by Bellman-Ford be h[0], h[1], .. h[V-1]. If we find a negative weight cycle, then return. Note that the negative weight cycle cannot be created by new vertex s as there is no edge to s. All edges are from s."
},
{
"code": null,
"e": 1603,
"s": 1485,
"text": "Reweight the edges of original graph. For each edge (u, v), assign the new weight as “original weight + h[u] – h[v]”."
},
{
"code": null,
"e": 1676,
"s": 1603,
"text": "Remove the added vertex s and run Dijkstra’s algorithm for every vertex."
},
{
"code": null,
"e": 1721,
"s": 1676,
"text": "Example:Let us consider the following graph."
},
{
"code": null,
"e": 1832,
"s": 1721,
"text": "We add a source s and add edges from s to all vertices of the original graph. In the following diagram s is 4."
},
{
"code": null,
"e": 2176,
"s": 1832,
"text": "We calculate the shortest distances from 4 to all other vertices using Bellman-Ford algorithm. The shortest distances from 4 to 0, 1, 2 and 3 are 0, -5, -1 and 0 respectively, i.e., h[] = {0, -5, -1, 0}. Once we get these distances, we remove the source vertex 4 and reweight the edges using following formula. w(u, v) = w(u, v) + h[u] – h[v]."
},
{
"code": null,
"e": 2286,
"s": 2176,
"text": "Since all weights are positive now, we can run Dijkstra’s shortest path algorithm for every vertex as source."
},
{
"code": null,
"e": 2336,
"s": 2286,
"text": "Below is the implementation of the above approach"
},
{
"code": "# Implementation of Johnson's algorithm in Python3 # Import function to initialize the dictionaryfrom collections import defaultdictMAX_INT = float('Inf') # Returns the vertex with minimum # distance from the sourcedef minDistance(dist, visited): (minimum, minVertex) = (MAX_INT, 0) for vertex in range(len(dist)): if minimum > dist[vertex] and visited[vertex] == False: (minimum, minVertex) = (dist[vertex], vertex) return minVertex # Dijkstra Algorithm for Modified # Graph (removing negative weights)def Dijkstra(graph, modifiedGraph, src): # Number of vertices in the graph num_vertices = len(graph) # Dictionary to check if given vertex is # already included in the shortest path tree sptSet = defaultdict(lambda : False) # Shortest distance of all vertices from the source dist = [MAX_INT] * num_vertices dist[src] = 0 for count in range(num_vertices): # The current vertex which is at min Distance # from the source and not yet included in the # shortest path tree curVertex = minDistance(dist, sptSet) sptSet[curVertex] = True for vertex in range(num_vertices): if ((sptSet[vertex] == False) and (dist[vertex] > (dist[curVertex] + modifiedGraph[curVertex][vertex])) and (graph[curVertex][vertex] != 0)): dist[vertex] = (dist[curVertex] + modifiedGraph[curVertex][vertex]); # Print the Shortest distance from the source for vertex in range(num_vertices): print ('Vertex ' + str(vertex) + ': ' + str(dist[vertex])) # Function to calculate shortest distances from source# to all other vertices using Bellman-Ford algorithmdef BellmanFord(edges, graph, num_vertices): # Add a source s and calculate its min # distance from every other node dist = [MAX_INT] * (num_vertices + 1) dist[num_vertices] = 0 for i in range(num_vertices): edges.append([num_vertices, i, 0]) for i in range(num_vertices): for (src, des, weight) in edges: if((dist[src] != MAX_INT) and (dist[src] + weight < dist[des])): dist[des] = dist[src] + weight # Don't send the value for the source added return dist[0:num_vertices] # Function to implement Johnson Algorithmdef JohnsonAlgorithm(graph): edges = [] # Create a list of edges for Bellman-Ford Algorithm for i in range(len(graph)): for j in range(len(graph[i])): if graph[i][j] != 0: edges.append([i, j, graph[i][j]]) # Weights used to modify the original weights modifyWeights = BellmanFord(edges, graph, len(graph)) modifiedGraph = [[0 for x in range(len(graph))] for y in range(len(graph))] # Modify the weights to get rid of negative weights for i in range(len(graph)): for j in range(len(graph[i])): if graph[i][j] != 0: modifiedGraph[i][j] = (graph[i][j] + modifyWeights[i] - modifyWeights[j]); print ('Modified Graph: ' + str(modifiedGraph)) # Run Dijkstra for every vertex as source one by one for src in range(len(graph)): print ('\\nShortest Distance with vertex ' + str(src) + ' as the source:\\n') Dijkstra(graph, modifiedGraph, src) # Driver Codegraph = [[0, -5, 2, 3], [0, 0, 4, 0], [0, 0, 0, 1], [0, 0, 0, 0]] JohnsonAlgorithm(graph)",
"e": 5891,
"s": 2336,
"text": null
},
{
"code": null,
"e": 6365,
"s": 5891,
"text": "Modified Graph: [[0, 0, 3, 3], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\n\nShortest Distance with vertex 0 as the source:\n\nVertex 0: 0\nVertex 1: 0\nVertex 2: 0\nVertex 3: 0\n\nShortest Distance with vertex 1 as the source:\n\nVertex 0: inf\nVertex 1: 0\nVertex 2: 0\nVertex 3: 0\n\nShortest Distance with vertex 2 as the source:\n\nVertex 0: inf\nVertex 1: inf\nVertex 2: 0\nVertex 3: 0\n\nShortest Distance with vertex 3 as the source:\n\nVertex 0: inf\nVertex 1: inf\nVertex 2: inf\nVertex 3: 0\n"
},
{
"code": null,
"e": 6619,
"s": 6365,
"text": "Time Complexity: The time complexity of the above algorithm is as Dijkstra’s Algorithm takes for adjacency matrix. Note that the above algorithm can be made more efficient by using adjacency list instead of the adjacency matrix to represent the Graph."
},
{
"code": null,
"e": 6656,
"s": 6619,
"text": "Algorithms-Graph Shortest Paths Quiz"
},
{
"code": null,
"e": 6682,
"s": 6656,
"text": "Graph Shortest Paths Quiz"
},
{
"code": null,
"e": 6689,
"s": 6682,
"text": "Picked"
},
{
"code": null,
"e": 6713,
"s": 6689,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 6729,
"s": 6713,
"text": "Data Structures"
},
{
"code": null,
"e": 6735,
"s": 6729,
"text": "Graph"
},
{
"code": null,
"e": 6754,
"s": 6735,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6770,
"s": 6754,
"text": "Data Structures"
},
{
"code": null,
"e": 6776,
"s": 6770,
"text": "Graph"
},
{
"code": null,
"e": 6874,
"s": 6776,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6918,
"s": 6874,
"text": "Advantages and Disadvantages of Linked List"
},
{
"code": null,
"e": 6955,
"s": 6918,
"text": "Data Structures | Array | Question 2"
},
{
"code": null,
"e": 6994,
"s": 6955,
"text": "Amazon Interview Experience for SDE-II"
},
{
"code": null,
"e": 7031,
"s": 6994,
"text": "Data Structures | Queue | Question 2"
},
{
"code": null,
"e": 7067,
"s": 7031,
"text": "Data Structures | Hash | Question 5"
},
{
"code": null,
"e": 7107,
"s": 7067,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 7145,
"s": 7107,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 7196,
"s": 7145,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 7247,
"s": 7196,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
}
]
|
Program to convert given number of days in terms of Years, Weeks and Days | 30 Jun, 2021
Given number of days, convert it in terms of Years, Week and Days.
Examples :
Input : 30
Output : years = 0
week = 4
days = 2
Input : 20
Output : years = 0
week = 2
days = 6
Approach :
Number of years will be the quotient when number of days will be divided by 365 i.e days / 365 = years.Number of weeks will be the result of (Number_of_days % 365) / 7.Number of days will be the result of (Number_of_days % 365) % 7.
Number of years will be the quotient when number of days will be divided by 365 i.e days / 365 = years.
Number of weeks will be the result of (Number_of_days % 365) / 7.
Number of days will be the result of (Number_of_days % 365) % 7.
Below is the program implementing above approach:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to convert given// number of days in terms of// Years, Weeks and Days#include <bits/stdc++.h>using namespace std; #define DAYS_IN_WEEK 7 // Function to find year,// week, daysvoid find(int number_of_days){ int year, week, days; // Assume that years is // of 365 days year = number_of_days / 365; week = (number_of_days % 365) / DAYS_IN_WEEK; days = (number_of_days % 365) % DAYS_IN_WEEK; cout << "years = " << year; cout << "\nweeks = " << week; cout << "\ndays = " << days; } // Driver Codeint main(){ int number_of_days = 200; find(number_of_days); return 0;} // This code is contributed by shivanisinghss2110
// C program to convert given// number of days in terms of// Years, Weeks and Days#include <stdio.h>#define DAYS_IN_WEEK 7 // Function to find year,// week, daysvoid find(int number_of_days){ int year, week, days; // Assume that years is // of 365 days year = number_of_days / 365; week = (number_of_days % 365) / DAYS_IN_WEEK; days = (number_of_days % 365) % DAYS_IN_WEEK; printf("years = %d",year); printf("\nweeks = %d", week); printf("\ndays = %d ",days); } // Driver Codeint main(){ int number_of_days = 200; find(number_of_days); return 0;}
// Java program to convert given// number of days in terms of// Years, Weeks and Daysclass GFG{ static final int DAYS_IN_WEEK = 7; // Function to find year, week, days static void find(int number_of_days) { int year, week, days; // Assume that years // is of 365 days year = number_of_days / 365; week = (number_of_days % 365) / DAYS_IN_WEEK; days = (number_of_days % 365) % DAYS_IN_WEEK; System.out.println("years = " + year); System.out.println("weeks = " + week); System.out.println("days = " + days); } // Driver Code public static void main(String[] args) { int number_of_days = 200; find(number_of_days); }} // This code is contributed by Azkia Anam.
# Python3 code to convert given# number of days in terms of# Years, Weeks and Days DAYS_IN_WEEK = 7 # Function to find# year, week, daysdef find( number_of_days ): # Assume that years is # of 365 days year = int(number_of_days / 365) week = int((number_of_days % 365) / DAYS_IN_WEEK) days = (number_of_days % 365) % DAYS_IN_WEEK print("years = ",year, "\nweeks = ",week, "\ndays = ",days) # Driver Codenumber_of_days = 200find(number_of_days) # This code contributed#by "Sharad_Bhardwaj"
// C# program to convert given// number of days in terms of// Years, Weeks and Daysusing System; class GFG{ static int DAYS_IN_WEEK = 7; // Function to find // year, week, days static void find(int number_of_days) { int year, week, days; // Assume that years // is of 365 days year = number_of_days / 365; week = (number_of_days % 365) / DAYS_IN_WEEK; days = (number_of_days % 365) % DAYS_IN_WEEK; Console.WriteLine("years = " + year); Console.WriteLine("weeks = " + week); Console.WriteLine("days = " + days); } // Driver Code public static void Main() { int number_of_days = 200; find(number_of_days); }} // This code is contributed by vt_m.
<?php// PHP program to convert// given number of days in// terms of Years, Weeks and Days$DAYS_IN_WEEK = 7; // Function to find// year, week, daysfunction find($number_of_days){ global $DAYS_IN_WEEK; $year; $week; $days; // Assume that years // is of 365 days $year = (int)($number_of_days / 365); $week = (int)(($number_of_days % 365) / $DAYS_IN_WEEK); $days = ($number_of_days % 365) % $DAYS_IN_WEEK; echo("years = " . $year . "\nweeks = " . $week . "\ndays = " . $days);} // Driver Code$number_of_days = 200;find($number_of_days); // This code is contributed by Ajit.?>
<script> // JavaScript program to convert given// number of days in terms of// Years, Weeks and Days var DAYS_IN_WEEK = 7; // Function to find year, week, days function find(number_of_days) { var year, week, days; // Assume that years // is of 365 days year = parseInt(number_of_days / 365); week = parseInt((number_of_days % 365) / DAYS_IN_WEEK); days = (number_of_days % 365) % DAYS_IN_WEEK; document.write("years = " + year + "<br/>"); document.write("weeks = " + week + "<br/>"); document.write("days = " + days + "<br/>"); } // Driver Code var number_of_days = 200; find(number_of_days); // This code contributed by Rajput-Ji </script>
Output :
years = 0
weeks = 28
days = 4
jit_t
Rajput-Ji
shivanisinghss2110
date-time-program
C Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Difference between break and continue statement in C
C Hello World Program
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 119,
"s": 52,
"text": "Given number of days, convert it in terms of Years, Week and Days."
},
{
"code": null,
"e": 131,
"s": 119,
"text": "Examples : "
},
{
"code": null,
"e": 264,
"s": 131,
"text": "Input : 30\nOutput : years = 0\n week = 4\n days = 2\n\nInput : 20\nOutput : years = 0\n week = 2\n days = 6"
},
{
"code": null,
"e": 277,
"s": 264,
"text": "Approach : "
},
{
"code": null,
"e": 510,
"s": 277,
"text": "Number of years will be the quotient when number of days will be divided by 365 i.e days / 365 = years.Number of weeks will be the result of (Number_of_days % 365) / 7.Number of days will be the result of (Number_of_days % 365) % 7."
},
{
"code": null,
"e": 614,
"s": 510,
"text": "Number of years will be the quotient when number of days will be divided by 365 i.e days / 365 = years."
},
{
"code": null,
"e": 680,
"s": 614,
"text": "Number of weeks will be the result of (Number_of_days % 365) / 7."
},
{
"code": null,
"e": 745,
"s": 680,
"text": "Number of days will be the result of (Number_of_days % 365) % 7."
},
{
"code": null,
"e": 797,
"s": 745,
"text": "Below is the program implementing above approach: "
},
{
"code": null,
"e": 801,
"s": 797,
"text": "C++"
},
{
"code": null,
"e": 803,
"s": 801,
"text": "C"
},
{
"code": null,
"e": 808,
"s": 803,
"text": "Java"
},
{
"code": null,
"e": 816,
"s": 808,
"text": "Python3"
},
{
"code": null,
"e": 819,
"s": 816,
"text": "C#"
},
{
"code": null,
"e": 823,
"s": 819,
"text": "PHP"
},
{
"code": null,
"e": 834,
"s": 823,
"text": "Javascript"
},
{
"code": "// C++ program to convert given// number of days in terms of// Years, Weeks and Days#include <bits/stdc++.h>using namespace std; #define DAYS_IN_WEEK 7 // Function to find year,// week, daysvoid find(int number_of_days){ int year, week, days; // Assume that years is // of 365 days year = number_of_days / 365; week = (number_of_days % 365) / DAYS_IN_WEEK; days = (number_of_days % 365) % DAYS_IN_WEEK; cout << \"years = \" << year; cout << \"\\nweeks = \" << week; cout << \"\\ndays = \" << days; } // Driver Codeint main(){ int number_of_days = 200; find(number_of_days); return 0;} // This code is contributed by shivanisinghss2110",
"e": 1540,
"s": 834,
"text": null
},
{
"code": "// C program to convert given// number of days in terms of// Years, Weeks and Days#include <stdio.h>#define DAYS_IN_WEEK 7 // Function to find year,// week, daysvoid find(int number_of_days){ int year, week, days; // Assume that years is // of 365 days year = number_of_days / 365; week = (number_of_days % 365) / DAYS_IN_WEEK; days = (number_of_days % 365) % DAYS_IN_WEEK; printf(\"years = %d\",year); printf(\"\\nweeks = %d\", week); printf(\"\\ndays = %d \",days); } // Driver Codeint main(){ int number_of_days = 200; find(number_of_days); return 0;}",
"e": 2153,
"s": 1540,
"text": null
},
{
"code": "// Java program to convert given// number of days in terms of// Years, Weeks and Daysclass GFG{ static final int DAYS_IN_WEEK = 7; // Function to find year, week, days static void find(int number_of_days) { int year, week, days; // Assume that years // is of 365 days year = number_of_days / 365; week = (number_of_days % 365) / DAYS_IN_WEEK; days = (number_of_days % 365) % DAYS_IN_WEEK; System.out.println(\"years = \" + year); System.out.println(\"weeks = \" + week); System.out.println(\"days = \" + days); } // Driver Code public static void main(String[] args) { int number_of_days = 200; find(number_of_days); }} // This code is contributed by Azkia Anam.",
"e": 2972,
"s": 2153,
"text": null
},
{
"code": "# Python3 code to convert given# number of days in terms of# Years, Weeks and Days DAYS_IN_WEEK = 7 # Function to find# year, week, daysdef find( number_of_days ): # Assume that years is # of 365 days year = int(number_of_days / 365) week = int((number_of_days % 365) / DAYS_IN_WEEK) days = (number_of_days % 365) % DAYS_IN_WEEK print(\"years = \",year, \"\\nweeks = \",week, \"\\ndays = \",days) # Driver Codenumber_of_days = 200find(number_of_days) # This code contributed#by \"Sharad_Bhardwaj\"",
"e": 3521,
"s": 2972,
"text": null
},
{
"code": "// C# program to convert given// number of days in terms of// Years, Weeks and Daysusing System; class GFG{ static int DAYS_IN_WEEK = 7; // Function to find // year, week, days static void find(int number_of_days) { int year, week, days; // Assume that years // is of 365 days year = number_of_days / 365; week = (number_of_days % 365) / DAYS_IN_WEEK; days = (number_of_days % 365) % DAYS_IN_WEEK; Console.WriteLine(\"years = \" + year); Console.WriteLine(\"weeks = \" + week); Console.WriteLine(\"days = \" + days); } // Driver Code public static void Main() { int number_of_days = 200; find(number_of_days); }} // This code is contributed by vt_m.",
"e": 4426,
"s": 3521,
"text": null
},
{
"code": "<?php// PHP program to convert// given number of days in// terms of Years, Weeks and Days$DAYS_IN_WEEK = 7; // Function to find// year, week, daysfunction find($number_of_days){ global $DAYS_IN_WEEK; $year; $week; $days; // Assume that years // is of 365 days $year = (int)($number_of_days / 365); $week = (int)(($number_of_days % 365) / $DAYS_IN_WEEK); $days = ($number_of_days % 365) % $DAYS_IN_WEEK; echo(\"years = \" . $year . \"\\nweeks = \" . $week . \"\\ndays = \" . $days);} // Driver Code$number_of_days = 200;find($number_of_days); // This code is contributed by Ajit.?>",
"e": 5074,
"s": 4426,
"text": null
},
{
"code": "<script> // JavaScript program to convert given// number of days in terms of// Years, Weeks and Days var DAYS_IN_WEEK = 7; // Function to find year, week, days function find(number_of_days) { var year, week, days; // Assume that years // is of 365 days year = parseInt(number_of_days / 365); week = parseInt((number_of_days % 365) / DAYS_IN_WEEK); days = (number_of_days % 365) % DAYS_IN_WEEK; document.write(\"years = \" + year + \"<br/>\"); document.write(\"weeks = \" + week + \"<br/>\"); document.write(\"days = \" + days + \"<br/>\"); } // Driver Code var number_of_days = 200; find(number_of_days); // This code contributed by Rajput-Ji </script>",
"e": 5818,
"s": 5074,
"text": null
},
{
"code": null,
"e": 5827,
"s": 5818,
"text": "Output :"
},
{
"code": null,
"e": 5857,
"s": 5827,
"text": "years = 0\nweeks = 28\ndays = 4"
},
{
"code": null,
"e": 5865,
"s": 5859,
"text": "jit_t"
},
{
"code": null,
"e": 5875,
"s": 5865,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 5894,
"s": 5875,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 5912,
"s": 5894,
"text": "date-time-program"
},
{
"code": null,
"e": 5923,
"s": 5912,
"text": "C Programs"
},
{
"code": null,
"e": 5942,
"s": 5923,
"text": "School Programming"
},
{
"code": null,
"e": 6040,
"s": 5942,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6081,
"s": 6040,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 6112,
"s": 6081,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 6165,
"s": 6112,
"text": "Difference between break and continue statement in C"
},
{
"code": null,
"e": 6187,
"s": 6165,
"text": "C Hello World Program"
},
{
"code": null,
"e": 6277,
"s": 6187,
"text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++"
},
{
"code": null,
"e": 6295,
"s": 6277,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6320,
"s": 6295,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 6336,
"s": 6320,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 6359,
"s": 6336,
"text": "Introduction To PYTHON"
}
]
|
How to store XML data into a MySQL database using Python? | 27 Mar, 2021
In this article, we are going to store XML data into the MySQL database using python through XAMPP server. So we are taking student XML data and storing the values into the database.
XAMPP server: It is a cross-platform web server used to develop and test programs on a local server. It is developed and managed by Apache Friends and is open-source. It has an Apache HTTP Server, MariaDB, and interpreter for 11 different programming languages like Perl and PHP. XAMPP Stands for cross-platform, Apache, MySQL, PHP, and Perl. It can be easily installed from here.
MySQL connector: MySQL Connector module of Python is used to connect MySQL databases with the Python programs, it does that using the Python Database API Specification v2.0 (PEP 249). It uses the Python standard library and has no dependencies. It can be installed using the below command:
pip install mysql.connector
Start XAMPP server
Create XML file.
XML Structure:
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
We are going to use the XML module.
xml.etree.ElementTree
This is an Element Tree XML API that is used to implement a simple and efficient API for parsing and creating XML data. So we need to import this module.
Syntax:
import xml.etree.ElementTree
The XML file to be created is names vignan.xml.
XML
<?xml version="1.0"?><studentdata> <student> <name>Sravan Kumar</name> <id>7058</id> <department>IT</department> </student> <student> <name>Meghana</name> <id>7034</id> <department>IT</department> </student> <student> <name>Pranathi</name> <id>7046</id> <department>EEE</department> </student> <student> <name>Durga</name> <id>7078</id> <department>Mech</department> </student> <student> <name>Ishitha</name> <id>7093</id> <department>MBA</department> </student></studentdata>
For Python code:
Create a python file names a.py.Import required module.Establish connection.Read XML file.Retrieve data from the XML and insert it into a table in the database.Display message on successful insertion of data.
Create a python file names a.py.
Import required module.
Establish connection.
Read XML file.
Retrieve data from the XML and insert it into a table in the database.
Display message on successful insertion of data.
Python
# import xml element treeimport xml.etree.ElementTree as ET # import mysql connectorimport mysql.connector # give the connection parameters# user name is root# password is empty# server is localhost# database name is databaseconn = mysql.connector.connect(user='root', password='', host='localhost', database='database') # reading xml file , file name is vignan.xmltree = ET.parse('vignan.xml') # in our xml file student is the root for all # student data.data2 = tree.findall('student') # retrieving the data and insert into table# i value for xml data #j value printing number of # values that are storedfor i, j in zip(data2, range(1, 6)): name = i.find('name').text id = i.find('id').text department = i.find('department').text # sql query to insert data into database data = """INSERT INTO vignan(name,id,department) VALUES(%s,%s,%s)""" # creating the cursor object c = conn.cursor() # executing cursor object c.execute(data, (name, id, department)) conn.commit() print("vignan student No-", j, " stored successfully")
Output:
Save both files
Verify the content of the table in which the values were recently inserted.
Python-mySQL
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Mar, 2021"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "In this article, we are going to store XML data into the MySQL database using python through XAMPP server. So we are taking student XML data and storing the values into the database."
},
{
"code": null,
"e": 592,
"s": 211,
"text": "XAMPP server: It is a cross-platform web server used to develop and test programs on a local server. It is developed and managed by Apache Friends and is open-source. It has an Apache HTTP Server, MariaDB, and interpreter for 11 different programming languages like Perl and PHP. XAMPP Stands for cross-platform, Apache, MySQL, PHP, and Perl. It can be easily installed from here."
},
{
"code": null,
"e": 882,
"s": 592,
"text": "MySQL connector: MySQL Connector module of Python is used to connect MySQL databases with the Python programs, it does that using the Python Database API Specification v2.0 (PEP 249). It uses the Python standard library and has no dependencies. It can be installed using the below command:"
},
{
"code": null,
"e": 910,
"s": 882,
"text": "pip install mysql.connector"
},
{
"code": null,
"e": 929,
"s": 910,
"text": "Start XAMPP server"
},
{
"code": null,
"e": 946,
"s": 929,
"text": "Create XML file."
},
{
"code": null,
"e": 961,
"s": 946,
"text": "XML Structure:"
},
{
"code": null,
"e": 968,
"s": 961,
"text": "<root>"
},
{
"code": null,
"e": 977,
"s": 968,
"text": " <child>"
},
{
"code": null,
"e": 1007,
"s": 977,
"text": " <subchild>.....</subchild>"
},
{
"code": null,
"e": 1017,
"s": 1007,
"text": " </child>"
},
{
"code": null,
"e": 1025,
"s": 1017,
"text": "</root>"
},
{
"code": null,
"e": 1061,
"s": 1025,
"text": "We are going to use the XML module."
},
{
"code": null,
"e": 1083,
"s": 1061,
"text": "xml.etree.ElementTree"
},
{
"code": null,
"e": 1237,
"s": 1083,
"text": "This is an Element Tree XML API that is used to implement a simple and efficient API for parsing and creating XML data. So we need to import this module."
},
{
"code": null,
"e": 1245,
"s": 1237,
"text": "Syntax:"
},
{
"code": null,
"e": 1274,
"s": 1245,
"text": "import xml.etree.ElementTree"
},
{
"code": null,
"e": 1322,
"s": 1274,
"text": "The XML file to be created is names vignan.xml."
},
{
"code": null,
"e": 1326,
"s": 1322,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\"?><studentdata> <student> <name>Sravan Kumar</name> <id>7058</id> <department>IT</department> </student> <student> <name>Meghana</name> <id>7034</id> <department>IT</department> </student> <student> <name>Pranathi</name> <id>7046</id> <department>EEE</department> </student> <student> <name>Durga</name> <id>7078</id> <department>Mech</department> </student> <student> <name>Ishitha</name> <id>7093</id> <department>MBA</department> </student></studentdata>",
"e": 1938,
"s": 1326,
"text": null
},
{
"code": null,
"e": 1955,
"s": 1938,
"text": "For Python code:"
},
{
"code": null,
"e": 2164,
"s": 1955,
"text": "Create a python file names a.py.Import required module.Establish connection.Read XML file.Retrieve data from the XML and insert it into a table in the database.Display message on successful insertion of data."
},
{
"code": null,
"e": 2197,
"s": 2164,
"text": "Create a python file names a.py."
},
{
"code": null,
"e": 2221,
"s": 2197,
"text": "Import required module."
},
{
"code": null,
"e": 2243,
"s": 2221,
"text": "Establish connection."
},
{
"code": null,
"e": 2258,
"s": 2243,
"text": "Read XML file."
},
{
"code": null,
"e": 2329,
"s": 2258,
"text": "Retrieve data from the XML and insert it into a table in the database."
},
{
"code": null,
"e": 2378,
"s": 2329,
"text": "Display message on successful insertion of data."
},
{
"code": null,
"e": 2385,
"s": 2378,
"text": "Python"
},
{
"code": "# import xml element treeimport xml.etree.ElementTree as ET # import mysql connectorimport mysql.connector # give the connection parameters# user name is root# password is empty# server is localhost# database name is databaseconn = mysql.connector.connect(user='root', password='', host='localhost', database='database') # reading xml file , file name is vignan.xmltree = ET.parse('vignan.xml') # in our xml file student is the root for all # student data.data2 = tree.findall('student') # retrieving the data and insert into table# i value for xml data #j value printing number of # values that are storedfor i, j in zip(data2, range(1, 6)): name = i.find('name').text id = i.find('id').text department = i.find('department').text # sql query to insert data into database data = \"\"\"INSERT INTO vignan(name,id,department) VALUES(%s,%s,%s)\"\"\" # creating the cursor object c = conn.cursor() # executing cursor object c.execute(data, (name, id, department)) conn.commit() print(\"vignan student No-\", j, \" stored successfully\")",
"e": 3554,
"s": 2385,
"text": null
},
{
"code": null,
"e": 3562,
"s": 3554,
"text": "Output:"
},
{
"code": null,
"e": 3578,
"s": 3562,
"text": "Save both files"
},
{
"code": null,
"e": 3654,
"s": 3578,
"text": "Verify the content of the table in which the values were recently inserted."
},
{
"code": null,
"e": 3667,
"s": 3654,
"text": "Python-mySQL"
},
{
"code": null,
"e": 3674,
"s": 3667,
"text": "Python"
},
{
"code": null,
"e": 3772,
"s": 3674,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3804,
"s": 3772,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3831,
"s": 3804,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3852,
"s": 3831,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3883,
"s": 3852,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3939,
"s": 3883,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3962,
"s": 3939,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4004,
"s": 3962,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4046,
"s": 4004,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4085,
"s": 4046,
"text": "Python | datetime.timedelta() function"
}
]
|
Topological Sort of a graph using departure time of vertex | 04 Jul, 2022
Given a Directed Acyclic Graph (DAG), find Topological Sort of the graph.
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.
For example, a topological sorting of the following graph is “5 4 2 3 1 0”. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is “4 5 2 3 1 0”.
Please note that the first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no incoming edges). For above graph, vertex 4 and 5 have no incoming edges.
We have already discussed a DFS-based algorithm using stack and Kahn’s Algorithm for Topological Sorting. We have also discussed how to print all topological sorts of the DAG here. In this post, another DFS based approach is discussed for finding Topological sort of a graph by introducing concept of arrival and departure time of a vertex in DFS.
What is Arrival Time & Departure Time of Vertices in DFS? In DFS, Arrival Time is the time at which the vertex was explored for the first time and Departure Time is the time at which we have explored all the neighbors of the vertex and we are ready to backtrack.
How to find Topological Sort of a graph using departure time? To find Topological Sort of a graph, we run DFS starting from all unvisited vertices one by one. For any vertex, before exploring any of its neighbors, we note the arrival time of that vertex and after exploring all the neighbors of the vertex, we note its departure time. Please note only departure time is needed to find Topological Sort of a graph, so we can skip arrival time of vertex. Finally, after we have visited all the vertices of the graph, we print the vertices in order of their decreasing departure time which is our desired Topological Order of Vertices.
Below is C++ implementation of above idea –
C++
Python3
C#
Javascript
// A C++ program to print topological sorting of a DAG#include <bits/stdc++.h>using namespace std; // Graph class represents a directed graph using adjacency// list representationclass Graph { int V; // No. of vertices // Pointer to an array containing adjacency lists list<int>* adj; public: Graph(int); // Constructor ~Graph(); // Destructor // function to add an edge to graph void addEdge(int, int); // The function to do DFS traversal void DFS(int, vector<bool>&, vector<int>&, int&); // The function to do Topological Sort. void topologicalSort();}; Graph::Graph(int V){ this->V = V; this->adj = new list<int>[V];} Graph::~Graph() { delete[] this->adj; } void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v's list.} // The function to do DFS() and stores departure time// of all vertexvoid Graph::DFS(int v, vector<bool>& visited, vector<int>& departure, int& time){ visited[v] = true; // time++; // arrival time of vertex v for (int i : adj[v]) if (!visited[i]) DFS(i, visited, departure, time); // set departure time of vertex v departure[time++] = v;} // The function to do Topological Sort. It uses DFS().void Graph::topologicalSort(){ // vector to store departure time of vertex. vector<int> departure(V, -1); // Mark all the vertices as not visited vector<bool> visited(V, false); int time = 0; // perform DFS on all unvisited vertices for (int i = 0; i < V; i++) { if (visited[i] == 0) { DFS(i, visited, departure, time); } } // print the topological sort for (int i = V - 1; i >= 0; i--) cout << departure[i] << " ";} // Driver program to test above functionsint main(){ // Create a graph given in the above diagram Graph g(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); cout << "Topological Sort of the given graph is \n"; g.topologicalSort(); return 0;}
# A Python3 program to print topological sorting of a DAGdef addEdge(u, v): global adj adj[u].append(v) # The function to do DFS() and stores departure time# of all vertexdef DFS(v): global visited, departure, time visited[v] = 1 for i in adj[v]: if visited[i] == 0: DFS(i) departure[time] = v time += 1 # The function to do Topological Sort. It uses DFS().def topologicalSort(): # perform DFS on all unvisited vertices for i in range(V): if(visited[i] == 0): DFS(i) # Print vertices in topological order for i in range(V - 1, -1, -1): print(departure[i], end = " ") # Driver codeif __name__ == '__main__': # Create a graph given in the above diagram V,time, adj, visited, departure = 6, 0, [[] for i in range(7)], [0 for i in range(7)],[-1 for i in range(7)] addEdge(5, 2) addEdge(5, 0) addEdge(4, 0) addEdge(4, 1) addEdge(2, 3) addEdge(3, 1) print("Topological Sort of the given graph is") topologicalSort() # This code is contributed by mohit kumar 29
// C# program to print topological sorting of a DAGusing System;using System.Collections.Generic; // Graph class represents a directed graph using adjacency// list representationpublic class Graph { private int V; private List<int>[] adj; // constructor public Graph(int v) { V = v; adj = new List<int>[ v ]; for (int i = 0; i < v; i++) adj[i] = new List<int>(); } // Add an edge public void AddEdge(int v, int w) { adj[v].Add(w); // Add w to v's list } // The function to do DFS() and stores departure time // of all vertex private void DFS(int v, bool[] visited, int[] departure, ref int time) { visited[v] = true; // time++; // arrival time of vertex v foreach(int i in adj[v]) { if (!visited[i]) DFS(i, visited, departure, ref time); } // set departure time of vertex v departure[time++] = v; } // The function to do Topological Sort. It uses DFS(). public void TopologicalSort() { // vector to store departure time of vertex. int[] departure = new int[V]; for (int i = 0; i < V; i++) departure[i] = -1; // Mark all the vertices as not visited bool[] visited = new bool[V]; int time = 0; // perform DFS on all unvisited vertices for (int i = 0; i < V; i++) { if (visited[i] == false) { DFS(i, visited, departure, ref time); } } // print the topological sort for (int i = V - 1; i >= 0; i--) Console.Write(departure[i] + " "); Console.WriteLine(); }} class GFG { // Driver program to test above functions static void Main(string[] args) { // Create a graph given in the above diagram Graph g = new Graph(6); g.AddEdge(5, 2); g.AddEdge(5, 0); g.AddEdge(4, 0); g.AddEdge(4, 1); g.AddEdge(2, 3); g.AddEdge(3, 1); Console.WriteLine( "Topological Sort of the given graph is"); g.TopologicalSort(); }} // This code is contributed by cavi4762
<script> // A JavaScript program to print topological// sorting of a DAG let adj=new Array(7); for(let i=0;i<adj.length;i++) { adj[i]=[]; } let V=6; let time=0; let visited=new Array(7); let departure =new Array(7); for(let i=0;i<7;i++) { visited[i]=0; departure[i]=-1; } function addEdge(u, v) { adj[u].push(v) } // The function to do DFS() and // stores departure time // of all vertex function DFS(v) { visited[v] = 1; for(let i=0;i<adj[v].length;i++) { if(visited[adj[v][i]]==0) DFS(adj[v][i]); } departure[time] = v time += 1 } // The function to do Topological // Sort. It uses DFS(). function topologicalSort() { //perform DFS on all unvisited vertices for(let i=0;i<V;i++) { if(visited[i] == 0) DFS(i) } //perform DFS on all unvisited vertices for(let i=V-1;i>=0;i--) { document.write(departure[i]+" "); } } // Create a graph given in the above diagram addEdge(5, 2); addEdge(5, 0); addEdge(4, 0); addEdge(4, 1); addEdge(2, 3); addEdge(3, 1); document.write( "Topological Sort of the given graph is<br>" ); topologicalSort() // This code is contributed by unknown2108 </script>
Topological Sort of the given graph is
5 4 2 3 1 0
Time Complexity of above solution is O(V + E).
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
mohit kumar 29
unknown2108
Apoorva_Kumar
cavi4762
hardikkoriintern
Topological Sorting
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Find if there is a path between two vertices in a directed graph
Detect Cycle in a Directed Graph
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Bellman–Ford Algorithm | DP-23
Find if there is a path between two vertices in an undirected graph
Minimum number of swaps required to sort an array
m Coloring Problem | Backtracking-5 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 128,
"s": 54,
"text": "Given a Directed Acyclic Graph (DAG), find Topological Sort of the graph."
},
{
"code": null,
"e": 368,
"s": 128,
"text": "Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG."
},
{
"code": null,
"e": 586,
"s": 368,
"text": "For example, a topological sorting of the following graph is “5 4 2 3 1 0”. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is “4 5 2 3 1 0”."
},
{
"code": null,
"e": 773,
"s": 586,
"text": "Please note that the first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no incoming edges). For above graph, vertex 4 and 5 have no incoming edges."
},
{
"code": null,
"e": 1121,
"s": 773,
"text": "We have already discussed a DFS-based algorithm using stack and Kahn’s Algorithm for Topological Sorting. We have also discussed how to print all topological sorts of the DAG here. In this post, another DFS based approach is discussed for finding Topological sort of a graph by introducing concept of arrival and departure time of a vertex in DFS."
},
{
"code": null,
"e": 1384,
"s": 1121,
"text": "What is Arrival Time & Departure Time of Vertices in DFS? In DFS, Arrival Time is the time at which the vertex was explored for the first time and Departure Time is the time at which we have explored all the neighbors of the vertex and we are ready to backtrack."
},
{
"code": null,
"e": 2017,
"s": 1384,
"text": "How to find Topological Sort of a graph using departure time? To find Topological Sort of a graph, we run DFS starting from all unvisited vertices one by one. For any vertex, before exploring any of its neighbors, we note the arrival time of that vertex and after exploring all the neighbors of the vertex, we note its departure time. Please note only departure time is needed to find Topological Sort of a graph, so we can skip arrival time of vertex. Finally, after we have visited all the vertices of the graph, we print the vertices in order of their decreasing departure time which is our desired Topological Order of Vertices."
},
{
"code": null,
"e": 2061,
"s": 2017,
"text": "Below is C++ implementation of above idea –"
},
{
"code": null,
"e": 2065,
"s": 2061,
"text": "C++"
},
{
"code": null,
"e": 2073,
"s": 2065,
"text": "Python3"
},
{
"code": null,
"e": 2076,
"s": 2073,
"text": "C#"
},
{
"code": null,
"e": 2087,
"s": 2076,
"text": "Javascript"
},
{
"code": "// A C++ program to print topological sorting of a DAG#include <bits/stdc++.h>using namespace std; // Graph class represents a directed graph using adjacency// list representationclass Graph { int V; // No. of vertices // Pointer to an array containing adjacency lists list<int>* adj; public: Graph(int); // Constructor ~Graph(); // Destructor // function to add an edge to graph void addEdge(int, int); // The function to do DFS traversal void DFS(int, vector<bool>&, vector<int>&, int&); // The function to do Topological Sort. void topologicalSort();}; Graph::Graph(int V){ this->V = V; this->adj = new list<int>[V];} Graph::~Graph() { delete[] this->adj; } void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v's list.} // The function to do DFS() and stores departure time// of all vertexvoid Graph::DFS(int v, vector<bool>& visited, vector<int>& departure, int& time){ visited[v] = true; // time++; // arrival time of vertex v for (int i : adj[v]) if (!visited[i]) DFS(i, visited, departure, time); // set departure time of vertex v departure[time++] = v;} // The function to do Topological Sort. It uses DFS().void Graph::topologicalSort(){ // vector to store departure time of vertex. vector<int> departure(V, -1); // Mark all the vertices as not visited vector<bool> visited(V, false); int time = 0; // perform DFS on all unvisited vertices for (int i = 0; i < V; i++) { if (visited[i] == 0) { DFS(i, visited, departure, time); } } // print the topological sort for (int i = V - 1; i >= 0; i--) cout << departure[i] << \" \";} // Driver program to test above functionsint main(){ // Create a graph given in the above diagram Graph g(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); cout << \"Topological Sort of the given graph is \\n\"; g.topologicalSort(); return 0;}",
"e": 4131,
"s": 2087,
"text": null
},
{
"code": "# A Python3 program to print topological sorting of a DAGdef addEdge(u, v): global adj adj[u].append(v) # The function to do DFS() and stores departure time# of all vertexdef DFS(v): global visited, departure, time visited[v] = 1 for i in adj[v]: if visited[i] == 0: DFS(i) departure[time] = v time += 1 # The function to do Topological Sort. It uses DFS().def topologicalSort(): # perform DFS on all unvisited vertices for i in range(V): if(visited[i] == 0): DFS(i) # Print vertices in topological order for i in range(V - 1, -1, -1): print(departure[i], end = \" \") # Driver codeif __name__ == '__main__': # Create a graph given in the above diagram V,time, adj, visited, departure = 6, 0, [[] for i in range(7)], [0 for i in range(7)],[-1 for i in range(7)] addEdge(5, 2) addEdge(5, 0) addEdge(4, 0) addEdge(4, 1) addEdge(2, 3) addEdge(3, 1) print(\"Topological Sort of the given graph is\") topologicalSort() # This code is contributed by mohit kumar 29",
"e": 5198,
"s": 4131,
"text": null
},
{
"code": "// C# program to print topological sorting of a DAGusing System;using System.Collections.Generic; // Graph class represents a directed graph using adjacency// list representationpublic class Graph { private int V; private List<int>[] adj; // constructor public Graph(int v) { V = v; adj = new List<int>[ v ]; for (int i = 0; i < v; i++) adj[i] = new List<int>(); } // Add an edge public void AddEdge(int v, int w) { adj[v].Add(w); // Add w to v's list } // The function to do DFS() and stores departure time // of all vertex private void DFS(int v, bool[] visited, int[] departure, ref int time) { visited[v] = true; // time++; // arrival time of vertex v foreach(int i in adj[v]) { if (!visited[i]) DFS(i, visited, departure, ref time); } // set departure time of vertex v departure[time++] = v; } // The function to do Topological Sort. It uses DFS(). public void TopologicalSort() { // vector to store departure time of vertex. int[] departure = new int[V]; for (int i = 0; i < V; i++) departure[i] = -1; // Mark all the vertices as not visited bool[] visited = new bool[V]; int time = 0; // perform DFS on all unvisited vertices for (int i = 0; i < V; i++) { if (visited[i] == false) { DFS(i, visited, departure, ref time); } } // print the topological sort for (int i = V - 1; i >= 0; i--) Console.Write(departure[i] + \" \"); Console.WriteLine(); }} class GFG { // Driver program to test above functions static void Main(string[] args) { // Create a graph given in the above diagram Graph g = new Graph(6); g.AddEdge(5, 2); g.AddEdge(5, 0); g.AddEdge(4, 0); g.AddEdge(4, 1); g.AddEdge(2, 3); g.AddEdge(3, 1); Console.WriteLine( \"Topological Sort of the given graph is\"); g.TopologicalSort(); }} // This code is contributed by cavi4762",
"e": 7135,
"s": 5198,
"text": null
},
{
"code": "<script> // A JavaScript program to print topological// sorting of a DAG let adj=new Array(7); for(let i=0;i<adj.length;i++) { adj[i]=[]; } let V=6; let time=0; let visited=new Array(7); let departure =new Array(7); for(let i=0;i<7;i++) { visited[i]=0; departure[i]=-1; } function addEdge(u, v) { adj[u].push(v) } // The function to do DFS() and // stores departure time // of all vertex function DFS(v) { visited[v] = 1; for(let i=0;i<adj[v].length;i++) { if(visited[adj[v][i]]==0) DFS(adj[v][i]); } departure[time] = v time += 1 } // The function to do Topological // Sort. It uses DFS(). function topologicalSort() { //perform DFS on all unvisited vertices for(let i=0;i<V;i++) { if(visited[i] == 0) DFS(i) } //perform DFS on all unvisited vertices for(let i=V-1;i>=0;i--) { document.write(departure[i]+\" \"); } } // Create a graph given in the above diagram addEdge(5, 2); addEdge(5, 0); addEdge(4, 0); addEdge(4, 1); addEdge(2, 3); addEdge(3, 1); document.write( \"Topological Sort of the given graph is<br>\" ); topologicalSort() // This code is contributed by unknown2108 </script>",
"e": 8557,
"s": 7135,
"text": null
},
{
"code": null,
"e": 8610,
"s": 8557,
"text": "Topological Sort of the given graph is \n5 4 2 3 1 0 "
},
{
"code": null,
"e": 8657,
"s": 8610,
"text": "Time Complexity of above solution is O(V + E)."
},
{
"code": null,
"e": 8952,
"s": 8657,
"text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 8967,
"s": 8952,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8979,
"s": 8967,
"text": "unknown2108"
},
{
"code": null,
"e": 8993,
"s": 8979,
"text": "Apoorva_Kumar"
},
{
"code": null,
"e": 9002,
"s": 8993,
"text": "cavi4762"
},
{
"code": null,
"e": 9019,
"s": 9002,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 9039,
"s": 9019,
"text": "Topological Sorting"
},
{
"code": null,
"e": 9045,
"s": 9039,
"text": "Graph"
},
{
"code": null,
"e": 9051,
"s": 9045,
"text": "Graph"
},
{
"code": null,
"e": 9149,
"s": 9051,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9200,
"s": 9149,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 9258,
"s": 9200,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 9323,
"s": 9258,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 9356,
"s": 9323,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 9388,
"s": 9356,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9452,
"s": 9388,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9483,
"s": 9452,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 9551,
"s": 9483,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 9601,
"s": 9551,
"text": "Minimum number of swaps required to sort an array"
}
]
|
Node.js path.delimiter Property | 11 Oct, 2021
The path.delimiter property is an inbuilt application programming interface of the path module which is used to get platform-specific path delimiter.
Syntax:
path.delimiter;
Return Value: This property returns a string that represents platform specific path delimiter. The returned value is : for POSIX and ; for Windows.
Below examples illustrate the use of path.delimiter in Node.js:
Example 1:
// Node.js program to demonstrate the // path.delimiter property // Allocating path moduleconst path = require('path'); // Printing path.delimiter valueconsole.log(path.delimiter);
Output:
;
Example 2:
// Node.js program to demonstrate the // path.delimiter property // Allocating path moduleconst path = require('path'); // Allocating process moduleconst process = require('process'); // Printing path.delimiter valuevar delimiter = path.delimiter; console.log(process.env.PATH);console.log(process.env.PATH.split(path.delimiter));
Output:
C:\wamp64\bin\php\php7.3.1\ext\ImageMagick;C:\Program Files (x86)\Common
Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;
C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;
C:\Windows\System32\OpenSSH\;D:\programfiles\Git\cmd;
D:\programfiles\Cmake\bin;
C:\Program
Files\nodejs\;C:\Users\gekcho\AppData\Local\Microsoft\WindowsApps;
C:\Users\gekcho\AppData\Roaming\npm
[ 'C:\\wamp64\\bin\\php\\php7.3.1\\ext\\ImageMagick',
'C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath',
'C:\\Windows\\system32',
'C:\\Windows',
'C:\\Windows\\System32\\Wbem',
'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\',
'C:\\Windows\\System32\\OpenSSH\\',
'D:\\programfiles\\Git\\cmd',
'D:\\programfiles\\Cmake\\bin',
'C:\\Program Files\\nodejs\\',
'C:\\Users\\gekcho\\AppData\\Local\\Microsoft\\WindowsApps',
'C:\\Users\\gekcho\\AppData\\Roaming\\npm' ]
Note: The above program will compile and run by using the node filename.js command.
Reference: https://nodejs.org/api/path.html#path_path_delimiter
Node.js-path-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 178,
"s": 28,
"text": "The path.delimiter property is an inbuilt application programming interface of the path module which is used to get platform-specific path delimiter."
},
{
"code": null,
"e": 186,
"s": 178,
"text": "Syntax:"
},
{
"code": null,
"e": 202,
"s": 186,
"text": "path.delimiter;"
},
{
"code": null,
"e": 350,
"s": 202,
"text": "Return Value: This property returns a string that represents platform specific path delimiter. The returned value is : for POSIX and ; for Windows."
},
{
"code": null,
"e": 414,
"s": 350,
"text": "Below examples illustrate the use of path.delimiter in Node.js:"
},
{
"code": null,
"e": 425,
"s": 414,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the // path.delimiter property // Allocating path moduleconst path = require('path'); // Printing path.delimiter valueconsole.log(path.delimiter);",
"e": 610,
"s": 425,
"text": null
},
{
"code": null,
"e": 618,
"s": 610,
"text": "Output:"
},
{
"code": null,
"e": 620,
"s": 618,
"text": ";"
},
{
"code": null,
"e": 631,
"s": 620,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the // path.delimiter property // Allocating path moduleconst path = require('path'); // Allocating process moduleconst process = require('process'); // Printing path.delimiter valuevar delimiter = path.delimiter; console.log(process.env.PATH);console.log(process.env.PATH.split(path.delimiter));",
"e": 970,
"s": 631,
"text": null
},
{
"code": null,
"e": 978,
"s": 970,
"text": "Output:"
},
{
"code": null,
"e": 1876,
"s": 978,
"text": "C:\\wamp64\\bin\\php\\php7.3.1\\ext\\ImageMagick;C:\\Program Files (x86)\\Common \nFiles\\Oracle\\Java\\javapath;C:\\Windows\\system32;C:\\Windows;\nC:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;\nC:\\Windows\\System32\\OpenSSH\\;D:\\programfiles\\Git\\cmd;\nD:\\programfiles\\Cmake\\bin;\nC:\\Program\nFiles\\nodejs\\;C:\\Users\\gekcho\\AppData\\Local\\Microsoft\\WindowsApps;\nC:\\Users\\gekcho\\AppData\\Roaming\\npm\n[ 'C:\\\\wamp64\\\\bin\\\\php\\\\php7.3.1\\\\ext\\\\ImageMagick',\n 'C:\\\\Program Files (x86)\\\\Common Files\\\\Oracle\\\\Java\\\\javapath',\n 'C:\\\\Windows\\\\system32',\n 'C:\\\\Windows',\n 'C:\\\\Windows\\\\System32\\\\Wbem',\n 'C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\',\n 'C:\\\\Windows\\\\System32\\\\OpenSSH\\\\',\n 'D:\\\\programfiles\\\\Git\\\\cmd',\n 'D:\\\\programfiles\\\\Cmake\\\\bin',\n 'C:\\\\Program Files\\\\nodejs\\\\',\n 'C:\\\\Users\\\\gekcho\\\\AppData\\\\Local\\\\Microsoft\\\\WindowsApps',\n 'C:\\\\Users\\\\gekcho\\\\AppData\\\\Roaming\\\\npm' ]\n"
},
{
"code": null,
"e": 1960,
"s": 1876,
"text": "Note: The above program will compile and run by using the node filename.js command."
},
{
"code": null,
"e": 2024,
"s": 1960,
"text": "Reference: https://nodejs.org/api/path.html#path_path_delimiter"
},
{
"code": null,
"e": 2044,
"s": 2024,
"text": "Node.js-path-module"
},
{
"code": null,
"e": 2052,
"s": 2044,
"text": "Node.js"
},
{
"code": null,
"e": 2069,
"s": 2052,
"text": "Web Technologies"
}
]
|
Running PyTorch on TPU: a bag of tricks | by Zahar Chikishev | Towards Data Science | At the time of writing these lines running PyTorch code on TPUs is not a well-trodden path. Naturally, TPUs have been optimized for and mainly used with TensorFlow. But Kaggle and Google distribute free TPU time on some of its competitions, and one doesn’t simply change his favorite framework, so this is a memo on my (mostly successful) experience of training PyTorch models with TPU on GCP.
PyTorch/XLA is the project that allows doing it. It is still in active development, issues get fixed. Hopefully in the near future the experience of running it will get smoother, with some bugs fixed and the best practices better communicated.
My setup includes:
GCP Compute Engine virtual machine with prebuilt PyTorch/XLA image. Follow section “Consume Prebuilt Compute VM Images” on PyTorch/XLA github page to setup.TPU node, use this instruction with “GCP Console” option to create one for yourself. If your GCP project has a free TPU quota you received an email describing versions and zones that you can use. Besides that, I did not find a direct way to verify that created TPU node is indeed free, besides looking at the bill.Jupyter notebook, follow this funny article to set it up. I just can’t work without jupyter anymore. You may notice that you breathe deeper when it works for you.I have also found it convenient to work with Google Cloud Storage to transfer files in some cases. For example you can use the following lines on your virtual machine to copy Kaggle API token and download competition data with it. Use gsutil cp also to copy your files back to GS bucket.
GCP Compute Engine virtual machine with prebuilt PyTorch/XLA image. Follow section “Consume Prebuilt Compute VM Images” on PyTorch/XLA github page to setup.
TPU node, use this instruction with “GCP Console” option to create one for yourself. If your GCP project has a free TPU quota you received an email describing versions and zones that you can use. Besides that, I did not find a direct way to verify that created TPU node is indeed free, besides looking at the bill.
Jupyter notebook, follow this funny article to set it up. I just can’t work without jupyter anymore. You may notice that you breathe deeper when it works for you.
I have also found it convenient to work with Google Cloud Storage to transfer files in some cases. For example you can use the following lines on your virtual machine to copy Kaggle API token and download competition data with it. Use gsutil cp also to copy your files back to GS bucket.
gcloud auth logingsutil cp gs://bucket-name/kaggle-keys/kaggle.json ~/.kagglechmod 600 ~/.kaggle/kaggle.jsonkaggle competitions download -c recursion-cellular-image-classification
Besides google storage I used github repository to transfer data and code from my local machine to the GCP virtual machine and back.
Note that there are software versions running on TPU node as well. It must match the conda environment that you use on your VM. As PyTorch/XLA is under active development at the moment I use nightly TPU version:
Let’s get to the code. PyTorch/XLA has its own way of running multi-core, and as TPUs are multi-core you want to exploit it. But before you do, you may want to replace device = ‘cuda’ in your model with
import torch_xla_py.xla_model as xm...device = xm.xla_device()...xm.optimizer_step(optimizer)xm.mark_step()...
to test your model on only one core of TPU. The last two lines in the code snippet above replace the regular optimizer.step() call.
For multi-core training PyTorch/XLA uses its own DataParallel class. An example of a training loop with DataParallel can be found here in the test directory, and I want to highlight the following three points related to it.
1) DataParallel holds copies of the model object (one per TPU device), which are kept synchronized with identical weights. One can save the weights by accessing one of the models:
torch.save(model_parallel._models[0].state_dict(), filepath)
2) DataParallel cores must run the same number of batches each, and only full batches are allowed. Therefore, each epoch runs with less than 100% of the samples, and the residual is left out. With a dataset shuffling, it is not a big issue for the training loop, but it becomes a problem for inference. I am using single-core run for inference, as described above.
3) DataParallel code running directly from a jupyter notebook is highly unstable for me. It can run for some time, but then it throws system errors, kernel dies or even jupyter crashes. Running it as a script seems to be stable, so I created a second notebook for running with the following lines:
!jupyter nbconvert --to script MyModel.ipynb!python MyModel.py
PyTorch/XLA design results in a list of limitations on PyTorch functionality. In fact, these limitations are general to TPU devices, and apparently apply to TensorFlow models as well, at least partially. Specifically
Tensor shapes are advised to be the same between iterations, which also limits usage of masks.Loops with a different number of iterations between steps are to be avoided.
Tensor shapes are advised to be the same between iterations, which also limits usage of masks.
Loops with a different number of iterations between steps are to be avoided.
Not following the guidelines results in (severe) performance degradation. Unfortunately, in my loss function I needed to use both masks and loops. In my case I moved everything to CPU and it is much faster now. Just do my_tensor.cpu().detach().numpy() on all your tensors. Of course, it does not work on tensors where one needs to track the gradients, and it also incurs a slowdown of its own because of moving to CPU.
My Kaggle competition teammate Yuval Reina has kindly agreed to share his machine configuration and training speed for comparison in this section. I have also added a column for my notebook (a physical machine, not a jupyter this time), but it is not a match to these heavy-weights and the code running on it was not well-optimized for performance.
The input to the networks is 512 by 512 images with 6 channels. We measured the images per second processed in the training loop, and on this metric the described TPU configuration outperforms Yuval’s Tesla V100 by 110 to 57.
The performance for single core TPU as described above (without DataParallel) is 26 images per second, approximately 4 times slower than all 8 cores together.
We do not disclose the architecture used by Yuval as the competition is still ongoing, but it is not significantly different in size from resnet50. But please note that as we did not run the same architectures the comparison is not fair.
Trying to switch to GCP SSD disk for the train images did not improve performance.
In summary, my experience with PyTorch/XLA is mixed. I have encountered several bugs/artifacts (not all mentioned here), the existing documentation and examples are limited and the TPU intrinsic limitations can be too prohibitive for more creative architectures. On the other hand, it mostly works, and when it works the performance is good.
Finally, and arguably most important, don’t forget to stop your GCP VM when you are finished! | [
{
"code": null,
"e": 566,
"s": 172,
"text": "At the time of writing these lines running PyTorch code on TPUs is not a well-trodden path. Naturally, TPUs have been optimized for and mainly used with TensorFlow. But Kaggle and Google distribute free TPU time on some of its competitions, and one doesn’t simply change his favorite framework, so this is a memo on my (mostly successful) experience of training PyTorch models with TPU on GCP."
},
{
"code": null,
"e": 810,
"s": 566,
"text": "PyTorch/XLA is the project that allows doing it. It is still in active development, issues get fixed. Hopefully in the near future the experience of running it will get smoother, with some bugs fixed and the best practices better communicated."
},
{
"code": null,
"e": 829,
"s": 810,
"text": "My setup includes:"
},
{
"code": null,
"e": 1749,
"s": 829,
"text": "GCP Compute Engine virtual machine with prebuilt PyTorch/XLA image. Follow section “Consume Prebuilt Compute VM Images” on PyTorch/XLA github page to setup.TPU node, use this instruction with “GCP Console” option to create one for yourself. If your GCP project has a free TPU quota you received an email describing versions and zones that you can use. Besides that, I did not find a direct way to verify that created TPU node is indeed free, besides looking at the bill.Jupyter notebook, follow this funny article to set it up. I just can’t work without jupyter anymore. You may notice that you breathe deeper when it works for you.I have also found it convenient to work with Google Cloud Storage to transfer files in some cases. For example you can use the following lines on your virtual machine to copy Kaggle API token and download competition data with it. Use gsutil cp also to copy your files back to GS bucket."
},
{
"code": null,
"e": 1906,
"s": 1749,
"text": "GCP Compute Engine virtual machine with prebuilt PyTorch/XLA image. Follow section “Consume Prebuilt Compute VM Images” on PyTorch/XLA github page to setup."
},
{
"code": null,
"e": 2221,
"s": 1906,
"text": "TPU node, use this instruction with “GCP Console” option to create one for yourself. If your GCP project has a free TPU quota you received an email describing versions and zones that you can use. Besides that, I did not find a direct way to verify that created TPU node is indeed free, besides looking at the bill."
},
{
"code": null,
"e": 2384,
"s": 2221,
"text": "Jupyter notebook, follow this funny article to set it up. I just can’t work without jupyter anymore. You may notice that you breathe deeper when it works for you."
},
{
"code": null,
"e": 2672,
"s": 2384,
"text": "I have also found it convenient to work with Google Cloud Storage to transfer files in some cases. For example you can use the following lines on your virtual machine to copy Kaggle API token and download competition data with it. Use gsutil cp also to copy your files back to GS bucket."
},
{
"code": null,
"e": 2852,
"s": 2672,
"text": "gcloud auth logingsutil cp gs://bucket-name/kaggle-keys/kaggle.json ~/.kagglechmod 600 ~/.kaggle/kaggle.jsonkaggle competitions download -c recursion-cellular-image-classification"
},
{
"code": null,
"e": 2985,
"s": 2852,
"text": "Besides google storage I used github repository to transfer data and code from my local machine to the GCP virtual machine and back."
},
{
"code": null,
"e": 3197,
"s": 2985,
"text": "Note that there are software versions running on TPU node as well. It must match the conda environment that you use on your VM. As PyTorch/XLA is under active development at the moment I use nightly TPU version:"
},
{
"code": null,
"e": 3400,
"s": 3197,
"text": "Let’s get to the code. PyTorch/XLA has its own way of running multi-core, and as TPUs are multi-core you want to exploit it. But before you do, you may want to replace device = ‘cuda’ in your model with"
},
{
"code": null,
"e": 3511,
"s": 3400,
"text": "import torch_xla_py.xla_model as xm...device = xm.xla_device()...xm.optimizer_step(optimizer)xm.mark_step()..."
},
{
"code": null,
"e": 3643,
"s": 3511,
"text": "to test your model on only one core of TPU. The last two lines in the code snippet above replace the regular optimizer.step() call."
},
{
"code": null,
"e": 3867,
"s": 3643,
"text": "For multi-core training PyTorch/XLA uses its own DataParallel class. An example of a training loop with DataParallel can be found here in the test directory, and I want to highlight the following three points related to it."
},
{
"code": null,
"e": 4047,
"s": 3867,
"text": "1) DataParallel holds copies of the model object (one per TPU device), which are kept synchronized with identical weights. One can save the weights by accessing one of the models:"
},
{
"code": null,
"e": 4108,
"s": 4047,
"text": "torch.save(model_parallel._models[0].state_dict(), filepath)"
},
{
"code": null,
"e": 4473,
"s": 4108,
"text": "2) DataParallel cores must run the same number of batches each, and only full batches are allowed. Therefore, each epoch runs with less than 100% of the samples, and the residual is left out. With a dataset shuffling, it is not a big issue for the training loop, but it becomes a problem for inference. I am using single-core run for inference, as described above."
},
{
"code": null,
"e": 4771,
"s": 4473,
"text": "3) DataParallel code running directly from a jupyter notebook is highly unstable for me. It can run for some time, but then it throws system errors, kernel dies or even jupyter crashes. Running it as a script seems to be stable, so I created a second notebook for running with the following lines:"
},
{
"code": null,
"e": 4834,
"s": 4771,
"text": "!jupyter nbconvert --to script MyModel.ipynb!python MyModel.py"
},
{
"code": null,
"e": 5051,
"s": 4834,
"text": "PyTorch/XLA design results in a list of limitations on PyTorch functionality. In fact, these limitations are general to TPU devices, and apparently apply to TensorFlow models as well, at least partially. Specifically"
},
{
"code": null,
"e": 5222,
"s": 5051,
"text": "Tensor shapes are advised to be the same between iterations, which also limits usage of masks.Loops with a different number of iterations between steps are to be avoided."
},
{
"code": null,
"e": 5317,
"s": 5222,
"text": "Tensor shapes are advised to be the same between iterations, which also limits usage of masks."
},
{
"code": null,
"e": 5394,
"s": 5317,
"text": "Loops with a different number of iterations between steps are to be avoided."
},
{
"code": null,
"e": 5813,
"s": 5394,
"text": "Not following the guidelines results in (severe) performance degradation. Unfortunately, in my loss function I needed to use both masks and loops. In my case I moved everything to CPU and it is much faster now. Just do my_tensor.cpu().detach().numpy() on all your tensors. Of course, it does not work on tensors where one needs to track the gradients, and it also incurs a slowdown of its own because of moving to CPU."
},
{
"code": null,
"e": 6162,
"s": 5813,
"text": "My Kaggle competition teammate Yuval Reina has kindly agreed to share his machine configuration and training speed for comparison in this section. I have also added a column for my notebook (a physical machine, not a jupyter this time), but it is not a match to these heavy-weights and the code running on it was not well-optimized for performance."
},
{
"code": null,
"e": 6388,
"s": 6162,
"text": "The input to the networks is 512 by 512 images with 6 channels. We measured the images per second processed in the training loop, and on this metric the described TPU configuration outperforms Yuval’s Tesla V100 by 110 to 57."
},
{
"code": null,
"e": 6547,
"s": 6388,
"text": "The performance for single core TPU as described above (without DataParallel) is 26 images per second, approximately 4 times slower than all 8 cores together."
},
{
"code": null,
"e": 6785,
"s": 6547,
"text": "We do not disclose the architecture used by Yuval as the competition is still ongoing, but it is not significantly different in size from resnet50. But please note that as we did not run the same architectures the comparison is not fair."
},
{
"code": null,
"e": 6868,
"s": 6785,
"text": "Trying to switch to GCP SSD disk for the train images did not improve performance."
},
{
"code": null,
"e": 7210,
"s": 6868,
"text": "In summary, my experience with PyTorch/XLA is mixed. I have encountered several bugs/artifacts (not all mentioned here), the existing documentation and examples are limited and the TPU intrinsic limitations can be too prohibitive for more creative architectures. On the other hand, it mostly works, and when it works the performance is good."
}
]
|
MySQL query to select maximum and minimum salary row? | For this, use sub query along with MIN() and MAX(). To display both the maximum and minimum value, use UNION ALL. Let us first create a table −
mysql> create table DemoTable
-> (
-> EmployeeName varchar(20),
-> EmployeeSalary int
-> );
Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Bob',8800);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Chris',9800);
Query OK, 1 row affected (0.63 sec)
mysql> insert into DemoTable values('David',7600);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Sam',9600);
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+----------------+
| EmployeeName | EmployeeSalary |
+--------------+----------------+
| Bob | 8800 |
| Chris | 9800 |
| David | 7600 |
| Sam | 9600 |
+--------------+----------------+
4 rows in set (0.00 sec)
Here is the query to select minimum salary row −
mysql> select *from DemoTable
-> where EmployeeSalary in ( select max(EmployeeSalary) from DemoTable
-> union all
-> select min(EmployeeSalary) from DemoTable
-> );
This will produce the following output −
+--------------+----------------+
| EmployeeName | EmployeeSalary |
+--------------+----------------+
| Chris | 9800 |
| David | 7600 |
+--------------+----------------+
2 rows in set (0.05 sec) | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "For this, use sub query along with MIN() and MAX(). To display both the maximum and minimum value, use UNION ALL. Let us first create a table −"
},
{
"code": null,
"e": 1347,
"s": 1206,
"text": "mysql> create table DemoTable\n -> (\n -> EmployeeName varchar(20),\n -> EmployeeSalary int\n -> );\nQuery OK, 0 rows affected (0.70 sec)"
},
{
"code": null,
"e": 1403,
"s": 1347,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1747,
"s": 1403,
"text": "mysql> insert into DemoTable values('Bob',8800);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values('Chris',9800);\nQuery OK, 1 row affected (0.63 sec)\nmysql> insert into DemoTable values('David',7600);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values('Sam',9600);\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1807,
"s": 1747,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1838,
"s": 1807,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1879,
"s": 1838,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2176,
"s": 1879,
"text": "+--------------+----------------+\n| EmployeeName | EmployeeSalary |\n+--------------+----------------+\n| Bob | 8800 |\n| Chris | 9800 |\n| David | 7600 |\n| Sam | 9600 |\n+--------------+----------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2225,
"s": 2176,
"text": "Here is the query to select minimum salary row −"
},
{
"code": null,
"e": 2402,
"s": 2225,
"text": "mysql> select *from DemoTable\n -> where EmployeeSalary in ( select max(EmployeeSalary) from DemoTable\n -> union all\n -> select min(EmployeeSalary) from DemoTable\n -> );"
},
{
"code": null,
"e": 2443,
"s": 2402,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2672,
"s": 2443,
"text": "+--------------+----------------+\n| EmployeeName | EmployeeSalary |\n+--------------+----------------+\n| Chris | 9800 |\n| David | 7600 |\n+--------------+----------------+\n2 rows in set (0.05 sec)"
}
]
|
What is spread Operator (...) in JavaScript? | With Spread Operator, allow the expression to expand to multiple arguments, elements, variables, etc.
You can try to run the following code to learn how to work with spread operator −
<html>
<body>
<script>
var a, b, c,d, e, f, g;
a = [10,20];
b = "rank";
c = [30,"points"];
d = "run"
// concat method.
e = a.concat(b, c, d);
// spread operator
f = [...a,b, ...c, d];
document.write(e);
document.write("<br>"+f);
</script>
</body>
</html> | [
{
"code": null,
"e": 1164,
"s": 1062,
"text": "With Spread Operator, allow the expression to expand to multiple arguments, elements, variables, etc."
},
{
"code": null,
"e": 1246,
"s": 1164,
"text": "You can try to run the following code to learn how to work with spread operator −"
},
{
"code": null,
"e": 1645,
"s": 1246,
"text": "<html>\n <body>\n <script>\n var a, b, c,d, e, f, g; \n a = [10,20];\n b = \"rank\";\n c = [30,\"points\"]; \n d = \"run\"\n \n // concat method. \n e = a.concat(b, c, d); \n\n // spread operator \n f = [...a,b, ...c, d]; \n \n document.write(e); \n document.write(\"<br>\"+f);\n </script>\n </body>\n</html>"
}
]
|
Print Linked List elements | Practice | GeeksforGeeks | Given a linked list. Print all the elements of the linked list.
Example 1:
Input:
N=2
LinkedList={1 , 2}
Output:
1 2
Explanation:
The linked list contains two
elements 1 and 2.The elements
are printed in a single line.
Example 2:
Input:
N = 3
Linked List = { 49, 10, 30}
Output:
49 10 30
Explanation:
The linked list contains 3
elements 49, 10 and 30. The
elements are printed in a single
line.
0
mayank180919991 week ago
void display(struct Node *head)
{
//add code here
struct Node *temp=head;
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
}
0
rk09817251 week ago
Simple Java code snippet
Node n = head; while(n != null){ System.out.print(n.data + " "); n = n.next; }
0
kininarasimha2 weeks ago
#Javascript
class Solution { display(head){ //code here let curr = head; let str = ""; while (curr) { str += curr.data + " "; curr = curr.next; } console.log(str); }}
+1
shahabuddinbravo402 weeks ago
void display(Node *head) { while(head!=NULL){ cout<<head->data<<" "; head=head->next; } }
0
neelasatyasai932 weeks ago
#PYTHON
class Solution:
def display(self,node):
#code here
t=node
if t==None:
return 0
print(t.data,end=" " )
while t.next!=None:
t=t.next
print(t.data,end=" ")
+1
abhiramjammula2 weeks ago
void display(struct Node *head){ //add code here while(head!=NULL) { printf("%d ",head->data); head=head->next; }}
0
hharshit81183 weeks ago
void display(struct Node *head){ while(head){ printf("%d ", head->data); head = head->next; }}
0
shilsoumyadip3 weeks ago
class Solution{ public: void display(Node *head) { while(head!=NULL) { cout<<head->data<<" "; head=head->next ; } }};
0
yash7raut4 weeks ago
class Solution: def display(self,node): #code here temp = node while(temp): print(temp.data,end=" ") temp = temp.next
0
technophyle11 month ago
Simple and Easy Code :
class Solution
{
public:
void display(Node *head)
{
//your code goes here
Node* tmp=head;
while(tmp!=NULL)
{
cout<<tmp->data<<" ";
tmp=tmp->next ;
}
}
};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 290,
"s": 226,
"text": "Given a linked list. Print all the elements of the linked list."
},
{
"code": null,
"e": 301,
"s": 290,
"text": "Example 1:"
},
{
"code": null,
"e": 447,
"s": 301,
"text": "Input:\nN=2\nLinkedList={1 , 2}\nOutput:\n1 2\nExplanation:\nThe linked list contains two \nelements 1 and 2.The elements \nare printed in a single line."
},
{
"code": null,
"e": 458,
"s": 447,
"text": "Example 2:"
},
{
"code": null,
"e": 627,
"s": 458,
"text": "Input:\nN = 3\nLinked List = { 49, 10, 30}\nOutput: \n49 10 30\nExplanation:\nThe linked list contains 3 \nelements 49, 10 and 30. The \nelements are printed in a single \nline."
},
{
"code": null,
"e": 629,
"s": 627,
"text": "0"
},
{
"code": null,
"e": 654,
"s": 629,
"text": "mayank180919991 week ago"
},
{
"code": null,
"e": 820,
"s": 654,
"text": "void display(struct Node *head)\n{\n //add code here\n struct Node *temp=head;\n while(temp!=NULL){\n printf(\"%d \",temp->data);\n temp=temp->next;\n }\n}"
},
{
"code": null,
"e": 822,
"s": 820,
"text": "0"
},
{
"code": null,
"e": 842,
"s": 822,
"text": "rk09817251 week ago"
},
{
"code": null,
"e": 867,
"s": 842,
"text": "Simple Java code snippet"
},
{
"code": null,
"e": 981,
"s": 869,
"text": " Node n = head; while(n != null){ System.out.print(n.data + \" \"); n = n.next; }"
},
{
"code": null,
"e": 983,
"s": 981,
"text": "0"
},
{
"code": null,
"e": 1008,
"s": 983,
"text": "kininarasimha2 weeks ago"
},
{
"code": null,
"e": 1021,
"s": 1008,
"text": "#Javascript "
},
{
"code": null,
"e": 1202,
"s": 1023,
"text": "class Solution { display(head){ //code here let curr = head; let str = \"\"; while (curr) { str += curr.data + \" \"; curr = curr.next; } console.log(str); }}"
},
{
"code": null,
"e": 1205,
"s": 1202,
"text": "+1"
},
{
"code": null,
"e": 1235,
"s": 1205,
"text": "shahabuddinbravo402 weeks ago"
},
{
"code": null,
"e": 1354,
"s": 1235,
"text": " void display(Node *head) { while(head!=NULL){ cout<<head->data<<\" \"; head=head->next; } }"
},
{
"code": null,
"e": 1356,
"s": 1354,
"text": "0"
},
{
"code": null,
"e": 1383,
"s": 1356,
"text": "neelasatyasai932 weeks ago"
},
{
"code": null,
"e": 1391,
"s": 1383,
"text": "#PYTHON"
},
{
"code": null,
"e": 1615,
"s": 1391,
"text": "class Solution:\n def display(self,node):\n #code here\n t=node\n if t==None:\n return 0\n print(t.data,end=\" \" )\n while t.next!=None:\n t=t.next\n print(t.data,end=\" \")"
},
{
"code": null,
"e": 1618,
"s": 1615,
"text": "+1"
},
{
"code": null,
"e": 1644,
"s": 1618,
"text": "abhiramjammula2 weeks ago"
},
{
"code": null,
"e": 1773,
"s": 1644,
"text": "void display(struct Node *head){ //add code here while(head!=NULL) { printf(\"%d \",head->data); head=head->next; }}"
},
{
"code": null,
"e": 1775,
"s": 1773,
"text": "0"
},
{
"code": null,
"e": 1799,
"s": 1775,
"text": "hharshit81183 weeks ago"
},
{
"code": null,
"e": 1906,
"s": 1799,
"text": "void display(struct Node *head){ while(head){ printf(\"%d \", head->data); head = head->next; }}"
},
{
"code": null,
"e": 1908,
"s": 1906,
"text": "0"
},
{
"code": null,
"e": 1933,
"s": 1908,
"text": "shilsoumyadip3 weeks ago"
},
{
"code": null,
"e": 2086,
"s": 1933,
"text": "class Solution{ public: void display(Node *head) { while(head!=NULL) { cout<<head->data<<\" \"; head=head->next ; } }}; "
},
{
"code": null,
"e": 2088,
"s": 2086,
"text": "0"
},
{
"code": null,
"e": 2109,
"s": 2088,
"text": "yash7raut4 weeks ago"
},
{
"code": null,
"e": 2267,
"s": 2109,
"text": "class Solution: def display(self,node): #code here temp = node while(temp): print(temp.data,end=\" \") temp = temp.next"
},
{
"code": null,
"e": 2269,
"s": 2267,
"text": "0"
},
{
"code": null,
"e": 2293,
"s": 2269,
"text": "technophyle11 month ago"
},
{
"code": null,
"e": 2316,
"s": 2293,
"text": "Simple and Easy Code :"
},
{
"code": null,
"e": 2536,
"s": 2316,
"text": "class Solution\n{\n public:\n void display(Node *head)\n {\n //your code goes here\n Node* tmp=head;\n while(tmp!=NULL)\n {\n cout<<tmp->data<<\" \";\n tmp=tmp->next ;\n }\n }\n};"
},
{
"code": null,
"e": 2682,
"s": 2536,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 2718,
"s": 2682,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2728,
"s": 2718,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2738,
"s": 2728,
"text": "\nContest\n"
},
{
"code": null,
"e": 2801,
"s": 2738,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2949,
"s": 2801,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 3157,
"s": 2949,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 3263,
"s": 3157,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Find missing numbers in a sorted list range in Python | Given a list with sorted numbers, we want to find out which numbers are missing from the given range of numbers.
we can design a for loop to check for the range of numbers and use an if condition with the not in operator to check for the missing elements.
Live Demo
listA = [1,5,6, 7,11,14]
# Original list
print("Given list : ",listA)
# using range
res = [x for x in range(listA[0], listA[-1]+1)
if x not in listA]
# Result
print("Missing elements from the list : \n" ,res)
Running the above code gives us the following result −
Given list : [1, 5, 6, 7, 11, 14]
Missing elements from the list :
[2, 3, 4, 8, 9, 10, 12, 13]
The ZIP function
Live Demo
listA = [1,5,6, 7,11,14]
# printing original list
print("Given list : ",listA)
# using zip
res = []
for m,n in zip(listA,listA[1:]):
if n - m > 1:
for i in range(m+1,n):
res.append(i)
# Result
print("Missing elements from the list : \n" ,res)
Running the above code gives us the following result −
Given list : [1, 5, 6, 7, 11, 14]
Missing elements from the list :
[2, 3, 4, 8, 9, 10, 12, 13] | [
{
"code": null,
"e": 1175,
"s": 1062,
"text": "Given a list with sorted numbers, we want to find out which numbers are missing from the given range of numbers."
},
{
"code": null,
"e": 1318,
"s": 1175,
"text": "we can design a for loop to check for the range of numbers and use an if condition with the not in operator to check for the missing elements."
},
{
"code": null,
"e": 1329,
"s": 1318,
"text": " Live Demo"
},
{
"code": null,
"e": 1570,
"s": 1329,
"text": "listA = [1,5,6, 7,11,14]\n\n# Original list\nprint(\"Given list : \",listA)\n\n# using range\nres = [x for x in range(listA[0], listA[-1]+1)\n if x not in listA]\n# Result\nprint(\"Missing elements from the list : \\n\" ,res)"
},
{
"code": null,
"e": 1625,
"s": 1570,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1720,
"s": 1625,
"text": "Given list : [1, 5, 6, 7, 11, 14]\nMissing elements from the list :\n[2, 3, 4, 8, 9, 10, 12, 13]"
},
{
"code": null,
"e": 1737,
"s": 1720,
"text": "The ZIP function"
},
{
"code": null,
"e": 1748,
"s": 1737,
"text": " Live Demo"
},
{
"code": null,
"e": 2012,
"s": 1748,
"text": "listA = [1,5,6, 7,11,14]\n\n# printing original list\nprint(\"Given list : \",listA)\n\n# using zip\nres = []\nfor m,n in zip(listA,listA[1:]):\n if n - m > 1:\n for i in range(m+1,n):\n res.append(i)\n\n# Result\nprint(\"Missing elements from the list : \\n\" ,res)"
},
{
"code": null,
"e": 2067,
"s": 2012,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2162,
"s": 2067,
"text": "Given list : [1, 5, 6, 7, 11, 14]\nMissing elements from the list :\n[2, 3, 4, 8, 9, 10, 12, 13]"
}
]
|
Closest Pair of Points Problem | In this problem, a set of n points are given on the 2D plane. In this problem, we have to find the pair of points, whose distance is minimum.
To solve this problem, we have to divide points into two halves, after that smallest distance between two points is calculated in a recursive way. Using distances from the middle line, the points are separated into some strips. We will find the smallest distance from the strip array. At first two lists are created with data points, one list will hold points which are sorted on x values, another will hold data points, sorted on y values.
The time complexity of this algorithm will be O(n log n).
Input:
A set of different points are given. (2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)
Output:
Find the minimum distance from each pair of given points.
Here the minimum distance is: 1.41421 unit
findMinDist(pointsList, n)
Input: Given point list and number of points in the list.
Output − Finds minimum distance from two points.
Begin
min := ∞
for all items i in the pointsList, do
for j := i+1 to n-1, do
if distance between pointList[i] and pointList[j] < min, then
min = distance of pointList[i] and pointList[j]
done
done
return min
End
stripClose(strips, size, dist)
Input − Different points in the strip, number of points, distance from the midline.
Output − Closest distance from two points in a strip.
Begin
for all items i in the strip, do
for j := i+1 to size-1 and (y difference of ithand jth points) <min, do
if distance between strip[i] and strip [j] < min, then
min = distance of strip [i] and strip [j]
done
done
return min
End
findClosest(xSorted, ySorted, n)
Input − Points sorted on x values, and points sorted on y values, number of points.
Output − Find minimum distance from the total set of points.
Begin
if n <= 3, then
call findMinDist(xSorted, n)
return the result
mid := n/2
midpoint := xSorted[mid]
define two sub lists of points to separate points along vertical line.
the sub lists are, ySortedLeft and ySortedRight
leftDist := findClosest(xSorted, ySortedLeft, mid) //find left distance
rightDist := findClosest(xSorted, ySortedRight, n - mid) //find right distance
dist := minimum of leftDist and rightDist
make strip of points
j := 0
for i := 0 to n-1, do
if difference of ySorted[i].x and midPoint.x<dist, then
strip[j] := ySorted[i]
j := j+1
done
close := stripClose(strip, j, dist)
return minimum of close and dist
End
#include <iostream>
#include<cmath>
#include<algorithm>
using namespace std;
struct point {
int x, y;
};
intcmpX(point p1, point p2) { //to sort according to x value
return (p1.x < p2.x);
}
intcmpY(point p1, point p2) { //to sort according to y value
return (p1.y < p2.y);
}
float dist(point p1, point p2) { //find distance between p1 and p2
return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));
}
float findMinDist(point pts[], int n) { //find minimum distance between two points in a set
float min = 9999;
for (int i = 0; i < n; ++i)
for (int j = i+1; j < n; ++j)
if (dist(pts[i], pts[j]) < min)
min = dist(pts[i], pts[j]);
return min;
}
float min(float a, float b) {
return (a < b)? a : b;
}
float stripClose(point strip[], int size, float d) { //find closest distance of two points in a strip
float min = d;
for (int i = 0; i < size; ++i)
for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j)
if (dist(strip[i],strip[j]) < min)
min = dist(strip[i], strip[j]);
return min;
}
float findClosest(point xSorted[], point ySorted[], int n){
if (n <= 3)
return findMinDist(xSorted, n);
int mid = n/2;
point midPoint = xSorted[mid];
point ySortedLeft[mid+1]; // y sorted points in the left side
point ySortedRight[n-mid-1]; // y sorted points in the right side
intleftIndex = 0, rightIndex = 0;
for (int i = 0; i < n; i++) { //separate y sorted points to left and right
if (ySorted[i].x <= midPoint.x)
ySortedLeft[leftIndex++] = ySorted[i];
else
ySortedRight[rightIndex++] = ySorted[i];
}
float leftDist = findClosest(xSorted, ySortedLeft, mid);
float rightDist = findClosest(ySorted + mid, ySortedRight, n-mid);
float dist = min(leftDist, rightDist);
point strip[n]; //hold points closer to the vertical line
int j = 0;
for (int i = 0; i < n; i++)
if (abs(ySorted[i].x - midPoint.x) <dist) {
strip[j] = ySorted[i];
j++;
}
return min(dist, stripClose(strip, j, dist)); //find minimum using dist and closest pair in strip
}
float closestPair(point pts[], int n) { //find distance of closest pair in a set of points
point xSorted[n];
point ySorted[n];
for (int i = 0; i < n; i++) {
xSorted[i] = pts[i];
ySorted[i] = pts[i];
}
sort(xSorted, xSorted+n, cmpX);
sort(ySorted, ySorted+n, cmpY);
return findClosest(xSorted, ySorted, n);
}
int main() {
point P[] ={{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}};
int n = 6;
cout<< "The minimum distance is " <<closestPair(P, n);
}
The minimum distance is 1.41421 | [
{
"code": null,
"e": 1204,
"s": 1062,
"text": "In this problem, a set of n points are given on the 2D plane. In this problem, we have to find the pair of points, whose distance is minimum."
},
{
"code": null,
"e": 1645,
"s": 1204,
"text": "To solve this problem, we have to divide points into two halves, after that smallest distance between two points is calculated in a recursive way. Using distances from the middle line, the points are separated into some strips. We will find the smallest distance from the strip array. At first two lists are created with data points, one list will hold points which are sorted on x values, another will hold data points, sorted on y values."
},
{
"code": null,
"e": 1703,
"s": 1645,
"text": "The time complexity of this algorithm will be O(n log n)."
},
{
"code": null,
"e": 1909,
"s": 1703,
"text": "Input:\nA set of different points are given. (2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)\nOutput:\nFind the minimum distance from each pair of given points.\nHere the minimum distance is: 1.41421 unit"
},
{
"code": null,
"e": 1936,
"s": 1909,
"text": "findMinDist(pointsList, n)"
},
{
"code": null,
"e": 1994,
"s": 1936,
"text": "Input: Given point list and number of points in the list."
},
{
"code": null,
"e": 2044,
"s": 1994,
"text": "Output − Finds minimum distance from two points."
},
{
"code": null,
"e": 2300,
"s": 2044,
"text": "Begin\n min := ∞\n for all items i in the pointsList, do\n for j := i+1 to n-1, do\n if distance between pointList[i] and pointList[j] < min, then\n min = distance of pointList[i] and pointList[j]\n done\n done\n return min\nEnd"
},
{
"code": null,
"e": 2331,
"s": 2300,
"text": "stripClose(strips, size, dist)"
},
{
"code": null,
"e": 2415,
"s": 2331,
"text": "Input − Different points in the strip, number of points, distance from the midline."
},
{
"code": null,
"e": 2469,
"s": 2415,
"text": "Output − Closest distance from two points in a strip."
},
{
"code": null,
"e": 2744,
"s": 2469,
"text": "Begin\n for all items i in the strip, do\n for j := i+1 to size-1 and (y difference of ithand jth points) <min, do\n if distance between strip[i] and strip [j] < min, then\n min = distance of strip [i] and strip [j]\n done\n done\n return min\nEnd"
},
{
"code": null,
"e": 2777,
"s": 2744,
"text": "findClosest(xSorted, ySorted, n)"
},
{
"code": null,
"e": 2861,
"s": 2777,
"text": "Input − Points sorted on x values, and points sorted on y values, number of points."
},
{
"code": null,
"e": 2922,
"s": 2861,
"text": "Output − Find minimum distance from the total set of points."
},
{
"code": null,
"e": 3647,
"s": 2922,
"text": "Begin\n if n <= 3, then\n call findMinDist(xSorted, n)\n return the result\n mid := n/2\n midpoint := xSorted[mid]\n define two sub lists of points to separate points along vertical line.\n the sub lists are, ySortedLeft and ySortedRight\n\n leftDist := findClosest(xSorted, ySortedLeft, mid) //find left distance\n rightDist := findClosest(xSorted, ySortedRight, n - mid) //find right distance\n\n dist := minimum of leftDist and rightDist\n\n make strip of points\n j := 0\n for i := 0 to n-1, do\n if difference of ySorted[i].x and midPoint.x<dist, then\n strip[j] := ySorted[i]\n j := j+1\n done\n\n close := stripClose(strip, j, dist)\n return minimum of close and dist\nEnd"
},
{
"code": null,
"e": 6347,
"s": 3647,
"text": "#include <iostream>\n#include<cmath>\n#include<algorithm>\nusing namespace std;\n\nstruct point {\n int x, y;\n};\n\nintcmpX(point p1, point p2) { //to sort according to x value\n return (p1.x < p2.x);\n}\n\nintcmpY(point p1, point p2) { //to sort according to y value\n return (p1.y < p2.y);\n}\n\nfloat dist(point p1, point p2) { //find distance between p1 and p2\n return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));\n}\n\nfloat findMinDist(point pts[], int n) { //find minimum distance between two points in a set\n float min = 9999;\n for (int i = 0; i < n; ++i)\n for (int j = i+1; j < n; ++j)\n if (dist(pts[i], pts[j]) < min)\n min = dist(pts[i], pts[j]);\n return min;\n}\n\nfloat min(float a, float b) {\n return (a < b)? a : b;\n}\n\nfloat stripClose(point strip[], int size, float d) { //find closest distance of two points in a strip\n float min = d;\n for (int i = 0; i < size; ++i)\n for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j)\n if (dist(strip[i],strip[j]) < min)\n min = dist(strip[i], strip[j]);\n return min;\n}\n\nfloat findClosest(point xSorted[], point ySorted[], int n){\n if (n <= 3)\n return findMinDist(xSorted, n);\n int mid = n/2;\n\n point midPoint = xSorted[mid];\n point ySortedLeft[mid+1]; // y sorted points in the left side\n point ySortedRight[n-mid-1]; // y sorted points in the right side\n intleftIndex = 0, rightIndex = 0;\n\n for (int i = 0; i < n; i++) { //separate y sorted points to left and right\n if (ySorted[i].x <= midPoint.x)\n ySortedLeft[leftIndex++] = ySorted[i];\n else\n ySortedRight[rightIndex++] = ySorted[i];\n }\n\n float leftDist = findClosest(xSorted, ySortedLeft, mid);\n float rightDist = findClosest(ySorted + mid, ySortedRight, n-mid);\n float dist = min(leftDist, rightDist);\n\n point strip[n]; //hold points closer to the vertical line\n int j = 0;\n\n for (int i = 0; i < n; i++)\n if (abs(ySorted[i].x - midPoint.x) <dist) {\n strip[j] = ySorted[i];\n j++;\n }\n return min(dist, stripClose(strip, j, dist)); //find minimum using dist and closest pair in strip\n}\n\nfloat closestPair(point pts[], int n) { //find distance of closest pair in a set of points\n point xSorted[n];\n point ySorted[n];\n\n for (int i = 0; i < n; i++) {\n xSorted[i] = pts[i];\n ySorted[i] = pts[i];\n }\n\n sort(xSorted, xSorted+n, cmpX);\n sort(ySorted, ySorted+n, cmpY);\n return findClosest(xSorted, ySorted, n);\n}\n\nint main() {\n point P[] ={{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}};\n int n = 6;\n cout<< \"The minimum distance is \" <<closestPair(P, n);\n}"
},
{
"code": null,
"e": 6379,
"s": 6347,
"text": "The minimum distance is 1.41421"
}
]
|
Determine when a Frame or Window is Opened in Java | To determine when a Window is opened in Java, use the WindowListener, which is the listener interface for receiving window events..
WindowListener listener = new WindowAdapter() {
public void windowOpened(WindowEvent evt) {
Frame frame = (Frame) evt.getSource();
System.out.println("Opened "+frame.getTitle());
}
};
Above, we have used the windowOpened() method, which is invoked when a window has been opened −
public void windowOpened(WindowEvent evt) {
Frame frame = (Frame) evt.getSource();
System.out.println("Opened "+frame.getTitle());
}
The following is an example to determine when a frame or window is opened in Java −
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class SwingDemo {
public static void main(String args[]) throws BadLocationException {
JFrame frame = new JFrame("Demo");
WindowListener listener = new WindowAdapter() {
public void windowOpened(WindowEvent evt) {
Frame frame = (Frame) evt.getSource();
System.out.println("Opened "+frame.getTitle());
}
};
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = frame.getContentPane();
JTextPane pane = new JTextPane();
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet, true);
StyleConstants.setForeground(attributeSet, Color.black);
StyleConstants.setBackground(attributeSet, Color.orange);
pane.setCharacterAttributes(attributeSet, true);
pane.setText("We are learning Java and this is a demo text!");
JScrollPane scrollPane = new JScrollPane(pane);
container.add(scrollPane, BorderLayout.CENTER);
frame.setSize(550, 300);
frame.addWindowListener(listener);
frame.setVisible(true);
}
} | [
{
"code": null,
"e": 1194,
"s": 1062,
"text": "To determine when a Window is opened in Java, use the WindowListener, which is the listener interface for receiving window events.."
},
{
"code": null,
"e": 1396,
"s": 1194,
"text": "WindowListener listener = new WindowAdapter() {\n public void windowOpened(WindowEvent evt) {\n Frame frame = (Frame) evt.getSource();\n System.out.println(\"Opened \"+frame.getTitle());\n }\n};"
},
{
"code": null,
"e": 1492,
"s": 1396,
"text": "Above, we have used the windowOpened() method, which is invoked when a window has been opened −"
},
{
"code": null,
"e": 1631,
"s": 1492,
"text": "public void windowOpened(WindowEvent evt) {\n Frame frame = (Frame) evt.getSource();\n System.out.println(\"Opened \"+frame.getTitle());\n}"
},
{
"code": null,
"e": 1715,
"s": 1631,
"text": "The following is an example to determine when a frame or window is opened in Java −"
},
{
"code": null,
"e": 3273,
"s": 1715,
"text": "package my;\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Container;\nimport java.awt.Frame;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.awt.event.WindowListener;\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextPane;\nimport javax.swing.text.BadLocationException;\nimport javax.swing.text.SimpleAttributeSet;\nimport javax.swing.text.StyleConstants;\npublic class SwingDemo {\n public static void main(String args[]) throws BadLocationException {\n JFrame frame = new JFrame(\"Demo\");\n WindowListener listener = new WindowAdapter() {\n public void windowOpened(WindowEvent evt) {\n Frame frame = (Frame) evt.getSource();\n System.out.println(\"Opened \"+frame.getTitle());\n }\n };\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n Container container = frame.getContentPane();\n JTextPane pane = new JTextPane();\n SimpleAttributeSet attributeSet = new SimpleAttributeSet();\n StyleConstants.setItalic(attributeSet, true);\n StyleConstants.setForeground(attributeSet, Color.black);\n StyleConstants.setBackground(attributeSet, Color.orange);\n pane.setCharacterAttributes(attributeSet, true);\n pane.setText(\"We are learning Java and this is a demo text!\");\n JScrollPane scrollPane = new JScrollPane(pane);\n container.add(scrollPane, BorderLayout.CENTER);\n frame.setSize(550, 300);\n frame.addWindowListener(listener);\n frame.setVisible(true);\n }\n}"
}
]
|
Automatically Update Data Sources in Python | by Joe T. Santhanavanich | Towards Data Science | In Data Sciences, several times, you get an external data source such as a csv table for your Python project from the open-source website or git repository. Some of these datasets may update periodically. Then, you might end up with open a web browser to download that dataset before running your Python script to get the most updated result. This article will show you an essential guide on how to automate this process to keep your data up-to-date in an easy way.
Several open-source datasets can be retrieved from the URL. You may useurllib module to open and read the URL directly in Python. It is a pre-installed module in most Python versions. So you can just import this module and use the following codes to download the data from any URL.
import urllib.requesturl = '<Your URL Here>'output = '<Your output filename/location>'urllib.request.urlretrieve(url, output)#.. Continue data analysis with updated output file
For instance, an example script below shows an example of updating German COVID-19 data from Robert Koch-Institut (RKI, a German Research Institute for disease control and prevention) The data is in csv format and available at this URL. In real practice, some URLs may change or depreciate over time, which makes the Python script run to an error, so we may include try/except to check if the URL is still valid or not. Assume that you want to keep all versions of downloaded files, you may use thedatetime module to add a timestamp to the output filename too.
* Please note that if you use macOS, you should have a Python certificate installed before you can use the urllib library. You can easily do this by running a install certificates.command file in your Macintosh HD > Applications > Python3.x folder.
If your python project relies on the data from the git repository. After you clone the repository and get the dataset to your local machine, you might have to periodically do git fetch or pull to keep your dataset up-to-date. In this case, you may use the GitPython module to automatically update your project dataset automatically. To use this module, you have to install it first, which you can easily use pip to do so.
pip install gitpython
If you run to an error, you may check this full GitPython document to check the requirements you might not have of your os environment. After you have the module installed, you can just easily follow these codes to automatically do the git pull every time you run your code.
import gitrepo = git.Repo('<your repository folder location>')repo.remotes.origin.pull()#... Continue with your Code.
As an example, the JHU CSSE Github repository has provided the COVID-19 time-series dataset in csv format in which the datasets are daily updated. After you clone the repository to your machine, you may add the above codes to the beginning of your Python script to automatically pull the last version every time. In this way, you can make sure that your result is up-to-date.
For the git authentication, if you use ssh, it would be straightforward. In case you use HTTPs, it will be more convenient to save your username and password to your environment. In Mac and Windows, the authentication information is saved automatically after you input for the first time. In Linux, you may force a machine to remember your credentials by changing the credential timeout. For example, you can use the following command to make your machine remember your credentials for one year. (31,536,000 seconds)
$ git config --global credential.helper 'cache --timeout=31536000'
This article shows step-by-step guidelines for updating the dataset from any URL or git repository directly at the beginning of your Python script. In this way, you can make sure that you run a script based on the up-to-date dataset.
I hope you like this article and found it useful for your daily work or projects. Feel free to leave me a message if you have any questions or comments.
About me & Check out all my blog contents: Link
Be Safe and Healthy! 💪
Thank you for Reading. 📚 | [
{
"code": null,
"e": 638,
"s": 172,
"text": "In Data Sciences, several times, you get an external data source such as a csv table for your Python project from the open-source website or git repository. Some of these datasets may update periodically. Then, you might end up with open a web browser to download that dataset before running your Python script to get the most updated result. This article will show you an essential guide on how to automate this process to keep your data up-to-date in an easy way."
},
{
"code": null,
"e": 920,
"s": 638,
"text": "Several open-source datasets can be retrieved from the URL. You may useurllib module to open and read the URL directly in Python. It is a pre-installed module in most Python versions. So you can just import this module and use the following codes to download the data from any URL."
},
{
"code": null,
"e": 1097,
"s": 920,
"text": "import urllib.requesturl = '<Your URL Here>'output = '<Your output filename/location>'urllib.request.urlretrieve(url, output)#.. Continue data analysis with updated output file"
},
{
"code": null,
"e": 1658,
"s": 1097,
"text": "For instance, an example script below shows an example of updating German COVID-19 data from Robert Koch-Institut (RKI, a German Research Institute for disease control and prevention) The data is in csv format and available at this URL. In real practice, some URLs may change or depreciate over time, which makes the Python script run to an error, so we may include try/except to check if the URL is still valid or not. Assume that you want to keep all versions of downloaded files, you may use thedatetime module to add a timestamp to the output filename too."
},
{
"code": null,
"e": 1907,
"s": 1658,
"text": "* Please note that if you use macOS, you should have a Python certificate installed before you can use the urllib library. You can easily do this by running a install certificates.command file in your Macintosh HD > Applications > Python3.x folder."
},
{
"code": null,
"e": 2329,
"s": 1907,
"text": "If your python project relies on the data from the git repository. After you clone the repository and get the dataset to your local machine, you might have to periodically do git fetch or pull to keep your dataset up-to-date. In this case, you may use the GitPython module to automatically update your project dataset automatically. To use this module, you have to install it first, which you can easily use pip to do so."
},
{
"code": null,
"e": 2351,
"s": 2329,
"text": "pip install gitpython"
},
{
"code": null,
"e": 2626,
"s": 2351,
"text": "If you run to an error, you may check this full GitPython document to check the requirements you might not have of your os environment. After you have the module installed, you can just easily follow these codes to automatically do the git pull every time you run your code."
},
{
"code": null,
"e": 2744,
"s": 2626,
"text": "import gitrepo = git.Repo('<your repository folder location>')repo.remotes.origin.pull()#... Continue with your Code."
},
{
"code": null,
"e": 3120,
"s": 2744,
"text": "As an example, the JHU CSSE Github repository has provided the COVID-19 time-series dataset in csv format in which the datasets are daily updated. After you clone the repository to your machine, you may add the above codes to the beginning of your Python script to automatically pull the last version every time. In this way, you can make sure that your result is up-to-date."
},
{
"code": null,
"e": 3637,
"s": 3120,
"text": "For the git authentication, if you use ssh, it would be straightforward. In case you use HTTPs, it will be more convenient to save your username and password to your environment. In Mac and Windows, the authentication information is saved automatically after you input for the first time. In Linux, you may force a machine to remember your credentials by changing the credential timeout. For example, you can use the following command to make your machine remember your credentials for one year. (31,536,000 seconds)"
},
{
"code": null,
"e": 3704,
"s": 3637,
"text": "$ git config --global credential.helper 'cache --timeout=31536000'"
},
{
"code": null,
"e": 3938,
"s": 3704,
"text": "This article shows step-by-step guidelines for updating the dataset from any URL or git repository directly at the beginning of your Python script. In this way, you can make sure that you run a script based on the up-to-date dataset."
},
{
"code": null,
"e": 4091,
"s": 3938,
"text": "I hope you like this article and found it useful for your daily work or projects. Feel free to leave me a message if you have any questions or comments."
},
{
"code": null,
"e": 4139,
"s": 4091,
"text": "About me & Check out all my blog contents: Link"
},
{
"code": null,
"e": 4162,
"s": 4139,
"text": "Be Safe and Healthy! 💪"
}
]
|
Program to remove HTML tags from a given String - GeeksforGeeks | 11 Feb, 2022
Given a string str which contains some HTML tags, the task is to remove all the tags present in the given string str.Examples:
Input: str = “<div><b>Geeks for Geeks</b></div>” Output: Geeks for GeeksInput: str = “<a href=”https://www.geeksforgeeks.org/”>GFG</a>” Output: GFG
Approach: The idea is to use the Regular Expression to solve this problem. The following steps can be followed to compute the resultant string:
Get the string.Since every HTML tags are enclosed in angular brackets(<>). Therefore use replaceAll() function in regex to replace every substring start with “<“ and ends with “>” to empty string.The function is used as:
Get the string.
Since every HTML tags are enclosed in angular brackets(<>). Therefore use replaceAll() function in regex to replace every substring start with “<“ and ends with “>” to empty string.
The function is used as:
String str;
str.replaceAll("\\", "");
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>#include <regex>using namespace std; // Function to remove the HTML tags// from the given stringvoid RemoveHTMLTags(string s){ const regex pattern("\\<.*?\\>"); // Use regex_replace function in regex // to erase every tags enclosed in <> s = regex_replace(s, pattern, ""); // Print string after removing tags cout << s; return ;} // Driver Codeint main(){ // Given String string str = "<div><b>Geeks for Geeks</b></div>"; // Function call to print the // HTML string after removing tags RemoveHTMLTags(str) ; return 0;} // This code is contributed by yuvraj_chandra
// Java program for the above approach class GFG { // Function to remove the HTML tags // from the given tags static void RemoveHTMLTags(String str) { // Use replaceAll function in regex // to erase every tags enclosed in <> str = str.replaceAll("\\<.*?\\>", ""); // Print string after removing tags System.out.println(str); } // Driver Code public static void main(String[] args) { String str; // Given String str = "<div><b>Geeks for Geeks</b></div>"; // Function call to print the // HTML string after removing tags RemoveHTMLTags(str); }}
# Python3 program for the# above approachimport re # Function to remove the HTML tags# from the given tagsdef RemoveHTMLTags(strr): # Print string after removing tags print(re.compile(r'<[^>]+>').sub('', strr)) # Driver codeif __name__=='__main__': # Given String strr = "<div><b>Geeks for Geeks</b></div>" # Function call to print the HTML # string after removing tags RemoveHTMLTags(strr); # This code is contributed by vikas_g
// C# program for the above approachusing System; class GFG{ // Function to remove the HTML tags// from the given tagsstatic void RemoveHTMLTags(String str){ // Use replaceAll function in regex // to erase every tags enclosed in <> // str = Regex.Replace(str, "<.*?>", String.Empty) System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("<[^>]*>"); str = rx.Replace(str, ""); // Print string after removing tags Console.WriteLine(str);} // Driver codepublic static void Main(String []args){ String str; // Given String str = "<div><b>Geeks for Geeks</b></div>"; // Function call to print the // HTML string after removing tags RemoveHTMLTags(str);}} // This code is contributed by vikas_g
<script> // JavaScript program for the above approach // Function to remove the HTML tags// from the given stringfunction RemoveHTMLTags(s) { const pattern = new RegExp("\\<.*?\\>"); // Use regex_replace function in regex // to erase every tags enclosed in <> s = new String(s).replace(pattern, ""); // Print string after removing tags document.write(s); return;} // Driver Code // Given Stringlet str = "<div><b>Geeks for Geeks</b></div>"; // Function call to print the// HTML string after removing tagsRemoveHTMLTags(str); </script>
Geeks for Geeks
vikas_g
yuvraj_chandra
_saurabh_jaiswal
rkbhola5
CPP-regex
HTML-Tags
java-regular-expression
regular-expression
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
Hill Cipher
Naive algorithm for Pattern Searching
Vigenère Cipher
Convert character array to string in C++
Reverse words in a given String in Python
sprintf() in C
String class in Java | Set 1
How to Append a Character to a String in C
Print all the duplicates in the input string | [
{
"code": null,
"e": 24773,
"s": 24745,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 24902,
"s": 24773,
"text": "Given a string str which contains some HTML tags, the task is to remove all the tags present in the given string str.Examples: "
},
{
"code": null,
"e": 25052,
"s": 24902,
"text": "Input: str = “<div><b>Geeks for Geeks</b></div>” Output: Geeks for GeeksInput: str = “<a href=”https://www.geeksforgeeks.org/”>GFG</a>” Output: GFG "
},
{
"code": null,
"e": 25200,
"s": 25054,
"text": "Approach: The idea is to use the Regular Expression to solve this problem. The following steps can be followed to compute the resultant string: "
},
{
"code": null,
"e": 25423,
"s": 25200,
"text": "Get the string.Since every HTML tags are enclosed in angular brackets(<>). Therefore use replaceAll() function in regex to replace every substring start with “<“ and ends with “>” to empty string.The function is used as: "
},
{
"code": null,
"e": 25439,
"s": 25423,
"text": "Get the string."
},
{
"code": null,
"e": 25621,
"s": 25439,
"text": "Since every HTML tags are enclosed in angular brackets(<>). Therefore use replaceAll() function in regex to replace every substring start with “<“ and ends with “>” to empty string."
},
{
"code": null,
"e": 25648,
"s": 25621,
"text": "The function is used as: "
},
{
"code": null,
"e": 25686,
"s": 25648,
"text": "String str;\nstr.replaceAll(\"\\\\\", \"\");"
},
{
"code": null,
"e": 25738,
"s": 25686,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25742,
"s": 25738,
"text": "C++"
},
{
"code": null,
"e": 25747,
"s": 25742,
"text": "Java"
},
{
"code": null,
"e": 25755,
"s": 25747,
"text": "Python3"
},
{
"code": null,
"e": 25758,
"s": 25755,
"text": "C#"
},
{
"code": null,
"e": 25769,
"s": 25758,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <iostream>#include <regex>using namespace std; // Function to remove the HTML tags// from the given stringvoid RemoveHTMLTags(string s){ const regex pattern(\"\\\\<.*?\\\\>\"); // Use regex_replace function in regex // to erase every tags enclosed in <> s = regex_replace(s, pattern, \"\"); // Print string after removing tags cout << s; return ;} // Driver Codeint main(){ // Given String string str = \"<div><b>Geeks for Geeks</b></div>\"; // Function call to print the // HTML string after removing tags RemoveHTMLTags(str) ; return 0;} // This code is contributed by yuvraj_chandra",
"e": 26412,
"s": 25769,
"text": null
},
{
"code": "// Java program for the above approach class GFG { // Function to remove the HTML tags // from the given tags static void RemoveHTMLTags(String str) { // Use replaceAll function in regex // to erase every tags enclosed in <> str = str.replaceAll(\"\\\\<.*?\\\\>\", \"\"); // Print string after removing tags System.out.println(str); } // Driver Code public static void main(String[] args) { String str; // Given String str = \"<div><b>Geeks for Geeks</b></div>\"; // Function call to print the // HTML string after removing tags RemoveHTMLTags(str); }}",
"e": 27065,
"s": 26412,
"text": null
},
{
"code": "# Python3 program for the# above approachimport re # Function to remove the HTML tags# from the given tagsdef RemoveHTMLTags(strr): # Print string after removing tags print(re.compile(r'<[^>]+>').sub('', strr)) # Driver codeif __name__=='__main__': # Given String strr = \"<div><b>Geeks for Geeks</b></div>\" # Function call to print the HTML # string after removing tags RemoveHTMLTags(strr); # This code is contributed by vikas_g",
"e": 27539,
"s": 27065,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to remove the HTML tags// from the given tagsstatic void RemoveHTMLTags(String str){ // Use replaceAll function in regex // to erase every tags enclosed in <> // str = Regex.Replace(str, \"<.*?>\", String.Empty) System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex(\"<[^>]*>\"); str = rx.Replace(str, \"\"); // Print string after removing tags Console.WriteLine(str);} // Driver codepublic static void Main(String []args){ String str; // Given String str = \"<div><b>Geeks for Geeks</b></div>\"; // Function call to print the // HTML string after removing tags RemoveHTMLTags(str);}} // This code is contributed by vikas_g",
"e": 28312,
"s": 27539,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to remove the HTML tags// from the given stringfunction RemoveHTMLTags(s) { const pattern = new RegExp(\"\\\\<.*?\\\\>\"); // Use regex_replace function in regex // to erase every tags enclosed in <> s = new String(s).replace(pattern, \"\"); // Print string after removing tags document.write(s); return;} // Driver Code // Given Stringlet str = \"<div><b>Geeks for Geeks</b></div>\"; // Function call to print the// HTML string after removing tagsRemoveHTMLTags(str); </script>",
"e": 28873,
"s": 28312,
"text": null
},
{
"code": null,
"e": 28889,
"s": 28873,
"text": "Geeks for Geeks"
},
{
"code": null,
"e": 28899,
"s": 28891,
"text": "vikas_g"
},
{
"code": null,
"e": 28914,
"s": 28899,
"text": "yuvraj_chandra"
},
{
"code": null,
"e": 28931,
"s": 28914,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 28940,
"s": 28931,
"text": "rkbhola5"
},
{
"code": null,
"e": 28950,
"s": 28940,
"text": "CPP-regex"
},
{
"code": null,
"e": 28960,
"s": 28950,
"text": "HTML-Tags"
},
{
"code": null,
"e": 28984,
"s": 28960,
"text": "java-regular-expression"
},
{
"code": null,
"e": 29003,
"s": 28984,
"text": "regular-expression"
},
{
"code": null,
"e": 29011,
"s": 29003,
"text": "Strings"
},
{
"code": null,
"e": 29019,
"s": 29011,
"text": "Strings"
},
{
"code": null,
"e": 29117,
"s": 29019,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29126,
"s": 29117,
"text": "Comments"
},
{
"code": null,
"e": 29139,
"s": 29126,
"text": "Old Comments"
},
{
"code": null,
"e": 29184,
"s": 29139,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 29196,
"s": 29184,
"text": "Hill Cipher"
},
{
"code": null,
"e": 29234,
"s": 29196,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 29251,
"s": 29234,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 29292,
"s": 29251,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 29334,
"s": 29292,
"text": "Reverse words in a given String in Python"
},
{
"code": null,
"e": 29349,
"s": 29334,
"text": "sprintf() in C"
},
{
"code": null,
"e": 29378,
"s": 29349,
"text": "String class in Java | Set 1"
},
{
"code": null,
"e": 29421,
"s": 29378,
"text": "How to Append a Character to a String in C"
}
]
|
Material Design Lite - Tabs | The Material Design Lite (MDL) tab component is a user interface component which helps to show multiple screens in a single space in an exclusive manner.
MDL provides various CSS classes to apply various predefined visual and behavioral enhancements to the tabs. The following table mentions the available classes and their effects.
mdl-layout
Identifies a container as an MDL component. Required on outer container element.
mdl-tabs
Identifies a tabs container as an MDL component. Required on "outer" div element.
mdl-js-tabs
Sets basic MDL behavior to tabs container. Required on "outer" div element.
mdl-js-ripple-effect
Adds ripple click effect to tab links. Optional; goes on "outer" div element.
mdl-tabs__tab-bar
Identifies a container as an MDL tabs link bar. Required on first "inner" div element.
mdl-tabs__tab
Identifies an anchor (link) as an MDL tab activator. Required on all links in first "inner" div element.
is-active
Identifies a tab as the default display tab. Required on one (and only one) of the "inner" div (tab) elements.
mdl-tabs__panel
Identifies a container as tab content. Required on each of the "inner" div (tab) elements.
The following example will help you understand the use of the mdl-tab class to layout contents on various tabs.
The MDL classes given below will be used in this example −
mdl-layout − Identifies a div as an MDL component.
mdl-layout − Identifies a div as an MDL component.
mdl-js-layout − Adds basic MDL behavior to outer div.
mdl-js-layout − Adds basic MDL behavior to outer div.
mdl-layout--fixed-header − Makes the header always visible, even in small screens.
mdl-layout--fixed-header − Makes the header always visible, even in small screens.
mdl-layout__header-row − Identifies container as MDL header row.
mdl-layout__header-row − Identifies container as MDL header row.
mdl-layout-title − Identifies layout title text.
mdl-layout-title − Identifies layout title text.
mdl-layout__content − Identifies div as MDL layout content.
mdl-layout__content − Identifies div as MDL layout content.
mdl-tabs − Identifies a tabs container as an MDL component.
mdl-tabs − Identifies a tabs container as an MDL component.
mdl-js-tabs − Sets basic MDL behavior to tabs container.
mdl-js-tabs − Sets basic MDL behavior to tabs container.
mdl-tabs__tab-bar − Identifies a container as an MDL tabs link bar.
mdl-tabs__tab-bar − Identifies a container as an MDL tabs link bar.
mdl-tabs__tab − Identifies an anchor (link) as an MDL tab activator.
mdl-tabs__tab − Identifies an anchor (link) as an MDL tab activator.
is-active − Identifies a tab as the default display tab.
is-active − Identifies a tab as the default display tab.
mdl-tabs__panel − Identifies a container as tab content.
mdl-tabs__panel − Identifies a container as tab content.
<html>
<head>
<link rel = "stylesheet"
href = "https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-pink.min.css">
<script src = "https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js">
</script>
<link rel = "stylesheet"
href = "https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>
<div class = "mdl-layout mdl-js-layout mdl-layout--fixed-header">
<header class = "mdl-layout__header">
<div class = "mdl-layout__header-row">
<span class = "mdl-layout-title">Material Design Tabs</span>
</div>
</header>
<main class = "mdl-layout__content">
<div class = "mdl-tabs mdl-js-tabs">
<div class = "mdl-tabs__tab-bar">
<a href = "#tab1-panel" class = "mdl-tabs__tab is-active">Tab 1</a>
<a href = "#tab2-panel" class = "mdl-tabs__tab">Tab 2</a>
<a href = "#tab3-panel" class = "mdl-tabs__tab">Tab 3</a>
</div>
<div class = "mdl-tabs__panel is-active" id = "tab1-panel">
<p>Tab 1 Content</p>
</div>
<div class = "mdl-tabs__panel" id = "tab2-panel">
<p>Tab 2 Content</p>
</div>
<div class = "mdl-tabs__panel" id = "tab3-panel">
<p>Tab 3 Content</p>
</div>
</div>
</main>
</div>
</body>
</html>
Verify the result.
Tab 1 Content
Tab 2 Content
Tab 3 Content
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2040,
"s": 1886,
"text": "The Material Design Lite (MDL) tab component is a user interface component which helps to show multiple screens in a single space in an exclusive manner."
},
{
"code": null,
"e": 2219,
"s": 2040,
"text": "MDL provides various CSS classes to apply various predefined visual and behavioral enhancements to the tabs. The following table mentions the available classes and their effects."
},
{
"code": null,
"e": 2230,
"s": 2219,
"text": "mdl-layout"
},
{
"code": null,
"e": 2311,
"s": 2230,
"text": "Identifies a container as an MDL component. Required on outer container element."
},
{
"code": null,
"e": 2320,
"s": 2311,
"text": "mdl-tabs"
},
{
"code": null,
"e": 2402,
"s": 2320,
"text": "Identifies a tabs container as an MDL component. Required on \"outer\" div element."
},
{
"code": null,
"e": 2414,
"s": 2402,
"text": "mdl-js-tabs"
},
{
"code": null,
"e": 2490,
"s": 2414,
"text": "Sets basic MDL behavior to tabs container. Required on \"outer\" div element."
},
{
"code": null,
"e": 2511,
"s": 2490,
"text": "mdl-js-ripple-effect"
},
{
"code": null,
"e": 2589,
"s": 2511,
"text": "Adds ripple click effect to tab links. Optional; goes on \"outer\" div element."
},
{
"code": null,
"e": 2607,
"s": 2589,
"text": "mdl-tabs__tab-bar"
},
{
"code": null,
"e": 2694,
"s": 2607,
"text": "Identifies a container as an MDL tabs link bar. Required on first \"inner\" div element."
},
{
"code": null,
"e": 2708,
"s": 2694,
"text": "mdl-tabs__tab"
},
{
"code": null,
"e": 2813,
"s": 2708,
"text": "Identifies an anchor (link) as an MDL tab activator. Required on all links in first \"inner\" div element."
},
{
"code": null,
"e": 2823,
"s": 2813,
"text": "is-active"
},
{
"code": null,
"e": 2934,
"s": 2823,
"text": "Identifies a tab as the default display tab.\tRequired on one (and only one) of the \"inner\" div (tab) elements."
},
{
"code": null,
"e": 2950,
"s": 2934,
"text": "mdl-tabs__panel"
},
{
"code": null,
"e": 3041,
"s": 2950,
"text": "Identifies a container as tab content.\tRequired on each of the \"inner\" div (tab) elements."
},
{
"code": null,
"e": 3153,
"s": 3041,
"text": "The following example will help you understand the use of the mdl-tab class to layout contents on various tabs."
},
{
"code": null,
"e": 3212,
"s": 3153,
"text": "The MDL classes given below will be used in this example −"
},
{
"code": null,
"e": 3263,
"s": 3212,
"text": "mdl-layout − Identifies a div as an MDL component."
},
{
"code": null,
"e": 3314,
"s": 3263,
"text": "mdl-layout − Identifies a div as an MDL component."
},
{
"code": null,
"e": 3368,
"s": 3314,
"text": "mdl-js-layout − Adds basic MDL behavior to outer div."
},
{
"code": null,
"e": 3422,
"s": 3368,
"text": "mdl-js-layout − Adds basic MDL behavior to outer div."
},
{
"code": null,
"e": 3505,
"s": 3422,
"text": "mdl-layout--fixed-header − Makes the header always visible, even in small screens."
},
{
"code": null,
"e": 3588,
"s": 3505,
"text": "mdl-layout--fixed-header − Makes the header always visible, even in small screens."
},
{
"code": null,
"e": 3653,
"s": 3588,
"text": "mdl-layout__header-row − Identifies container as MDL header row."
},
{
"code": null,
"e": 3718,
"s": 3653,
"text": "mdl-layout__header-row − Identifies container as MDL header row."
},
{
"code": null,
"e": 3767,
"s": 3718,
"text": "mdl-layout-title − Identifies layout title text."
},
{
"code": null,
"e": 3816,
"s": 3767,
"text": "mdl-layout-title − Identifies layout title text."
},
{
"code": null,
"e": 3876,
"s": 3816,
"text": "mdl-layout__content − Identifies div as MDL layout content."
},
{
"code": null,
"e": 3936,
"s": 3876,
"text": "mdl-layout__content − Identifies div as MDL layout content."
},
{
"code": null,
"e": 3996,
"s": 3936,
"text": "mdl-tabs − Identifies a tabs container as an MDL component."
},
{
"code": null,
"e": 4056,
"s": 3996,
"text": "mdl-tabs − Identifies a tabs container as an MDL component."
},
{
"code": null,
"e": 4113,
"s": 4056,
"text": "mdl-js-tabs − Sets basic MDL behavior to tabs container."
},
{
"code": null,
"e": 4170,
"s": 4113,
"text": "mdl-js-tabs − Sets basic MDL behavior to tabs container."
},
{
"code": null,
"e": 4238,
"s": 4170,
"text": "mdl-tabs__tab-bar − Identifies a container as an MDL tabs link bar."
},
{
"code": null,
"e": 4306,
"s": 4238,
"text": "mdl-tabs__tab-bar − Identifies a container as an MDL tabs link bar."
},
{
"code": null,
"e": 4375,
"s": 4306,
"text": "mdl-tabs__tab − Identifies an anchor (link) as an MDL tab activator."
},
{
"code": null,
"e": 4444,
"s": 4375,
"text": "mdl-tabs__tab − Identifies an anchor (link) as an MDL tab activator."
},
{
"code": null,
"e": 4501,
"s": 4444,
"text": "is-active − Identifies a tab as the default display tab."
},
{
"code": null,
"e": 4558,
"s": 4501,
"text": "is-active − Identifies a tab as the default display tab."
},
{
"code": null,
"e": 4615,
"s": 4558,
"text": "mdl-tabs__panel − Identifies a container as tab content."
},
{
"code": null,
"e": 4672,
"s": 4615,
"text": "mdl-tabs__panel − Identifies a container as tab content."
},
{
"code": null,
"e": 6288,
"s": 4672,
"text": "<html>\n <head>\n <link rel = \"stylesheet\" \n href = \"https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-pink.min.css\">\n <script src = \"https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js\">\n </script>\n <link rel = \"stylesheet\" \n href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n </head>\n \n <body>\n <div class = \"mdl-layout mdl-js-layout mdl-layout--fixed-header\">\n <header class = \"mdl-layout__header\">\n <div class = \"mdl-layout__header-row\"> \n <span class = \"mdl-layout-title\">Material Design Tabs</span> \n </div> \n </header> \n \n <main class = \"mdl-layout__content\"> \n <div class = \"mdl-tabs mdl-js-tabs\">\n <div class = \"mdl-tabs__tab-bar\">\n <a href = \"#tab1-panel\" class = \"mdl-tabs__tab is-active\">Tab 1</a>\n <a href = \"#tab2-panel\" class = \"mdl-tabs__tab\">Tab 2</a>\n <a href = \"#tab3-panel\" class = \"mdl-tabs__tab\">Tab 3</a>\n </div>\n \n <div class = \"mdl-tabs__panel is-active\" id = \"tab1-panel\">\n <p>Tab 1 Content</p>\n </div>\n \n <div class = \"mdl-tabs__panel\" id = \"tab2-panel\">\n <p>Tab 2 Content</p>\n </div>\n \n <div class = \"mdl-tabs__panel\" id = \"tab3-panel\">\n <p>Tab 3 Content</p>\n </div>\n </div>\n </main>\n </div> \n </body>\n</html>"
},
{
"code": null,
"e": 6307,
"s": 6288,
"text": "Verify the result."
},
{
"code": null,
"e": 6321,
"s": 6307,
"text": "Tab 1 Content"
},
{
"code": null,
"e": 6335,
"s": 6321,
"text": "Tab 2 Content"
},
{
"code": null,
"e": 6349,
"s": 6335,
"text": "Tab 3 Content"
},
{
"code": null,
"e": 6356,
"s": 6349,
"text": " Print"
},
{
"code": null,
"e": 6367,
"s": 6356,
"text": " Add Notes"
}
]
|
Tryit Editor v3.6 - Show Node.js | var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'}); | [
{
"code": null,
"e": 28,
"s": 0,
"text": "var http = require('http');"
},
{
"code": null,
"e": 30,
"s": 28,
"text": ""
},
{
"code": null,
"e": 70,
"s": 30,
"text": "http.createServer(function (req, res) {"
}
]
|
Complex Numbers in Java | Complex numbers are those that have an imaginary part and a real part associated with it. They can
be added and subtracted like regular numbers. The real parts and imaginary parts are respectively
added or subtracted or even multiplied and divided.
Live Demo
public class Demo{
double my_real;
double my_imag;
public Demo(double my_real, double my_imag){
this.my_real = my_real;
this.my_imag = my_imag;
}
public static void main(String[] args){
Demo n1 = new Demo(76.8, 24.0),
n2 = new Demo(65.9, 11.23),
temp;
temp = add(n1, n2);
System.out.printf("The sum of two complex numbers is %.1f + %.1fi", temp.my_real,
temp.my_imag);
}
public static Demo add(Demo n1, Demo n2){
Demo temp = new Demo(0.0, 0.0);
temp.my_real = n1.my_real + n2.my_real;
temp.my_imag = n1.my_imag + n2.my_imag;
return(temp);
}
}
The sum of two complex numbers is 142.7 + 35.2i
A class named Demo defines two double valued numbers, my_real, and my_imag. A constructor is
defined, that takes these two values. In the main function, an instance of the Demo class is created,
and the elements are added using the ‘add’ function and assigned to a temporary object (it is
created in the main function).
Next, they are displayed on the console. In the main function, another temporary instance is
created, and the real parts and imaginary parts of the complex numbers are added respectively, and
this temporary object is returned as output. | [
{
"code": null,
"e": 1311,
"s": 1062,
"text": "Complex numbers are those that have an imaginary part and a real part associated with it. They can\nbe added and subtracted like regular numbers. The real parts and imaginary parts are respectively\nadded or subtracted or even multiplied and divided."
},
{
"code": null,
"e": 1322,
"s": 1311,
"text": " Live Demo"
},
{
"code": null,
"e": 1961,
"s": 1322,
"text": "public class Demo{\n double my_real;\n double my_imag;\n public Demo(double my_real, double my_imag){\n this.my_real = my_real;\n this.my_imag = my_imag;\n }\n public static void main(String[] args){\n Demo n1 = new Demo(76.8, 24.0),\n n2 = new Demo(65.9, 11.23),\n temp;\n temp = add(n1, n2);\n System.out.printf(\"The sum of two complex numbers is %.1f + %.1fi\", temp.my_real,\n temp.my_imag);\n }\n public static Demo add(Demo n1, Demo n2){\n Demo temp = new Demo(0.0, 0.0);\n temp.my_real = n1.my_real + n2.my_real;\n temp.my_imag = n1.my_imag + n2.my_imag;\n return(temp);\n }\n}"
},
{
"code": null,
"e": 2009,
"s": 1961,
"text": "The sum of two complex numbers is 142.7 + 35.2i"
},
{
"code": null,
"e": 2329,
"s": 2009,
"text": "A class named Demo defines two double valued numbers, my_real, and my_imag. A constructor is\ndefined, that takes these two values. In the main function, an instance of the Demo class is created,\nand the elements are added using the ‘add’ function and assigned to a temporary object (it is\ncreated in the main function)."
},
{
"code": null,
"e": 2566,
"s": 2329,
"text": "Next, they are displayed on the console. In the main function, another temporary instance is\ncreated, and the real parts and imaginary parts of the complex numbers are added respectively, and\nthis temporary object is returned as output."
}
]
|
How to Build an AutoML App in Python | by Chanin Nantasenamat | Towards Data Science | Automated machine learning (AutoML) helps to lower the barrier to entry for machine learning model building by streamlining the process thereby allowing non-technical users to harness the power of machine learning. On the other hand, the availability of AutoML also helps to free up the time of data scientists (that they would have otherwise spent doing redundant and repetitive pre-processing tasks or model building tasks) by allowing them to explore other areas of the data analytics pipeline.
In a nutshell, users can supply an input dataset to the AutoML system that it uses for model building (feature transformation, feature selection, hyperparameter optimization, etc.) and finally it returns the predictions as the output.
Wouldn’t it be great if you can build your very own AutoML App that you can custom tailor to your heart’s content? The development of this AutoML App is 2 folds: (1) Model deployment helps to complete the data life cycle and (2) AutoML helps to make ML accessible to non-technical users.
In this article, we will be build an AutoML App in Python using the Streamlit and Scikit-learn library. This web app will allow users to upload their own CSV file and the web app will automatically build random forest models by performing a grid hyperparameter search.
It should be noted that this article is inspired by a video (How to Build a Machine Learning Hyperparameter Optimization App) I made some time ago on my YouTube channel (Data Professor).
The AutoML App that we are building today is well less than 200 lines of code at 171 lines to be exact.
The web app is going to be built in Python using the following libraries:
streamlit — the web framework
pandas — handle dataframes
numpy — numerical data processing
base64 — encoding data to be downloaded
scikit-learn — perform hyperparameter optimization and build machine learning model
The web app has a simple interface comprising of 2 panels: (1) Left Panel accepts the input CSV data and the Parameter settings while the (2) Main Panel displays the output consisting of printing out the dataframe of the input dataset, the model’s performance metric, the best parameters from hyperparameter tuning as well as the 3D contour plot of the tuned hyperparameters.
Let’s take a glimpse of the web app as shown in the 2 screenshots below so that you can get a feel of the app that you are going to be building.
1.3.1. AutoML App using the Example Dataset
The easiest way to try out the web app is to use the supplied Example dataset by clicking on the Press to use Example Dataset button in the Main Panel, which will load the Diabetes Dataset as an example dataset.
1.3.2. AutoML App using Uploaded CSV Data
Alternatively, you can also upload your own CSV datasets either by dragging and dropping the file directly into the upload box (as shown in the screenshot below) or by clicking on the Browse files button and choosing the input file to be uploaded.
In both of the above screenshots, upon providing either the example dataset or the uploaded CSV dataset, the App prints out the dataframe of the dataset, automatically builds several machine learning models by using the supplied input learning parameters to perform hyperparameter optimization followed by printing out the model performance metrics. Finally, an interactive 3D contour plot of the tuned hyperparameters is provided at the bottom of the Main Panel.
You can also take the App for a test drive by click on the following link:
Demo link of the AutoML App
Let’s now take a dive into the inner workings of the AutoML App. As you can see, the entire App uses up only 171 lines of code.
It should be noted that all comments provided in the code (denoted by lines containing the hash tag symbols #) are used to make the code more readable by documenting what each code blocks are doing.
Imports the necessary libraries consisting of streamlit, pandas, numpy, base64, plotly and scikit-learn.
The set_page_config() function allows us to specify the webpage title to page_title=‘The Machine Learning Hyperparameter Optimization App’ as well as setting the page layout to be in full width mode as specified by the layout=’wide’ input argument.
Here, we use the st.write() function together with markdown syntax, write the webpage header text as done on line 20 via the use of the # tag in front of the header text The Machine Learning Hyperparameter Optimization App. On subsequent lines we write the description of the web app.
These blocks of code pertains to the input widgets in the Left Panel that accepts the user input CSV data and model parameters.
Lines 29–33 — Line 29 prints the header text for the Left sidebar panel via the st.sidebar.header() function where sidebar in the function dictates the location of the input widget that it should be placed in the Left sidebar panel. Line 30 accepts the user input CSV data via the st.sidebar.file_uploader() function. As we can see, there are 2 input arguments where the first is the text label Upload your input CSV file while the second input argument type=[“csv”] makes a restriction to only accept CSV files only. Lines 31–33 prints the link to the example dataset in Markdown syntax via the st.sidebar.markdown() function.
Line 36 — Prints the header text Set Parameters via the st.sidebar.header() function.
Line 37 displays a slider bar via the st.sidebar.slider() function where it allows the user to specify the data split ratio by simply adjusting the slider bar. The first input argument prints the widget label text Data split ratio (% for Training Set) where the next 4 values represents the minimum value, maximum value, default value and the increment step size. Finally, the specified value is assigned to the split_size variable.
Lines 39–47 displays the input widgets for Learning Parameters while Lines 49–54 displays the input widgets for General Parameters. Similar to the explanation for Line 37, these lines of code also make use of the st.sidebar.slider() as the input widget for accepting the user specified values for the model parameters. Lines 56–58 combines the user specified value from the slider input into an aggregated form where it then serves as input to the GridSearchCV() function that is responsible for the hyperparameter tuning.
A sub-header text saying Dataset is added above the input dataframe via the st.subheader() function.
This block of code will encode and decode the model performance results via the base64 library as a downloadable CSV file.
At a high-level, this block of code is the build_model() custom function that will take the input dataset and together with the user specified parameters it will then perform the model building and hyperparameter tuning.
Lines 76–77 — The input dataframe is separated into X (deletes the last column which is the Y variable) and Y (specifically select the last column) variables.
Line 79 —Here w notify the user via the st.markdown() function that the model is being built. Then in Line 80 the column name of the Y variable is printed inside an info box via the st.info() function.
Line 83 — Data splitting is performed via the train_test_split() function by using X and Y variables as the input data while the user specified value for the split ratio is specified by the split_size variable, which takes its value from the slider bar described on Line 37.
Lines 87–95 — Instantiates the random forest model via the RandomForestRegressor() function that is assigned to the rf variable. As you can see, all of the model parameters as defined inside the RandomForestRegressor() function takes its parameter values from the input widgets that the user specifies as discussed above on Lines 29–58.
Lines 97–98 — Performs the Hyperparameter tuning. → Line 97 — The above random forest model as specified in the rf variable is assigned as an input argument to the estimator parameter inside the GridSearchCV() function, which will perform the hyperparameter tuning. The hyperparameter value range to explore in the hyperparameter tuning is specified in the param_grid variable that in turn takes its value directly from the user specified value as obtained from the slider bar (Lines 40–43) and pre-processed as the param_grid variable (Lines 56–58). → Line 98 — The hyperparameter tuning process begins by taking in X_train and Y_train as input data.
Line 100 — Print the Model Performance sub-header text via the st.subheader() function. The following lines will then print the model performance metrics.
Line 102 — The best model from the hyperparameter tuning process as stored in the grid variable is applied for making predictions on the X_test data.
Lines 103–104 — Prints the R2 score via the r2_score() function that uses Y_test and Y_pred_test as input argument.
Lines 106–107 — Prints the MSE score via the mean_squared_error() function that uses Y_test and Y_pred_test as input argument.
Lines 109–110 — Prints the best parameters and rounds it to 2 decimal places. The best parameter values are obtained from grid.best_params_ and grid.best_score_ variables.
Line 112–113 — Line 112 prints the sub-header Model Parameters via the st.subheader() function. Line 113 prints the model parameters stored in grid.get_params() via the st.write() function.
Lines 116–125 — Model performance metrics are obtained from grid.cv_results_ and reshaped to x, y and z. → Line 116 — We’re going to selectively extract some data from grid.cv_results_ that will be used to create a dataframe containing the 2 hyperparameter combinations along with their corresponding performance metric, which in this case is the R2 score. Particularly, the pd.concat() function will be used to combine the 2 hyperparameters (params) and the performance metric (mean_test_score). → Line 118 — Data reshaping will now be performed to prepare the data to be in a suitable format for creating the contour plot. Particularly, the groupby() function from the pandaslibrary will be used to literally group the dataframe according to 2 columns (max_features and n_estimators) whereby the contents of the first column (max_features) are merged.
Lines 120–122 — Data will now be pivoted into an m ⨯ n matrix whereby the rows and columns correspond to the max_features and n_estimators, respectively.
Lines 123–125 — Finally, the reshaped data to the respective x, y and z variables that will then be used for making the contour plot.
Lines 128–146 — These code blocks will now create the 3D contour plot using the x, y and z variables via the plotly library.
Lines 149–152 — The x, y and z variables are then combined into a df dataframe.
Line 153 — The model performance results stored in the grid_results variable will now be made downloadable via the filedownload() custom function (Lines 69–73).
At a high-level, these code blocks will perform the logic of the App. This is comprised of 2 code blocks. The first is the if code block (Lines 156-159) and the second is the else code block (Lines 160–171). Every time the web app loads, it will default to running the else code block while the if code block will be activated upon the upload of the input CSV file.
For both code blocks, the logic is the same, the only difference is the contents of the df data dataframe (whether it is coming from the input CSV data or from the example data). Next, the contents of the df dataframe is displayed via the st.write() function. Finally, the model building process is initiated via the build_model() custom function.
Now that we have coded the App, let’s proceed to launching it.
Let’s first start by creating a new conda environment (in order to ensure reproducibility of the code).
Firstly, create a new conda environment called automl as follows in a terminal command line:
conda create -n automl python=3.7.9
Secondly, we will login to the automl environment
conda activate automl
Firstly, download the requirements.txt file
wget https://raw.githubusercontent.com/dataprofessor/ml-opt-app/main/requirements.txt
Secondly, install the libraries as shown below
pip install -r requirements.txt
You can either download the web app files that are hosted on the GitHub repo of the Data Professor or you could also use the 171 lines of code found above.
wget https://github.com/dataprofessor/ml-opt-app/archive/main.zip
Next, unzip the file contents
unzip main.zip
Now enter the main directory via the cd command
cd main
Now that you’re inside the main directory you should be able to see the ml-opt-app.py file.
To launch the App, type the following commands into a terminal prompt (i.e. ensure that the ml-opt-app.py file is in the current working directory):
streamlit run ml-opt-app.py
In a few seconds, the following message in the terminal prompt.
> streamlit run ml-opt-app.pyYou can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://10.0.0.11:8501
Finally, a browser should pop up and the App appears.
You can also test the AutoML App at the following link:
Demo link of the AutoML App
Now that you have created the AutoML App as described in this article, what next? You can perhaps tweak the App by to another machine learning algorithm. Additional features such as feature importance plot could also be added to the App. The possibilities are endless and have fun customizing the App! Please feel free to drop a comment on how you’ve modified the App for your own projects.
I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page).
www.youtube.com
✅ YouTube: http://youtube.com/dataprofessor/✅ Website: http://dataprofessor.org/ (Under construction)✅ LinkedIn: https://www.linkedin.com/company/dataprofessor/✅ Twitter: https://twitter.com/thedataprof/✅ FaceBook: http://facebook.com/dataprofessor/✅ GitHub: https://github.com/dataprofessor/✅ Instagram: https://www.instagram.com/data.professor/ | [
{
"code": null,
"e": 669,
"s": 171,
"text": "Automated machine learning (AutoML) helps to lower the barrier to entry for machine learning model building by streamlining the process thereby allowing non-technical users to harness the power of machine learning. On the other hand, the availability of AutoML also helps to free up the time of data scientists (that they would have otherwise spent doing redundant and repetitive pre-processing tasks or model building tasks) by allowing them to explore other areas of the data analytics pipeline."
},
{
"code": null,
"e": 904,
"s": 669,
"text": "In a nutshell, users can supply an input dataset to the AutoML system that it uses for model building (feature transformation, feature selection, hyperparameter optimization, etc.) and finally it returns the predictions as the output."
},
{
"code": null,
"e": 1192,
"s": 904,
"text": "Wouldn’t it be great if you can build your very own AutoML App that you can custom tailor to your heart’s content? The development of this AutoML App is 2 folds: (1) Model deployment helps to complete the data life cycle and (2) AutoML helps to make ML accessible to non-technical users."
},
{
"code": null,
"e": 1461,
"s": 1192,
"text": "In this article, we will be build an AutoML App in Python using the Streamlit and Scikit-learn library. This web app will allow users to upload their own CSV file and the web app will automatically build random forest models by performing a grid hyperparameter search."
},
{
"code": null,
"e": 1648,
"s": 1461,
"text": "It should be noted that this article is inspired by a video (How to Build a Machine Learning Hyperparameter Optimization App) I made some time ago on my YouTube channel (Data Professor)."
},
{
"code": null,
"e": 1752,
"s": 1648,
"text": "The AutoML App that we are building today is well less than 200 lines of code at 171 lines to be exact."
},
{
"code": null,
"e": 1826,
"s": 1752,
"text": "The web app is going to be built in Python using the following libraries:"
},
{
"code": null,
"e": 1856,
"s": 1826,
"text": "streamlit — the web framework"
},
{
"code": null,
"e": 1883,
"s": 1856,
"text": "pandas — handle dataframes"
},
{
"code": null,
"e": 1917,
"s": 1883,
"text": "numpy — numerical data processing"
},
{
"code": null,
"e": 1957,
"s": 1917,
"text": "base64 — encoding data to be downloaded"
},
{
"code": null,
"e": 2041,
"s": 1957,
"text": "scikit-learn — perform hyperparameter optimization and build machine learning model"
},
{
"code": null,
"e": 2417,
"s": 2041,
"text": "The web app has a simple interface comprising of 2 panels: (1) Left Panel accepts the input CSV data and the Parameter settings while the (2) Main Panel displays the output consisting of printing out the dataframe of the input dataset, the model’s performance metric, the best parameters from hyperparameter tuning as well as the 3D contour plot of the tuned hyperparameters."
},
{
"code": null,
"e": 2562,
"s": 2417,
"text": "Let’s take a glimpse of the web app as shown in the 2 screenshots below so that you can get a feel of the app that you are going to be building."
},
{
"code": null,
"e": 2606,
"s": 2562,
"text": "1.3.1. AutoML App using the Example Dataset"
},
{
"code": null,
"e": 2818,
"s": 2606,
"text": "The easiest way to try out the web app is to use the supplied Example dataset by clicking on the Press to use Example Dataset button in the Main Panel, which will load the Diabetes Dataset as an example dataset."
},
{
"code": null,
"e": 2860,
"s": 2818,
"text": "1.3.2. AutoML App using Uploaded CSV Data"
},
{
"code": null,
"e": 3108,
"s": 2860,
"text": "Alternatively, you can also upload your own CSV datasets either by dragging and dropping the file directly into the upload box (as shown in the screenshot below) or by clicking on the Browse files button and choosing the input file to be uploaded."
},
{
"code": null,
"e": 3572,
"s": 3108,
"text": "In both of the above screenshots, upon providing either the example dataset or the uploaded CSV dataset, the App prints out the dataframe of the dataset, automatically builds several machine learning models by using the supplied input learning parameters to perform hyperparameter optimization followed by printing out the model performance metrics. Finally, an interactive 3D contour plot of the tuned hyperparameters is provided at the bottom of the Main Panel."
},
{
"code": null,
"e": 3647,
"s": 3572,
"text": "You can also take the App for a test drive by click on the following link:"
},
{
"code": null,
"e": 3675,
"s": 3647,
"text": "Demo link of the AutoML App"
},
{
"code": null,
"e": 3803,
"s": 3675,
"text": "Let’s now take a dive into the inner workings of the AutoML App. As you can see, the entire App uses up only 171 lines of code."
},
{
"code": null,
"e": 4002,
"s": 3803,
"text": "It should be noted that all comments provided in the code (denoted by lines containing the hash tag symbols #) are used to make the code more readable by documenting what each code blocks are doing."
},
{
"code": null,
"e": 4107,
"s": 4002,
"text": "Imports the necessary libraries consisting of streamlit, pandas, numpy, base64, plotly and scikit-learn."
},
{
"code": null,
"e": 4356,
"s": 4107,
"text": "The set_page_config() function allows us to specify the webpage title to page_title=‘The Machine Learning Hyperparameter Optimization App’ as well as setting the page layout to be in full width mode as specified by the layout=’wide’ input argument."
},
{
"code": null,
"e": 4641,
"s": 4356,
"text": "Here, we use the st.write() function together with markdown syntax, write the webpage header text as done on line 20 via the use of the # tag in front of the header text The Machine Learning Hyperparameter Optimization App. On subsequent lines we write the description of the web app."
},
{
"code": null,
"e": 4769,
"s": 4641,
"text": "These blocks of code pertains to the input widgets in the Left Panel that accepts the user input CSV data and model parameters."
},
{
"code": null,
"e": 5397,
"s": 4769,
"text": "Lines 29–33 — Line 29 prints the header text for the Left sidebar panel via the st.sidebar.header() function where sidebar in the function dictates the location of the input widget that it should be placed in the Left sidebar panel. Line 30 accepts the user input CSV data via the st.sidebar.file_uploader() function. As we can see, there are 2 input arguments where the first is the text label Upload your input CSV file while the second input argument type=[“csv”] makes a restriction to only accept CSV files only. Lines 31–33 prints the link to the example dataset in Markdown syntax via the st.sidebar.markdown() function."
},
{
"code": null,
"e": 5483,
"s": 5397,
"text": "Line 36 — Prints the header text Set Parameters via the st.sidebar.header() function."
},
{
"code": null,
"e": 5916,
"s": 5483,
"text": "Line 37 displays a slider bar via the st.sidebar.slider() function where it allows the user to specify the data split ratio by simply adjusting the slider bar. The first input argument prints the widget label text Data split ratio (% for Training Set) where the next 4 values represents the minimum value, maximum value, default value and the increment step size. Finally, the specified value is assigned to the split_size variable."
},
{
"code": null,
"e": 6439,
"s": 5916,
"text": "Lines 39–47 displays the input widgets for Learning Parameters while Lines 49–54 displays the input widgets for General Parameters. Similar to the explanation for Line 37, these lines of code also make use of the st.sidebar.slider() as the input widget for accepting the user specified values for the model parameters. Lines 56–58 combines the user specified value from the slider input into an aggregated form where it then serves as input to the GridSearchCV() function that is responsible for the hyperparameter tuning."
},
{
"code": null,
"e": 6540,
"s": 6439,
"text": "A sub-header text saying Dataset is added above the input dataframe via the st.subheader() function."
},
{
"code": null,
"e": 6663,
"s": 6540,
"text": "This block of code will encode and decode the model performance results via the base64 library as a downloadable CSV file."
},
{
"code": null,
"e": 6884,
"s": 6663,
"text": "At a high-level, this block of code is the build_model() custom function that will take the input dataset and together with the user specified parameters it will then perform the model building and hyperparameter tuning."
},
{
"code": null,
"e": 7043,
"s": 6884,
"text": "Lines 76–77 — The input dataframe is separated into X (deletes the last column which is the Y variable) and Y (specifically select the last column) variables."
},
{
"code": null,
"e": 7245,
"s": 7043,
"text": "Line 79 —Here w notify the user via the st.markdown() function that the model is being built. Then in Line 80 the column name of the Y variable is printed inside an info box via the st.info() function."
},
{
"code": null,
"e": 7520,
"s": 7245,
"text": "Line 83 — Data splitting is performed via the train_test_split() function by using X and Y variables as the input data while the user specified value for the split ratio is specified by the split_size variable, which takes its value from the slider bar described on Line 37."
},
{
"code": null,
"e": 7857,
"s": 7520,
"text": "Lines 87–95 — Instantiates the random forest model via the RandomForestRegressor() function that is assigned to the rf variable. As you can see, all of the model parameters as defined inside the RandomForestRegressor() function takes its parameter values from the input widgets that the user specifies as discussed above on Lines 29–58."
},
{
"code": null,
"e": 8510,
"s": 7857,
"text": "Lines 97–98 — Performs the Hyperparameter tuning. → Line 97 — The above random forest model as specified in the rf variable is assigned as an input argument to the estimator parameter inside the GridSearchCV() function, which will perform the hyperparameter tuning. The hyperparameter value range to explore in the hyperparameter tuning is specified in the param_grid variable that in turn takes its value directly from the user specified value as obtained from the slider bar (Lines 40–43) and pre-processed as the param_grid variable (Lines 56–58). → Line 98 — The hyperparameter tuning process begins by taking in X_train and Y_train as input data."
},
{
"code": null,
"e": 8665,
"s": 8510,
"text": "Line 100 — Print the Model Performance sub-header text via the st.subheader() function. The following lines will then print the model performance metrics."
},
{
"code": null,
"e": 8815,
"s": 8665,
"text": "Line 102 — The best model from the hyperparameter tuning process as stored in the grid variable is applied for making predictions on the X_test data."
},
{
"code": null,
"e": 8931,
"s": 8815,
"text": "Lines 103–104 — Prints the R2 score via the r2_score() function that uses Y_test and Y_pred_test as input argument."
},
{
"code": null,
"e": 9058,
"s": 8931,
"text": "Lines 106–107 — Prints the MSE score via the mean_squared_error() function that uses Y_test and Y_pred_test as input argument."
},
{
"code": null,
"e": 9230,
"s": 9058,
"text": "Lines 109–110 — Prints the best parameters and rounds it to 2 decimal places. The best parameter values are obtained from grid.best_params_ and grid.best_score_ variables."
},
{
"code": null,
"e": 9420,
"s": 9230,
"text": "Line 112–113 — Line 112 prints the sub-header Model Parameters via the st.subheader() function. Line 113 prints the model parameters stored in grid.get_params() via the st.write() function."
},
{
"code": null,
"e": 10275,
"s": 9420,
"text": "Lines 116–125 — Model performance metrics are obtained from grid.cv_results_ and reshaped to x, y and z. → Line 116 — We’re going to selectively extract some data from grid.cv_results_ that will be used to create a dataframe containing the 2 hyperparameter combinations along with their corresponding performance metric, which in this case is the R2 score. Particularly, the pd.concat() function will be used to combine the 2 hyperparameters (params) and the performance metric (mean_test_score). → Line 118 — Data reshaping will now be performed to prepare the data to be in a suitable format for creating the contour plot. Particularly, the groupby() function from the pandaslibrary will be used to literally group the dataframe according to 2 columns (max_features and n_estimators) whereby the contents of the first column (max_features) are merged."
},
{
"code": null,
"e": 10429,
"s": 10275,
"text": "Lines 120–122 — Data will now be pivoted into an m ⨯ n matrix whereby the rows and columns correspond to the max_features and n_estimators, respectively."
},
{
"code": null,
"e": 10563,
"s": 10429,
"text": "Lines 123–125 — Finally, the reshaped data to the respective x, y and z variables that will then be used for making the contour plot."
},
{
"code": null,
"e": 10688,
"s": 10563,
"text": "Lines 128–146 — These code blocks will now create the 3D contour plot using the x, y and z variables via the plotly library."
},
{
"code": null,
"e": 10768,
"s": 10688,
"text": "Lines 149–152 — The x, y and z variables are then combined into a df dataframe."
},
{
"code": null,
"e": 10929,
"s": 10768,
"text": "Line 153 — The model performance results stored in the grid_results variable will now be made downloadable via the filedownload() custom function (Lines 69–73)."
},
{
"code": null,
"e": 11295,
"s": 10929,
"text": "At a high-level, these code blocks will perform the logic of the App. This is comprised of 2 code blocks. The first is the if code block (Lines 156-159) and the second is the else code block (Lines 160–171). Every time the web app loads, it will default to running the else code block while the if code block will be activated upon the upload of the input CSV file."
},
{
"code": null,
"e": 11643,
"s": 11295,
"text": "For both code blocks, the logic is the same, the only difference is the contents of the df data dataframe (whether it is coming from the input CSV data or from the example data). Next, the contents of the df dataframe is displayed via the st.write() function. Finally, the model building process is initiated via the build_model() custom function."
},
{
"code": null,
"e": 11706,
"s": 11643,
"text": "Now that we have coded the App, let’s proceed to launching it."
},
{
"code": null,
"e": 11810,
"s": 11706,
"text": "Let’s first start by creating a new conda environment (in order to ensure reproducibility of the code)."
},
{
"code": null,
"e": 11903,
"s": 11810,
"text": "Firstly, create a new conda environment called automl as follows in a terminal command line:"
},
{
"code": null,
"e": 11939,
"s": 11903,
"text": "conda create -n automl python=3.7.9"
},
{
"code": null,
"e": 11989,
"s": 11939,
"text": "Secondly, we will login to the automl environment"
},
{
"code": null,
"e": 12011,
"s": 11989,
"text": "conda activate automl"
},
{
"code": null,
"e": 12055,
"s": 12011,
"text": "Firstly, download the requirements.txt file"
},
{
"code": null,
"e": 12141,
"s": 12055,
"text": "wget https://raw.githubusercontent.com/dataprofessor/ml-opt-app/main/requirements.txt"
},
{
"code": null,
"e": 12188,
"s": 12141,
"text": "Secondly, install the libraries as shown below"
},
{
"code": null,
"e": 12220,
"s": 12188,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 12376,
"s": 12220,
"text": "You can either download the web app files that are hosted on the GitHub repo of the Data Professor or you could also use the 171 lines of code found above."
},
{
"code": null,
"e": 12442,
"s": 12376,
"text": "wget https://github.com/dataprofessor/ml-opt-app/archive/main.zip"
},
{
"code": null,
"e": 12472,
"s": 12442,
"text": "Next, unzip the file contents"
},
{
"code": null,
"e": 12487,
"s": 12472,
"text": "unzip main.zip"
},
{
"code": null,
"e": 12535,
"s": 12487,
"text": "Now enter the main directory via the cd command"
},
{
"code": null,
"e": 12543,
"s": 12535,
"text": "cd main"
},
{
"code": null,
"e": 12635,
"s": 12543,
"text": "Now that you’re inside the main directory you should be able to see the ml-opt-app.py file."
},
{
"code": null,
"e": 12784,
"s": 12635,
"text": "To launch the App, type the following commands into a terminal prompt (i.e. ensure that the ml-opt-app.py file is in the current working directory):"
},
{
"code": null,
"e": 12812,
"s": 12784,
"text": "streamlit run ml-opt-app.py"
},
{
"code": null,
"e": 12876,
"s": 12812,
"text": "In a few seconds, the following message in the terminal prompt."
},
{
"code": null,
"e": 13024,
"s": 12876,
"text": "> streamlit run ml-opt-app.pyYou can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://10.0.0.11:8501"
},
{
"code": null,
"e": 13078,
"s": 13024,
"text": "Finally, a browser should pop up and the App appears."
},
{
"code": null,
"e": 13134,
"s": 13078,
"text": "You can also test the AutoML App at the following link:"
},
{
"code": null,
"e": 13162,
"s": 13134,
"text": "Demo link of the AutoML App"
},
{
"code": null,
"e": 13553,
"s": 13162,
"text": "Now that you have created the AutoML App as described in this article, what next? You can perhaps tweak the App by to another machine learning algorithm. Additional features such as feature importance plot could also be added to the App. The possibilities are endless and have fun customizing the App! Please feel free to drop a comment on how you’ve modified the App for your own projects."
},
{
"code": null,
"e": 13915,
"s": 13553,
"text": "I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page)."
},
{
"code": null,
"e": 13931,
"s": 13915,
"text": "www.youtube.com"
}
]
|
Ethical Hacking - Metasploit | Metasploit is one of the most powerful exploit tools. Most of its resources can be found at: https://www.metasploit.com. It comes in two versions − commercial and free edition. There are no major differences in the two versions, so in this tutorial, we will be mostly using the Community version (free) of Metasploit.
As an Ethical Hacker, you will be using “Kali Distribution” which has the Metasploit community version embedded in it along with other ethical hacking tools. But if you want to install Metasploit as a separate tool, you can easily do so on systems that run on Linux, Windows, or Mac OS X.
The hardware requirements to install Metasploit are −
2 GHz+ processor
1 GB RAM available
1 GB+ available disk space
Matasploit can be used either with command prompt or with Web UI.
To open in Kali, go to Applications → Exploitation Tools → metasploit.
After Metasploit starts, you will see the following screen. Highlighted in red underline is the version of Metasploit.
From Vulnerability Scanner, we found that the Linux machine that we have for test is vulnerable to FTP service. Now, we will use the exploit that can work for us. The command is −
use “exploit path”
The screen will appear as follows −
Then type mfs> show options in order to see what parameters you have to set in order to make it functional. As shown in the following screenshot, we have to set RHOST as the “target IP”.
We type msf> set RHOST 192.168.1.101 and msf>set RPORT 21
Then, type mfs>run. If the exploit is successful, then it will open one session that you can interact with, as shown in the following screenshot.
Payload, in simple terms, are simple scripts that the hackers utilize to interact with a hacked system. Using payloads, they can transfer data to a victim system.
Metasploit payloads can be of three types −
Singles − Singles are very small and designed to create some kind of communication, then move to the next stage. For example, just creating a user.
Singles − Singles are very small and designed to create some kind of communication, then move to the next stage. For example, just creating a user.
Staged − It is a payload that an attacker can use to upload a bigger file onto a victim system.
Staged − It is a payload that an attacker can use to upload a bigger file onto a victim system.
Stages − Stages are payload components that are downloaded by Stagers modules. The various payload stages provide advanced features with no size limits such as Meterpreter and VNC Injection.
Stages − Stages are payload components that are downloaded by Stagers modules. The various payload stages provide advanced features with no size limits such as Meterpreter and VNC Injection.
We use the command show payloads. With this exploit, we can see the payloads that we can use, and it will also show the payloads that will help us upload /execute files onto a victim system.
To set the payload that we want, we will use the following command −
set PAYLOAD payload/path
Set the listen host and listen port (LHOST, LPORT) which are the attacker IP and port. Then set remote host and port (RPORT, LHOST) which are the victim IP and port.
Type “exploit”. It will create a session as shown below −
Now we can play with the system according to the settings that this payload offers.
36 Lectures
5 hours
Sharad Kumar
31 Lectures
3.5 hours
Abhilash Nelson
22 Lectures
3 hours
Blair Cook
74 Lectures
4.5 hours
199courses
75 Lectures
4.5 hours
199courses
148 Lectures
28.5 hours
Joseph Delgadillo
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2797,
"s": 2479,
"text": "Metasploit is one of the most powerful exploit tools. Most of its resources can be found at: https://www.metasploit.com. It comes in two versions − commercial and free edition. There are no major differences in the two versions, so in this tutorial, we will be mostly using the Community version (free) of Metasploit."
},
{
"code": null,
"e": 3086,
"s": 2797,
"text": "As an Ethical Hacker, you will be using “Kali Distribution” which has the Metasploit community version embedded in it along with other ethical hacking tools. But if you want to install Metasploit as a separate tool, you can easily do so on systems that run on Linux, Windows, or Mac OS X."
},
{
"code": null,
"e": 3140,
"s": 3086,
"text": "The hardware requirements to install Metasploit are −"
},
{
"code": null,
"e": 3157,
"s": 3140,
"text": "2 GHz+ processor"
},
{
"code": null,
"e": 3176,
"s": 3157,
"text": "1 GB RAM available"
},
{
"code": null,
"e": 3203,
"s": 3176,
"text": "1 GB+ available disk space"
},
{
"code": null,
"e": 3269,
"s": 3203,
"text": "Matasploit can be used either with command prompt or with Web UI."
},
{
"code": null,
"e": 3340,
"s": 3269,
"text": "To open in Kali, go to Applications → Exploitation Tools → metasploit."
},
{
"code": null,
"e": 3459,
"s": 3340,
"text": "After Metasploit starts, you will see the following screen. Highlighted in red underline is the version of Metasploit."
},
{
"code": null,
"e": 3639,
"s": 3459,
"text": "From Vulnerability Scanner, we found that the Linux machine that we have for test is vulnerable to FTP service. Now, we will use the exploit that can work for us. The command is −"
},
{
"code": null,
"e": 3659,
"s": 3639,
"text": "use “exploit path”\n"
},
{
"code": null,
"e": 3695,
"s": 3659,
"text": "The screen will appear as follows −"
},
{
"code": null,
"e": 3882,
"s": 3695,
"text": "Then type mfs> show options in order to see what parameters you have to set in order to make it functional. As shown in the following screenshot, we have to set RHOST as the “target IP”."
},
{
"code": null,
"e": 3940,
"s": 3882,
"text": "We type msf> set RHOST 192.168.1.101 and msf>set RPORT 21"
},
{
"code": null,
"e": 4086,
"s": 3940,
"text": "Then, type mfs>run. If the exploit is successful, then it will open one session that you can interact with, as shown in the following screenshot."
},
{
"code": null,
"e": 4249,
"s": 4086,
"text": "Payload, in simple terms, are simple scripts that the hackers utilize to interact with a hacked system. Using payloads, they can transfer data to a victim system."
},
{
"code": null,
"e": 4293,
"s": 4249,
"text": "Metasploit payloads can be of three types −"
},
{
"code": null,
"e": 4441,
"s": 4293,
"text": "Singles − Singles are very small and designed to create some kind of communication, then move to the next stage. For example, just creating a user."
},
{
"code": null,
"e": 4589,
"s": 4441,
"text": "Singles − Singles are very small and designed to create some kind of communication, then move to the next stage. For example, just creating a user."
},
{
"code": null,
"e": 4685,
"s": 4589,
"text": "Staged − It is a payload that an attacker can use to upload a bigger file onto a victim system."
},
{
"code": null,
"e": 4781,
"s": 4685,
"text": "Staged − It is a payload that an attacker can use to upload a bigger file onto a victim system."
},
{
"code": null,
"e": 4972,
"s": 4781,
"text": "Stages − Stages are payload components that are downloaded by Stagers modules. The various payload stages provide advanced features with no size limits such as Meterpreter and VNC Injection."
},
{
"code": null,
"e": 5163,
"s": 4972,
"text": "Stages − Stages are payload components that are downloaded by Stagers modules. The various payload stages provide advanced features with no size limits such as Meterpreter and VNC Injection."
},
{
"code": null,
"e": 5354,
"s": 5163,
"text": "We use the command show payloads. With this exploit, we can see the payloads that we can use, and it will also show the payloads that will help us upload /execute files onto a victim system."
},
{
"code": null,
"e": 5423,
"s": 5354,
"text": "To set the payload that we want, we will use the following command −"
},
{
"code": null,
"e": 5449,
"s": 5423,
"text": "set PAYLOAD payload/path\n"
},
{
"code": null,
"e": 5615,
"s": 5449,
"text": "Set the listen host and listen port (LHOST, LPORT) which are the attacker IP and port. Then set remote host and port (RPORT, LHOST) which are the victim IP and port."
},
{
"code": null,
"e": 5673,
"s": 5615,
"text": "Type “exploit”. It will create a session as shown below −"
},
{
"code": null,
"e": 5757,
"s": 5673,
"text": "Now we can play with the system according to the settings that this payload offers."
},
{
"code": null,
"e": 5790,
"s": 5757,
"text": "\n 36 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5804,
"s": 5790,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 5839,
"s": 5804,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5856,
"s": 5839,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5889,
"s": 5856,
"text": "\n 22 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5901,
"s": 5889,
"text": " Blair Cook"
},
{
"code": null,
"e": 5936,
"s": 5901,
"text": "\n 74 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5948,
"s": 5936,
"text": " 199courses"
},
{
"code": null,
"e": 5983,
"s": 5948,
"text": "\n 75 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5995,
"s": 5983,
"text": " 199courses"
},
{
"code": null,
"e": 6032,
"s": 5995,
"text": "\n 148 Lectures \n 28.5 hours \n"
},
{
"code": null,
"e": 6051,
"s": 6032,
"text": " Joseph Delgadillo"
},
{
"code": null,
"e": 6058,
"s": 6051,
"text": " Print"
},
{
"code": null,
"e": 6069,
"s": 6058,
"text": " Add Notes"
}
]
|
First Fit algorithm in Memory Management using Linked List - GeeksforGeeks | 25 Nov, 2021
First Fit Algorithm for Memory Management: The first memory partition which is sufficient to accommodate the process is allocated.We have already discussed first fit algorithm using arrays in this article. However, here we are going to look into another approach using a linked list where the deletion of allocated nodes is also possible.Examples:
Input: blockSize[] = {100, 500, 200}
processSize[] = {417, 112, 426, 95}
Output:
Block of size 426 can't be allocated
Tag Block ID Size
0 1 417
1 2 112
2 0 95
After deleting block with tag id 0.
Tag Block ID Size
1 2 112
2 0 95
3 1 426
Approach: The idea is to use the memory block with a unique tag id. Each process of different sizes are given block id, which signifies to which memory block they belong to, and unique tag id to delete particular process to free up space. Create a free list of given memory block sizes and allocated list of processes.Create allocated list: Create an allocated list of given process sizes by finding the first memory block with sufficient size to allocate memory from. If the memory block is not found, then simply print it. Otherwise, create a node and add it to the allocated linked list.Delete process: Each process is given a unique tag id. Delete the process node from the allocated linked list to free up some space for other processes. After deleting, use the block id of the deleted node to increase the memory block size in the free list.Below is the implementation of the approach:
C/C++
// C++ implementation of the First
// sit memory management algorithm
// using linked list
#include <bits/stdc++.h>
using namespace std;
// Two global counters
int g = 0, k = 0;
// Structure for free list
struct free {
int tag;
int size;
struct free* next;
}* free_head = NULL, *prev_free = NULL;
// Structure for allocated list
struct alloc {
int block_id;
int tag;
int size;
struct alloc* next;
}* alloc_head = NULL, *prev_alloc = NULL;
// Function to create free
// list with given sizes
void create_free(int c)
{
struct free* p = (struct free*)
malloc(sizeof(struct free));
p->size = c;
p->tag = g;
p->next = NULL;
if (free_head == NULL)
free_head = p;
else
prev_free->next = p;
prev_free = p;
g++;
}
// Function to print free list which
// prints free blocks of given sizes
void print_free()
{
struct free* p = free_head;
cout << "Tag\tSize\n";
while (p != NULL) {
cout << p->tag << "\t"
<< p->size << "\n";
p = p->next;
}
}
// Function to print allocated list which
// prints allocated blocks and their block ids
void print_alloc()
{
struct alloc* p = alloc_head;
cout << "Tag\tBlock ID\tSize\n";
while (p != NULL) {
cout << p->tag << "\t "
<< p->block_id << "\t\t"
<< p->size << "\n";
p = p->next;
}
}
// Function to allocate memory to
// blocks as per First fit algorithm
void create_alloc(int c)
{
// create node for process of given size
struct alloc* q = (struct alloc*)
malloc(sizeof(struct alloc));
q->size = c;
q->tag = k;
q->next = NULL;
struct free* p = free_head;
// Iterate to find first memory
// block with appropriate size
while (p != NULL) {
if (q->size <= p->size)
break;
p = p->next;
}
// Node found to allocate
if (p != NULL) {
// Adding node to allocated list
q->block_id = p->tag;
p->size -= q->size;
if (alloc_head == NULL)
alloc_head = q;
else {
prev_alloc = alloc_head;
while (prev_alloc->next != NULL)
prev_alloc = prev_alloc->next;
prev_alloc->next = q;
}
k++;
}
else // Node found to allocate space from
cout << "Block of size " << c
<< " can't be allocated\n";
}
// Function to delete node from
// allocated list to free some space
void delete_alloc(int t)
{
// Standard delete function
// of a linked list node
struct alloc *p = alloc_head, *q = NULL;
// First, find the node according
// to given tag id
while (p != NULL) {
if (p->tag == t)
break;
q = p;
p = p->next;
}
if (p == NULL)
cout << "Tag ID doesn't exist\n";
else if (p == alloc_head)
alloc_head = alloc_head->next;
else
q->next = p->next;
struct free* temp = free_head;
while (temp != NULL) {
if (temp->tag == p->block_id) {
temp->size += p->size;
break;
}
temp = temp->next;
}
}
// Driver Code
int main()
{
int blockSize[] = { 100, 500, 200 };
int processSize[] = { 417, 112, 426, 95 };
int m = sizeof(blockSize)
/ sizeof(blockSize[0]);
int n = sizeof(processSize)
/ sizeof(processSize[0]);
for (int i = 0; i < m; i++)
create_free(blockSize[i]);
for (int i = 0; i < n; i++)
create_alloc(processSize[i]);
print_alloc();
// Block of tag id 0 deleted
// to free space for block of size 426
delete_alloc(0);
create_alloc(426);
cout << "After deleting block"
<< " with tag id 0.\n";
print_alloc();
}
Python3
# Python3 implementation of the First# sit memory management algorithm# using linked list # Two global countersg = 0; k = 0 # Structure for free listclass free: def __init__(self): self.tag=-1 self.size=0 self.next=Nonefree_head = None; prev_free = None # Structure for allocated listclass alloc: def __init__(self): self.block_id=-1 self.tag=-1 self.size=0 self.next=None alloc_head = None;prev_alloc = None # Function to create free# list with given sizesdef create_free(c): global g,prev_free,free_head p = free() p.size = c p.tag = g p.next = None if free_head is None: free_head = p else: prev_free.next = p prev_free = p g+=1 # Function to print free list which# prints free blocks of given sizesdef print_free(): p = free_head print("Tag\tSize") while (p != None) : print("{}\t{}".format(p.tag,p.size)) p = p.next # Function to print allocated list which# prints allocated blocks and their block idsdef print_alloc(): p = alloc_head print("Tag\tBlock ID\tSize") while (p is not None) : print("{}\t{}\t{}\t".format(p.tag,p.block_id,p.size)) p = p.next # Function to allocate memory to# blocks as per First fit algorithmdef create_alloc(c): global k,alloc_head # create node for process of given size q = alloc() q.size = c q.tag = k q.next = None p = free_head # Iterate to find first memory # block with appropriate size while (p != None) : if (q.size <= p.size): break p = p.next # Node found to allocate if (p != None) : # Adding node to allocated list q.block_id = p.tag p.size -= q.size if (alloc_head == None): alloc_head = q else : prev_alloc = alloc_head while (prev_alloc.next != None): prev_alloc = prev_alloc.next prev_alloc.next = q k+=1 else: # Node found to allocate space from print("Block of size {} can't be allocated".format(c)) # Function to delete node from# allocated list to free some spacedef delete_alloc(t): global alloc_head # Standard delete function # of a linked list node p = alloc_head; q = None # First, find the node according # to given tag id while (p != None) : if (p.tag == t): break q = p p = p.next if (p == None): print("Tag ID doesn't exist") elif (p == alloc_head): alloc_head = alloc_head.next else: q.next = p.next temp = free_head while (temp != None) : if (temp.tag == p.block_id) : temp.size += p.size break temp = temp.next # Driver Codeif __name__ == '__main__': blockSize = [100, 500, 200] processSize = [417, 112, 426, 95] m = len(blockSize) n = len(processSize) for i in range(m): create_free(blockSize[i]) for i in range(n): create_alloc(processSize[i]) print_alloc() # Block of tag id 0 deleted # to free space for block of size 426 delete_alloc(0) create_alloc(426) print("After deleting block with tag id 0.") print_alloc()
Block of size 426 can't be allocated
Tag Block ID Size
0 1 417
1 2 112
2 0 95
After deleting block with tag id 0.
Tag Block ID Size
1 2 112
2 0 95
3 1 426
Akanksha_Rai
amartyaghoshgfg
memory-management
Algorithms
Data Structures
Linked List
Operating Systems
Data Structures
Linked List
Operating Systems
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Difference between Informed and Uninformed Search in AI
SCAN (Elevator) Disk Scheduling Algorithms
Quadratic Probing in Hashing
K means Clustering - Introduction
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
Implementing a Linked List in Java using Class
Abstract Data Types
Hash Map in Python | [
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 24651,
"s": 24301,
"text": "First Fit Algorithm for Memory Management: The first memory partition which is sufficient to accommodate the process is allocated.We have already discussed first fit algorithm using arrays in this article. However, here we are going to look into another approach using a linked list where the deletion of allocated nodes is also possible.Examples: "
},
{
"code": null,
"e": 24998,
"s": 24651,
"text": "Input: blockSize[] = {100, 500, 200}\n processSize[] = {417, 112, 426, 95} \nOutput:\nBlock of size 426 can't be allocated\nTag Block ID Size\n0 1 417\n1 2 112\n2 0 95\nAfter deleting block with tag id 0.\nTag Block ID Size\n1 2 112\n2 0 95\n3 1 426"
},
{
"code": null,
"e": 25895,
"s": 25002,
"text": "Approach: The idea is to use the memory block with a unique tag id. Each process of different sizes are given block id, which signifies to which memory block they belong to, and unique tag id to delete particular process to free up space. Create a free list of given memory block sizes and allocated list of processes.Create allocated list: Create an allocated list of given process sizes by finding the first memory block with sufficient size to allocate memory from. If the memory block is not found, then simply print it. Otherwise, create a node and add it to the allocated linked list.Delete process: Each process is given a unique tag id. Delete the process node from the allocated linked list to free up some space for other processes. After deleting, use the block id of the deleted node to increase the memory block size in the free list.Below is the implementation of the approach: "
},
{
"code": null,
"e": 25901,
"s": 25895,
"text": "C/C++"
},
{
"code": null,
"e": 29689,
"s": 25901,
"text": "// C++ implementation of the First\n// sit memory management algorithm\n// using linked list\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n// Two global counters\nint g = 0, k = 0;\n\n// Structure for free list\nstruct free {\n int tag;\n int size;\n struct free* next;\n}* free_head = NULL, *prev_free = NULL;\n\n// Structure for allocated list\nstruct alloc {\n int block_id;\n int tag;\n int size;\n struct alloc* next;\n}* alloc_head = NULL, *prev_alloc = NULL;\n\n// Function to create free\n// list with given sizes\nvoid create_free(int c)\n{\n struct free* p = (struct free*)\n malloc(sizeof(struct free));\n p->size = c;\n p->tag = g;\n p->next = NULL;\n if (free_head == NULL)\n free_head = p;\n else\n prev_free->next = p;\n prev_free = p;\n g++;\n}\n\n// Function to print free list which\n// prints free blocks of given sizes\nvoid print_free()\n{\n struct free* p = free_head;\n cout << \"Tag\\tSize\\n\";\n while (p != NULL) {\n cout << p->tag << \"\\t\"\n << p->size << \"\\n\";\n p = p->next;\n }\n}\n\n// Function to print allocated list which\n// prints allocated blocks and their block ids\nvoid print_alloc()\n{\n struct alloc* p = alloc_head;\n cout << \"Tag\\tBlock ID\\tSize\\n\";\n while (p != NULL) {\n cout << p->tag << \"\\t \"\n << p->block_id << \"\\t\\t\"\n << p->size << \"\\n\";\n p = p->next;\n }\n}\n\n// Function to allocate memory to\n// blocks as per First fit algorithm\nvoid create_alloc(int c)\n{\n // create node for process of given size\n struct alloc* q = (struct alloc*)\n malloc(sizeof(struct alloc));\n q->size = c;\n q->tag = k;\n q->next = NULL;\n struct free* p = free_head;\n\n // Iterate to find first memory\n // block with appropriate size\n while (p != NULL) {\n if (q->size <= p->size)\n break;\n p = p->next;\n }\n\n // Node found to allocate\n if (p != NULL) {\n // Adding node to allocated list\n q->block_id = p->tag;\n p->size -= q->size;\n if (alloc_head == NULL)\n alloc_head = q;\n else {\n prev_alloc = alloc_head;\n while (prev_alloc->next != NULL)\n prev_alloc = prev_alloc->next;\n prev_alloc->next = q;\n }\n k++;\n }\n else // Node found to allocate space from\n cout << \"Block of size \" << c\n << \" can't be allocated\\n\";\n}\n\n// Function to delete node from\n// allocated list to free some space\nvoid delete_alloc(int t)\n{\n // Standard delete function\n // of a linked list node\n struct alloc *p = alloc_head, *q = NULL;\n\n // First, find the node according\n // to given tag id\n while (p != NULL) {\n if (p->tag == t)\n break;\n q = p;\n p = p->next;\n }\n if (p == NULL)\n cout << \"Tag ID doesn't exist\\n\";\n else if (p == alloc_head)\n alloc_head = alloc_head->next;\n else\n q->next = p->next;\n struct free* temp = free_head;\n while (temp != NULL) {\n if (temp->tag == p->block_id) {\n temp->size += p->size;\n break;\n }\n temp = temp->next;\n }\n}\n\n// Driver Code\nint main()\n{\n int blockSize[] = { 100, 500, 200 };\n int processSize[] = { 417, 112, 426, 95 };\n int m = sizeof(blockSize)\n / sizeof(blockSize[0]);\n int n = sizeof(processSize)\n / sizeof(processSize[0]);\n\n for (int i = 0; i < m; i++)\n create_free(blockSize[i]);\n\n for (int i = 0; i < n; i++)\n create_alloc(processSize[i]);\n\n print_alloc();\n\n // Block of tag id 0 deleted\n // to free space for block of size 426\n delete_alloc(0);\n\n create_alloc(426);\n cout << \"After deleting block\"\n << \" with tag id 0.\\n\";\n print_alloc();\n}\n"
},
{
"code": null,
"e": 29699,
"s": 29691,
"text": "Python3"
},
{
"code": "# Python3 implementation of the First# sit memory management algorithm# using linked list # Two global countersg = 0; k = 0 # Structure for free listclass free: def __init__(self): self.tag=-1 self.size=0 self.next=Nonefree_head = None; prev_free = None # Structure for allocated listclass alloc: def __init__(self): self.block_id=-1 self.tag=-1 self.size=0 self.next=None alloc_head = None;prev_alloc = None # Function to create free# list with given sizesdef create_free(c): global g,prev_free,free_head p = free() p.size = c p.tag = g p.next = None if free_head is None: free_head = p else: prev_free.next = p prev_free = p g+=1 # Function to print free list which# prints free blocks of given sizesdef print_free(): p = free_head print(\"Tag\\tSize\") while (p != None) : print(\"{}\\t{}\".format(p.tag,p.size)) p = p.next # Function to print allocated list which# prints allocated blocks and their block idsdef print_alloc(): p = alloc_head print(\"Tag\\tBlock ID\\tSize\") while (p is not None) : print(\"{}\\t{}\\t{}\\t\".format(p.tag,p.block_id,p.size)) p = p.next # Function to allocate memory to# blocks as per First fit algorithmdef create_alloc(c): global k,alloc_head # create node for process of given size q = alloc() q.size = c q.tag = k q.next = None p = free_head # Iterate to find first memory # block with appropriate size while (p != None) : if (q.size <= p.size): break p = p.next # Node found to allocate if (p != None) : # Adding node to allocated list q.block_id = p.tag p.size -= q.size if (alloc_head == None): alloc_head = q else : prev_alloc = alloc_head while (prev_alloc.next != None): prev_alloc = prev_alloc.next prev_alloc.next = q k+=1 else: # Node found to allocate space from print(\"Block of size {} can't be allocated\".format(c)) # Function to delete node from# allocated list to free some spacedef delete_alloc(t): global alloc_head # Standard delete function # of a linked list node p = alloc_head; q = None # First, find the node according # to given tag id while (p != None) : if (p.tag == t): break q = p p = p.next if (p == None): print(\"Tag ID doesn't exist\") elif (p == alloc_head): alloc_head = alloc_head.next else: q.next = p.next temp = free_head while (temp != None) : if (temp.tag == p.block_id) : temp.size += p.size break temp = temp.next # Driver Codeif __name__ == '__main__': blockSize = [100, 500, 200] processSize = [417, 112, 426, 95] m = len(blockSize) n = len(processSize) for i in range(m): create_free(blockSize[i]) for i in range(n): create_alloc(processSize[i]) print_alloc() # Block of tag id 0 deleted # to free space for block of size 426 delete_alloc(0) create_alloc(426) print(\"After deleting block with tag id 0.\") print_alloc()",
"e": 32937,
"s": 29699,
"text": null
},
{
"code": null,
"e": 33176,
"s": 32937,
"text": "Block of size 426 can't be allocated\nTag Block ID Size\n0 1 417\n1 2 112\n2 0 95\nAfter deleting block with tag id 0.\nTag Block ID Size\n1 2 112\n2 0 95\n3 1 426"
},
{
"code": null,
"e": 33191,
"s": 33178,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 33207,
"s": 33191,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 33225,
"s": 33207,
"text": "memory-management"
},
{
"code": null,
"e": 33236,
"s": 33225,
"text": "Algorithms"
},
{
"code": null,
"e": 33252,
"s": 33236,
"text": "Data Structures"
},
{
"code": null,
"e": 33264,
"s": 33252,
"text": "Linked List"
},
{
"code": null,
"e": 33282,
"s": 33264,
"text": "Operating Systems"
},
{
"code": null,
"e": 33298,
"s": 33282,
"text": "Data Structures"
},
{
"code": null,
"e": 33310,
"s": 33298,
"text": "Linked List"
},
{
"code": null,
"e": 33328,
"s": 33310,
"text": "Operating Systems"
},
{
"code": null,
"e": 33339,
"s": 33328,
"text": "Algorithms"
},
{
"code": null,
"e": 33437,
"s": 33339,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33446,
"s": 33437,
"text": "Comments"
},
{
"code": null,
"e": 33459,
"s": 33446,
"text": "Old Comments"
},
{
"code": null,
"e": 33484,
"s": 33459,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33540,
"s": 33484,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 33583,
"s": 33540,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 33612,
"s": 33583,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 33646,
"s": 33612,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 33671,
"s": 33646,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33727,
"s": 33671,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 33774,
"s": 33727,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 33794,
"s": 33774,
"text": "Abstract Data Types"
}
]
|
C program to find out the maximum value of AND, OR, and XOR operations that are less than a given value | Suppose we are given two integers k and n. Our task is to perform three operations; bitwise AND, bitwise OR, and bitwise XOR between all pairs of numbers up to range n. We return the maximum value of all three operations between any two pairs of numbers that is less than the given value k.
So, if the input is like n = 5, k = 5, then the output will be 4 3 4.
The greatest value of AND, OR, and XOR operations between all pairs of numbers that are less than 5 are 4, 3, and 4 respectively. We can see that the values of these operations are less than that of the given value k, which is 5.
To solve this, we will follow these steps −
andMax := 0, orMax = 0, xorMax = 0
value1 := 0, value2 = 0, value3 = 0
for initialize i := 1, when i <= n, update (increase i by 1), do:value1 := i AND jvalue2 := i OR jvalue3 := i XOR jif value1 > andMax and value1 < k, then −andMax := value1if value2 > orMax and value2 < k, then −orMax := value2if value3 > xorMax and value3 < k, then −xorMax := value3
value1 := i AND j
value2 := i OR j
value3 := i XOR j
if value1 > andMax and value1 < k, then −andMax := value1
andMax := value1
if value2 > orMax and value2 < k, then −orMax := value2
orMax := value2
if value3 > xorMax and value3 < k, then −xorMax := value3
xorMax := value3
print(andMax, orMax, xorMax)
Let us see the following implementation to get better understanding −
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void solve(int n, int k) {
int andMax = 0, orMax = 0, xorMax = 0;
int value1 = 0, value2 = 0, value3 = 0;
for (int i = 1; i <= n; i++) {
for (int j = i+1; j <= n; j++) {
value1 = i & j;
value2 = i | j;
value3 = i ^ j;
if (value1 > andMax && value1 < k)
andMax = value1;
if (value2 > orMax && value2 < k)
orMax = value2;
if (value3 > xorMax && value3 < k)
xorMax = value3;
}
}
printf("%d %d %d ", andMax, orMax, xorMax);
}
int main() {
solve(5, 5);
return 0;
}
5, 5
4 3 4 | [
{
"code": null,
"e": 1353,
"s": 1062,
"text": "Suppose we are given two integers k and n. Our task is to perform three operations; bitwise AND, bitwise OR, and bitwise XOR between all pairs of numbers up to range n. We return the maximum value of all three operations between any two pairs of numbers that is less than the given value k."
},
{
"code": null,
"e": 1423,
"s": 1353,
"text": "So, if the input is like n = 5, k = 5, then the output will be 4 3 4."
},
{
"code": null,
"e": 1653,
"s": 1423,
"text": "The greatest value of AND, OR, and XOR operations between all pairs of numbers that are less than 5 are 4, 3, and 4 respectively. We can see that the values of these operations are less than that of the given value k, which is 5."
},
{
"code": null,
"e": 1697,
"s": 1653,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1732,
"s": 1697,
"text": "andMax := 0, orMax = 0, xorMax = 0"
},
{
"code": null,
"e": 1768,
"s": 1732,
"text": "value1 := 0, value2 = 0, value3 = 0"
},
{
"code": null,
"e": 2053,
"s": 1768,
"text": "for initialize i := 1, when i <= n, update (increase i by 1), do:value1 := i AND jvalue2 := i OR jvalue3 := i XOR jif value1 > andMax and value1 < k, then −andMax := value1if value2 > orMax and value2 < k, then −orMax := value2if value3 > xorMax and value3 < k, then −xorMax := value3"
},
{
"code": null,
"e": 2071,
"s": 2053,
"text": "value1 := i AND j"
},
{
"code": null,
"e": 2088,
"s": 2071,
"text": "value2 := i OR j"
},
{
"code": null,
"e": 2106,
"s": 2088,
"text": "value3 := i XOR j"
},
{
"code": null,
"e": 2164,
"s": 2106,
"text": "if value1 > andMax and value1 < k, then −andMax := value1"
},
{
"code": null,
"e": 2181,
"s": 2164,
"text": "andMax := value1"
},
{
"code": null,
"e": 2237,
"s": 2181,
"text": "if value2 > orMax and value2 < k, then −orMax := value2"
},
{
"code": null,
"e": 2253,
"s": 2237,
"text": "orMax := value2"
},
{
"code": null,
"e": 2311,
"s": 2253,
"text": "if value3 > xorMax and value3 < k, then −xorMax := value3"
},
{
"code": null,
"e": 2328,
"s": 2311,
"text": "xorMax := value3"
},
{
"code": null,
"e": 2357,
"s": 2328,
"text": "print(andMax, orMax, xorMax)"
},
{
"code": null,
"e": 2427,
"s": 2357,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3088,
"s": 2427,
"text": "#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include <stdlib.h>\n\nvoid solve(int n, int k) {\n int andMax = 0, orMax = 0, xorMax = 0;\n int value1 = 0, value2 = 0, value3 = 0;\n for (int i = 1; i <= n; i++) {\n for (int j = i+1; j <= n; j++) {\n value1 = i & j;\n value2 = i | j;\n value3 = i ^ j;\n if (value1 > andMax && value1 < k)\n andMax = value1;\n if (value2 > orMax && value2 < k)\n orMax = value2;\n if (value3 > xorMax && value3 < k)\n xorMax = value3;\n }\n }\n printf(\"%d %d %d \", andMax, orMax, xorMax);\n}\nint main() {\n solve(5, 5);\n return 0;\n}"
},
{
"code": null,
"e": 3093,
"s": 3088,
"text": "5, 5"
},
{
"code": null,
"e": 3099,
"s": 3093,
"text": "4 3 4"
}
]
|
HTML - <bdo> Tag | The HTML <bdo> tag is used to override the default text direction.
<!DOCTYPE html>
<html>
<head>
<title>HTML bdo Tag</title>
</head>
<body>
<bdo dir = "rtl">Here's some English embedded in text in another language
requiring a right-to-left presentation.</bdo>
</body>
</html>
This will produce the following result −
This tag supports all the global attributes described in HTML Attribute Reference
The HTML <bdo> tag also supports the following additional attributes −
This tag supports all the event attributes described in HTML Events Reference
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 | [
{
"code": null,
"e": 2441,
"s": 2374,
"text": "The HTML <bdo> tag is used to override the default text direction."
},
{
"code": null,
"e": 2686,
"s": 2441,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML bdo Tag</title>\n </head>\n\n <body>\n <bdo dir = \"rtl\">Here's some English embedded in text in another language\n requiring a right-to-left presentation.</bdo>\n </body>\n\n</html>"
},
{
"code": null,
"e": 2727,
"s": 2686,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2809,
"s": 2727,
"text": "This tag supports all the global attributes described in HTML Attribute Reference"
},
{
"code": null,
"e": 2881,
"s": 2809,
"text": "The HTML <bdo> tag also supports the following additional attributes −"
},
{
"code": null,
"e": 2959,
"s": 2881,
"text": "This tag supports all the event attributes described in HTML Events Reference"
},
{
"code": null,
"e": 2992,
"s": 2959,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3006,
"s": 2992,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3041,
"s": 3006,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3055,
"s": 3041,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3090,
"s": 3055,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3107,
"s": 3090,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3142,
"s": 3107,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3173,
"s": 3142,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3206,
"s": 3173,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3237,
"s": 3206,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3272,
"s": 3237,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3303,
"s": 3272,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3310,
"s": 3303,
"text": " Print"
},
{
"code": null,
"e": 3321,
"s": 3310,
"text": " Add Notes"
}
]
|
SQL query using COUNT and HAVING clause - GeeksforGeeks | 07 Apr, 2020
Consider a table STUDENT having the following schema:
STUDENT (Student_id, Student_Name, Address, Marks)
Student_id is the primary column of STUDENT table.
Let first create the table structure with CREATE Command in SQL:
CREATE TABLE STUDENT
(STUDENT_ID NUMBER (4),
STUDENT_NAME VARCHAR2 (20),
ADDRESS VARCHAR2 (20),
MARKS NUMBER (3),
PRIMARY KEY (STUDENT_ID));
Now, insert values into the table using INSERT INTO Command in SQL:
INSERT INTO STUDENT
VALUES (100, ‘PUJA’, ’NOIDA’, 10);
INSERT INTO STUDENT
VALUES (101, ‘SUDO’, ’PUNE’, 30);
INSERT INTO STUDENT
VALUES (102, ‘BHALU’, ’NASHIK’, 40);
INSERT INTO STUDENT
VALUES (103, ‘CHETENA’, ’NOIDA’, 20);
INSERT INTO STUDENT
VALUES (104, ‘MOMO’, ’NOIDA’, 40);
Now display the content of STUDENT table:
SELECT *
FROM STUDENT;
Student_id Student_Name Address Marks
------------------------------------------------
100 PUJA NOIDA 10
101 SUDO PUNE 30
102 BHALU NASHIK 40
103 CHETENA NOIDA 20
104 MOMO NOIDA 40
Query-1:Print the marks and number of student having marks more than the average marks of student from NOIDA city.
Explanation:To get the average marks of student from NOIDA city we use this query:
SELECT AVG(MARKS)
FROM STUDENT
WHERE ADDRESS =’NOIDA’
We use this above sub query using GROUP BY and HAVING clause :
SELECT MARKS, COUNT (DISTINCT STUDENT_ID)
FROM STUDENT
GROUP BY MARKS
HAVING MARKS > (SELECT AVG(MARKS)
FROM STUDENT
WHERE ADDRESS = ’NOIDA’ );
In the above query we use GROUP BY MARKS means it cluster the rows with same Marks and we also use SELECT MARKS, COUNT(DISTINCT STUDENT_ID) which prints the Marks of each cluster and the count of rows of respective clusters i.e.,
MARKS COUNT
10 1
20 1
30 1
40 2
After that we use HAVING MARKS > (SELECT AVG(MARKS) FROM STUDENT WHERE ADDRESS =’NOIDA’), which is used to filter the result with condition that marks must be greater than the avg marks of student from Noida city i.e., more than
(10+20+40) / 3
= 23.3
Output:
MARKS COUNT (DISTINCT STUDENT_ID)
30 1
40 2
Query-2:Display the Names and Addresses of the students whose name’s second letter is U.
Explanation:For matching the pattern of the STUDENT_NAME field we used LIKE string comparison operator with two reserved character % and _ . % replaces an arbitrary number of characters, and ‘_’ replaces a single arbitrary character.Here, we need to compare the second letter of STUDENT_NAME thus we use the pattern ‘_U%’.
SELECT Student_Name, Address
FROM STUDENT
WHERE STUDENT_NAME LIKE ‘_U%’
Output:
STUDENT_NAME ADDRESS
PUJA NOIDA
SUDO PUNE
Query-3:Print the details of the student obtaining highest marks (if there is more then one student getting highest marks then highest will be according to the alphabetical order of their names).
Explanation:To get the highest marks from the MARKS field we use the MAX command i.e.,
SELECT MAX(MARKS)
FROM STUDENT;
We use the above sub-query which returns ‘40’ and it will be used with WHERE command. To arrange according to alphabetical order of STUDENT_NAME field we used ORDER BY clause and for getting the top row, LIMIT 1 will be used. Combining all these:
SELECT *
FROM STUDENT
WHERE MARKS = (SELECT MAX (MARKS)
FROM STUDENT)
ORDER BY STUDENT_NAME LIMIT 1;
Output:
Student_id Student_Name Address Marks
102 BHALU NASHIK 40
Query-4:Change the name and address of the student with ID 103 to RITA and DELHI respectively.
Explanation:To change the value of any attributes we will use UPDATE command with SET clause to specify their new values.
UPDATE STUDENT
SET STUDENT_NAME = ’RITA’, ADDRESS=’DELHI’
WHERE STUDENT_ID=103 ;
Output:
1 row updated
To see the changes we will use,
SELECT *
FROM STUDENT;
Output:
Student_id Student_Name Address Marks
100 PUJA NOIDA 10
101 SUDO PUNE 30
102 BHALU NASHIK 40
103 RITA DELHI 20
104 MOMO NOIDA 40
Query-5:DELETE the details from the STUDENT table those are getting lowest mark.
Explanation:To find the lowest mark we will use,
SELECT MIN(MARKS)
FROM STUDENT;
It will return ‘10’ as a lowest marks.
To delete rows we will use DELETE command with WHERE command for specify the condition.
DELETE FROM STUDENT
WHERE MARKS = (SELECT MIN(MARKS)
FROM STUDENT);
Output:
1 row affected
To see the changes we will use,
SELECT *
FROM STUDENT;
Output:
Student_id Student_Name Address Marks
101 SUDO PUNE 30
102 BHALU NASHIK 40
103 RITA DELHI 20
104 MOMO NOIDA 40
DBMS-SQL
SQL-Clauses
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
CTE in SQL
SQL | Views
SQL Interview Questions
Third Normal Form (3NF)
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Views | [
{
"code": null,
"e": 23994,
"s": 23966,
"text": "\n07 Apr, 2020"
},
{
"code": null,
"e": 24048,
"s": 23994,
"text": "Consider a table STUDENT having the following schema:"
},
{
"code": null,
"e": 24100,
"s": 24048,
"text": "STUDENT (Student_id, Student_Name, Address, Marks) "
},
{
"code": null,
"e": 24151,
"s": 24100,
"text": "Student_id is the primary column of STUDENT table."
},
{
"code": null,
"e": 24216,
"s": 24151,
"text": "Let first create the table structure with CREATE Command in SQL:"
},
{
"code": null,
"e": 24362,
"s": 24216,
"text": "CREATE TABLE STUDENT \n(STUDENT_ID NUMBER (4), \nSTUDENT_NAME VARCHAR2 (20), \nADDRESS VARCHAR2 (20), \nMARKS NUMBER (3), \nPRIMARY KEY (STUDENT_ID));"
},
{
"code": null,
"e": 24430,
"s": 24362,
"text": "Now, insert values into the table using INSERT INTO Command in SQL:"
},
{
"code": null,
"e": 24722,
"s": 24430,
"text": "INSERT INTO STUDENT \nVALUES (100, ‘PUJA’, ’NOIDA’, 10); \n\nINSERT INTO STUDENT \nVALUES (101, ‘SUDO’, ’PUNE’, 30); \n\nINSERT INTO STUDENT \nVALUES (102, ‘BHALU’, ’NASHIK’, 40); \n\nINSERT INTO STUDENT \nVALUES (103, ‘CHETENA’, ’NOIDA’, 20); \n\nINSERT INTO STUDENT \nVALUES (104, ‘MOMO’, ’NOIDA’, 40);"
},
{
"code": null,
"e": 24764,
"s": 24722,
"text": "Now display the content of STUDENT table:"
},
{
"code": null,
"e": 24788,
"s": 24764,
"text": "SELECT * \nFROM STUDENT;"
},
{
"code": null,
"e": 25110,
"s": 24788,
"text": "Student_id Student_Name Address Marks\n------------------------------------------------\n100 PUJA NOIDA 10\n101 SUDO PUNE 30\n102 BHALU NASHIK 40\n103 CHETENA NOIDA 20\n104 MOMO NOIDA 40\n"
},
{
"code": null,
"e": 25225,
"s": 25110,
"text": "Query-1:Print the marks and number of student having marks more than the average marks of student from NOIDA city."
},
{
"code": null,
"e": 25308,
"s": 25225,
"text": "Explanation:To get the average marks of student from NOIDA city we use this query:"
},
{
"code": null,
"e": 25365,
"s": 25308,
"text": "SELECT AVG(MARKS) \nFROM STUDENT \nWHERE ADDRESS =’NOIDA’ "
},
{
"code": null,
"e": 25428,
"s": 25365,
"text": "We use this above sub query using GROUP BY and HAVING clause :"
},
{
"code": null,
"e": 25616,
"s": 25428,
"text": "SELECT MARKS, COUNT (DISTINCT STUDENT_ID) \nFROM STUDENT \nGROUP BY MARKS \nHAVING MARKS > (SELECT AVG(MARKS) \n FROM STUDENT \n WHERE ADDRESS = ’NOIDA’ ); "
},
{
"code": null,
"e": 25846,
"s": 25616,
"text": "In the above query we use GROUP BY MARKS means it cluster the rows with same Marks and we also use SELECT MARKS, COUNT(DISTINCT STUDENT_ID) which prints the Marks of each cluster and the count of rows of respective clusters i.e.,"
},
{
"code": null,
"e": 25922,
"s": 25846,
"text": "MARKS COUNT\n10 1\n20 1\n30 1\n40 2 "
},
{
"code": null,
"e": 26151,
"s": 25922,
"text": "After that we use HAVING MARKS > (SELECT AVG(MARKS) FROM STUDENT WHERE ADDRESS =’NOIDA’), which is used to filter the result with condition that marks must be greater than the avg marks of student from Noida city i.e., more than"
},
{
"code": null,
"e": 26175,
"s": 26151,
"text": "(10+20+40) / 3 \n= 23.3 "
},
{
"code": null,
"e": 26183,
"s": 26175,
"text": "Output:"
},
{
"code": null,
"e": 26258,
"s": 26183,
"text": "MARKS COUNT (DISTINCT STUDENT_ID)\n30 1\n40 2 "
},
{
"code": null,
"e": 26347,
"s": 26258,
"text": "Query-2:Display the Names and Addresses of the students whose name’s second letter is U."
},
{
"code": null,
"e": 26670,
"s": 26347,
"text": "Explanation:For matching the pattern of the STUDENT_NAME field we used LIKE string comparison operator with two reserved character % and _ . % replaces an arbitrary number of characters, and ‘_’ replaces a single arbitrary character.Here, we need to compare the second letter of STUDENT_NAME thus we use the pattern ‘_U%’."
},
{
"code": null,
"e": 26745,
"s": 26670,
"text": "SELECT Student_Name, Address \nFROM STUDENT \nWHERE STUDENT_NAME LIKE ‘_U%’ "
},
{
"code": null,
"e": 26753,
"s": 26745,
"text": "Output:"
},
{
"code": null,
"e": 26819,
"s": 26753,
"text": "STUDENT_NAME ADDRESS\nPUJA NOIDA\nSUDO PUNE "
},
{
"code": null,
"e": 27015,
"s": 26819,
"text": "Query-3:Print the details of the student obtaining highest marks (if there is more then one student getting highest marks then highest will be according to the alphabetical order of their names)."
},
{
"code": null,
"e": 27102,
"s": 27015,
"text": "Explanation:To get the highest marks from the MARKS field we use the MAX command i.e.,"
},
{
"code": null,
"e": 27136,
"s": 27102,
"text": "SELECT MAX(MARKS) \nFROM STUDENT; "
},
{
"code": null,
"e": 27383,
"s": 27136,
"text": "We use the above sub-query which returns ‘40’ and it will be used with WHERE command. To arrange according to alphabetical order of STUDENT_NAME field we used ORDER BY clause and for getting the top row, LIMIT 1 will be used. Combining all these:"
},
{
"code": null,
"e": 27505,
"s": 27383,
"text": "SELECT * \nFROM STUDENT \nWHERE MARKS = (SELECT MAX (MARKS) \n FROM STUDENT) \nORDER BY STUDENT_NAME LIMIT 1; "
},
{
"code": null,
"e": 27513,
"s": 27505,
"text": "Output:"
},
{
"code": null,
"e": 27608,
"s": 27513,
"text": "Student_id Student_Name Address Marks\n102 BHALU NASHIK 40 "
},
{
"code": null,
"e": 27703,
"s": 27608,
"text": "Query-4:Change the name and address of the student with ID 103 to RITA and DELHI respectively."
},
{
"code": null,
"e": 27825,
"s": 27703,
"text": "Explanation:To change the value of any attributes we will use UPDATE command with SET clause to specify their new values."
},
{
"code": null,
"e": 27909,
"s": 27825,
"text": "UPDATE STUDENT \nSET STUDENT_NAME = ’RITA’, ADDRESS=’DELHI’ \nWHERE STUDENT_ID=103 ; "
},
{
"code": null,
"e": 27917,
"s": 27909,
"text": "Output:"
},
{
"code": null,
"e": 27932,
"s": 27917,
"text": "1 row updated "
},
{
"code": null,
"e": 27964,
"s": 27932,
"text": "To see the changes we will use,"
},
{
"code": null,
"e": 27989,
"s": 27964,
"text": "SELECT * \nFROM STUDENT; "
},
{
"code": null,
"e": 27997,
"s": 27989,
"text": "Output:"
},
{
"code": null,
"e": 28292,
"s": 27997,
"text": "Student_id Student_Name Address Marks\n100 PUJA NOIDA 10\n101 SUDO PUNE 30\n102 BHALU NASHIK 40\n103 RITA DELHI 20\n104 MOMO NOIDA 40 "
},
{
"code": null,
"e": 28373,
"s": 28292,
"text": "Query-5:DELETE the details from the STUDENT table those are getting lowest mark."
},
{
"code": null,
"e": 28422,
"s": 28373,
"text": "Explanation:To find the lowest mark we will use,"
},
{
"code": null,
"e": 28456,
"s": 28422,
"text": "SELECT MIN(MARKS) \nFROM STUDENT; "
},
{
"code": null,
"e": 28495,
"s": 28456,
"text": "It will return ‘10’ as a lowest marks."
},
{
"code": null,
"e": 28583,
"s": 28495,
"text": "To delete rows we will use DELETE command with WHERE command for specify the condition."
},
{
"code": null,
"e": 28669,
"s": 28583,
"text": "DELETE FROM STUDENT \nWHERE MARKS = (SELECT MIN(MARKS) \n FROM STUDENT); "
},
{
"code": null,
"e": 28677,
"s": 28669,
"text": "Output:"
},
{
"code": null,
"e": 28693,
"s": 28677,
"text": "1 row affected "
},
{
"code": null,
"e": 28725,
"s": 28693,
"text": "To see the changes we will use,"
},
{
"code": null,
"e": 28750,
"s": 28725,
"text": "SELECT * \nFROM STUDENT; "
},
{
"code": null,
"e": 28758,
"s": 28750,
"text": "Output:"
},
{
"code": null,
"e": 29004,
"s": 28758,
"text": "Student_id Student_Name Address Marks\n101 SUDO PUNE 30\n102 BHALU NASHIK 40\n103 RITA DELHI 20\n104 MOMO NOIDA 40 "
},
{
"code": null,
"e": 29013,
"s": 29004,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 29025,
"s": 29013,
"text": "SQL-Clauses"
},
{
"code": null,
"e": 29030,
"s": 29025,
"text": "DBMS"
},
{
"code": null,
"e": 29034,
"s": 29030,
"text": "SQL"
},
{
"code": null,
"e": 29039,
"s": 29034,
"text": "DBMS"
},
{
"code": null,
"e": 29043,
"s": 29039,
"text": "SQL"
},
{
"code": null,
"e": 29141,
"s": 29043,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29194,
"s": 29141,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 29205,
"s": 29194,
"text": "CTE in SQL"
},
{
"code": null,
"e": 29217,
"s": 29205,
"text": "SQL | Views"
},
{
"code": null,
"e": 29241,
"s": 29217,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 29265,
"s": 29241,
"text": "Third Normal Form (3NF)"
},
{
"code": null,
"e": 29309,
"s": 29265,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 29330,
"s": 29309,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 29341,
"s": 29330,
"text": "CTE in SQL"
},
{
"code": null,
"e": 29407,
"s": 29341,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
}
]
|
How to use spread operator to join two or more arrays in JavaScript? | Two join two or more arrays we have a built-in method called array.concat(). But we can join arrays much more easily by using spread operator.
var merged = [...arr1, ...arr2];
Lets' try to merge arrays without spread operator.
In the following example, instead of the spread operator, array.concat() method is used to join two arrays.
Live Demo
<html>
<body>
<script>
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var merged = arr1.concat(arr2);
document.write(merged);
</script>
</body>
</html>
1,2,3,4,5,6
In the following example, spread operator is used to join two arrays.
Live Demo
<html>
<body>
<script>
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var merged = [...arr1, ...arr2];
document.write(merged);
</script>
</body>
</html>
1,2,3,4,5,6
In the following example, spread operator is used to join 3 arrays. By using concat() method it is difficult if there are more arrays but by using spread operator it is very easy to join more number arrays.
Live Demo
<html>
<body>
<script>
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3 = [7,8,9];
var merged = [...arr1,...arr2,...arr3];
document.write(merged);
</script>
</body>
</html>
1,2,3,4,5,6,7,8,9 | [
{
"code": null,
"e": 1205,
"s": 1062,
"text": "Two join two or more arrays we have a built-in method called array.concat(). But we can join arrays much more easily by using spread operator."
},
{
"code": null,
"e": 1238,
"s": 1205,
"text": "var merged = [...arr1, ...arr2];"
},
{
"code": null,
"e": 1289,
"s": 1238,
"text": "Lets' try to merge arrays without spread operator."
},
{
"code": null,
"e": 1397,
"s": 1289,
"text": "In the following example, instead of the spread operator, array.concat() method is used to join two arrays."
},
{
"code": null,
"e": 1407,
"s": 1397,
"text": "Live Demo"
},
{
"code": null,
"e": 1582,
"s": 1407,
"text": "<html>\n<body>\n <script>\n var arr1 = [1,2,3];\n var arr2 = [4,5,6];\n var merged = arr1.concat(arr2);\n document.write(merged);\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 1594,
"s": 1582,
"text": "1,2,3,4,5,6"
},
{
"code": null,
"e": 1664,
"s": 1594,
"text": "In the following example, spread operator is used to join two arrays."
},
{
"code": null,
"e": 1674,
"s": 1664,
"text": "Live Demo"
},
{
"code": null,
"e": 1850,
"s": 1674,
"text": "<html>\n<body>\n <script>\n var arr1 = [1,2,3];\n var arr2 = [4,5,6];\n var merged = [...arr1, ...arr2];\n document.write(merged);\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 1862,
"s": 1850,
"text": "1,2,3,4,5,6"
},
{
"code": null,
"e": 2069,
"s": 1862,
"text": "In the following example, spread operator is used to join 3 arrays. By using concat() method it is difficult if there are more arrays but by using spread operator it is very easy to join more number arrays."
},
{
"code": null,
"e": 2079,
"s": 2069,
"text": "Live Demo"
},
{
"code": null,
"e": 2288,
"s": 2079,
"text": "<html>\n<body>\n <script>\n var arr1 = [1,2,3];\n var arr2 = [4,5,6];\n var arr3 = [7,8,9];\n var merged = [...arr1,...arr2,...arr3];\n document.write(merged);\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 2306,
"s": 2288,
"text": "1,2,3,4,5,6,7,8,9"
}
]
|
Running Airflow with Docker on EC2 + CI/CD with GitLab | by Ammar Chalifah | Towards Data Science | I’ve been learning data science for a year, yet until several weeks ago I still found myself completely clueless on the engineering side. Data analysis and artificial intelligence are stuff on the top of the pyramid, which requires strong data pipeline foundation. With this post, I will share my lessons learned while trying to built a simple data pipeline using Airflow, an open source orchestration tool. This orchestrator is deployed on top of Amazon EC2, utilizing GitLab’s CI/CD to ease up development process. Okay, one by one, let’s talk about definition of each terms.
Based on its website, Airflow is a “platform created by the community to programmatically author, schedule and monitor workflows.” Airflow usually used by Data Engineers to orchestrating workflows and pipelines. Let’s say a Data Engineer need to move data from a source to another destination four times a day (e.g. to keep the freshness of the data). Instead of doing that task manually, they can automate the script to run on a particular schedule using Airflow. Airflow can also be used to manage dependencies, monitor workflow executions, and visualize workflows.
Airflow needs to be installed in a machine. Instead of using local computer, it is better to install it in a cloud-based host to improve reliability.
Amazon EC2 (stands for Elastic Compute Cloud) is a rented cloud-based computers offered by Amazon Web Services. EC2 will serve as the host, which Airflow will be deployed on. EC2 is just a computer, like our local laptop/computer, but the machine will be up 99% of the time and managed by AWS team. We can ‘tunnel’ our way inside the command line interface of EC2’s machine by using SSH. Later on, we will learn how we can use SSH and git to deploy codes from a remote repository to EC2.
Airflow won’t be installed directly on EC2 local machine, but installed inside a Docker container. Docker is a set of platform that creates virtual OS called containers. We use Docker to reduce setups, as all setups will be managed by the maintainer of the Docker images (in this case, Airflow contributors). A Docker image contains application code, libraries, tools, dependencies and other files needed to make an application run. We will pull an image from Docker image registry, build it, start the container, and run Airflow inside.
GitLab will be used as our repository and DevOps lifecycle tool. There are practically countless way we can utilize CI/CD in GitLab, but for the sake of simplicity we will only use the ‘CD’ part. Every time user merge any branch into the main branch, the deployment script will be triggered. Deployment pipeline consists of SSH tunneling into our EC2, pulling main branch from GitLab repository into EC2, write several variables to a file, and rebuild + restart the Docker container.
Before diving into the details, check this repository, which contains the complete codebase and summary of the steps that we will take to successfully create a continuous deployment pipeline of Airflow. Okay, let’s start!
Access AWS Console, then prepare an EC2 instance. I recommend using instance with ubuntu OS with lower-mid performance. Download the SSH key of your EC2 instance (usually ends with .pem suffix), and write down the IP address of your instance. Then, configure your instance to open all ports (at least open port 8080 to access the Airflow webserver). Lastly, access the EC2 by using the SSH key to install Docker and docker-compose from command line interface.
ssh -i ssh-key.pem ubuntu@EC2_ADDRESS
Guide for EC2 provision: https://www.youtube.com/watch?v=YB_qanudIzA
Sign up on GitLab (https://gitlab.com) and create a new project. Clone the contents from the github repository to our new GitLab repository. After the repository is filled with the codes, we need to configure GitLab runner and set repository variables. GitLab runner is used to execute CI/CD scripts which we defined in gitlab-ci.yml . Repository variables are used to store sensitive informations (such as username, password, IP address of your EC2, and SSH key of the EC2). Repository variables are loaded as environment variables in CI/CD pipelines, where it could be deployed to the server as variables/files.
Follow instructions in GitLab runner configuration guide to configure our runner. For me, I used EC2 instance with ubuntu OS to install my runner. You don’t have to configure your own runner if you activate GitLab’s free trial by giving your credit card information, as GitLab will provide a shared runner for you.
GitLab Repository Variables
There are six repository variables that we need to set. Go to Settings > CI/CD > Variables, click Expand, and start adding variables.
The first two are _AIRFLOW_WWW_USER_PASSWORD and _AIRFLOW_WWW_USER_USERNAME, which will be used to log in to the Airflow server once it is deployed. Choose any arbitrary value for these two variables.
The second pair is EC2_ADDRESS (IP address of your EC2 instance) and SSH_KEY_EC2 (SSH key of your EC2 instance, usually ends with .pem suffix). These values will be used to access your EC2 machine. Set SSH_KEY_EC2 as file instead of variable.
The last pair is GITLAB_PASSWORD and GITLAB_USERNAME, used for credentials to pulling commits from GitLab repository.
Start by looking at the directory structure below.
The three directories (dags, logs, and plugins) are basic Airflow directories. We leave logs and plugins (almost) empty, because those folders will be filled after deployment. Scripts that we wish to automate are written inside dags, which we will cover later.
During any push to GitLab’s repo, the scripts in .gitlab-ci.yml (which define CI/CD pipeline) will be triggered. The script execute series of commands to deploy the repository to EC2. Inside EC2, we will build the Docker container containing Airflow by using docker-compose up on the docker-compose.yaml.
Before getting more complex, please refer to this guide to understand what GitLab’s CI/CD is.
The CI/CD pipeline is defined in .gitlab-ci.yml.
Because I’m using GitLab runner that executes pipelines using Docker, the default image is specified at the top. I used ubuntu:latest as my default Docker image.
As stated earlier, we won’t utilize the continuous integration aspect of CI/CD. We only use deployment that only triggered in main branch. That means all push to other branches beside main won’t results in deployment.
deploy-prod: only: - main stage: deploy before_script: ... script: ...
deploy-prod is the name of our pipeline, which will only run in main branch. The stage of this pipeline is deployment stage (in contrast to other stages such as testing or building). Commands are specified inside before_script and script.
before_script:- ls -la- pwd- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'- eval $(ssh-agent -s)- mkdir -p ~/.ssh- chmod 700 ~/.ssh- cat $SSH_KEY_EC2- echo "$(cat $SSH_KEY_EC2)" >> ~/.ssh/ssh-key.pem- chmod 400 ~/.ssh/ssh-key.pem- cat ~/.ssh/ssh-key.pem- echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config- apt-get update -y- apt-get -y install rsync
before_script consists of several commands that prepare our runner for deployment. The commands are used to install open-ssh, evaluate ssh-agent, dump SSH key from repository variable to file, change permission of the SSH key, set ssh config, and install rsync.
ssh -i ~/.ssh/ssh-key.pem ubuntu@$EC2_ADDRESS \'git config --global --replace-all user.name "Full Name"&& git config --global --replace-all user.email "[email protected]"'
The script section are divided into three sections. Each sections are started with ssh tunneling into the EC2. The first section is used to set git config to use your full name and email as the global config.
ssh -i ~/.ssh/ssh-key.pem ubuntu@$EC2_ADDRESS \'if [ -d airflow-pipeline ];then cd airflow-pipeline&& git status&& git restore .env&& git pull --rebase&& git status&& sed -i s:%AIRFLOW_UID%:'"$(id -u)"':g .env&& sed -i s:%AIRFLOW_GID%:0:g .env&& sed -i s:%_AIRFLOW_WWW_USER_USERNAME%:'"$_AIRFLOW_WWW_USER_USERNAME"':g .env&& sed -i s:%_AIRFLOW_WWW_USER_PASSWORD%:'"$_AIRFLOW_WWW_USER_PASSWORD"':g .envelse git clone https://'"$GITLAB_USERNAME"':'"$GITLAB_PASSWORD"'@gitlab.com/gitlab-group/gitlab-project.git&& cd airflow-pipeline&& ls -la&& chmod 777 logs&& sed -i s:%AIRFLOW_UID%:'"$(id -u)"':g .env&& sed -i s:%AIRFLOW_GID%:0:g .env&& sed -i s:%_AIRFLOW_WWW_USER_USERNAME%:'"$_AIRFLOW_WWW_USER_USERNAME"':g .env&& sed -i s:%_AIRFLOW_WWW_USER_PASSWORD%:'"$_AIRFLOW_WWW_USER_PASSWORD"':g .env&& docker-compose up airflow-init;fi'
The second section is used to pulling changes from main branch in GitLab repository and writing environment variables into .env file. Here we use conditions based on existence of the directory on the EC2 home directory. If we have cloned GitLab repository before, we only executed: restore all changes from .env file, pulling changes from remote GitLab repository, and writing environment variables to .env. If we haven’t, we start by cloning the repository, then write environment variables to .env file, and starting the Docker container.
ssh -i ~/.ssh/ssh-key.pem ubuntu@$EC2_ADDRESS \'cd airflow-pipeline &&if [ docker ps | grep -q keyword ];then docker-compose down && docker-compose up -d --build;else docker-compose up -d --build;fi;'
The latest section is used to restart the Docker to incorporate new changes.
CI/CD pipeline can be monitored on CI/CD > Pipelines on GitLab.
If everything went smoothly, your Airflow webserver will be ready. Go to https://{EC2_ADDRESS}:8080 on browser to log in to the user interface. Log in with Airflow username and password that you set on the repository variables before.
Later, any script you wish to automate can be written inside a DAG (or directed acyclic graph, a directed graph with no directed cycles. Tasks inside a DAG are framed as a node of a graph, where dependencies can be defined. Any changes in the repository could be deployed by pushing changes to GitLab repository, merge to main branch (or push to main branch directly), and wait until CI/CD pipeline succeeded.
You can define many things inside a DAG, such as data ingestion tasks, data querying task, send automated email, scrape data, make API call, etc.
It is not recommended to log Airflow activity locally. However, due to time and cost constraint, I log all activities locally, especially under /logs directory. Besides logs, DAG execution also create caches in /dags/__pycache__/. Hence, I ignored those files by using .gitignore to safely pull changes without causing conflicts.
If anything goes wrong, you can always inspect what happens inside EC2 by using the SSH key.
ssh -i ssh-key.pem ubuntu@EC2_ADDRESS
Delete unused files, unused Docker images, or make any adjustments from inside!
[1] https://airflow.apache.org/[2] https://aws.amazon.com/ec2/[3] https://www.docker.com/[4] https://about.gitlab.com/[5] https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html [6] Code references from Bunga Amalia K for setting up GitLab runner | [
{
"code": null,
"e": 749,
"s": 171,
"text": "I’ve been learning data science for a year, yet until several weeks ago I still found myself completely clueless on the engineering side. Data analysis and artificial intelligence are stuff on the top of the pyramid, which requires strong data pipeline foundation. With this post, I will share my lessons learned while trying to built a simple data pipeline using Airflow, an open source orchestration tool. This orchestrator is deployed on top of Amazon EC2, utilizing GitLab’s CI/CD to ease up development process. Okay, one by one, let’s talk about definition of each terms."
},
{
"code": null,
"e": 1317,
"s": 749,
"text": "Based on its website, Airflow is a “platform created by the community to programmatically author, schedule and monitor workflows.” Airflow usually used by Data Engineers to orchestrating workflows and pipelines. Let’s say a Data Engineer need to move data from a source to another destination four times a day (e.g. to keep the freshness of the data). Instead of doing that task manually, they can automate the script to run on a particular schedule using Airflow. Airflow can also be used to manage dependencies, monitor workflow executions, and visualize workflows."
},
{
"code": null,
"e": 1467,
"s": 1317,
"text": "Airflow needs to be installed in a machine. Instead of using local computer, it is better to install it in a cloud-based host to improve reliability."
},
{
"code": null,
"e": 1955,
"s": 1467,
"text": "Amazon EC2 (stands for Elastic Compute Cloud) is a rented cloud-based computers offered by Amazon Web Services. EC2 will serve as the host, which Airflow will be deployed on. EC2 is just a computer, like our local laptop/computer, but the machine will be up 99% of the time and managed by AWS team. We can ‘tunnel’ our way inside the command line interface of EC2’s machine by using SSH. Later on, we will learn how we can use SSH and git to deploy codes from a remote repository to EC2."
},
{
"code": null,
"e": 2493,
"s": 1955,
"text": "Airflow won’t be installed directly on EC2 local machine, but installed inside a Docker container. Docker is a set of platform that creates virtual OS called containers. We use Docker to reduce setups, as all setups will be managed by the maintainer of the Docker images (in this case, Airflow contributors). A Docker image contains application code, libraries, tools, dependencies and other files needed to make an application run. We will pull an image from Docker image registry, build it, start the container, and run Airflow inside."
},
{
"code": null,
"e": 2977,
"s": 2493,
"text": "GitLab will be used as our repository and DevOps lifecycle tool. There are practically countless way we can utilize CI/CD in GitLab, but for the sake of simplicity we will only use the ‘CD’ part. Every time user merge any branch into the main branch, the deployment script will be triggered. Deployment pipeline consists of SSH tunneling into our EC2, pulling main branch from GitLab repository into EC2, write several variables to a file, and rebuild + restart the Docker container."
},
{
"code": null,
"e": 3199,
"s": 2977,
"text": "Before diving into the details, check this repository, which contains the complete codebase and summary of the steps that we will take to successfully create a continuous deployment pipeline of Airflow. Okay, let’s start!"
},
{
"code": null,
"e": 3659,
"s": 3199,
"text": "Access AWS Console, then prepare an EC2 instance. I recommend using instance with ubuntu OS with lower-mid performance. Download the SSH key of your EC2 instance (usually ends with .pem suffix), and write down the IP address of your instance. Then, configure your instance to open all ports (at least open port 8080 to access the Airflow webserver). Lastly, access the EC2 by using the SSH key to install Docker and docker-compose from command line interface."
},
{
"code": null,
"e": 3697,
"s": 3659,
"text": "ssh -i ssh-key.pem ubuntu@EC2_ADDRESS"
},
{
"code": null,
"e": 3766,
"s": 3697,
"text": "Guide for EC2 provision: https://www.youtube.com/watch?v=YB_qanudIzA"
},
{
"code": null,
"e": 4380,
"s": 3766,
"text": "Sign up on GitLab (https://gitlab.com) and create a new project. Clone the contents from the github repository to our new GitLab repository. After the repository is filled with the codes, we need to configure GitLab runner and set repository variables. GitLab runner is used to execute CI/CD scripts which we defined in gitlab-ci.yml . Repository variables are used to store sensitive informations (such as username, password, IP address of your EC2, and SSH key of the EC2). Repository variables are loaded as environment variables in CI/CD pipelines, where it could be deployed to the server as variables/files."
},
{
"code": null,
"e": 4695,
"s": 4380,
"text": "Follow instructions in GitLab runner configuration guide to configure our runner. For me, I used EC2 instance with ubuntu OS to install my runner. You don’t have to configure your own runner if you activate GitLab’s free trial by giving your credit card information, as GitLab will provide a shared runner for you."
},
{
"code": null,
"e": 4723,
"s": 4695,
"text": "GitLab Repository Variables"
},
{
"code": null,
"e": 4857,
"s": 4723,
"text": "There are six repository variables that we need to set. Go to Settings > CI/CD > Variables, click Expand, and start adding variables."
},
{
"code": null,
"e": 5058,
"s": 4857,
"text": "The first two are _AIRFLOW_WWW_USER_PASSWORD and _AIRFLOW_WWW_USER_USERNAME, which will be used to log in to the Airflow server once it is deployed. Choose any arbitrary value for these two variables."
},
{
"code": null,
"e": 5301,
"s": 5058,
"text": "The second pair is EC2_ADDRESS (IP address of your EC2 instance) and SSH_KEY_EC2 (SSH key of your EC2 instance, usually ends with .pem suffix). These values will be used to access your EC2 machine. Set SSH_KEY_EC2 as file instead of variable."
},
{
"code": null,
"e": 5419,
"s": 5301,
"text": "The last pair is GITLAB_PASSWORD and GITLAB_USERNAME, used for credentials to pulling commits from GitLab repository."
},
{
"code": null,
"e": 5470,
"s": 5419,
"text": "Start by looking at the directory structure below."
},
{
"code": null,
"e": 5731,
"s": 5470,
"text": "The three directories (dags, logs, and plugins) are basic Airflow directories. We leave logs and plugins (almost) empty, because those folders will be filled after deployment. Scripts that we wish to automate are written inside dags, which we will cover later."
},
{
"code": null,
"e": 6036,
"s": 5731,
"text": "During any push to GitLab’s repo, the scripts in .gitlab-ci.yml (which define CI/CD pipeline) will be triggered. The script execute series of commands to deploy the repository to EC2. Inside EC2, we will build the Docker container containing Airflow by using docker-compose up on the docker-compose.yaml."
},
{
"code": null,
"e": 6130,
"s": 6036,
"text": "Before getting more complex, please refer to this guide to understand what GitLab’s CI/CD is."
},
{
"code": null,
"e": 6179,
"s": 6130,
"text": "The CI/CD pipeline is defined in .gitlab-ci.yml."
},
{
"code": null,
"e": 6341,
"s": 6179,
"text": "Because I’m using GitLab runner that executes pipelines using Docker, the default image is specified at the top. I used ubuntu:latest as my default Docker image."
},
{
"code": null,
"e": 6559,
"s": 6341,
"text": "As stated earlier, we won’t utilize the continuous integration aspect of CI/CD. We only use deployment that only triggered in main branch. That means all push to other branches beside main won’t results in deployment."
},
{
"code": null,
"e": 6636,
"s": 6559,
"text": "deploy-prod: only: - main stage: deploy before_script: ... script: ..."
},
{
"code": null,
"e": 6875,
"s": 6636,
"text": "deploy-prod is the name of our pipeline, which will only run in main branch. The stage of this pipeline is deployment stage (in contrast to other stages such as testing or building). Commands are specified inside before_script and script."
},
{
"code": null,
"e": 7274,
"s": 6875,
"text": "before_script:- ls -la- pwd- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'- eval $(ssh-agent -s)- mkdir -p ~/.ssh- chmod 700 ~/.ssh- cat $SSH_KEY_EC2- echo \"$(cat $SSH_KEY_EC2)\" >> ~/.ssh/ssh-key.pem- chmod 400 ~/.ssh/ssh-key.pem- cat ~/.ssh/ssh-key.pem- echo -e \"Host *\\n\\tStrictHostKeyChecking no\\n\\n\" > ~/.ssh/config- apt-get update -y- apt-get -y install rsync"
},
{
"code": null,
"e": 7536,
"s": 7274,
"text": "before_script consists of several commands that prepare our runner for deployment. The commands are used to install open-ssh, evaluate ssh-agent, dump SSH key from repository variable to file, change permission of the SSH key, set ssh config, and install rsync."
},
{
"code": null,
"e": 7706,
"s": 7536,
"text": "ssh -i ~/.ssh/ssh-key.pem ubuntu@$EC2_ADDRESS \\'git config --global --replace-all user.name \"Full Name\"&& git config --global --replace-all user.email \"[email protected]\"'"
},
{
"code": null,
"e": 7915,
"s": 7706,
"text": "The script section are divided into three sections. Each sections are started with ssh tunneling into the EC2. The first section is used to set git config to use your full name and email as the global config."
},
{
"code": null,
"e": 8746,
"s": 7915,
"text": "ssh -i ~/.ssh/ssh-key.pem ubuntu@$EC2_ADDRESS \\'if [ -d airflow-pipeline ];then cd airflow-pipeline&& git status&& git restore .env&& git pull --rebase&& git status&& sed -i s:%AIRFLOW_UID%:'\"$(id -u)\"':g .env&& sed -i s:%AIRFLOW_GID%:0:g .env&& sed -i s:%_AIRFLOW_WWW_USER_USERNAME%:'\"$_AIRFLOW_WWW_USER_USERNAME\"':g .env&& sed -i s:%_AIRFLOW_WWW_USER_PASSWORD%:'\"$_AIRFLOW_WWW_USER_PASSWORD\"':g .envelse git clone https://'\"$GITLAB_USERNAME\"':'\"$GITLAB_PASSWORD\"'@gitlab.com/gitlab-group/gitlab-project.git&& cd airflow-pipeline&& ls -la&& chmod 777 logs&& sed -i s:%AIRFLOW_UID%:'\"$(id -u)\"':g .env&& sed -i s:%AIRFLOW_GID%:0:g .env&& sed -i s:%_AIRFLOW_WWW_USER_USERNAME%:'\"$_AIRFLOW_WWW_USER_USERNAME\"':g .env&& sed -i s:%_AIRFLOW_WWW_USER_PASSWORD%:'\"$_AIRFLOW_WWW_USER_PASSWORD\"':g .env&& docker-compose up airflow-init;fi'"
},
{
"code": null,
"e": 9287,
"s": 8746,
"text": "The second section is used to pulling changes from main branch in GitLab repository and writing environment variables into .env file. Here we use conditions based on existence of the directory on the EC2 home directory. If we have cloned GitLab repository before, we only executed: restore all changes from .env file, pulling changes from remote GitLab repository, and writing environment variables to .env. If we haven’t, we start by cloning the repository, then write environment variables to .env file, and starting the Docker container."
},
{
"code": null,
"e": 9488,
"s": 9287,
"text": "ssh -i ~/.ssh/ssh-key.pem ubuntu@$EC2_ADDRESS \\'cd airflow-pipeline &&if [ docker ps | grep -q keyword ];then docker-compose down && docker-compose up -d --build;else docker-compose up -d --build;fi;'"
},
{
"code": null,
"e": 9565,
"s": 9488,
"text": "The latest section is used to restart the Docker to incorporate new changes."
},
{
"code": null,
"e": 9629,
"s": 9565,
"text": "CI/CD pipeline can be monitored on CI/CD > Pipelines on GitLab."
},
{
"code": null,
"e": 9864,
"s": 9629,
"text": "If everything went smoothly, your Airflow webserver will be ready. Go to https://{EC2_ADDRESS}:8080 on browser to log in to the user interface. Log in with Airflow username and password that you set on the repository variables before."
},
{
"code": null,
"e": 10274,
"s": 9864,
"text": "Later, any script you wish to automate can be written inside a DAG (or directed acyclic graph, a directed graph with no directed cycles. Tasks inside a DAG are framed as a node of a graph, where dependencies can be defined. Any changes in the repository could be deployed by pushing changes to GitLab repository, merge to main branch (or push to main branch directly), and wait until CI/CD pipeline succeeded."
},
{
"code": null,
"e": 10420,
"s": 10274,
"text": "You can define many things inside a DAG, such as data ingestion tasks, data querying task, send automated email, scrape data, make API call, etc."
},
{
"code": null,
"e": 10750,
"s": 10420,
"text": "It is not recommended to log Airflow activity locally. However, due to time and cost constraint, I log all activities locally, especially under /logs directory. Besides logs, DAG execution also create caches in /dags/__pycache__/. Hence, I ignored those files by using .gitignore to safely pull changes without causing conflicts."
},
{
"code": null,
"e": 10843,
"s": 10750,
"text": "If anything goes wrong, you can always inspect what happens inside EC2 by using the SSH key."
},
{
"code": null,
"e": 10881,
"s": 10843,
"text": "ssh -i ssh-key.pem ubuntu@EC2_ADDRESS"
},
{
"code": null,
"e": 10961,
"s": 10881,
"text": "Delete unused files, unused Docker images, or make any adjustments from inside!"
}
]
|
String tokenisation function in C | In this section, we will see how to tokenize strings in C. The C has library function for this. The C library function char *strtok(char *str, const char *delim) breaks string str into a series of tokens using the delimiter delim.
Following is the declaration for strtok() function.
char *strtok(char *str, const char *delim)
It takes two parameters. The str - The contents of this string are modified and broken into smaller strings (tokens), and delim - This is the C string containing the delimiters. These may vary from one call to another. This function returns a pointer to the first token found in the string. A null pointer is returned if there are no tokens left to retrieve.
Live Demo
#include <string.h>
#include <stdio.h>
int main () {
char str[80] = "This is - www.tutorialspoint.com - website";
const char s[2] = "-";
char *token;
/* get the first token */
token = strtok(str, s);
/* walk through other tokens */
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, s);
}
return(0);
}
This is
www.tutorialspoint.com
website | [
{
"code": null,
"e": 1293,
"s": 1062,
"text": "In this section, we will see how to tokenize strings in C. The C has library function for this. The C library function char *strtok(char *str, const char *delim) breaks string str into a series of tokens using the delimiter delim."
},
{
"code": null,
"e": 1345,
"s": 1293,
"text": "Following is the declaration for strtok() function."
},
{
"code": null,
"e": 1388,
"s": 1345,
"text": "char *strtok(char *str, const char *delim)"
},
{
"code": null,
"e": 1747,
"s": 1388,
"text": "It takes two parameters. The str - The contents of this string are modified and broken into smaller strings (tokens), and delim - This is the C string containing the delimiters. These may vary from one call to another. This function returns a pointer to the first token found in the string. A null pointer is returned if there are no tokens left to retrieve."
},
{
"code": null,
"e": 1758,
"s": 1747,
"text": " Live Demo"
},
{
"code": null,
"e": 2123,
"s": 1758,
"text": "#include <string.h>\n#include <stdio.h>\n\nint main () {\n char str[80] = \"This is - www.tutorialspoint.com - website\";\n const char s[2] = \"-\";\n char *token;\n\n /* get the first token */\n token = strtok(str, s);\n\n /* walk through other tokens */\n while( token != NULL ) {\n printf( \" %s\\n\", token );\n token = strtok(NULL, s);\n }\n return(0);\n}"
},
{
"code": null,
"e": 2162,
"s": 2123,
"text": "This is\nwww.tutorialspoint.com\nwebsite"
}
]
|
How to automate drag & drop functionality using Selenium WebDriver Java? | The drag and drop action is done with the help of a mouse. It happens when we drag and then place an element from one place to another. This is a common scenario when we try to move a file from one folder to another by simply drag and drop action.
Selenium uses the Actions class to perform the drag drop action. The dragAndDrop(source, destination) is a method under Actions class to do drag and drop operation. The method will first do a left click on the element, then continue the click to hold the source element. Next it shall move to the destination location and release the mouse.
Our aim to drag and drop the first box to the second box.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.interactions.Actions;
public class DragDrop{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://jqueryui.com/droppable/";
driver.get(url);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.switchTo().frame(0);
// identify source and target element
WebElement s=driver.findElement(By.("draggable"));
WebElement t=driver.findElement(By.("droppable"));
/Actions class with dragAndDrop()
Actions act = new Actions(driver);
act.dragAndDrop(s, t).build().perform();
driver.quit();
}
} | [
{
"code": null,
"e": 1310,
"s": 1062,
"text": "The drag and drop action is done with the help of a mouse. It happens when we drag and then place an element from one place to another. This is a common scenario when we try to move a file from one folder to another by simply drag and drop action."
},
{
"code": null,
"e": 1651,
"s": 1310,
"text": "Selenium uses the Actions class to perform the drag drop action. The dragAndDrop(source, destination) is a method under Actions class to do drag and drop operation. The method will first do a left click on the element, then continue the click to hold the source element. Next it shall move to the destination location and release the mouse."
},
{
"code": null,
"e": 1709,
"s": 1651,
"text": "Our aim to drag and drop the first box to the second box."
},
{
"code": null,
"e": 1730,
"s": 1709,
"text": "Code Implementation."
},
{
"code": null,
"e": 2688,
"s": 1730,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.interactions.Actions;\npublic class DragDrop{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://jqueryui.com/droppable/\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.switchTo().frame(0);\n // identify source and target element\n WebElement s=driver.findElement(By.(\"draggable\"));\n WebElement t=driver.findElement(By.(\"droppable\"));\n /Actions class with dragAndDrop()\n Actions act = new Actions(driver);\n act.dragAndDrop(s, t).build().perform();\n driver.quit();\n }\n}"
}
]
|
What are the benefits of a module in Java 9? | An important feature introduced in Java 9 is Module. By using a module, we can divide the code into smaller components called modules. It means each module has its own responsibility and declare its dependency on other modules to work correctly.
Below are the steps to create a modular project in Java 9:
Initially, we can create a file named "module-info.java" and add to a package(module) for which it is created. For instance, if our package name is com.mycompany.mypackage then the file goes to the same package (src/com.mycompany.mypackage/module-info.java). We can create a module by declaring "exports" and "requires" expressions.
If our modules require another module we can write below code
module com.tutorialspoint.greetings {
requires org.tutorix;
}
To expose module contents, we can write below code
module org.tutorix {
exports org.tutorix;
}
The modules hide unwanted and internal details very safely for better security. It means that a module can access only exported package contents and not all the contents or public/internal API of other modules, so the public in one module is not public to other modules.
The application becomes small and fast because we can use only whatever modules we want.
Easy deployment on small devices as memory requirements are very less.
Easy to support the single responsibility principle.
Easy to support less coupling between components. | [
{
"code": null,
"e": 1308,
"s": 1062,
"text": "An important feature introduced in Java 9 is Module. By using a module, we can divide the code into smaller components called modules. It means each module has its own responsibility and declare its dependency on other modules to work correctly."
},
{
"code": null,
"e": 1367,
"s": 1308,
"text": "Below are the steps to create a modular project in Java 9:"
},
{
"code": null,
"e": 1700,
"s": 1367,
"text": "Initially, we can create a file named \"module-info.java\" and add to a package(module) for which it is created. For instance, if our package name is com.mycompany.mypackage then the file goes to the same package (src/com.mycompany.mypackage/module-info.java). We can create a module by declaring \"exports\" and \"requires\" expressions."
},
{
"code": null,
"e": 1762,
"s": 1700,
"text": "If our modules require another module we can write below code"
},
{
"code": null,
"e": 1827,
"s": 1762,
"text": "module com.tutorialspoint.greetings {\n requires org.tutorix;\n}"
},
{
"code": null,
"e": 1878,
"s": 1827,
"text": "To expose module contents, we can write below code"
},
{
"code": null,
"e": 1925,
"s": 1878,
"text": "module org.tutorix {\n exports org.tutorix;\n}"
},
{
"code": null,
"e": 2196,
"s": 1925,
"text": "The modules hide unwanted and internal details very safely for better security. It means that a module can access only exported package contents and not all the contents or public/internal API of other modules, so the public in one module is not public to other modules."
},
{
"code": null,
"e": 2285,
"s": 2196,
"text": "The application becomes small and fast because we can use only whatever modules we want."
},
{
"code": null,
"e": 2356,
"s": 2285,
"text": "Easy deployment on small devices as memory requirements are very less."
},
{
"code": null,
"e": 2409,
"s": 2356,
"text": "Easy to support the single responsibility principle."
},
{
"code": null,
"e": 2459,
"s": 2409,
"text": "Easy to support less coupling between components."
}
]
|
PostgreSQL - DATE/TIME Functions and Operators | We had discussed about the Date/Time data types in the chapter Data Types. Now, let us see the Date/Time operators and Functions.
The following table lists the behaviors of the basic arithmetic operators −
The following is the list of all important Date and Time related functions available.
Subtract arguments
Current date and time
Get subfield (equivalent to extract)
Get subfield
Test for finite date, time and interval (not +/-infinity)
Adjust interval
AGE(timestamp, timestamp)
When invoked with the TIMESTAMP form of the second argument, AGE() subtract arguments, producing a "symbolic" result that uses years and months and is of type INTERVAL.
AGE(timestamp)
When invoked with only the TIMESTAMP as argument, AGE() subtracts from the current_date (at midnight).
Example of the function AGE(timestamp, timestamp) is −
testdb=# SELECT AGE(timestamp '2001-04-10', timestamp '1957-06-13');
The above given PostgreSQL statement will produce the following result −
age
-------------------------
43 years 9 mons 27 days
Example of the function AGE(timestamp) is −
testdb=# select age(timestamp '1957-06-13');
The above given PostgreSQL statement will produce the following result −
age
--------------------------
55 years 10 mons 22 days
PostgreSQL provides a number of functions that return values related to the current date and time. Following are some functions −
CURRENT_DATE
Delivers current date.
CURRENT_TIME
Delivers values with time zone.
CURRENT_TIMESTAMP
Delivers values with time zone.
CURRENT_TIME(precision)
Optionally takes a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field.
CURRENT_TIMESTAMP(precision)
Optionally takes a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field.
LOCALTIME
Delivers values without time zone.
LOCALTIMESTAMP
Delivers values without time zone.
LOCALTIME(precision)
Optionally takes a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field.
LOCALTIMESTAMP(precision)
Optionally takes a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field.
Examples using the functions from the table above −
testdb=# SELECT CURRENT_TIME;
timetz
--------------------
08:01:34.656+05:30
(1 row)
testdb=# SELECT CURRENT_DATE;
date
------------
2013-05-05
(1 row)
testdb=# SELECT CURRENT_TIMESTAMP;
now
-------------------------------
2013-05-05 08:01:45.375+05:30
(1 row)
testdb=# SELECT CURRENT_TIMESTAMP(2);
timestamptz
------------------------------
2013-05-05 08:01:50.89+05:30
(1 row)
testdb=# SELECT LOCALTIMESTAMP;
timestamp
------------------------
2013-05-05 08:01:55.75
(1 row)
PostgreSQL also provides functions that return the start time of the current statement, as well as the actual current time at the instant the function is called. These functions are −
transaction_timestamp()
It is equivalent to CURRENT_TIMESTAMP, but is named to clearly reflect what it returns.
statement_timestamp()
It returns the start time of the current statement.
clock_timestamp()
It returns the actual current time, and therefore its value changes even within a single SQL command.
timeofday()
It returns the actual current time, but as a formatted text string rather than a timestamp with time zone value.
now()
It is a traditional PostgreSQL equivalent to transaction_timestamp().
DATE_PART('field', source)
These functions get the subfields. The field parameter needs to be a string value, not a name.
The valid field names are: century, day, decade, dow, doy, epoch, hour, isodow, isoyear, microseconds, millennium, milliseconds, minute, month, quarter, second, timezone, timezone_hour, timezone_minute, week, year.
DATE_TRUNC('field', source)
This function is conceptually similar to the trunc function for numbers. source is a value expression of type timestamp or interval. field selects to which precision to truncate the input value. The return value is of type timestamp or interval.
The valid values for field are : microseconds, milliseconds, second, minute, hour, day, week, month, quarter, year, decade, century, millennium
The following are examples for DATE_PART('field', source) functions −
testdb=# SELECT date_part('day', TIMESTAMP '2001-02-16 20:38:40');
date_part
-----------
16
(1 row)
testdb=# SELECT date_part('hour', INTERVAL '4 hours 3 minutes');
date_part
-----------
4
(1 row)
The following are examples for DATE_TRUNC('field', source) functions −
testdb=# SELECT date_trunc('hour', TIMESTAMP '2001-02-16 20:38:40');
date_trunc
---------------------
2001-02-16 20:00:00
(1 row)
testdb=# SELECT date_trunc('year', TIMESTAMP '2001-02-16 20:38:40');
date_trunc
---------------------
2001-01-01 00:00:00
(1 row)
The EXTRACT(field FROM source) function retrieves subfields such as year or hour from date/time values. The source must be a value expression of type timestamp, time, or interval. The field is an identifier or string that selects what field to extract from the source value. The EXTRACT function returns values of type double precision.
The following are valid field names (similar to DATE_PART function field names): century, day, decade, dow, doy, epoch, hour, isodow, isoyear, microseconds, millennium, milliseconds, minute, month, quarter, second, timezone, timezone_hour, timezone_minute, week, year.
The following are examples of EXTRACT('field', source) functions −
testdb=# SELECT EXTRACT(CENTURY FROM TIMESTAMP '2000-12-16 12:21:13');
date_part
-----------
20
(1 row)
testdb=# SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40');
date_part
-----------
16
(1 row)
ISFINITE(date)
Tests for finite date.
ISFINITE(timestamp)
Tests for finite time stamp.
ISFINITE(interval)
Tests for finite interval.
The following are the examples of the ISFINITE() functions −
testdb=# SELECT isfinite(date '2001-02-16');
isfinite
----------
t
(1 row)
testdb=# SELECT isfinite(timestamp '2001-02-16 21:28:30');
isfinite
----------
t
(1 row)
testdb=# SELECT isfinite(interval '4 hours');
isfinite
----------
t
(1 row)
JUSTIFY_DAYS(interval)
Adjusts interval so 30-day time periods are represented as months. Return the interval type
JUSTIFY_HOURS(interval)
Adjusts interval so 24-hour time periods are represented as days. Return the interval type
JUSTIFY_INTERVAL(interval)
Adjusts interval using JUSTIFY_DAYS and JUSTIFY_HOURS, with additional sign adjustments. Return the interval type
The following are the examples for the ISFINITE() functions −
testdb=# SELECT justify_days(interval '35 days');
justify_days
--------------
1 mon 5 days
(1 row)
testdb=# SELECT justify_hours(interval '27 hours');
justify_hours
----------------
1 day 03:00:00
(1 row)
testdb=# SELECT justify_interval(interval '1 mon -1 hour');
justify_interval
------------------
29 days 23:00:00
(1 row)
23 Lectures
1.5 hours
John Elder
49 Lectures
3.5 hours
Niyazi Erdogan
126 Lectures
10.5 hours
Abhishek And Pukhraj
35 Lectures
5 hours
Karthikeya T
5 Lectures
51 mins
Vinay Kumar
5 Lectures
52 mins
Vinay Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2955,
"s": 2825,
"text": "We had discussed about the Date/Time data types in the chapter Data Types. Now, let us see the Date/Time operators and Functions."
},
{
"code": null,
"e": 3031,
"s": 2955,
"text": "The following table lists the behaviors of the basic arithmetic operators −"
},
{
"code": null,
"e": 3117,
"s": 3031,
"text": "The following is the list of all important Date and Time related functions available."
},
{
"code": null,
"e": 3136,
"s": 3117,
"text": "Subtract arguments"
},
{
"code": null,
"e": 3158,
"s": 3136,
"text": "Current date and time"
},
{
"code": null,
"e": 3195,
"s": 3158,
"text": "Get subfield (equivalent to extract)"
},
{
"code": null,
"e": 3208,
"s": 3195,
"text": "Get subfield"
},
{
"code": null,
"e": 3266,
"s": 3208,
"text": "Test for finite date, time and interval (not +/-infinity)"
},
{
"code": null,
"e": 3282,
"s": 3266,
"text": "Adjust interval"
},
{
"code": null,
"e": 3308,
"s": 3282,
"text": "AGE(timestamp, timestamp)"
},
{
"code": null,
"e": 3477,
"s": 3308,
"text": "When invoked with the TIMESTAMP form of the second argument, AGE() subtract arguments, producing a \"symbolic\" result that uses years and months and is of type INTERVAL."
},
{
"code": null,
"e": 3492,
"s": 3477,
"text": "AGE(timestamp)"
},
{
"code": null,
"e": 3595,
"s": 3492,
"text": "When invoked with only the TIMESTAMP as argument, AGE() subtracts from the current_date (at midnight)."
},
{
"code": null,
"e": 3650,
"s": 3595,
"text": "Example of the function AGE(timestamp, timestamp) is −"
},
{
"code": null,
"e": 3719,
"s": 3650,
"text": "testdb=# SELECT AGE(timestamp '2001-04-10', timestamp '1957-06-13');"
},
{
"code": null,
"e": 3792,
"s": 3719,
"text": "The above given PostgreSQL statement will produce the following result −"
},
{
"code": null,
"e": 3858,
"s": 3792,
"text": " age\n-------------------------\n 43 years 9 mons 27 days"
},
{
"code": null,
"e": 3902,
"s": 3858,
"text": "Example of the function AGE(timestamp) is −"
},
{
"code": null,
"e": 3947,
"s": 3902,
"text": "testdb=# select age(timestamp '1957-06-13');"
},
{
"code": null,
"e": 4020,
"s": 3947,
"text": "The above given PostgreSQL statement will produce the following result −"
},
{
"code": null,
"e": 4088,
"s": 4020,
"text": " age\n--------------------------\n 55 years 10 mons 22 days"
},
{
"code": null,
"e": 4218,
"s": 4088,
"text": "PostgreSQL provides a number of functions that return values related to the current date and time. Following are some functions −"
},
{
"code": null,
"e": 4231,
"s": 4218,
"text": "CURRENT_DATE"
},
{
"code": null,
"e": 4254,
"s": 4231,
"text": "Delivers current date."
},
{
"code": null,
"e": 4267,
"s": 4254,
"text": "CURRENT_TIME"
},
{
"code": null,
"e": 4299,
"s": 4267,
"text": "Delivers values with time zone."
},
{
"code": null,
"e": 4317,
"s": 4299,
"text": "CURRENT_TIMESTAMP"
},
{
"code": null,
"e": 4349,
"s": 4317,
"text": "Delivers values with time zone."
},
{
"code": null,
"e": 4373,
"s": 4349,
"text": "CURRENT_TIME(precision)"
},
{
"code": null,
"e": 4504,
"s": 4373,
"text": "Optionally takes a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field."
},
{
"code": null,
"e": 4533,
"s": 4504,
"text": "CURRENT_TIMESTAMP(precision)"
},
{
"code": null,
"e": 4664,
"s": 4533,
"text": "Optionally takes a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field."
},
{
"code": null,
"e": 4674,
"s": 4664,
"text": "LOCALTIME"
},
{
"code": null,
"e": 4709,
"s": 4674,
"text": "Delivers values without time zone."
},
{
"code": null,
"e": 4724,
"s": 4709,
"text": "LOCALTIMESTAMP"
},
{
"code": null,
"e": 4759,
"s": 4724,
"text": "Delivers values without time zone."
},
{
"code": null,
"e": 4780,
"s": 4759,
"text": "LOCALTIME(precision)"
},
{
"code": null,
"e": 4911,
"s": 4780,
"text": "Optionally takes a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field."
},
{
"code": null,
"e": 4937,
"s": 4911,
"text": "LOCALTIMESTAMP(precision)"
},
{
"code": null,
"e": 5068,
"s": 4937,
"text": "Optionally takes a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field."
},
{
"code": null,
"e": 5120,
"s": 5068,
"text": "Examples using the functions from the table above −"
},
{
"code": null,
"e": 5651,
"s": 5120,
"text": "testdb=# SELECT CURRENT_TIME;\n timetz\n--------------------\n 08:01:34.656+05:30\n(1 row)\n\n\ntestdb=# SELECT CURRENT_DATE;\n date\n------------\n 2013-05-05\n(1 row)\n\n\ntestdb=# SELECT CURRENT_TIMESTAMP;\n now\n-------------------------------\n 2013-05-05 08:01:45.375+05:30\n(1 row)\n\n\ntestdb=# SELECT CURRENT_TIMESTAMP(2);\n timestamptz\n------------------------------\n 2013-05-05 08:01:50.89+05:30\n(1 row)\n\n\ntestdb=# SELECT LOCALTIMESTAMP;\n timestamp\n------------------------\n 2013-05-05 08:01:55.75\n(1 row)"
},
{
"code": null,
"e": 5835,
"s": 5651,
"text": "PostgreSQL also provides functions that return the start time of the current statement, as well as the actual current time at the instant the function is called. These functions are −"
},
{
"code": null,
"e": 5859,
"s": 5835,
"text": "transaction_timestamp()"
},
{
"code": null,
"e": 5947,
"s": 5859,
"text": "It is equivalent to CURRENT_TIMESTAMP, but is named to clearly reflect what it returns."
},
{
"code": null,
"e": 5969,
"s": 5947,
"text": "statement_timestamp()"
},
{
"code": null,
"e": 6022,
"s": 5969,
"text": " It returns the start time of the current statement."
},
{
"code": null,
"e": 6040,
"s": 6022,
"text": "clock_timestamp()"
},
{
"code": null,
"e": 6142,
"s": 6040,
"text": "It returns the actual current time, and therefore its value changes even within a single SQL command."
},
{
"code": null,
"e": 6154,
"s": 6142,
"text": "timeofday()"
},
{
"code": null,
"e": 6267,
"s": 6154,
"text": "It returns the actual current time, but as a formatted text string rather than a timestamp with time zone value."
},
{
"code": null,
"e": 6273,
"s": 6267,
"text": "now()"
},
{
"code": null,
"e": 6343,
"s": 6273,
"text": "It is a traditional PostgreSQL equivalent to transaction_timestamp()."
},
{
"code": null,
"e": 6370,
"s": 6343,
"text": "DATE_PART('field', source)"
},
{
"code": null,
"e": 6465,
"s": 6370,
"text": "These functions get the subfields. The field parameter needs to be a string value, not a name."
},
{
"code": null,
"e": 6680,
"s": 6465,
"text": "The valid field names are: century, day, decade, dow, doy, epoch, hour, isodow, isoyear, microseconds, millennium, milliseconds, minute, month, quarter, second, timezone, timezone_hour, timezone_minute, week, year."
},
{
"code": null,
"e": 6708,
"s": 6680,
"text": "DATE_TRUNC('field', source)"
},
{
"code": null,
"e": 6954,
"s": 6708,
"text": "This function is conceptually similar to the trunc function for numbers. source is a value expression of type timestamp or interval. field selects to which precision to truncate the input value. The return value is of type timestamp or interval."
},
{
"code": null,
"e": 7098,
"s": 6954,
"text": "The valid values for field are : microseconds, milliseconds, second, minute, hour, day, week, month, quarter, year, decade, century, millennium"
},
{
"code": null,
"e": 7168,
"s": 7098,
"text": "The following are examples for DATE_PART('field', source) functions −"
},
{
"code": null,
"e": 7386,
"s": 7168,
"text": "testdb=# SELECT date_part('day', TIMESTAMP '2001-02-16 20:38:40');\n date_part\n-----------\n 16\n(1 row)\n\n\ntestdb=# SELECT date_part('hour', INTERVAL '4 hours 3 minutes');\n date_part\n-----------\n 4\n(1 row)"
},
{
"code": null,
"e": 7457,
"s": 7386,
"text": "The following are examples for DATE_TRUNC('field', source) functions −"
},
{
"code": null,
"e": 7731,
"s": 7457,
"text": "testdb=# SELECT date_trunc('hour', TIMESTAMP '2001-02-16 20:38:40');\n date_trunc\n---------------------\n 2001-02-16 20:00:00\n(1 row)\n\n\ntestdb=# SELECT date_trunc('year', TIMESTAMP '2001-02-16 20:38:40');\n date_trunc\n---------------------\n 2001-01-01 00:00:00\n(1 row)"
},
{
"code": null,
"e": 8068,
"s": 7731,
"text": "The EXTRACT(field FROM source) function retrieves subfields such as year or hour from date/time values. The source must be a value expression of type timestamp, time, or interval. The field is an identifier or string that selects what field to extract from the source value. The EXTRACT function returns values of type double precision."
},
{
"code": null,
"e": 8337,
"s": 8068,
"text": "The following are valid field names (similar to DATE_PART function field names): century, day, decade, dow, doy, epoch, hour, isodow, isoyear, microseconds, millennium, milliseconds, minute, month, quarter, second, timezone, timezone_hour, timezone_minute, week, year."
},
{
"code": null,
"e": 8404,
"s": 8337,
"text": "The following are examples of EXTRACT('field', source) functions −"
},
{
"code": null,
"e": 8628,
"s": 8404,
"text": "testdb=# SELECT EXTRACT(CENTURY FROM TIMESTAMP '2000-12-16 12:21:13');\n date_part\n-----------\n 20\n(1 row)\n\n\ntestdb=# SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40');\n date_part\n-----------\n 16\n(1 row)"
},
{
"code": null,
"e": 8643,
"s": 8628,
"text": "ISFINITE(date)"
},
{
"code": null,
"e": 8666,
"s": 8643,
"text": "Tests for finite date."
},
{
"code": null,
"e": 8686,
"s": 8666,
"text": "ISFINITE(timestamp)"
},
{
"code": null,
"e": 8715,
"s": 8686,
"text": "Tests for finite time stamp."
},
{
"code": null,
"e": 8734,
"s": 8715,
"text": "ISFINITE(interval)"
},
{
"code": null,
"e": 8761,
"s": 8734,
"text": "Tests for finite interval."
},
{
"code": null,
"e": 8822,
"s": 8761,
"text": "The following are the examples of the ISFINITE() functions −"
},
{
"code": null,
"e": 9072,
"s": 8822,
"text": "testdb=# SELECT isfinite(date '2001-02-16');\n isfinite\n----------\n t\n(1 row)\n\n\ntestdb=# SELECT isfinite(timestamp '2001-02-16 21:28:30');\n isfinite\n----------\n t\n(1 row)\n\n\ntestdb=# SELECT isfinite(interval '4 hours');\n isfinite\n----------\n t\n(1 row)"
},
{
"code": null,
"e": 9095,
"s": 9072,
"text": "JUSTIFY_DAYS(interval)"
},
{
"code": null,
"e": 9187,
"s": 9095,
"text": "Adjusts interval so 30-day time periods are represented as months. Return the interval type"
},
{
"code": null,
"e": 9211,
"s": 9187,
"text": "JUSTIFY_HOURS(interval)"
},
{
"code": null,
"e": 9302,
"s": 9211,
"text": "Adjusts interval so 24-hour time periods are represented as days. Return the interval type"
},
{
"code": null,
"e": 9329,
"s": 9302,
"text": "JUSTIFY_INTERVAL(interval)"
},
{
"code": null,
"e": 9443,
"s": 9329,
"text": "Adjusts interval using JUSTIFY_DAYS and JUSTIFY_HOURS, with additional sign adjustments. Return the interval type"
},
{
"code": null,
"e": 9505,
"s": 9443,
"text": "The following are the examples for the ISFINITE() functions −"
},
{
"code": null,
"e": 9841,
"s": 9505,
"text": "testdb=# SELECT justify_days(interval '35 days');\n justify_days\n--------------\n 1 mon 5 days\n(1 row)\n\n\ntestdb=# SELECT justify_hours(interval '27 hours');\n justify_hours\n----------------\n 1 day 03:00:00\n(1 row)\n\n\ntestdb=# SELECT justify_interval(interval '1 mon -1 hour');\n justify_interval\n------------------\n 29 days 23:00:00\n(1 row)"
},
{
"code": null,
"e": 9876,
"s": 9841,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9888,
"s": 9876,
"text": " John Elder"
},
{
"code": null,
"e": 9923,
"s": 9888,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9939,
"s": 9923,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 9976,
"s": 9939,
"text": "\n 126 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 9998,
"s": 9976,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 10031,
"s": 9998,
"text": "\n 35 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 10045,
"s": 10031,
"text": " Karthikeya T"
},
{
"code": null,
"e": 10076,
"s": 10045,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 10089,
"s": 10076,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 10120,
"s": 10089,
"text": "\n 5 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 10133,
"s": 10120,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 10140,
"s": 10133,
"text": " Print"
},
{
"code": null,
"e": 10151,
"s": 10140,
"text": " Add Notes"
}
]
|
Flask â HTTP methods | Http protocol is the foundation of data communication in world wide web. Different methods of data retrieval from specified URL are defined in this protocol.
The following table summarizes different http methods −
GET
Sends data in unencrypted form to the server. Most common method.
HEAD
Same as GET, but without response body
POST
Used to send HTML form data to server. Data received by POST method is not cached by server.
PUT
Replaces all current representations of the target resource with the uploaded content.
DELETE
Removes all current representations of the target resource given by a URL
By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator.
In order to demonstrate the use of POST method in URL routing, first let us create an HTML form and use the POST method to send form data to a URL.
Save the following script as login.html
<html>
<body>
<form action = "http://localhost:5000/login" method = "post">
<p>Enter Name:</p>
<p><input type = "text" name = "nm" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
Now enter the following script in Python shell.
from flask import Flask, redirect, url_for, request
app = Flask(__name__)
@app.route('/success/<name>')
def success(name):
return 'welcome %s' % name
@app.route('/login',methods = ['POST', 'GET'])
def login():
if request.method == 'POST':
user = request.form['nm']
return redirect(url_for('success',name = user))
else:
user = request.args.get('nm')
return redirect(url_for('success',name = user))
if __name__ == '__main__':
app.run(debug = True)
After the development server starts running, open login.html in the browser, enter name in the text field and click Submit.
Form data is POSTed to the URL in action clause of form tag.
http://localhost/login is mapped to the login() function. Since the server has received data by POST method, value of ‘nm’ parameter obtained from the form data is obtained by −
user = request.form['nm']
It is passed to ‘/success’ URL as variable part. The browser displays a welcome message in the window.
Change the method parameter to ‘GET’ in login.html and open it again in the browser. The data received on server is by the GET method. The value of ‘nm’ parameter is now obtained by −
User = request.args.get(‘nm’)
Here, args is dictionary object containing a list of pairs of form parameter and its corresponding value. The value corresponding to ‘nm’ parameter is passed on to ‘/success’ URL as before.
22 Lectures
6 hours
Malhar Lathkar
21 Lectures
1.5 hours
Jack Chan
16 Lectures
4 hours
Malhar Lathkar
54 Lectures
6 hours
Srikanth Guskra
88 Lectures
3.5 hours
Jorge Escobar
80 Lectures
12 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2191,
"s": 2033,
"text": "Http protocol is the foundation of data communication in world wide web. Different methods of data retrieval from specified URL are defined in this protocol."
},
{
"code": null,
"e": 2247,
"s": 2191,
"text": "The following table summarizes different http methods −"
},
{
"code": null,
"e": 2251,
"s": 2247,
"text": "GET"
},
{
"code": null,
"e": 2317,
"s": 2251,
"text": "Sends data in unencrypted form to the server. Most common method."
},
{
"code": null,
"e": 2322,
"s": 2317,
"text": "HEAD"
},
{
"code": null,
"e": 2361,
"s": 2322,
"text": "Same as GET, but without response body"
},
{
"code": null,
"e": 2366,
"s": 2361,
"text": "POST"
},
{
"code": null,
"e": 2459,
"s": 2366,
"text": "Used to send HTML form data to server. Data received by POST method is not cached by server."
},
{
"code": null,
"e": 2463,
"s": 2459,
"text": "PUT"
},
{
"code": null,
"e": 2550,
"s": 2463,
"text": "Replaces all current representations of the target resource with the uploaded content."
},
{
"code": null,
"e": 2557,
"s": 2550,
"text": "DELETE"
},
{
"code": null,
"e": 2631,
"s": 2557,
"text": "Removes all current representations of the target resource given by a URL"
},
{
"code": null,
"e": 2781,
"s": 2631,
"text": "By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator."
},
{
"code": null,
"e": 2929,
"s": 2781,
"text": "In order to demonstrate the use of POST method in URL routing, first let us create an HTML form and use the POST method to send form data to a URL."
},
{
"code": null,
"e": 2969,
"s": 2929,
"text": "Save the following script as login.html"
},
{
"code": null,
"e": 3226,
"s": 2969,
"text": "<html>\n <body>\n <form action = \"http://localhost:5000/login\" method = \"post\">\n <p>Enter Name:</p>\n <p><input type = \"text\" name = \"nm\" /></p>\n <p><input type = \"submit\" value = \"submit\" /></p>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 3274,
"s": 3226,
"text": "Now enter the following script in Python shell."
},
{
"code": null,
"e": 3759,
"s": 3274,
"text": "from flask import Flask, redirect, url_for, request\napp = Flask(__name__)\n\[email protected]('/success/<name>')\ndef success(name):\n return 'welcome %s' % name\n\[email protected]('/login',methods = ['POST', 'GET'])\ndef login():\n if request.method == 'POST':\n user = request.form['nm']\n return redirect(url_for('success',name = user))\n else:\n user = request.args.get('nm')\n return redirect(url_for('success',name = user))\n\nif __name__ == '__main__':\n app.run(debug = True)"
},
{
"code": null,
"e": 3883,
"s": 3759,
"text": "After the development server starts running, open login.html in the browser, enter name in the text field and click Submit."
},
{
"code": null,
"e": 3944,
"s": 3883,
"text": "Form data is POSTed to the URL in action clause of form tag."
},
{
"code": null,
"e": 4122,
"s": 3944,
"text": "http://localhost/login is mapped to the login() function. Since the server has received data by POST method, value of ‘nm’ parameter obtained from the form data is obtained by −"
},
{
"code": null,
"e": 4149,
"s": 4122,
"text": "user = request.form['nm']\n"
},
{
"code": null,
"e": 4252,
"s": 4149,
"text": "It is passed to ‘/success’ URL as variable part. The browser displays a welcome message in the window."
},
{
"code": null,
"e": 4436,
"s": 4252,
"text": "Change the method parameter to ‘GET’ in login.html and open it again in the browser. The data received on server is by the GET method. The value of ‘nm’ parameter is now obtained by −"
},
{
"code": null,
"e": 4467,
"s": 4436,
"text": "User = request.args.get(‘nm’)\n"
},
{
"code": null,
"e": 4657,
"s": 4467,
"text": "Here, args is dictionary object containing a list of pairs of form parameter and its corresponding value. The value corresponding to ‘nm’ parameter is passed on to ‘/success’ URL as before."
},
{
"code": null,
"e": 4690,
"s": 4657,
"text": "\n 22 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4706,
"s": 4690,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4741,
"s": 4706,
"text": "\n 21 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4752,
"s": 4741,
"text": " Jack Chan"
},
{
"code": null,
"e": 4785,
"s": 4752,
"text": "\n 16 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4801,
"s": 4785,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4834,
"s": 4801,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4851,
"s": 4834,
"text": " Srikanth Guskra"
},
{
"code": null,
"e": 4886,
"s": 4851,
"text": "\n 88 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4901,
"s": 4886,
"text": " Jorge Escobar"
},
{
"code": null,
"e": 4935,
"s": 4901,
"text": "\n 80 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 4958,
"s": 4935,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 4965,
"s": 4958,
"text": " Print"
},
{
"code": null,
"e": 4976,
"s": 4965,
"text": " Add Notes"
}
]
|
Hidden Markov Model — Implemented from scratch | by Oleg Żero | Towards Data Science | I want to expand this work into a series of μ-tutorial videos. If you’re interested, please subscribe to my newsletter to stay in touch.
The Internet is full of good articles that explain the theory behind the Hidden Markov Model (HMM) well (e.g. 1, 2, 3 and 4). However, many of these works contain a fair amount of rather advanced mathematical equations. While equations are necessary if one wants to explain the theory, we decided to take it to the next level and create a gentle step by step practical implementation to complement the good work of others.
In this short series of two articles, we will focus on translating all of the complicated mathematics into code. Our starting point is the document written by Mark Stamp. We will use this paper to define our code (this article) and then use a somewhat peculiar example of “Morning Insanity” to demonstrate its performance in practice.
Before we begin, let’s revisit the notation we will be using. By the way, don’t worry if some of that is unclear to you. We will hold your hand.
T - length of the observation sequence.
N - number of latent (hidden) states.
M - number of observables.
Q = {q0, q1, ...} - hidden states.
V = {0, 1, ..., M — 1} - set of possible observations.
A - state transition matrix.
B - emission probability matrix.
π- initial state probability distribution.
O - observation sequence.
X = (x0, x1, ...), x_t ∈ Q - hidden state sequence.
Having that set defined, we can calculate the probability of any state and observation using the matrices:
A = {a_ij} — begin an transition matrix.
B = {b_j(k)} — being an emission matrix.
The probabilities associated with transition and observation (emission) are:
The model is therefore defined as a collection:
Since HMM is based on probability vectors and matrices, let’s first define objects that will represent the fundamental concepts. To be useful, the objects must reflect on certain properties. For example, all elements of a probability vector must be numbers 0 ≤ x ≤ 1 and they must sum up to 1. Therefore, let’s design the objects the way they will inherently safeguard the mathematical properties.
import numpy as npimport pandas as pdclass ProbabilityVector: def __init__(self, probabilities: dict): states = probabilities.keys() probs = probabilities.values() assert len(states) == len(probs), "The probabilities must match the states." assert len(states) == len(set(states)), "The states must be unique." assert abs(sum(probs) - 1.0) < 1e-12, "Probabilities must sum up to 1." assert len(list(filter(lambda x: 0 <= x <= 1, probs))) == len(probs), \ "Probabilities must be numbers from [0, 1] interval." self.states = sorted(probabilities) self.values = np.array(list(map(lambda x: probabilities[x], self.states))).reshape(1, -1) @classmethod def initialize(cls, states: list): size = len(states) rand = np.random.rand(size) / (size**2) + 1 / size rand /= rand.sum(axis=0) return cls(dict(zip(states, rand))) @classmethod def from_numpy(cls, array: np.ndarray, state: list): return cls(dict(zip(states, list(array)))) @property def dict(self): return {k:v for k, v in zip(self.states, list(self.values.flatten()))} @property def df(self): return pd.DataFrame(self.values, columns=self.states, index=['probability']) def __repr__(self): return "P({}) = {}.".format(self.states, self.values) def __eq__(self, other): if not isinstance(other, ProbabilityVector): raise NotImplementedError if (self.states == other.states) and (self.values == other.values).all(): return True return False def __getitem__(self, state: str) -> float: if state not in self.states: raise ValueError("Requesting unknown probability state from vector.") index = self.states.index(state) return float(self.values[0, index]) def __mul__(self, other) -> np.ndarray: if isinstance(other, ProbabilityVector): return self.values * other.values elif isinstance(other, (int, float)): return self.values * other else: NotImplementedError def __rmul__(self, other) -> np.ndarray: return self.__mul__(other) def __matmul__(self, other) -> np.ndarray: if isinstance(other, ProbabilityMatrix): return self.values @ other.values def __truediv__(self, number) -> np.ndarray: if not isinstance(number, (int, float)): raise NotImplementedError x = self.values return x / number if number != 0 else x / (number + 1e-12) def argmax(self): index = self.values.argmax() return self.states[index]
The most natural way to initialize this object is to use a dictionary as it associates values with unique keys. Dictionaries, unfortunately, do not provide any assertion mechanisms that put any constraints on the values. Consequently, we build our custom ProbabilityVector object to ensure that our values behave correctly. Most importantly, we enforce the following:
The number of values must equal the number of the keys (names of our states). Although this is not a problem when initializing the object from a dictionary, we will use other ways later.
All names of the states must be unique (the same arguments apply).
The probabilities must sum up to 1 (up to a certain tolerance).
All probabilities must be 0 ≤ p ≤ 1.
Having ensured that, we also provide two alternative ways to instantiate ProbabilityVector objects (decorated with @classmethod).
We instantiate the objects randomly — it will be useful when training.We use ready-made numpy arrays and use values therein, and only providing the names for the states.
We instantiate the objects randomly — it will be useful when training.
We use ready-made numpy arrays and use values therein, and only providing the names for the states.
For convenience and debugging, we provide two additional methods for requesting the values. Decorated with, they return the content of the PV object as a dictionary or a pandas dataframe.
The PV objects need to satisfy the following mathematical operations (for the purpose of constructing of HMM):
comparison (__eq__) - to know if any two PV's are equal,element-wise multiplication of two PV’s or multiplication with a scalar (__mul__ and __rmul__).dot product (__matmul__) - to perform vector-matrix multiplicationdivision by number (__truediv__),argmax to find for which state the probability is the highest.__getitem__ to enable selecting value by the key.
comparison (__eq__) - to know if any two PV's are equal,
element-wise multiplication of two PV’s or multiplication with a scalar (__mul__ and __rmul__).
dot product (__matmul__) - to perform vector-matrix multiplication
division by number (__truediv__),
argmax to find for which state the probability is the highest.
__getitem__ to enable selecting value by the key.
Note that when e.g. multiplying a PV with a scalar, the returned structure is a resulting numpy array, not another PV. This is because multiplying by anything other than 1 would violate the integrity of the PV itself.
Internally, the values are stored as a numpy array of size (1 × N).
a1 = ProbabilityVector({'rain': 0.7, 'sun': 0.3})a2 = ProbabilityVector({'sun': 0.1, 'rain': 0.9})print(a1.df)print(a2.df)print("Comparison:", a1 == a2)print("Element-wise multiplication:", a1 * a2)print("Argmax:", a1.argmax())print("Getitem:", a1['rain'])# OUTPUT>>> rain sun probability 0.7 0.3 rain sun probability 0.9 0.1>>> Comparison: False>>> Element-wise multiplication: [[0.63 0.03]]>>> Argmax: rain>>> Getitem: 0.7
Another object is a Probability Matrix, which is a core part of the HMM definition. Formally, the A and B matrices must be row-stochastic, meaning that the values of every row must sum up to 1. We can, therefore, define our PM by stacking several PV's, which we have constructed in a way to guarantee this constraint.
class ProbabilityMatrix: def __init__(self, prob_vec_dict: dict): assert len(prob_vec_dict) > 1, \ "The numebr of input probability vector must be greater than one." assert len(set([str(x.states) for x in prob_vec_dict.values()])) == 1, \ "All internal states of all the vectors must be indentical." assert len(prob_vec_dict.keys()) == len(set(prob_vec_dict.keys())), \ "All observables must be unique." self.states = sorted(prob_vec_dict) self.observables = prob_vec_dict[self.states[0]].states self.values = np.stack([prob_vec_dict[x].values \ for x in self.states]).squeeze() @classmethod def initialize(cls, states: list, observables: list): size = len(states) rand = np.random.rand(size, len(observables)) \ / (size**2) + 1 / size rand /= rand.sum(axis=1).reshape(-1, 1) aggr = [dict(zip(observables, rand[i, :])) for i in range(len(states))] pvec = [ProbabilityVector(x) for x in aggr] return cls(dict(zip(states, pvec))) @classmethod def from_numpy(cls, array: np.ndarray, states: list, observables: list): p_vecs = [ProbabilityVector(dict(zip(observables, x))) \ for x in array] return cls(dict(zip(states, p_vecs))) @property def dict(self): return self.df.to_dict() @property def df(self): return pd.DataFrame(self.values, columns=self.observables, index=self.states) def __repr__(self): return "PM {} states: {} -> obs: {}.".format( self.values.shape, self.states, self.observables) def __getitem__(self, observable: str) -> np.ndarray: if observable not in self.observables: raise ValueError("Requesting unknown probability observable from the matrix.") index = self.observables.index(observable) return self.values[:, index].reshape(-1, 1)
Here, the way we instantiate PM’s is by supplying a dictionary of PV’s to the constructor of the class. By doing this, we not only ensure that every row of PM is stochastic, but also supply the names for every observable.
Our PM can, therefore, give an array of coefficients for any observable. Mathematically, the PM is a matrix:
The other methods are implemented in similar way to PV.
a1 = ProbabilityVector({'rain': 0.7, 'sun': 0.3})a2 = ProbabilityVector({'rain': 0.6, 'sun': 0.4})A = ProbabilityMatrix({'hot': a1, 'cold': a2})print(A)print(A.df)>>> PM (2, 2) states: ['cold', 'hot'] -> obs: ['rain', 'sun'].>>> rain sun cold 0.6 0.4 hot 0.7 0.3b1 = ProbabilityVector({'0S': 0.1, '1M': 0.4, '2L': 0.5})b2 = ProbabilityVector({'0S': 0.7, '1M': 0.2, '2L': 0.1})B = ProbabilityMatrix({'0H': b1, '1C': b2})print(B)print(B.df)>>> PM (2, 3) states: ['0H', '1C'] -> obs: ['0S', '1M', '2L'].>>> 0S 1M 2L 0H 0.1 0.4 0.5 1C 0.7 0.2 0.1P = ProbabilityMatrix.initialize(list('abcd'), list('xyz'))print('Dot product:', a1 @ A)print('Initialization:', P)print(P.df)>>> Dot product: [[0.63 0.37]]>>> Initialization: PM (4, 3) states: ['a', 'b', 'c', 'd'] -> obs: ['x', 'y', 'z'].>>> x y z a 0.323803 0.327106 0.349091 b 0.318166 0.326356 0.355478 c 0.311833 0.347983 0.340185 d 0.337223 0.316850 0.345927
Before we proceed with calculating the score, let’s use our PV and PM definitions to implement the Hidden Markov Chain.
Again, we will do so as a class, calling it HiddenMarkovChain. It will collate at A, B and π. Later on, we will implement more methods that are applicable to this class.
Computing the score means to find what is the probability of a particular chain of observations O given our (known) model λ = (A, B, π). In other words, we are interested in finding p(O|λ).
We can find p(O|λ) by marginalizing all possible chains of the hidden variables X, where X = {x0, x1, ...}:
Since p(O|X, λ) = ∏ b(O) (the product of all probabilities related to the observables) and p(X|λ)=π ∏ a (the product of all probabilities of transitioning from x at t to x at t + 1, the probability we are looking for (the score) is:
This is a naive way of computing of the score, since we need to calculate the probability for every possible chain X. Either way, let’s implement it in python:
from itertools import productfrom functools import reduceclass HiddenMarkovChain: def __init__(self, T, E, pi): self.T = T # transmission matrix A self.E = E # emission matrix B self.pi = pi self.states = pi.states self.observables = E.observables def __repr__(self): return "HML states: {} -> observables: {}.".format( len(self.states), len(self.observables)) @classmethod def initialize(cls, states: list, observables: list): T = ProbabilityMatrix.initialize(states, states) E = ProbabilityMatrix.initialize(states, observables) pi = ProbabilityVector.initialize(states) return cls(T, E, pi) def _create_all_chains(self, chain_length): return list(product(*(self.states,) * chain_length)) def score(self, observations: list) -> float: def mul(x, y): return x * y score = 0 all_chains = self._create_all_chains(len(observations)) for idx, chain in enumerate(all_chains): expanded_chain = list(zip(chain, [self.T.states[0]] + list(chain))) expanded_obser = list(zip(observations, chain)) p_observations = list(map(lambda x: self.E.df.loc[x[1], x[0]], expanded_obser)) p_hidden_state = list(map(lambda x: self.T.df.loc[x[1], x[0]], expanded_chain)) p_hidden_state[0] = self.pi[chain[0]] score += reduce(mul, p_observations) * reduce(mul, p_hidden_state) return score
a1 = ProbabilityVector({'1H': 0.7, '2C': 0.3})a2 = ProbabilityVector({'1H': 0.4, '2C': 0.6})b1 = ProbabilityVector({'1S': 0.1, '2M': 0.4, '3L': 0.5})b2 = ProbabilityVector({'1S': 0.7, '2M': 0.2, '3L': 0.1})A = ProbabilityMatrix({'1H': a1, '2C': a2})B = ProbabilityMatrix({'1H': b1, '2C': b2})pi = ProbabilityVector({'1H': 0.6, '2C': 0.4})hmc = HiddenMarkovChain(A, B, pi)observations = ['1S', '2M', '3L', '2M', '1S']print("Score for {} is {:f}.".format(observations, hmc.score(observations)))>>> Score for ['1S', '2M', '3L', '2M', '1S'] is 0.003482.
If our implementation is correct, then all score values for all possible observation chains, for a given model should add up to one. Namely:
all_possible_observations = {'1S', '2M', '3L'}chain_length = 3 # any int > 0all_observation_chains = list(product(*(all_possible_observations,) * chain_length))all_possible_scores = list(map(lambda obs: hmc.score(obs), all_observation_chains))print("All possible scores added: {}.".format(sum(all_possible_scores)))>>> All possible scores added: 1.0.
Indeed.
Computing the score the way we did above is kind of naive. In order to find the number for a particular observation chain O, we have to compute the score for all possible latent variable sequences X. That requires 2TN^T multiplications, which even for small numbers takes time.
Another way to do it is to calculate partial observations of a sequence up to time t.
For and i ∈ {0, 1, ..., N-1} and t ∈ {0, 1, ..., T-1} :
Consequently,
and
Then
Note that α_t is a vector of length N. The sum of the product α a can, in fact, be written as a dot product. Therefore:
where by the star, we denote an element-wise multiplication.
With this implementation, we reduce the number of multiplication to N2T and can take advantage of vectorization.
class HiddenMarkovChain_FP(HiddenMarkovChain): def _alphas(self, observations: list) -> np.ndarray: alphas = np.zeros((len(observations), len(self.states))) alphas[0, :] = self.pi.values * self.E[observations[0]].T for t in range(1, len(observations)): alphas[t, :] = (alphas[t - 1, :].reshape(1, -1) @ self.T.values) * self.E[observations[t]].T return alphas def score(self, observations: list) -> float: alphas = self._alphas(observations) return float(alphas[-1].sum())
hmc_fp = HiddenMarkovChain_FP(A, B, pi)observations = ['1S', '2M', '3L', '2M', '1S']print("Score for {} is {:f}.".format(observations, hmc_fp.score(observations)))>>> All possible scores added: 1.0.
...yup.
Let’s test one more thing. Basically, let’s take our λ = (A, B, π) and use it to generate a sequence of random observables, starting from some initial state probability π.
If the desired length T is “large enough”, we would expect that the system to converge on a sequence that, on average, gives the same number of events as we would expect from A and B matrices directly. In other words, the transition and the emission matrices “decide”, with a certain probability, what the next state will be and what observation we will get, for every step, respectively. Therefore, what may initially look like random events, on average should reflect the coefficients of the matrices themselves. Let’s check that as well.
class HiddenMarkovChain_Simulation(HiddenMarkovChain): def run(self, length: int) -> (list, list): assert length >= 0, "The chain needs to be a non-negative number." s_history = [0] * (length + 1) o_history = [0] * (length + 1) prb = self.pi.values obs = prb @ self.E.values s_history[0] = np.random.choice(self.states, p=prb.flatten()) o_history[0] = np.random.choice(self.observables, p=obs.flatten()) for t in range(1, length + 1): prb = prb @ self.T.values obs = prb @ self.E.values s_history[t] = np.random.choice(self.states, p=prb.flatten()) o_history[t] = np.random.choice(self.observables, p=obs.flatten()) return o_history, s_history
hmc_s = HiddenMarkovChain_Simulation(A, B, pi)observation_hist, states_hist = hmc_s.run(100) # length = 100stats = pd.DataFrame({ 'observations': observation_hist, 'states': states_hist}).applymap(lambda x: int(x[0])).plot()
The state matrix A is given by the following coefficients:
Consequently, the probability of “being” in the state “1H” at t+1, regardless of the previous state, is equal to:
If we assume that the prior probabilities of being at some state at are totally random, then p(1H) = 1 and p(2C) = 0.9, which after renormalizing give 0.55 and 0.45, respectively.
If we count the number of occurrences of each state and divide it by the number of elements in our sequence, we would get closer and closer to these number as the length of the sequence grows.
hmc_s = HiddenMarkovChain_Simulation(A, B, pi)stats = {}for length in np.logspace(1, 5, 40).astype(int): observation_hist, states_hist = hmc_s.run(length) stats[length] = pd.DataFrame({ 'observations': observation_hist, 'states': states_hist}).applymap(lambda x: int(x[0]))S = np.array(list(map(lambda x: x['states'].value_counts().to_numpy() / len(x), stats.values())))plt.semilogx(np.logspace(1, 5, 40).astype(int), S)plt.xlabel('Chain length T')plt.ylabel('Probability')plt.title('Converging probabilities.')plt.legend(['1H', '2C'])plt.show()
Let’s take our HiddenMarkovChain class to the next level and supplement it with more methods. The methods will help us to discover the most probable sequence of hidden variables behind the observation sequence.
We have defined α to be the probability of partial observation of the sequence up to time .
Now, let’s define the “opposite” probability. Namely, the probability of observing the sequence from T - 1down to t.
For t= 0, 1, ..., T-1 and i=0, 1, ..., N-1, we define:
c`1As before, we can β(i) calculate recursively:
Then for t ≠ T-1:
which in vectorized form, will be:
Finally, we also define a new quantity γ to indicate the state q_i at time t, for which the probability (calculated forwards and backwards) is the maximum:
Consequently, for any step t = 0, 1, ..., T-1, the state of the maximum likelihood can be found using:
class HiddenMarkovChain_Uncover(HiddenMarkovChain_Simulation): def _alphas(self, observations: list) -> np.ndarray: alphas = np.zeros((len(observations), len(self.states))) alphas[0, :] = self.pi.values * self.E[observations[0]].T for t in range(1, len(observations)): alphas[t, :] = (alphas[t - 1, :].reshape(1, -1) @ self.T.values) \ * self.E[observations[t]].T return alphas def _betas(self, observations: list) -> np.ndarray: betas = np.zeros((len(observations), len(self.states))) betas[-1, :] = 1 for t in range(len(observations) - 2, -1, -1): betas[t, :] = (self.T.values @ (self.E[observations[t + 1]] \ * betas[t + 1, :].reshape(-1, 1))).reshape(1, -1) return betas def uncover(self, observations: list) -> list: alphas = self._alphas(observations) betas = self._betas(observations) maxargs = (alphas * betas).argmax(axis=1) return list(map(lambda x: self.states[x], maxargs))
To validate, let’s generate some observable sequence O. For that, we can use our model’s .run method. Then, we will use the.uncover method to find the most likely latent variable sequence.
np.random.seed(42)a1 = ProbabilityVector({'1H': 0.7, '2C': 0.3})a2 = ProbabilityVector({'1H': 0.4, '2C': 0.6})b1 = ProbabilityVector({'1S': 0.1, '2M': 0.4, '3L': 0.5}) b2 = ProbabilityVector({'1S': 0.7, '2M': 0.2, '3L': 0.1})A = ProbabilityMatrix({'1H': a1, '2C': a2})B = ProbabilityMatrix({'1H': b1, '2C': b2})pi = ProbabilityVector({'1H': 0.6, '2C': 0.4})hmc = HiddenMarkovChain_Uncover(A, B, pi)observed_sequence, latent_sequence = hmc.run(5)uncovered_sequence = hmc.uncover(observed_sequence)| | 0 | 1 | 2 | 3 | 4 | 5 ||:------------------:|:----|:----|:----|:----|:----|:----|| observed sequence | 3L | 3M | 1S | 3L | 3L | 3L || latent sequence | 1H | 2C | 1H | 1H | 2C | 1H || uncovered sequence | 1H | 1H | 2C | 1H | 1H | 1H |
As we can see, the most likely latent state chain (according to the algorithm) is not the same as the one that actually caused the observations. This is to be expected. After all, each observation sequence can only be manifested with certain probability, dependent on the latent sequence.
The code below, evaluates the likelihood of different latent sequences resulting in our observation sequence.
all_possible_states = {'1H', '2C'}chain_length = 6 # any int > 0all_states_chains = list(product(*(all_possible_states,) * chain_length))df = pd.DataFrame(all_states_chains)dfp = pd.DataFrame()for i in range(chain_length): dfp['p' + str(i)] = df.apply(lambda x: hmc.E.df.loc[x[i], observed_sequence[i]], axis=1)scores = dfp.sum(axis=1).sort_values(ascending=False)df = df.iloc[scores.index]df['score'] = scoresdf.head(10).reset_index()| index | 0 | 1 | 2 | 3 | 4 | 5 | score ||:--------:|:----|:----|:----|:----|:----|:----|--------:|| 8 | 1H | 1H | 2C | 1H | 1H | 1H | 3.1 || 24 | 1H | 2C | 2C | 1H | 1H | 1H | 2.9 || 40 | 2C | 1H | 2C | 1H | 1H | 1H | 2.7 || 12 | 1H | 1H | 2C | 2C | 1H | 1H | 2.7 || 10 | 1H | 1H | 2C | 1H | 2C | 1H | 2.7 || 9 | 1H | 1H | 2C | 1H | 1H | 2C | 2.7 || 25 | 1H | 2C | 2C | 1H | 1H | 2C | 2.5 || 0 | 1H | 1H | 1H | 1H | 1H | 1H | 2.5 || 26 | 1H | 2C | 2C | 1H | 2C | 1H | 2.5 || 28 | 1H | 2C | 2C | 2C | 1H | 1H | 2.5 |
The result above shows the sorted table of the latent sequences, given the observation sequence. The actual latent sequence (the one that caused the observations) places itself on the 35th position (we counted index from zero).
dfc = df.copy().reset_index()for i in range(chain_length): dfc = dfc[dfc[i] == latent_sequence[i]] dfc| index | 0 | 1 | 2 | 3 | 4 | 5 | score ||:-------:|:----|:----|:----|:----|:----|:----|--------:|| 18 | 1H | 2C | 1H | 1H | 2C | 1H | 1.9 |
The time has come to show the training procedure. Formally, we are interested in finding λ = (A, B, π) such that given a desired observation sequence O, our model λ would give the best fit.
Here, our starting point will be the HiddenMarkovModel_Uncover that we have defined earlier. We will add new methods to train it.
Knowing our latent states Q and possible observation states O, we automatically know the sizes of the matrices A and B, hence N and M. However, we need to determine a and b and π.
For t = 0, 1, ..., T-2 and i, j =0, 1, ..., N -1, we define “di-gammas”:
γ(i, j) is the probability of transitioning for q at t to t + 1. Writing it in terms of α, β, A, B we have:
Now, thinking in terms of implementation, we want to avoid looping over i, j and t at the same time, as it’s gonna be deadly slow. Fortunately, we can vectorize the equation:
Having the equation for γ(i, j), we can calculate
To find λ = (A, B, π), we do
For i = 0, 1, ..., N-1:
or
For i, j = 0, 1, ..., N-1:
For j = 0, 1, ..., N-1 and k = 0, 1, ..., M-1:
class HiddenMarkovLayer(HiddenMarkovChain_Uncover): def _digammas(self, observations: list) -> np.ndarray: L, N = len(observations), len(self.states) digammas = np.zeros((L - 1, N, N)) alphas = self._alphas(observations) betas = self._betas(observations) score = self.score(observations) for t in range(L - 1): P1 = (alphas[t, :].reshape(-1, 1) * self.T.values) P2 = self.E[observations[t + 1]].T * betas[t + 1].reshape(1, -1) digammas[t, :, :] = P1 * P2 / score return digammas
Having the “layer” supplemented with the ._difammas method, we should be able to perform all the necessary calculations. However, it makes sense to delegate the "management" of the layer to another class. In fact, the model training can be summarized as follows:
Initialize A, B and π.Calculate γ(i, j).Update the model’s A, B and π.We repeat the 2. and 3. until the score p(O|λ) no longer increases.
Initialize A, B and π.
Calculate γ(i, j).
Update the model’s A, B and π.
We repeat the 2. and 3. until the score p(O|λ) no longer increases.
class HiddenMarkovModel: def __init__(self, hml: HiddenMarkovLayer): self.layer = hml self._score_init = 0 self.score_history = [] @classmethod def initialize(cls, states: list, observables: list): layer = HiddenMarkovLayer.initialize(states, observables) return cls(layer) def update(self, observations: list) -> float: alpha = self.layer._alphas(observations) beta = self.layer._betas(observations) digamma = self.layer._digammas(observations) score = alpha[-1].sum() gamma = alpha * beta / score L = len(alpha) obs_idx = [self.layer.observables.index(x) \ for x in observations] capture = np.zeros((L, len(self.layer.states), len(self.layer.observables))) for t in range(L): capture[t, :, obs_idx[t]] = 1.0 pi = gamma[0] T = digamma.sum(axis=0) / gamma[:-1].sum(axis=0).reshape(-1, 1) E = (capture * gamma[:, :, np.newaxis]).sum(axis=0) / gamma.sum(axis=0).reshape(-1, 1) self.layer.pi = ProbabilityVector.from_numpy(pi, self.layer.states) self.layer.T = ProbabilityMatrix.from_numpy(T, self.layer.states, self.layer.states) self.layer.E = ProbabilityMatrix.from_numpy(E, self.layer.states, self.layer.observables) return score def train(self, observations: list, epochs: int, tol=None): self._score_init = 0 self.score_history = (epochs + 1) * [0] early_stopping = isinstance(tol, (int, float)) for epoch in range(1, epochs + 1): score = self.update(observations) print("Training... epoch = {} out of {}, score = {}.".format(epoch, epochs, score)) if early_stopping and abs(self._score_init - score) / score < tol: print("Early stopping.") break self._score_init = score self.score_history[epoch] = score
np.random.seed(42)observations = ['3L', '2M', '1S', '3L', '3L', '3L']states = ['1H', '2C']observables = ['1S', '2M', '3L']hml = HiddenMarkovLayer.initialize(states, observables)hmm = HiddenMarkovModel(hml)hmm.train(observations, 25)
Let’s look at the generated sequences. The “demanded” sequence is:
| | 0 | 1 | 2 | 3 | 4 | 5 ||---:|:----|:----|:----|:----|:----|:----|| 0 | 3L | 2M | 1S | 3L | 3L | 3L |RUNS = 100000T = 5chains = RUNS * [0]for i in range(len(chains)): chain = hmm.layer.run(T)[0] chains[i] = '-'.join(chain)
The table below summarizes simulated runs based on 100000 attempts (see above), with the frequency of occurrence and number of matching observations.
The bottom line is that if we have truly trained the model, we should see a strong tendency for it to generate us sequences that resemble the one we require. Let’s see if it happens.
df = pd.DataFrame(pd.Series(chains).value_counts(), columns=['counts']).reset_index().rename(columns={'index': 'chain'})df = pd.merge(df, df['chain'].str.split('-', expand=True), left_index=True, right_index=True)s = []for i in range(T + 1): s.append(df.apply(lambda x: x[i] == observations[i], axis=1))df['matched'] = pd.concat(s, axis=1).sum(axis=1)df['counts'] = df['counts'] / RUNS * 100df = df.drop(columns=['chain'])df.head(30)---|---:|---------:|:----|:----|:----|:----|:----|:----|----------:|| 0 | 8.907 | 3L | 3L | 3L | 3L | 3L | 3L | 4 || 1 | 4.422 | 3L | 2M | 3L | 3L | 3L | 3L | 5 || 2 | 4.286 | 1S | 3L | 3L | 3L | 3L | 3L | 3 || 3 | 4.284 | 3L | 3L | 3L | 3L | 3L | 2M | 3 || 4 | 4.278 | 3L | 3L | 3L | 2M | 3L | 3L | 3 || 5 | 4.227 | 3L | 3L | 1S | 3L | 3L | 3L | 5 || 6 | 4.179 | 3L | 3L | 3L | 3L | 1S | 3L | 3 || 7 | 2.179 | 3L | 2M | 3L | 2M | 3L | 3L | 4 || 8 | 2.173 | 3L | 2M | 3L | 3L | 1S | 3L | 4 || 9 | 2.165 | 1S | 3L | 1S | 3L | 3L | 3L | 4 || 10 | 2.147 | 3L | 2M | 3L | 3L | 3L | 2M | 4 || 11 | 2.136 | 3L | 3L | 3L | 2M | 3L | 2M | 2 || 12 | 2.121 | 3L | 2M | 1S | 3L | 3L | 3L | 6 || 13 | 2.111 | 1S | 3L | 3L | 2M | 3L | 3L | 2 || 14 | 2.1 | 1S | 2M | 3L | 3L | 3L | 3L | 4 || 15 | 2.075 | 3L | 3L | 3L | 2M | 1S | 3L | 2 || 16 | 2.05 | 1S | 3L | 3L | 3L | 3L | 2M | 2 || 17 | 2.04 | 3L | 3L | 1S | 3L | 3L | 2M | 4 || 18 | 2.038 | 3L | 3L | 1S | 2M | 3L | 3L | 4 || 19 | 2.022 | 3L | 3L | 1S | 3L | 1S | 3L | 4 || 20 | 2.008 | 1S | 3L | 3L | 3L | 1S | 3L | 2 || 21 | 1.955 | 3L | 3L | 3L | 3L | 1S | 2M | 2 || 22 | 1.079 | 1S | 2M | 3L | 2M | 3L | 3L | 3 || 23 | 1.077 | 1S | 2M | 3L | 3L | 3L | 2M | 3 || 24 | 1.075 | 3L | 2M | 1S | 2M | 3L | 3L | 5 || 25 | 1.064 | 1S | 2M | 1S | 3L | 3L | 3L | 5 || 26 | 1.052 | 1S | 2M | 3L | 3L | 1S | 3L | 3 || 27 | 1.048 | 3L | 2M | 3L | 2M | 1S | 3L | 3 || 28 | 1.032 | 1S | 3L | 1S | 2M | 3L | 3L | 3 || 29 | 1.024 | 1S | 3L | 1S | 3L | 1S | 3L | 3 |
And here are the sequences that we don’t want the model to create.
| | counts | 0 | 1 | 2 | 3 | 4 | 5 | matched ||----:|---------:|:----|:----|:----|:----|:----|:----|----------:|| 266 | 0.001 | 1S | 1S | 3L | 3L | 2M | 2M | 1 || 267 | 0.001 | 1S | 2M | 2M | 3L | 2M | 2M | 2 || 268 | 0.001 | 3L | 1S | 1S | 3L | 1S | 1S | 3 || 269 | 0.001 | 3L | 3L | 3L | 1S | 2M | 2M | 1 || 270 | 0.001 | 3L | 1S | 3L | 1S | 1S | 3L | 2 || 271 | 0.001 | 1S | 3L | 2M | 1S | 1S | 3L | 1 || 272 | 0.001 | 3L | 2M | 2M | 3L | 3L | 1S | 4 || 273 | 0.001 | 1S | 3L | 3L | 1S | 1S | 1S | 0 || 274 | 0.001 | 3L | 1S | 2M | 2M | 1S | 2M | 1 || 275 | 0.001 | 3L | 3L | 2M | 1S | 3L | 2M | 2 |
As we can see, there is a tendency for our model to generate sequences that resemble the one we require, although the exact one (the one that matches 6/6) places itself already at the 10th position! On the other hand, according to the table, the top 10 sequences are still the ones that are somewhat similar to the one we request.
To ultimately verify the quality of our model, let’s plot the outcomes together with the frequency of occurrence and compare it against a freshly initialized model, which is supposed to give us completely random sequences — just to compare.
hml_rand = HiddenMarkovLayer.initialize(states, observables)hmm_rand = HiddenMarkovModel(hml_rand)RUNS = 100000T = 5chains_rand = RUNS * [0]for i in range(len(chains_rand)): chain_rand = hmm_rand.layer.run(T)[0] chains_rand[i] = '-'.join(chain_rand)df2 = pd.DataFrame(pd.Series(chains_rand).value_counts(), columns=['counts']).reset_index().rename(columns={'index': 'chain'})df2 = pd.merge(df2, df2['chain'].str.split('-', expand=True), left_index=True, right_index=True)s = []for i in range(T + 1): s.append(df2.apply(lambda x: x[i] == observations[i], axis=1))df2['matched'] = pd.concat(s, axis=1).sum(axis=1)df2['counts'] = df2['counts'] / RUNS * 100df2 = df2.drop(columns=['chain'])fig, ax = plt.subplots(1, 1, figsize=(14, 6))ax.plot(df['matched'], 'g:')ax.plot(df2['matched'], 'k:')ax.set_xlabel('Ordered index')ax.set_ylabel('Matching observations')ax.set_title('Verification on a 6-observation chain.')ax2 = ax.twinx()ax2.plot(df['counts'], 'r', lw=3)ax2.plot(df2['counts'], 'k', lw=3)ax2.set_ylabel('Frequency of occurrence [%]')ax.legend(['trained', 'initialized'])ax2.legend(['trained', 'initialized'])plt.grid()plt.show()
It seems we have successfully implemented the training procedure. If we look at the curves, the initialized-only model generates observation sequences with almost equal probability. It’s completely random. However, the trained model gives sequences that are highly similar to the one we desire with much higher frequency. Despite the genuine sequence gets created in only 2% of total runs, the other similar sequences get generated approximately as often.
In this article, we have presented a step-by-step implementation of the Hidden Markov Model. We have created the code by adapting the first principles approach. More specifically, we have shown how the probabilistic concepts that are expressed through equations can be implemented as objects and methods. Finally, we demonstrated the usage of the model with finding the score, uncovering of the latent variable chain and applied the training procedure.
PS. I apologise for the poor rendering of the equations here. Basically, I needed to do it all manually. However, please feel free to read this article on my home blog. There, I took care of it ;)
I am planning to bring the articles to next level and offer short screencast video μ-tutorials.
If you want to be updated concerning the videos and future articles, subscribe to my newsletter. You can also let me know of your expectations by filling out the form. See you soon! | [
{
"code": null,
"e": 309,
"s": 172,
"text": "I want to expand this work into a series of μ-tutorial videos. If you’re interested, please subscribe to my newsletter to stay in touch."
},
{
"code": null,
"e": 732,
"s": 309,
"text": "The Internet is full of good articles that explain the theory behind the Hidden Markov Model (HMM) well (e.g. 1, 2, 3 and 4). However, many of these works contain a fair amount of rather advanced mathematical equations. While equations are necessary if one wants to explain the theory, we decided to take it to the next level and create a gentle step by step practical implementation to complement the good work of others."
},
{
"code": null,
"e": 1067,
"s": 732,
"text": "In this short series of two articles, we will focus on translating all of the complicated mathematics into code. Our starting point is the document written by Mark Stamp. We will use this paper to define our code (this article) and then use a somewhat peculiar example of “Morning Insanity” to demonstrate its performance in practice."
},
{
"code": null,
"e": 1212,
"s": 1067,
"text": "Before we begin, let’s revisit the notation we will be using. By the way, don’t worry if some of that is unclear to you. We will hold your hand."
},
{
"code": null,
"e": 1252,
"s": 1212,
"text": "T - length of the observation sequence."
},
{
"code": null,
"e": 1290,
"s": 1252,
"text": "N - number of latent (hidden) states."
},
{
"code": null,
"e": 1317,
"s": 1290,
"text": "M - number of observables."
},
{
"code": null,
"e": 1352,
"s": 1317,
"text": "Q = {q0, q1, ...} - hidden states."
},
{
"code": null,
"e": 1407,
"s": 1352,
"text": "V = {0, 1, ..., M — 1} - set of possible observations."
},
{
"code": null,
"e": 1436,
"s": 1407,
"text": "A - state transition matrix."
},
{
"code": null,
"e": 1469,
"s": 1436,
"text": "B - emission probability matrix."
},
{
"code": null,
"e": 1512,
"s": 1469,
"text": "π- initial state probability distribution."
},
{
"code": null,
"e": 1538,
"s": 1512,
"text": "O - observation sequence."
},
{
"code": null,
"e": 1590,
"s": 1538,
"text": "X = (x0, x1, ...), x_t ∈ Q - hidden state sequence."
},
{
"code": null,
"e": 1697,
"s": 1590,
"text": "Having that set defined, we can calculate the probability of any state and observation using the matrices:"
},
{
"code": null,
"e": 1738,
"s": 1697,
"text": "A = {a_ij} — begin an transition matrix."
},
{
"code": null,
"e": 1779,
"s": 1738,
"text": "B = {b_j(k)} — being an emission matrix."
},
{
"code": null,
"e": 1856,
"s": 1779,
"text": "The probabilities associated with transition and observation (emission) are:"
},
{
"code": null,
"e": 1904,
"s": 1856,
"text": "The model is therefore defined as a collection:"
},
{
"code": null,
"e": 2302,
"s": 1904,
"text": "Since HMM is based on probability vectors and matrices, let’s first define objects that will represent the fundamental concepts. To be useful, the objects must reflect on certain properties. For example, all elements of a probability vector must be numbers 0 ≤ x ≤ 1 and they must sum up to 1. Therefore, let’s design the objects the way they will inherently safeguard the mathematical properties."
},
{
"code": null,
"e": 5006,
"s": 2302,
"text": "import numpy as npimport pandas as pdclass ProbabilityVector: def __init__(self, probabilities: dict): states = probabilities.keys() probs = probabilities.values() assert len(states) == len(probs), \"The probabilities must match the states.\" assert len(states) == len(set(states)), \"The states must be unique.\" assert abs(sum(probs) - 1.0) < 1e-12, \"Probabilities must sum up to 1.\" assert len(list(filter(lambda x: 0 <= x <= 1, probs))) == len(probs), \\ \"Probabilities must be numbers from [0, 1] interval.\" self.states = sorted(probabilities) self.values = np.array(list(map(lambda x: probabilities[x], self.states))).reshape(1, -1) @classmethod def initialize(cls, states: list): size = len(states) rand = np.random.rand(size) / (size**2) + 1 / size rand /= rand.sum(axis=0) return cls(dict(zip(states, rand))) @classmethod def from_numpy(cls, array: np.ndarray, state: list): return cls(dict(zip(states, list(array)))) @property def dict(self): return {k:v for k, v in zip(self.states, list(self.values.flatten()))} @property def df(self): return pd.DataFrame(self.values, columns=self.states, index=['probability']) def __repr__(self): return \"P({}) = {}.\".format(self.states, self.values) def __eq__(self, other): if not isinstance(other, ProbabilityVector): raise NotImplementedError if (self.states == other.states) and (self.values == other.values).all(): return True return False def __getitem__(self, state: str) -> float: if state not in self.states: raise ValueError(\"Requesting unknown probability state from vector.\") index = self.states.index(state) return float(self.values[0, index]) def __mul__(self, other) -> np.ndarray: if isinstance(other, ProbabilityVector): return self.values * other.values elif isinstance(other, (int, float)): return self.values * other else: NotImplementedError def __rmul__(self, other) -> np.ndarray: return self.__mul__(other) def __matmul__(self, other) -> np.ndarray: if isinstance(other, ProbabilityMatrix): return self.values @ other.values def __truediv__(self, number) -> np.ndarray: if not isinstance(number, (int, float)): raise NotImplementedError x = self.values return x / number if number != 0 else x / (number + 1e-12) def argmax(self): index = self.values.argmax() return self.states[index]"
},
{
"code": null,
"e": 5374,
"s": 5006,
"text": "The most natural way to initialize this object is to use a dictionary as it associates values with unique keys. Dictionaries, unfortunately, do not provide any assertion mechanisms that put any constraints on the values. Consequently, we build our custom ProbabilityVector object to ensure that our values behave correctly. Most importantly, we enforce the following:"
},
{
"code": null,
"e": 5561,
"s": 5374,
"text": "The number of values must equal the number of the keys (names of our states). Although this is not a problem when initializing the object from a dictionary, we will use other ways later."
},
{
"code": null,
"e": 5628,
"s": 5561,
"text": "All names of the states must be unique (the same arguments apply)."
},
{
"code": null,
"e": 5692,
"s": 5628,
"text": "The probabilities must sum up to 1 (up to a certain tolerance)."
},
{
"code": null,
"e": 5729,
"s": 5692,
"text": "All probabilities must be 0 ≤ p ≤ 1."
},
{
"code": null,
"e": 5859,
"s": 5729,
"text": "Having ensured that, we also provide two alternative ways to instantiate ProbabilityVector objects (decorated with @classmethod)."
},
{
"code": null,
"e": 6029,
"s": 5859,
"text": "We instantiate the objects randomly — it will be useful when training.We use ready-made numpy arrays and use values therein, and only providing the names for the states."
},
{
"code": null,
"e": 6100,
"s": 6029,
"text": "We instantiate the objects randomly — it will be useful when training."
},
{
"code": null,
"e": 6200,
"s": 6100,
"text": "We use ready-made numpy arrays and use values therein, and only providing the names for the states."
},
{
"code": null,
"e": 6388,
"s": 6200,
"text": "For convenience and debugging, we provide two additional methods for requesting the values. Decorated with, they return the content of the PV object as a dictionary or a pandas dataframe."
},
{
"code": null,
"e": 6499,
"s": 6388,
"text": "The PV objects need to satisfy the following mathematical operations (for the purpose of constructing of HMM):"
},
{
"code": null,
"e": 6861,
"s": 6499,
"text": "comparison (__eq__) - to know if any two PV's are equal,element-wise multiplication of two PV’s or multiplication with a scalar (__mul__ and __rmul__).dot product (__matmul__) - to perform vector-matrix multiplicationdivision by number (__truediv__),argmax to find for which state the probability is the highest.__getitem__ to enable selecting value by the key."
},
{
"code": null,
"e": 6918,
"s": 6861,
"text": "comparison (__eq__) - to know if any two PV's are equal,"
},
{
"code": null,
"e": 7014,
"s": 6918,
"text": "element-wise multiplication of two PV’s or multiplication with a scalar (__mul__ and __rmul__)."
},
{
"code": null,
"e": 7081,
"s": 7014,
"text": "dot product (__matmul__) - to perform vector-matrix multiplication"
},
{
"code": null,
"e": 7115,
"s": 7081,
"text": "division by number (__truediv__),"
},
{
"code": null,
"e": 7178,
"s": 7115,
"text": "argmax to find for which state the probability is the highest."
},
{
"code": null,
"e": 7228,
"s": 7178,
"text": "__getitem__ to enable selecting value by the key."
},
{
"code": null,
"e": 7446,
"s": 7228,
"text": "Note that when e.g. multiplying a PV with a scalar, the returned structure is a resulting numpy array, not another PV. This is because multiplying by anything other than 1 would violate the integrity of the PV itself."
},
{
"code": null,
"e": 7514,
"s": 7446,
"text": "Internally, the values are stored as a numpy array of size (1 × N)."
},
{
"code": null,
"e": 7982,
"s": 7514,
"text": "a1 = ProbabilityVector({'rain': 0.7, 'sun': 0.3})a2 = ProbabilityVector({'sun': 0.1, 'rain': 0.9})print(a1.df)print(a2.df)print(\"Comparison:\", a1 == a2)print(\"Element-wise multiplication:\", a1 * a2)print(\"Argmax:\", a1.argmax())print(\"Getitem:\", a1['rain'])# OUTPUT>>> rain sun probability 0.7 0.3 rain sun probability 0.9 0.1>>> Comparison: False>>> Element-wise multiplication: [[0.63 0.03]]>>> Argmax: rain>>> Getitem: 0.7"
},
{
"code": null,
"e": 8300,
"s": 7982,
"text": "Another object is a Probability Matrix, which is a core part of the HMM definition. Formally, the A and B matrices must be row-stochastic, meaning that the values of every row must sum up to 1. We can, therefore, define our PM by stacking several PV's, which we have constructed in a way to guarantee this constraint."
},
{
"code": null,
"e": 10324,
"s": 8300,
"text": "class ProbabilityMatrix: def __init__(self, prob_vec_dict: dict): assert len(prob_vec_dict) > 1, \\ \"The numebr of input probability vector must be greater than one.\" assert len(set([str(x.states) for x in prob_vec_dict.values()])) == 1, \\ \"All internal states of all the vectors must be indentical.\" assert len(prob_vec_dict.keys()) == len(set(prob_vec_dict.keys())), \\ \"All observables must be unique.\" self.states = sorted(prob_vec_dict) self.observables = prob_vec_dict[self.states[0]].states self.values = np.stack([prob_vec_dict[x].values \\ for x in self.states]).squeeze() @classmethod def initialize(cls, states: list, observables: list): size = len(states) rand = np.random.rand(size, len(observables)) \\ / (size**2) + 1 / size rand /= rand.sum(axis=1).reshape(-1, 1) aggr = [dict(zip(observables, rand[i, :])) for i in range(len(states))] pvec = [ProbabilityVector(x) for x in aggr] return cls(dict(zip(states, pvec))) @classmethod def from_numpy(cls, array: np.ndarray, states: list, observables: list): p_vecs = [ProbabilityVector(dict(zip(observables, x))) \\ for x in array] return cls(dict(zip(states, p_vecs))) @property def dict(self): return self.df.to_dict() @property def df(self): return pd.DataFrame(self.values, columns=self.observables, index=self.states) def __repr__(self): return \"PM {} states: {} -> obs: {}.\".format( self.values.shape, self.states, self.observables) def __getitem__(self, observable: str) -> np.ndarray: if observable not in self.observables: raise ValueError(\"Requesting unknown probability observable from the matrix.\") index = self.observables.index(observable) return self.values[:, index].reshape(-1, 1)"
},
{
"code": null,
"e": 10546,
"s": 10324,
"text": "Here, the way we instantiate PM’s is by supplying a dictionary of PV’s to the constructor of the class. By doing this, we not only ensure that every row of PM is stochastic, but also supply the names for every observable."
},
{
"code": null,
"e": 10655,
"s": 10546,
"text": "Our PM can, therefore, give an array of coefficients for any observable. Mathematically, the PM is a matrix:"
},
{
"code": null,
"e": 10711,
"s": 10655,
"text": "The other methods are implemented in similar way to PV."
},
{
"code": null,
"e": 11710,
"s": 10711,
"text": "a1 = ProbabilityVector({'rain': 0.7, 'sun': 0.3})a2 = ProbabilityVector({'rain': 0.6, 'sun': 0.4})A = ProbabilityMatrix({'hot': a1, 'cold': a2})print(A)print(A.df)>>> PM (2, 2) states: ['cold', 'hot'] -> obs: ['rain', 'sun'].>>> rain sun cold 0.6 0.4 hot 0.7 0.3b1 = ProbabilityVector({'0S': 0.1, '1M': 0.4, '2L': 0.5})b2 = ProbabilityVector({'0S': 0.7, '1M': 0.2, '2L': 0.1})B = ProbabilityMatrix({'0H': b1, '1C': b2})print(B)print(B.df)>>> PM (2, 3) states: ['0H', '1C'] -> obs: ['0S', '1M', '2L'].>>> 0S 1M 2L 0H 0.1 0.4 0.5 1C 0.7 0.2 0.1P = ProbabilityMatrix.initialize(list('abcd'), list('xyz'))print('Dot product:', a1 @ A)print('Initialization:', P)print(P.df)>>> Dot product: [[0.63 0.37]]>>> Initialization: PM (4, 3) states: ['a', 'b', 'c', 'd'] -> obs: ['x', 'y', 'z'].>>> x y z a 0.323803 0.327106 0.349091 b 0.318166 0.326356 0.355478 c 0.311833 0.347983 0.340185 d 0.337223 0.316850 0.345927"
},
{
"code": null,
"e": 11830,
"s": 11710,
"text": "Before we proceed with calculating the score, let’s use our PV and PM definitions to implement the Hidden Markov Chain."
},
{
"code": null,
"e": 12000,
"s": 11830,
"text": "Again, we will do so as a class, calling it HiddenMarkovChain. It will collate at A, B and π. Later on, we will implement more methods that are applicable to this class."
},
{
"code": null,
"e": 12190,
"s": 12000,
"text": "Computing the score means to find what is the probability of a particular chain of observations O given our (known) model λ = (A, B, π). In other words, we are interested in finding p(O|λ)."
},
{
"code": null,
"e": 12298,
"s": 12190,
"text": "We can find p(O|λ) by marginalizing all possible chains of the hidden variables X, where X = {x0, x1, ...}:"
},
{
"code": null,
"e": 12531,
"s": 12298,
"text": "Since p(O|X, λ) = ∏ b(O) (the product of all probabilities related to the observables) and p(X|λ)=π ∏ a (the product of all probabilities of transitioning from x at t to x at t + 1, the probability we are looking for (the score) is:"
},
{
"code": null,
"e": 12691,
"s": 12531,
"text": "This is a naive way of computing of the score, since we need to calculate the probability for every possible chain X. Either way, let’s implement it in python:"
},
{
"code": null,
"e": 14214,
"s": 12691,
"text": "from itertools import productfrom functools import reduceclass HiddenMarkovChain: def __init__(self, T, E, pi): self.T = T # transmission matrix A self.E = E # emission matrix B self.pi = pi self.states = pi.states self.observables = E.observables def __repr__(self): return \"HML states: {} -> observables: {}.\".format( len(self.states), len(self.observables)) @classmethod def initialize(cls, states: list, observables: list): T = ProbabilityMatrix.initialize(states, states) E = ProbabilityMatrix.initialize(states, observables) pi = ProbabilityVector.initialize(states) return cls(T, E, pi) def _create_all_chains(self, chain_length): return list(product(*(self.states,) * chain_length)) def score(self, observations: list) -> float: def mul(x, y): return x * y score = 0 all_chains = self._create_all_chains(len(observations)) for idx, chain in enumerate(all_chains): expanded_chain = list(zip(chain, [self.T.states[0]] + list(chain))) expanded_obser = list(zip(observations, chain)) p_observations = list(map(lambda x: self.E.df.loc[x[1], x[0]], expanded_obser)) p_hidden_state = list(map(lambda x: self.T.df.loc[x[1], x[0]], expanded_chain)) p_hidden_state[0] = self.pi[chain[0]] score += reduce(mul, p_observations) * reduce(mul, p_hidden_state) return score"
},
{
"code": null,
"e": 14764,
"s": 14214,
"text": "a1 = ProbabilityVector({'1H': 0.7, '2C': 0.3})a2 = ProbabilityVector({'1H': 0.4, '2C': 0.6})b1 = ProbabilityVector({'1S': 0.1, '2M': 0.4, '3L': 0.5})b2 = ProbabilityVector({'1S': 0.7, '2M': 0.2, '3L': 0.1})A = ProbabilityMatrix({'1H': a1, '2C': a2})B = ProbabilityMatrix({'1H': b1, '2C': b2})pi = ProbabilityVector({'1H': 0.6, '2C': 0.4})hmc = HiddenMarkovChain(A, B, pi)observations = ['1S', '2M', '3L', '2M', '1S']print(\"Score for {} is {:f}.\".format(observations, hmc.score(observations)))>>> Score for ['1S', '2M', '3L', '2M', '1S'] is 0.003482."
},
{
"code": null,
"e": 14905,
"s": 14764,
"text": "If our implementation is correct, then all score values for all possible observation chains, for a given model should add up to one. Namely:"
},
{
"code": null,
"e": 15257,
"s": 14905,
"text": "all_possible_observations = {'1S', '2M', '3L'}chain_length = 3 # any int > 0all_observation_chains = list(product(*(all_possible_observations,) * chain_length))all_possible_scores = list(map(lambda obs: hmc.score(obs), all_observation_chains))print(\"All possible scores added: {}.\".format(sum(all_possible_scores)))>>> All possible scores added: 1.0."
},
{
"code": null,
"e": 15265,
"s": 15257,
"text": "Indeed."
},
{
"code": null,
"e": 15543,
"s": 15265,
"text": "Computing the score the way we did above is kind of naive. In order to find the number for a particular observation chain O, we have to compute the score for all possible latent variable sequences X. That requires 2TN^T multiplications, which even for small numbers takes time."
},
{
"code": null,
"e": 15629,
"s": 15543,
"text": "Another way to do it is to calculate partial observations of a sequence up to time t."
},
{
"code": null,
"e": 15685,
"s": 15629,
"text": "For and i ∈ {0, 1, ..., N-1} and t ∈ {0, 1, ..., T-1} :"
},
{
"code": null,
"e": 15699,
"s": 15685,
"text": "Consequently,"
},
{
"code": null,
"e": 15703,
"s": 15699,
"text": "and"
},
{
"code": null,
"e": 15708,
"s": 15703,
"text": "Then"
},
{
"code": null,
"e": 15828,
"s": 15708,
"text": "Note that α_t is a vector of length N. The sum of the product α a can, in fact, be written as a dot product. Therefore:"
},
{
"code": null,
"e": 15889,
"s": 15828,
"text": "where by the star, we denote an element-wise multiplication."
},
{
"code": null,
"e": 16002,
"s": 15889,
"text": "With this implementation, we reduce the number of multiplication to N2T and can take advantage of vectorization."
},
{
"code": null,
"e": 16563,
"s": 16002,
"text": "class HiddenMarkovChain_FP(HiddenMarkovChain): def _alphas(self, observations: list) -> np.ndarray: alphas = np.zeros((len(observations), len(self.states))) alphas[0, :] = self.pi.values * self.E[observations[0]].T for t in range(1, len(observations)): alphas[t, :] = (alphas[t - 1, :].reshape(1, -1) @ self.T.values) * self.E[observations[t]].T return alphas def score(self, observations: list) -> float: alphas = self._alphas(observations) return float(alphas[-1].sum())"
},
{
"code": null,
"e": 16762,
"s": 16563,
"text": "hmc_fp = HiddenMarkovChain_FP(A, B, pi)observations = ['1S', '2M', '3L', '2M', '1S']print(\"Score for {} is {:f}.\".format(observations, hmc_fp.score(observations)))>>> All possible scores added: 1.0."
},
{
"code": null,
"e": 16770,
"s": 16762,
"text": "...yup."
},
{
"code": null,
"e": 16942,
"s": 16770,
"text": "Let’s test one more thing. Basically, let’s take our λ = (A, B, π) and use it to generate a sequence of random observables, starting from some initial state probability π."
},
{
"code": null,
"e": 17483,
"s": 16942,
"text": "If the desired length T is “large enough”, we would expect that the system to converge on a sequence that, on average, gives the same number of events as we would expect from A and B matrices directly. In other words, the transition and the emission matrices “decide”, with a certain probability, what the next state will be and what observation we will get, for every step, respectively. Therefore, what may initially look like random events, on average should reflect the coefficients of the matrices themselves. Let’s check that as well."
},
{
"code": null,
"e": 18261,
"s": 17483,
"text": "class HiddenMarkovChain_Simulation(HiddenMarkovChain): def run(self, length: int) -> (list, list): assert length >= 0, \"The chain needs to be a non-negative number.\" s_history = [0] * (length + 1) o_history = [0] * (length + 1) prb = self.pi.values obs = prb @ self.E.values s_history[0] = np.random.choice(self.states, p=prb.flatten()) o_history[0] = np.random.choice(self.observables, p=obs.flatten()) for t in range(1, length + 1): prb = prb @ self.T.values obs = prb @ self.E.values s_history[t] = np.random.choice(self.states, p=prb.flatten()) o_history[t] = np.random.choice(self.observables, p=obs.flatten()) return o_history, s_history"
},
{
"code": null,
"e": 18493,
"s": 18261,
"text": "hmc_s = HiddenMarkovChain_Simulation(A, B, pi)observation_hist, states_hist = hmc_s.run(100) # length = 100stats = pd.DataFrame({ 'observations': observation_hist, 'states': states_hist}).applymap(lambda x: int(x[0])).plot()"
},
{
"code": null,
"e": 18552,
"s": 18493,
"text": "The state matrix A is given by the following coefficients:"
},
{
"code": null,
"e": 18666,
"s": 18552,
"text": "Consequently, the probability of “being” in the state “1H” at t+1, regardless of the previous state, is equal to:"
},
{
"code": null,
"e": 18846,
"s": 18666,
"text": "If we assume that the prior probabilities of being at some state at are totally random, then p(1H) = 1 and p(2C) = 0.9, which after renormalizing give 0.55 and 0.45, respectively."
},
{
"code": null,
"e": 19039,
"s": 18846,
"text": "If we count the number of occurrences of each state and divide it by the number of elements in our sequence, we would get closer and closer to these number as the length of the sequence grows."
},
{
"code": null,
"e": 19613,
"s": 19039,
"text": "hmc_s = HiddenMarkovChain_Simulation(A, B, pi)stats = {}for length in np.logspace(1, 5, 40).astype(int): observation_hist, states_hist = hmc_s.run(length) stats[length] = pd.DataFrame({ 'observations': observation_hist, 'states': states_hist}).applymap(lambda x: int(x[0]))S = np.array(list(map(lambda x: x['states'].value_counts().to_numpy() / len(x), stats.values())))plt.semilogx(np.logspace(1, 5, 40).astype(int), S)plt.xlabel('Chain length T')plt.ylabel('Probability')plt.title('Converging probabilities.')plt.legend(['1H', '2C'])plt.show()"
},
{
"code": null,
"e": 19824,
"s": 19613,
"text": "Let’s take our HiddenMarkovChain class to the next level and supplement it with more methods. The methods will help us to discover the most probable sequence of hidden variables behind the observation sequence."
},
{
"code": null,
"e": 19916,
"s": 19824,
"text": "We have defined α to be the probability of partial observation of the sequence up to time ."
},
{
"code": null,
"e": 20033,
"s": 19916,
"text": "Now, let’s define the “opposite” probability. Namely, the probability of observing the sequence from T - 1down to t."
},
{
"code": null,
"e": 20088,
"s": 20033,
"text": "For t= 0, 1, ..., T-1 and i=0, 1, ..., N-1, we define:"
},
{
"code": null,
"e": 20137,
"s": 20088,
"text": "c`1As before, we can β(i) calculate recursively:"
},
{
"code": null,
"e": 20156,
"s": 20137,
"text": "Then for t ≠ T-1:"
},
{
"code": null,
"e": 20191,
"s": 20156,
"text": "which in vectorized form, will be:"
},
{
"code": null,
"e": 20347,
"s": 20191,
"text": "Finally, we also define a new quantity γ to indicate the state q_i at time t, for which the probability (calculated forwards and backwards) is the maximum:"
},
{
"code": null,
"e": 20450,
"s": 20347,
"text": "Consequently, for any step t = 0, 1, ..., T-1, the state of the maximum likelihood can be found using:"
},
{
"code": null,
"e": 21506,
"s": 20450,
"text": "class HiddenMarkovChain_Uncover(HiddenMarkovChain_Simulation): def _alphas(self, observations: list) -> np.ndarray: alphas = np.zeros((len(observations), len(self.states))) alphas[0, :] = self.pi.values * self.E[observations[0]].T for t in range(1, len(observations)): alphas[t, :] = (alphas[t - 1, :].reshape(1, -1) @ self.T.values) \\ * self.E[observations[t]].T return alphas def _betas(self, observations: list) -> np.ndarray: betas = np.zeros((len(observations), len(self.states))) betas[-1, :] = 1 for t in range(len(observations) - 2, -1, -1): betas[t, :] = (self.T.values @ (self.E[observations[t + 1]] \\ * betas[t + 1, :].reshape(-1, 1))).reshape(1, -1) return betas def uncover(self, observations: list) -> list: alphas = self._alphas(observations) betas = self._betas(observations) maxargs = (alphas * betas).argmax(axis=1) return list(map(lambda x: self.states[x], maxargs))"
},
{
"code": null,
"e": 21695,
"s": 21506,
"text": "To validate, let’s generate some observable sequence O. For that, we can use our model’s .run method. Then, we will use the.uncover method to find the most likely latent variable sequence."
},
{
"code": null,
"e": 22484,
"s": 21695,
"text": "np.random.seed(42)a1 = ProbabilityVector({'1H': 0.7, '2C': 0.3})a2 = ProbabilityVector({'1H': 0.4, '2C': 0.6})b1 = ProbabilityVector({'1S': 0.1, '2M': 0.4, '3L': 0.5}) b2 = ProbabilityVector({'1S': 0.7, '2M': 0.2, '3L': 0.1})A = ProbabilityMatrix({'1H': a1, '2C': a2})B = ProbabilityMatrix({'1H': b1, '2C': b2})pi = ProbabilityVector({'1H': 0.6, '2C': 0.4})hmc = HiddenMarkovChain_Uncover(A, B, pi)observed_sequence, latent_sequence = hmc.run(5)uncovered_sequence = hmc.uncover(observed_sequence)| | 0 | 1 | 2 | 3 | 4 | 5 ||:------------------:|:----|:----|:----|:----|:----|:----|| observed sequence | 3L | 3M | 1S | 3L | 3L | 3L || latent sequence | 1H | 2C | 1H | 1H | 2C | 1H || uncovered sequence | 1H | 1H | 2C | 1H | 1H | 1H |"
},
{
"code": null,
"e": 22773,
"s": 22484,
"text": "As we can see, the most likely latent state chain (according to the algorithm) is not the same as the one that actually caused the observations. This is to be expected. After all, each observation sequence can only be manifested with certain probability, dependent on the latent sequence."
},
{
"code": null,
"e": 22883,
"s": 22773,
"text": "The code below, evaluates the likelihood of different latent sequences resulting in our observation sequence."
},
{
"code": null,
"e": 24027,
"s": 22883,
"text": "all_possible_states = {'1H', '2C'}chain_length = 6 # any int > 0all_states_chains = list(product(*(all_possible_states,) * chain_length))df = pd.DataFrame(all_states_chains)dfp = pd.DataFrame()for i in range(chain_length): dfp['p' + str(i)] = df.apply(lambda x: hmc.E.df.loc[x[i], observed_sequence[i]], axis=1)scores = dfp.sum(axis=1).sort_values(ascending=False)df = df.iloc[scores.index]df['score'] = scoresdf.head(10).reset_index()| index | 0 | 1 | 2 | 3 | 4 | 5 | score ||:--------:|:----|:----|:----|:----|:----|:----|--------:|| 8 | 1H | 1H | 2C | 1H | 1H | 1H | 3.1 || 24 | 1H | 2C | 2C | 1H | 1H | 1H | 2.9 || 40 | 2C | 1H | 2C | 1H | 1H | 1H | 2.7 || 12 | 1H | 1H | 2C | 2C | 1H | 1H | 2.7 || 10 | 1H | 1H | 2C | 1H | 2C | 1H | 2.7 || 9 | 1H | 1H | 2C | 1H | 1H | 2C | 2.7 || 25 | 1H | 2C | 2C | 1H | 1H | 2C | 2.5 || 0 | 1H | 1H | 1H | 1H | 1H | 1H | 2.5 || 26 | 1H | 2C | 2C | 1H | 2C | 1H | 2.5 || 28 | 1H | 2C | 2C | 2C | 1H | 1H | 2.5 |"
},
{
"code": null,
"e": 24255,
"s": 24027,
"text": "The result above shows the sorted table of the latent sequences, given the observation sequence. The actual latent sequence (the one that caused the observations) places itself on the 35th position (we counted index from zero)."
},
{
"code": null,
"e": 24535,
"s": 24255,
"text": "dfc = df.copy().reset_index()for i in range(chain_length): dfc = dfc[dfc[i] == latent_sequence[i]] dfc| index | 0 | 1 | 2 | 3 | 4 | 5 | score ||:-------:|:----|:----|:----|:----|:----|:----|--------:|| 18 | 1H | 2C | 1H | 1H | 2C | 1H | 1.9 |"
},
{
"code": null,
"e": 24725,
"s": 24535,
"text": "The time has come to show the training procedure. Formally, we are interested in finding λ = (A, B, π) such that given a desired observation sequence O, our model λ would give the best fit."
},
{
"code": null,
"e": 24855,
"s": 24725,
"text": "Here, our starting point will be the HiddenMarkovModel_Uncover that we have defined earlier. We will add new methods to train it."
},
{
"code": null,
"e": 25035,
"s": 24855,
"text": "Knowing our latent states Q and possible observation states O, we automatically know the sizes of the matrices A and B, hence N and M. However, we need to determine a and b and π."
},
{
"code": null,
"e": 25108,
"s": 25035,
"text": "For t = 0, 1, ..., T-2 and i, j =0, 1, ..., N -1, we define “di-gammas”:"
},
{
"code": null,
"e": 25216,
"s": 25108,
"text": "γ(i, j) is the probability of transitioning for q at t to t + 1. Writing it in terms of α, β, A, B we have:"
},
{
"code": null,
"e": 25391,
"s": 25216,
"text": "Now, thinking in terms of implementation, we want to avoid looping over i, j and t at the same time, as it’s gonna be deadly slow. Fortunately, we can vectorize the equation:"
},
{
"code": null,
"e": 25441,
"s": 25391,
"text": "Having the equation for γ(i, j), we can calculate"
},
{
"code": null,
"e": 25470,
"s": 25441,
"text": "To find λ = (A, B, π), we do"
},
{
"code": null,
"e": 25494,
"s": 25470,
"text": "For i = 0, 1, ..., N-1:"
},
{
"code": null,
"e": 25497,
"s": 25494,
"text": "or"
},
{
"code": null,
"e": 25524,
"s": 25497,
"text": "For i, j = 0, 1, ..., N-1:"
},
{
"code": null,
"e": 25571,
"s": 25524,
"text": "For j = 0, 1, ..., N-1 and k = 0, 1, ..., M-1:"
},
{
"code": null,
"e": 26135,
"s": 25571,
"text": "class HiddenMarkovLayer(HiddenMarkovChain_Uncover): def _digammas(self, observations: list) -> np.ndarray: L, N = len(observations), len(self.states) digammas = np.zeros((L - 1, N, N)) alphas = self._alphas(observations) betas = self._betas(observations) score = self.score(observations) for t in range(L - 1): P1 = (alphas[t, :].reshape(-1, 1) * self.T.values) P2 = self.E[observations[t + 1]].T * betas[t + 1].reshape(1, -1) digammas[t, :, :] = P1 * P2 / score return digammas"
},
{
"code": null,
"e": 26398,
"s": 26135,
"text": "Having the “layer” supplemented with the ._difammas method, we should be able to perform all the necessary calculations. However, it makes sense to delegate the \"management\" of the layer to another class. In fact, the model training can be summarized as follows:"
},
{
"code": null,
"e": 26536,
"s": 26398,
"text": "Initialize A, B and π.Calculate γ(i, j).Update the model’s A, B and π.We repeat the 2. and 3. until the score p(O|λ) no longer increases."
},
{
"code": null,
"e": 26559,
"s": 26536,
"text": "Initialize A, B and π."
},
{
"code": null,
"e": 26578,
"s": 26559,
"text": "Calculate γ(i, j)."
},
{
"code": null,
"e": 26609,
"s": 26578,
"text": "Update the model’s A, B and π."
},
{
"code": null,
"e": 26677,
"s": 26609,
"text": "We repeat the 2. and 3. until the score p(O|λ) no longer increases."
},
{
"code": null,
"e": 28602,
"s": 26677,
"text": "class HiddenMarkovModel: def __init__(self, hml: HiddenMarkovLayer): self.layer = hml self._score_init = 0 self.score_history = [] @classmethod def initialize(cls, states: list, observables: list): layer = HiddenMarkovLayer.initialize(states, observables) return cls(layer) def update(self, observations: list) -> float: alpha = self.layer._alphas(observations) beta = self.layer._betas(observations) digamma = self.layer._digammas(observations) score = alpha[-1].sum() gamma = alpha * beta / score L = len(alpha) obs_idx = [self.layer.observables.index(x) \\ for x in observations] capture = np.zeros((L, len(self.layer.states), len(self.layer.observables))) for t in range(L): capture[t, :, obs_idx[t]] = 1.0 pi = gamma[0] T = digamma.sum(axis=0) / gamma[:-1].sum(axis=0).reshape(-1, 1) E = (capture * gamma[:, :, np.newaxis]).sum(axis=0) / gamma.sum(axis=0).reshape(-1, 1) self.layer.pi = ProbabilityVector.from_numpy(pi, self.layer.states) self.layer.T = ProbabilityMatrix.from_numpy(T, self.layer.states, self.layer.states) self.layer.E = ProbabilityMatrix.from_numpy(E, self.layer.states, self.layer.observables) return score def train(self, observations: list, epochs: int, tol=None): self._score_init = 0 self.score_history = (epochs + 1) * [0] early_stopping = isinstance(tol, (int, float)) for epoch in range(1, epochs + 1): score = self.update(observations) print(\"Training... epoch = {} out of {}, score = {}.\".format(epoch, epochs, score)) if early_stopping and abs(self._score_init - score) / score < tol: print(\"Early stopping.\") break self._score_init = score self.score_history[epoch] = score"
},
{
"code": null,
"e": 28835,
"s": 28602,
"text": "np.random.seed(42)observations = ['3L', '2M', '1S', '3L', '3L', '3L']states = ['1H', '2C']observables = ['1S', '2M', '3L']hml = HiddenMarkovLayer.initialize(states, observables)hmm = HiddenMarkovModel(hml)hmm.train(observations, 25)"
},
{
"code": null,
"e": 28902,
"s": 28835,
"text": "Let’s look at the generated sequences. The “demanded” sequence is:"
},
{
"code": null,
"e": 29156,
"s": 28902,
"text": "| | 0 | 1 | 2 | 3 | 4 | 5 ||---:|:----|:----|:----|:----|:----|:----|| 0 | 3L | 2M | 1S | 3L | 3L | 3L |RUNS = 100000T = 5chains = RUNS * [0]for i in range(len(chains)): chain = hmm.layer.run(T)[0] chains[i] = '-'.join(chain)"
},
{
"code": null,
"e": 29306,
"s": 29156,
"text": "The table below summarizes simulated runs based on 100000 attempts (see above), with the frequency of occurrence and number of matching observations."
},
{
"code": null,
"e": 29489,
"s": 29306,
"text": "The bottom line is that if we have truly trained the model, we should see a strong tendency for it to generate us sequences that resemble the one we require. Let’s see if it happens."
},
{
"code": null,
"e": 31944,
"s": 29489,
"text": "df = pd.DataFrame(pd.Series(chains).value_counts(), columns=['counts']).reset_index().rename(columns={'index': 'chain'})df = pd.merge(df, df['chain'].str.split('-', expand=True), left_index=True, right_index=True)s = []for i in range(T + 1): s.append(df.apply(lambda x: x[i] == observations[i], axis=1))df['matched'] = pd.concat(s, axis=1).sum(axis=1)df['counts'] = df['counts'] / RUNS * 100df = df.drop(columns=['chain'])df.head(30)---|---:|---------:|:----|:----|:----|:----|:----|:----|----------:|| 0 | 8.907 | 3L | 3L | 3L | 3L | 3L | 3L | 4 || 1 | 4.422 | 3L | 2M | 3L | 3L | 3L | 3L | 5 || 2 | 4.286 | 1S | 3L | 3L | 3L | 3L | 3L | 3 || 3 | 4.284 | 3L | 3L | 3L | 3L | 3L | 2M | 3 || 4 | 4.278 | 3L | 3L | 3L | 2M | 3L | 3L | 3 || 5 | 4.227 | 3L | 3L | 1S | 3L | 3L | 3L | 5 || 6 | 4.179 | 3L | 3L | 3L | 3L | 1S | 3L | 3 || 7 | 2.179 | 3L | 2M | 3L | 2M | 3L | 3L | 4 || 8 | 2.173 | 3L | 2M | 3L | 3L | 1S | 3L | 4 || 9 | 2.165 | 1S | 3L | 1S | 3L | 3L | 3L | 4 || 10 | 2.147 | 3L | 2M | 3L | 3L | 3L | 2M | 4 || 11 | 2.136 | 3L | 3L | 3L | 2M | 3L | 2M | 2 || 12 | 2.121 | 3L | 2M | 1S | 3L | 3L | 3L | 6 || 13 | 2.111 | 1S | 3L | 3L | 2M | 3L | 3L | 2 || 14 | 2.1 | 1S | 2M | 3L | 3L | 3L | 3L | 4 || 15 | 2.075 | 3L | 3L | 3L | 2M | 1S | 3L | 2 || 16 | 2.05 | 1S | 3L | 3L | 3L | 3L | 2M | 2 || 17 | 2.04 | 3L | 3L | 1S | 3L | 3L | 2M | 4 || 18 | 2.038 | 3L | 3L | 1S | 2M | 3L | 3L | 4 || 19 | 2.022 | 3L | 3L | 1S | 3L | 1S | 3L | 4 || 20 | 2.008 | 1S | 3L | 3L | 3L | 1S | 3L | 2 || 21 | 1.955 | 3L | 3L | 3L | 3L | 1S | 2M | 2 || 22 | 1.079 | 1S | 2M | 3L | 2M | 3L | 3L | 3 || 23 | 1.077 | 1S | 2M | 3L | 3L | 3L | 2M | 3 || 24 | 1.075 | 3L | 2M | 1S | 2M | 3L | 3L | 5 || 25 | 1.064 | 1S | 2M | 1S | 3L | 3L | 3L | 5 || 26 | 1.052 | 1S | 2M | 3L | 3L | 1S | 3L | 3 || 27 | 1.048 | 3L | 2M | 3L | 2M | 1S | 3L | 3 || 28 | 1.032 | 1S | 3L | 1S | 2M | 3L | 3L | 3 || 29 | 1.024 | 1S | 3L | 1S | 3L | 1S | 3L | 3 |"
},
{
"code": null,
"e": 32011,
"s": 31944,
"text": "And here are the sequences that we don’t want the model to create."
},
{
"code": null,
"e": 32804,
"s": 32011,
"text": "| | counts | 0 | 1 | 2 | 3 | 4 | 5 | matched ||----:|---------:|:----|:----|:----|:----|:----|:----|----------:|| 266 | 0.001 | 1S | 1S | 3L | 3L | 2M | 2M | 1 || 267 | 0.001 | 1S | 2M | 2M | 3L | 2M | 2M | 2 || 268 | 0.001 | 3L | 1S | 1S | 3L | 1S | 1S | 3 || 269 | 0.001 | 3L | 3L | 3L | 1S | 2M | 2M | 1 || 270 | 0.001 | 3L | 1S | 3L | 1S | 1S | 3L | 2 || 271 | 0.001 | 1S | 3L | 2M | 1S | 1S | 3L | 1 || 272 | 0.001 | 3L | 2M | 2M | 3L | 3L | 1S | 4 || 273 | 0.001 | 1S | 3L | 3L | 1S | 1S | 1S | 0 || 274 | 0.001 | 3L | 1S | 2M | 2M | 1S | 2M | 1 || 275 | 0.001 | 3L | 3L | 2M | 1S | 3L | 2M | 2 |"
},
{
"code": null,
"e": 33135,
"s": 32804,
"text": "As we can see, there is a tendency for our model to generate sequences that resemble the one we require, although the exact one (the one that matches 6/6) places itself already at the 10th position! On the other hand, according to the table, the top 10 sequences are still the ones that are somewhat similar to the one we request."
},
{
"code": null,
"e": 33376,
"s": 33135,
"text": "To ultimately verify the quality of our model, let’s plot the outcomes together with the frequency of occurrence and compare it against a freshly initialized model, which is supposed to give us completely random sequences — just to compare."
},
{
"code": null,
"e": 34519,
"s": 33376,
"text": "hml_rand = HiddenMarkovLayer.initialize(states, observables)hmm_rand = HiddenMarkovModel(hml_rand)RUNS = 100000T = 5chains_rand = RUNS * [0]for i in range(len(chains_rand)): chain_rand = hmm_rand.layer.run(T)[0] chains_rand[i] = '-'.join(chain_rand)df2 = pd.DataFrame(pd.Series(chains_rand).value_counts(), columns=['counts']).reset_index().rename(columns={'index': 'chain'})df2 = pd.merge(df2, df2['chain'].str.split('-', expand=True), left_index=True, right_index=True)s = []for i in range(T + 1): s.append(df2.apply(lambda x: x[i] == observations[i], axis=1))df2['matched'] = pd.concat(s, axis=1).sum(axis=1)df2['counts'] = df2['counts'] / RUNS * 100df2 = df2.drop(columns=['chain'])fig, ax = plt.subplots(1, 1, figsize=(14, 6))ax.plot(df['matched'], 'g:')ax.plot(df2['matched'], 'k:')ax.set_xlabel('Ordered index')ax.set_ylabel('Matching observations')ax.set_title('Verification on a 6-observation chain.')ax2 = ax.twinx()ax2.plot(df['counts'], 'r', lw=3)ax2.plot(df2['counts'], 'k', lw=3)ax2.set_ylabel('Frequency of occurrence [%]')ax.legend(['trained', 'initialized'])ax2.legend(['trained', 'initialized'])plt.grid()plt.show()"
},
{
"code": null,
"e": 34975,
"s": 34519,
"text": "It seems we have successfully implemented the training procedure. If we look at the curves, the initialized-only model generates observation sequences with almost equal probability. It’s completely random. However, the trained model gives sequences that are highly similar to the one we desire with much higher frequency. Despite the genuine sequence gets created in only 2% of total runs, the other similar sequences get generated approximately as often."
},
{
"code": null,
"e": 35428,
"s": 34975,
"text": "In this article, we have presented a step-by-step implementation of the Hidden Markov Model. We have created the code by adapting the first principles approach. More specifically, we have shown how the probabilistic concepts that are expressed through equations can be implemented as objects and methods. Finally, we demonstrated the usage of the model with finding the score, uncovering of the latent variable chain and applied the training procedure."
},
{
"code": null,
"e": 35625,
"s": 35428,
"text": "PS. I apologise for the poor rendering of the equations here. Basically, I needed to do it all manually. However, please feel free to read this article on my home blog. There, I took care of it ;)"
},
{
"code": null,
"e": 35721,
"s": 35625,
"text": "I am planning to bring the articles to next level and offer short screencast video μ-tutorials."
}
]
|
Output of C programs | Set 43 - GeeksforGeeks | 28 Aug, 2017
1. What is the output of following program?
#include <stdio.h>int main(){ int a = 1, b = 2, c = 3; c = a == b; printf("%d", c); return 0;}
Choose the correct answer:(A) 0(B) 1(C) 2(D) 3
Answer : (A)
Explanation :“==” is relational operator which returns only two values, either 0 or 1.0: If a == b is false1: If a == b is trueSincea=1b=2So, a == b is false hence C = 0.
2. What is the output of following program?
#include <stdio.h>int main(){ int a = 20; ; ; printf("%d", a); ; return 0;}
Choose the correct answer:(A) 20(B) Error(C) ;20;(D) ;20
Answer : (A)
Explanation : ; (statement terminator) and no expression/statement is available here, so this is a null statement has no side effect, hence no error is occurred.
3. What is the output of following program?
#include <stdio.h>int main(){ int a = 15; float b = 1.234; printf("%*f", a, b); return 0;}
Choose the correct answer:
(A) 1.234(B) 1.234000(C) Compilation Error(D) Runtime error
Answer : (B)
Explanation : You can define width formatting at run time using %*, This is known as Indirect width precision. printf(“%*f”, a, b); is considered as “%15f”, hence value of b is printed with left padding by 15.
4. What is the output of following program?
#include <stdio.h>void main(){ int a = 1, b = 2, c = 3; char d = 0; if (a, b, c, d) { printf("EXAM"); }}
Choose the correct answer:(A) No Output and No Error(B) EXAM(C) Run time error(D) Compile time error
Answer : (A)
Explanation :Print statement will not execute because ‘ if ‘condition return false. Value of variable d is 0.
5. What is the output of following program?
#include <stdio.h>void main(){ int a = 25; printf("%o %x", a, a); getch();}
Choose the correct answer:(A) 25 25(B) 025 0x25(C) 12 42(D) 31 19(E) None of these
Answer : (D)
Explanation :%o is used to print the number in octal number format.%x is used to print the number in hexadecimal number format.Note: In c octal number starts with 0 and hexadecimal number starts with 0x.
This article is contributed by Siddharth Pandey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways to copy a string in C/C++
Runtime Errors
Output of Java Program | Set 3
Output of Java program | Set 5
Output of C++ Program | Set 1
Output of Java Program | Set 7
Output of python program | Set 2
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
How to show full column content in a PySpark Dataframe ?
Output of C Programs | Set 3 | [
{
"code": null,
"e": 24173,
"s": 24145,
"text": "\n28 Aug, 2017"
},
{
"code": null,
"e": 24217,
"s": 24173,
"text": "1. What is the output of following program?"
},
{
"code": "#include <stdio.h>int main(){ int a = 1, b = 2, c = 3; c = a == b; printf(\"%d\", c); return 0;}",
"e": 24324,
"s": 24217,
"text": null
},
{
"code": null,
"e": 24371,
"s": 24324,
"text": "Choose the correct answer:(A) 0(B) 1(C) 2(D) 3"
},
{
"code": null,
"e": 24384,
"s": 24371,
"text": "Answer : (A)"
},
{
"code": null,
"e": 24555,
"s": 24384,
"text": "Explanation :“==” is relational operator which returns only two values, either 0 or 1.0: If a == b is false1: If a == b is trueSincea=1b=2So, a == b is false hence C = 0."
},
{
"code": null,
"e": 24599,
"s": 24555,
"text": "2. What is the output of following program?"
},
{
"code": "#include <stdio.h>int main(){ int a = 20; ; ; printf(\"%d\", a); ; return 0;}",
"e": 24693,
"s": 24599,
"text": null
},
{
"code": null,
"e": 24750,
"s": 24693,
"text": "Choose the correct answer:(A) 20(B) Error(C) ;20;(D) ;20"
},
{
"code": null,
"e": 24763,
"s": 24750,
"text": "Answer : (A)"
},
{
"code": null,
"e": 24925,
"s": 24763,
"text": "Explanation : ; (statement terminator) and no expression/statement is available here, so this is a null statement has no side effect, hence no error is occurred."
},
{
"code": null,
"e": 24969,
"s": 24925,
"text": "3. What is the output of following program?"
},
{
"code": "#include <stdio.h>int main(){ int a = 15; float b = 1.234; printf(\"%*f\", a, b); return 0;}",
"e": 25072,
"s": 24969,
"text": null
},
{
"code": null,
"e": 25099,
"s": 25072,
"text": "Choose the correct answer:"
},
{
"code": null,
"e": 25159,
"s": 25099,
"text": "(A) 1.234(B) 1.234000(C) Compilation Error(D) Runtime error"
},
{
"code": null,
"e": 25172,
"s": 25159,
"text": "Answer : (B)"
},
{
"code": null,
"e": 25382,
"s": 25172,
"text": "Explanation : You can define width formatting at run time using %*, This is known as Indirect width precision. printf(“%*f”, a, b); is considered as “%15f”, hence value of b is printed with left padding by 15."
},
{
"code": null,
"e": 25426,
"s": 25382,
"text": "4. What is the output of following program?"
},
{
"code": "#include <stdio.h>void main(){ int a = 1, b = 2, c = 3; char d = 0; if (a, b, c, d) { printf(\"EXAM\"); }}",
"e": 25553,
"s": 25426,
"text": null
},
{
"code": null,
"e": 25654,
"s": 25553,
"text": "Choose the correct answer:(A) No Output and No Error(B) EXAM(C) Run time error(D) Compile time error"
},
{
"code": null,
"e": 25667,
"s": 25654,
"text": "Answer : (A)"
},
{
"code": null,
"e": 25777,
"s": 25667,
"text": "Explanation :Print statement will not execute because ‘ if ‘condition return false. Value of variable d is 0."
},
{
"code": null,
"e": 25821,
"s": 25777,
"text": "5. What is the output of following program?"
},
{
"code": "#include <stdio.h>void main(){ int a = 25; printf(\"%o %x\", a, a); getch();}",
"e": 25908,
"s": 25821,
"text": null
},
{
"code": null,
"e": 25991,
"s": 25908,
"text": "Choose the correct answer:(A) 25 25(B) 025 0x25(C) 12 42(D) 31 19(E) None of these"
},
{
"code": null,
"e": 26004,
"s": 25991,
"text": "Answer : (D)"
},
{
"code": null,
"e": 26208,
"s": 26004,
"text": "Explanation :%o is used to print the number in octal number format.%x is used to print the number in hexadecimal number format.Note: In c octal number starts with 0 and hexadecimal number starts with 0x."
},
{
"code": null,
"e": 26512,
"s": 26208,
"text": "This article is contributed by Siddharth Pandey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 26637,
"s": 26512,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26646,
"s": 26637,
"text": "C-Output"
},
{
"code": null,
"e": 26661,
"s": 26646,
"text": "Program Output"
},
{
"code": null,
"e": 26759,
"s": 26661,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26768,
"s": 26759,
"text": "Comments"
},
{
"code": null,
"e": 26781,
"s": 26768,
"text": "Old Comments"
},
{
"code": null,
"e": 26822,
"s": 26781,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 26837,
"s": 26822,
"text": "Runtime Errors"
},
{
"code": null,
"e": 26868,
"s": 26837,
"text": "Output of Java Program | Set 3"
},
{
"code": null,
"e": 26899,
"s": 26868,
"text": "Output of Java program | Set 5"
},
{
"code": null,
"e": 26929,
"s": 26899,
"text": "Output of C++ Program | Set 1"
},
{
"code": null,
"e": 26960,
"s": 26929,
"text": "Output of Java Program | Set 7"
},
{
"code": null,
"e": 26993,
"s": 26960,
"text": "Output of python program | Set 2"
},
{
"code": null,
"e": 27089,
"s": 26993,
"text": "error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++"
},
{
"code": null,
"e": 27146,
"s": 27089,
"text": "How to show full column content in a PySpark Dataframe ?"
}
]
|
Python | Merge first and last elements separately in a list - GeeksforGeeks | 07 Jun, 2019
Given a list of lists, where each sublist consists of only two elements, write a Python program to merge the first and last element of each sublist separately and finally, output a list of two sub-lists, one containing all first elements and other containing all last elements.
Examples:
Input : [['x', 'y'], ['a', 'b'], ['m', 'n']]
Output : [['x', 'a', 'm'], ['y', 'b', 'n']]
Input : [[1, 2], [3, 4], [5, 6], [7, 8]]
Output : [[1, 3, 5, 7], [2, 4, 6, 8]]
Approach #1 : List comprehension and zip
# Python3 program to Merge first and last# elements separately in a list of lists def merge(lst): return [list(ele) for ele in list(zip(*lst))] # Driver codelst = [['x', 'y'], ['a', 'b'], ['m', 'n']]print(merge(lst))
[['x', 'a', 'm'], ['y', 'b', 'n']]
Approach #2 : Using Numpy array
First convert the given list to numpy array and then return transpose of the array, and finally convert the array to list.
# Python3 program to Merge first and last# elements separately in a list of listsimport numpy as np def merge(lst): arr = np.array(lst) return arr.T.tolist() # Driver codelst = [['x', 'y'], ['a', 'b'], ['m', 'n']]print(merge(lst))
[['x', 'a', 'm'], ['y', 'b', 'n']]
Python list-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 ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 24236,
"s": 24208,
"text": "\n07 Jun, 2019"
},
{
"code": null,
"e": 24514,
"s": 24236,
"text": "Given a list of lists, where each sublist consists of only two elements, write a Python program to merge the first and last element of each sublist separately and finally, output a list of two sub-lists, one containing all first elements and other containing all last elements."
},
{
"code": null,
"e": 24524,
"s": 24514,
"text": "Examples:"
},
{
"code": null,
"e": 24694,
"s": 24524,
"text": "Input : [['x', 'y'], ['a', 'b'], ['m', 'n']]\nOutput : [['x', 'a', 'm'], ['y', 'b', 'n']]\n\nInput : [[1, 2], [3, 4], [5, 6], [7, 8]]\nOutput : [[1, 3, 5, 7], [2, 4, 6, 8]]\n"
},
{
"code": null,
"e": 24736,
"s": 24694,
"text": " Approach #1 : List comprehension and zip"
},
{
"code": "# Python3 program to Merge first and last# elements separately in a list of lists def merge(lst): return [list(ele) for ele in list(zip(*lst))] # Driver codelst = [['x', 'y'], ['a', 'b'], ['m', 'n']]print(merge(lst))",
"e": 24968,
"s": 24736,
"text": null
},
{
"code": null,
"e": 25004,
"s": 24968,
"text": "[['x', 'a', 'm'], ['y', 'b', 'n']]\n"
},
{
"code": null,
"e": 25037,
"s": 25004,
"text": " Approach #2 : Using Numpy array"
},
{
"code": null,
"e": 25160,
"s": 25037,
"text": "First convert the given list to numpy array and then return transpose of the array, and finally convert the array to list."
},
{
"code": "# Python3 program to Merge first and last# elements separately in a list of listsimport numpy as np def merge(lst): arr = np.array(lst) return arr.T.tolist() # Driver codelst = [['x', 'y'], ['a', 'b'], ['m', 'n']]print(merge(lst))",
"e": 25403,
"s": 25160,
"text": null
},
{
"code": null,
"e": 25439,
"s": 25403,
"text": "[['x', 'a', 'm'], ['y', 'b', 'n']]\n"
},
{
"code": null,
"e": 25460,
"s": 25439,
"text": "Python list-programs"
},
{
"code": null,
"e": 25467,
"s": 25460,
"text": "Python"
},
{
"code": null,
"e": 25483,
"s": 25467,
"text": "Python Programs"
},
{
"code": null,
"e": 25581,
"s": 25483,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25590,
"s": 25581,
"text": "Comments"
},
{
"code": null,
"e": 25603,
"s": 25590,
"text": "Old Comments"
},
{
"code": null,
"e": 25635,
"s": 25603,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25690,
"s": 25635,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25746,
"s": 25690,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25785,
"s": 25746,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25827,
"s": 25785,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25849,
"s": 25827,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25888,
"s": 25849,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 25934,
"s": 25888,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 25972,
"s": 25934,
"text": "Python | Convert a list to dictionary"
}
]
|
Perceptron: Explanation, Implementation and a Visual Example | by Dorian Lazar | Towards Data Science | The perceptron is the building block of artificial neural networks, it is a simplified model of the biological neurons in our brain. A perceptron is the simplest neural network, one that is comprised of just one neuron. The perceptron algorithm was invented in 1958 by Frank Rosenblatt.
Below is an illustration of a biological neuron:
The majority of the input signal to a neuron is received via the dendrites. There are about 1,000 to 10,000 connections that are formed by other neurons to these dendrites. The signal from the connections, called synapses, propagate through the dendrite into the cell body. The potential increases in the cell body and once it reaches a threshold, the neuron sends a spike along the axon that connects to roughly 100 other neurons through the axon terminal.
The perceptron is a simplified model of the real neuron that attempts to imitate it by the following process: it takes the input signals, let’s call them x1, x2, ..., xn, computes a weighted sum z of those inputs, then passes it through a threshold function φ and outputs the result.
But having w0 as a threshold is the same thing as adding w0 to the sum as bias and having instead a threshold of 0. That is, we consider an additional input signal x0 that is always set to 1.
Here is represented a perceptron:
To use vector notation, we can put all inputs x0, x1, ..., xn, and all weights w0, w1, ..., wn into vectors x and w, and output 1 when their dot product is positive and -1 otherwise.
Here is a geometrical representation of this using only 2 inputs x1 and x2, so that we can plot it in 2 dimensions:
As you see above, the decision boundary of a perceptron with 2 inputs is a line. If there were 3 inputs, the decision boundary would be a 2D plane. In general, if we have n inputs the decision boundary will be a n-1 dimensional object called a hyperplane that separates our n-dimensional feature space into 2 parts: one in which the points are classified as positive, and one in which the points are classified as negative(by convention, we will consider points that are exactly on the decision boundary as being negative). Hence the perceptron is a binary classifier that is linear in terms of its weights.
In the image above w’ represents the weights vector without the bias term w0. w’ has the property that it is perpendicular to the decision boundary and points towards the positively classified points. This vector determines the slope of the decision boundary, and the bias term w0 determines the offset of the decision boundary along the w’ axis.
So far we talked about how a perceptron takes a decision based on the input signals and its weights. But how a perceptron actually learns? How to find the right set of parameters w0, w1, ..., wn in order to make a good classification?The perceptron algorithm is an iterative algorithm that is based on the following simple update rule:
Where y is the label (either -1 or +1) of our current data point x, and w is the weights vector.
What does our update rule say? The dot product x⋅w is just the perceptron’s prediction based on the current weights (its sign is the same with the one of the predicted label). The expression y(x⋅w) can be less than or equal to 0 only if the real label y is different than the predicted label φ(x⋅w). So, if there is a mismatch between the true and predicted labels, then we update our weights: w = w+yx; otherwise, we let them as they are.
So, why the w = w + yx update rule works? It attempts to push the value of y(x⋅w), in the if condition, towards the positive side of 0, and thus classifying x correctly. And if the dataset is linearly separable, by doing this update rule for each point for a certain number of iterations, the weights will eventually converge to a state in which every point is correctly classified. Let’s see what’s the effect of the update rule by reevaluating the if condition after the update:
That is, after the weights update for a particular data point the expression in the if condition should be closer to being positive, and thus correctly classified.
The full perceptron algorithm in pseudocode is here:
We will now implement the perceptron algorithm from scratch in python using only numpy as an external library for matrix-vector operations. We will implement it as a class that has an interface similar to other classifiers in common machine learning packages like Sci-kit Learn. We will implement for this class 3 methods: .fit(), .predict(), and .score().
The .fit() method will be used for training the perceptron. It expects as the first parameter a 2D numpy array X. The rows of this array are samples from our dataset, and the columns are the features. The second parameter, y, should be a 1D numpy array that contains the labels for each row of data in X. The third parameter, n_iter, is the number of iterations for which we let the algorithm run.
def fit(self, X, y, n_iter=100): n_samples = X.shape[0] n_features = X.shape[1] # Add 1 for the bias term self.weights = np.zeros((n_features+1,)) # Add column of 1s X = np.concatenate([X, np.ones((n_samples, 1))], axis=1) for i in range(n_iter): for j in range(n_samples): if y[j]*np.dot(self.weights, X[j, :]) <= 0: self.weights += y[j]*X[j, :]
The .predict() method will be used for predicting labels of new data. It first checks if the weights object attribute exists, if not this means that the perceptron is not trained yet, and we show a warning message and return. The method expects one parameter, X, of the same shape as in the .fit() method. Then we just do a matrix multiplication between X and the weights, and map them to either -1 or +1. We use np.vectorize() to apply this mapping to all elements in the resulting vector of matrix multiplication.
def predict(self, X): if not hasattr(self, 'weights'): print('The model is not trained yet!') return n_samples = X.shape[0] # Add column of 1s X = np.concatenate([X, np.ones((n_samples, 1))], axis=1) y = np.matmul(X, self.weights) y = np.vectorize(lambda val: 1 if val > 0 else -1)(y) return y
The .score() method computes and returns the accuracy of the predictions. It expects as parameters an input matrix X and a labels vector y.
def score(self, X, y): pred_y = self.predict(X) return np.mean(y == pred_y)
Below is the full code:
What I want to do now is to show a few visual examples of how the decision boundary converges to a solution.
In order to do so, I will create a few 2-feature classification datasets consisting of 200 samples using Sci-kit Learn’s datasets.make_classification() and datasets.make_circles() functions. This is the code used to create the next 2 datasets:
X, y = make_classification( n_features=2, n_classes=2, n_samples=200, n_redundant=0, n_clusters_per_class=1)
And the last dataset:
X, y = make_circles(n_samples=200, noise=0.03, factor=0.7)
For each example, I will split the data into 150 for training and 50 for testing. On the left will be shown the training set and on the right the testing set. The decision boundary will be shown on both sides as it converges to a solution. But the decision boundary will be updated based on just the data on the left (training set).
The first dataset that I will show is a linearly separable one. Below is an image of the full dataset:
This is a simple dataset, and our perceptron algorithm will converge to a solution after just 2 iterations through the training set. So, the animation frames will change for each data point. The green point is the one that is currently tested in the algorithm.
On this dataset, the algorithm had correctly classified both the training and testing examples.
What if the dataset is not linearly separable? What if the positive and negative examples are mixed up like in the image below?
Well, the perceptron algorithm will not be able to correctly classify all examples, but it will attempt to find a line that best separates them. In this example, our perceptron got a 88% test accuracy. The animation frames below are updated after each iteration through all the training examples.
What about the below dataset?
It is separable, but clearly not linear. So you may think that a perceptron would not be good for this task. But the thing about a perceptron is that it’s decision boundary is linear in terms of the weights, not necessarily in terms of inputs. We can augment our input vectors x so that they contain non-linear functions of the original inputs. For example, in addition to the original inputs x1 and x2 we can add the terms x1 squared, x1 times x2, and x2 squared.
The polynomial_features(X, p) function below is able to transform the input matrix X into a matrix that contains as features all the terms of a polynomial of degree p. It makes use of the polynom() function which computes a list of indices that represent the columns to be multiplied for obtaining the p-order terms.
def polynom(indices_list, indices, a, b, p): indices = [*indices] if p == 0: indices_list.append(indices) return for i in range(a, b): indices.append(i) polynom(indices_list, indices, i, b, p-1) indices = indices[0:-1]def polynomial_features(X, p): n, d = X.shape features = [] for i in range(1, p+1): l = [] polynom(l, [], 0, d, i) for indices in l: x = np.ones((n,)) for idx in indices: x = x * X[:, idx] features.append(x) return np.stack(features, axis=1)
For our example, we will add degree 2 terms as new features in the X matrix.
X = polynomial_features(X, 2)
Now, let’s see what happens during training with this transformed dataset:
Note that for plotting, we used only the original inputs in order to keep it 2D. The decision boundary is still linear in the augmented feature space which is 5D now. But when we plot that decision boundary projected onto the original feature space it has a non-linear shape.
With this method, our perceptron algorithm was able to correctly classify both training and testing examples without any modification of the algorithm itself. All we changed was the dataset.
With this feature augmentation method, we are able to model very complex patterns in our data by using algorithms that were otherwise just linear.
But, this method is not very efficient. Imagine what would happen if we had 1000 input features and we want to augment it with up to 10-degree polynomial terms. Fortunately, this problem can be avoided using something called kernels. But that’s a topic for another article, I don’t want to make this one too long.
I hope you found this information useful and thanks for reading!
This article is also posted on my own website here. Feel free to have a look! | [
{
"code": null,
"e": 458,
"s": 171,
"text": "The perceptron is the building block of artificial neural networks, it is a simplified model of the biological neurons in our brain. A perceptron is the simplest neural network, one that is comprised of just one neuron. The perceptron algorithm was invented in 1958 by Frank Rosenblatt."
},
{
"code": null,
"e": 507,
"s": 458,
"text": "Below is an illustration of a biological neuron:"
},
{
"code": null,
"e": 965,
"s": 507,
"text": "The majority of the input signal to a neuron is received via the dendrites. There are about 1,000 to 10,000 connections that are formed by other neurons to these dendrites. The signal from the connections, called synapses, propagate through the dendrite into the cell body. The potential increases in the cell body and once it reaches a threshold, the neuron sends a spike along the axon that connects to roughly 100 other neurons through the axon terminal."
},
{
"code": null,
"e": 1249,
"s": 965,
"text": "The perceptron is a simplified model of the real neuron that attempts to imitate it by the following process: it takes the input signals, let’s call them x1, x2, ..., xn, computes a weighted sum z of those inputs, then passes it through a threshold function φ and outputs the result."
},
{
"code": null,
"e": 1441,
"s": 1249,
"text": "But having w0 as a threshold is the same thing as adding w0 to the sum as bias and having instead a threshold of 0. That is, we consider an additional input signal x0 that is always set to 1."
},
{
"code": null,
"e": 1475,
"s": 1441,
"text": "Here is represented a perceptron:"
},
{
"code": null,
"e": 1658,
"s": 1475,
"text": "To use vector notation, we can put all inputs x0, x1, ..., xn, and all weights w0, w1, ..., wn into vectors x and w, and output 1 when their dot product is positive and -1 otherwise."
},
{
"code": null,
"e": 1774,
"s": 1658,
"text": "Here is a geometrical representation of this using only 2 inputs x1 and x2, so that we can plot it in 2 dimensions:"
},
{
"code": null,
"e": 2382,
"s": 1774,
"text": "As you see above, the decision boundary of a perceptron with 2 inputs is a line. If there were 3 inputs, the decision boundary would be a 2D plane. In general, if we have n inputs the decision boundary will be a n-1 dimensional object called a hyperplane that separates our n-dimensional feature space into 2 parts: one in which the points are classified as positive, and one in which the points are classified as negative(by convention, we will consider points that are exactly on the decision boundary as being negative). Hence the perceptron is a binary classifier that is linear in terms of its weights."
},
{
"code": null,
"e": 2729,
"s": 2382,
"text": "In the image above w’ represents the weights vector without the bias term w0. w’ has the property that it is perpendicular to the decision boundary and points towards the positively classified points. This vector determines the slope of the decision boundary, and the bias term w0 determines the offset of the decision boundary along the w’ axis."
},
{
"code": null,
"e": 3065,
"s": 2729,
"text": "So far we talked about how a perceptron takes a decision based on the input signals and its weights. But how a perceptron actually learns? How to find the right set of parameters w0, w1, ..., wn in order to make a good classification?The perceptron algorithm is an iterative algorithm that is based on the following simple update rule:"
},
{
"code": null,
"e": 3162,
"s": 3065,
"text": "Where y is the label (either -1 or +1) of our current data point x, and w is the weights vector."
},
{
"code": null,
"e": 3602,
"s": 3162,
"text": "What does our update rule say? The dot product x⋅w is just the perceptron’s prediction based on the current weights (its sign is the same with the one of the predicted label). The expression y(x⋅w) can be less than or equal to 0 only if the real label y is different than the predicted label φ(x⋅w). So, if there is a mismatch between the true and predicted labels, then we update our weights: w = w+yx; otherwise, we let them as they are."
},
{
"code": null,
"e": 4083,
"s": 3602,
"text": "So, why the w = w + yx update rule works? It attempts to push the value of y(x⋅w), in the if condition, towards the positive side of 0, and thus classifying x correctly. And if the dataset is linearly separable, by doing this update rule for each point for a certain number of iterations, the weights will eventually converge to a state in which every point is correctly classified. Let’s see what’s the effect of the update rule by reevaluating the if condition after the update:"
},
{
"code": null,
"e": 4247,
"s": 4083,
"text": "That is, after the weights update for a particular data point the expression in the if condition should be closer to being positive, and thus correctly classified."
},
{
"code": null,
"e": 4300,
"s": 4247,
"text": "The full perceptron algorithm in pseudocode is here:"
},
{
"code": null,
"e": 4657,
"s": 4300,
"text": "We will now implement the perceptron algorithm from scratch in python using only numpy as an external library for matrix-vector operations. We will implement it as a class that has an interface similar to other classifiers in common machine learning packages like Sci-kit Learn. We will implement for this class 3 methods: .fit(), .predict(), and .score()."
},
{
"code": null,
"e": 5055,
"s": 4657,
"text": "The .fit() method will be used for training the perceptron. It expects as the first parameter a 2D numpy array X. The rows of this array are samples from our dataset, and the columns are the features. The second parameter, y, should be a 1D numpy array that contains the labels for each row of data in X. The third parameter, n_iter, is the number of iterations for which we let the algorithm run."
},
{
"code": null,
"e": 5456,
"s": 5055,
"text": "def fit(self, X, y, n_iter=100): n_samples = X.shape[0] n_features = X.shape[1] # Add 1 for the bias term self.weights = np.zeros((n_features+1,)) # Add column of 1s X = np.concatenate([X, np.ones((n_samples, 1))], axis=1) for i in range(n_iter): for j in range(n_samples): if y[j]*np.dot(self.weights, X[j, :]) <= 0: self.weights += y[j]*X[j, :]"
},
{
"code": null,
"e": 5972,
"s": 5456,
"text": "The .predict() method will be used for predicting labels of new data. It first checks if the weights object attribute exists, if not this means that the perceptron is not trained yet, and we show a warning message and return. The method expects one parameter, X, of the same shape as in the .fit() method. Then we just do a matrix multiplication between X and the weights, and map them to either -1 or +1. We use np.vectorize() to apply this mapping to all elements in the resulting vector of matrix multiplication."
},
{
"code": null,
"e": 6301,
"s": 5972,
"text": "def predict(self, X): if not hasattr(self, 'weights'): print('The model is not trained yet!') return n_samples = X.shape[0] # Add column of 1s X = np.concatenate([X, np.ones((n_samples, 1))], axis=1) y = np.matmul(X, self.weights) y = np.vectorize(lambda val: 1 if val > 0 else -1)(y) return y"
},
{
"code": null,
"e": 6441,
"s": 6301,
"text": "The .score() method computes and returns the accuracy of the predictions. It expects as parameters an input matrix X and a labels vector y."
},
{
"code": null,
"e": 6523,
"s": 6441,
"text": "def score(self, X, y): pred_y = self.predict(X) return np.mean(y == pred_y)"
},
{
"code": null,
"e": 6547,
"s": 6523,
"text": "Below is the full code:"
},
{
"code": null,
"e": 6656,
"s": 6547,
"text": "What I want to do now is to show a few visual examples of how the decision boundary converges to a solution."
},
{
"code": null,
"e": 6900,
"s": 6656,
"text": "In order to do so, I will create a few 2-feature classification datasets consisting of 200 samples using Sci-kit Learn’s datasets.make_classification() and datasets.make_circles() functions. This is the code used to create the next 2 datasets:"
},
{
"code": null,
"e": 7024,
"s": 6900,
"text": "X, y = make_classification( n_features=2, n_classes=2, n_samples=200, n_redundant=0, n_clusters_per_class=1)"
},
{
"code": null,
"e": 7046,
"s": 7024,
"text": "And the last dataset:"
},
{
"code": null,
"e": 7105,
"s": 7046,
"text": "X, y = make_circles(n_samples=200, noise=0.03, factor=0.7)"
},
{
"code": null,
"e": 7438,
"s": 7105,
"text": "For each example, I will split the data into 150 for training and 50 for testing. On the left will be shown the training set and on the right the testing set. The decision boundary will be shown on both sides as it converges to a solution. But the decision boundary will be updated based on just the data on the left (training set)."
},
{
"code": null,
"e": 7541,
"s": 7438,
"text": "The first dataset that I will show is a linearly separable one. Below is an image of the full dataset:"
},
{
"code": null,
"e": 7802,
"s": 7541,
"text": "This is a simple dataset, and our perceptron algorithm will converge to a solution after just 2 iterations through the training set. So, the animation frames will change for each data point. The green point is the one that is currently tested in the algorithm."
},
{
"code": null,
"e": 7898,
"s": 7802,
"text": "On this dataset, the algorithm had correctly classified both the training and testing examples."
},
{
"code": null,
"e": 8026,
"s": 7898,
"text": "What if the dataset is not linearly separable? What if the positive and negative examples are mixed up like in the image below?"
},
{
"code": null,
"e": 8323,
"s": 8026,
"text": "Well, the perceptron algorithm will not be able to correctly classify all examples, but it will attempt to find a line that best separates them. In this example, our perceptron got a 88% test accuracy. The animation frames below are updated after each iteration through all the training examples."
},
{
"code": null,
"e": 8353,
"s": 8323,
"text": "What about the below dataset?"
},
{
"code": null,
"e": 8818,
"s": 8353,
"text": "It is separable, but clearly not linear. So you may think that a perceptron would not be good for this task. But the thing about a perceptron is that it’s decision boundary is linear in terms of the weights, not necessarily in terms of inputs. We can augment our input vectors x so that they contain non-linear functions of the original inputs. For example, in addition to the original inputs x1 and x2 we can add the terms x1 squared, x1 times x2, and x2 squared."
},
{
"code": null,
"e": 9135,
"s": 8818,
"text": "The polynomial_features(X, p) function below is able to transform the input matrix X into a matrix that contains as features all the terms of a polynomial of degree p. It makes use of the polynom() function which computes a list of indices that represent the columns to be multiplied for obtaining the p-order terms."
},
{
"code": null,
"e": 9720,
"s": 9135,
"text": "def polynom(indices_list, indices, a, b, p): indices = [*indices] if p == 0: indices_list.append(indices) return for i in range(a, b): indices.append(i) polynom(indices_list, indices, i, b, p-1) indices = indices[0:-1]def polynomial_features(X, p): n, d = X.shape features = [] for i in range(1, p+1): l = [] polynom(l, [], 0, d, i) for indices in l: x = np.ones((n,)) for idx in indices: x = x * X[:, idx] features.append(x) return np.stack(features, axis=1)"
},
{
"code": null,
"e": 9797,
"s": 9720,
"text": "For our example, we will add degree 2 terms as new features in the X matrix."
},
{
"code": null,
"e": 9827,
"s": 9797,
"text": "X = polynomial_features(X, 2)"
},
{
"code": null,
"e": 9902,
"s": 9827,
"text": "Now, let’s see what happens during training with this transformed dataset:"
},
{
"code": null,
"e": 10178,
"s": 9902,
"text": "Note that for plotting, we used only the original inputs in order to keep it 2D. The decision boundary is still linear in the augmented feature space which is 5D now. But when we plot that decision boundary projected onto the original feature space it has a non-linear shape."
},
{
"code": null,
"e": 10369,
"s": 10178,
"text": "With this method, our perceptron algorithm was able to correctly classify both training and testing examples without any modification of the algorithm itself. All we changed was the dataset."
},
{
"code": null,
"e": 10516,
"s": 10369,
"text": "With this feature augmentation method, we are able to model very complex patterns in our data by using algorithms that were otherwise just linear."
},
{
"code": null,
"e": 10830,
"s": 10516,
"text": "But, this method is not very efficient. Imagine what would happen if we had 1000 input features and we want to augment it with up to 10-degree polynomial terms. Fortunately, this problem can be avoided using something called kernels. But that’s a topic for another article, I don’t want to make this one too long."
},
{
"code": null,
"e": 10895,
"s": 10830,
"text": "I hope you found this information useful and thanks for reading!"
}
]
|
Prototype - Form.Element getValue() Method | This method returns the current value of a form control. A string is returned for most controls; only multiple select boxes return an array of values. The global shortcut for this method is $F().
formElement.getValue();
It returns a string or array of strings.
Following is the example to show how a control receives focus −
<html>
<head>
<title>Prototype examples</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script>
function showResult() {
var value = $('age').getValue();
alert("Returned value is : " + value );
}
</script>
</head>
<body>
<p>Click the button to see the result.</p>
<br />
<form id = "example" action = "#" onsubmit = "return false">
<fieldset>
<legend>User info</legend>
<div>
<label for = "username">Username:</label>
<input name = "username" id = "username" value = "Sai" type = "text">
</div>
<div>
<label for = "age">Age:</label>
<input name = "age" id = "age" value = "23" size = "3" type = "text">
</div>
<div><label for = "hobbies">Your hobbies :</label>
<select name = "hobbies" id = "hobbies" multiple = "multiple">
<option>coding</option>
<option>swimming</option>
<option>hiking</option>
<option>drawing</option>
</select>
</div>
</fieldset>
</form>
<br />
<input type = "button" value = "Toggle" onclick = "showResult();"/>
</body>
</html>
Click the button to see the result.
127 Lectures
11.5 hours
Aleksandar Cucukovic
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2257,
"s": 2061,
"text": "This method returns the current value of a form control. A string is returned for most controls; only multiple select boxes return an array of values. The global shortcut for this method is $F()."
},
{
"code": null,
"e": 2282,
"s": 2257,
"text": "formElement.getValue();\n"
},
{
"code": null,
"e": 2323,
"s": 2282,
"text": "It returns a string or array of strings."
},
{
"code": null,
"e": 2387,
"s": 2323,
"text": "Following is the example to show how a control receives focus −"
},
{
"code": null,
"e": 3767,
"s": 2387,
"text": "<html>\n <head>\n <title>Prototype examples</title>\n <script type = \"text/javascript\" src = \"/javascript/prototype.js\"></script>\n \n <script>\n function showResult() {\n var value = $('age').getValue();\n alert(\"Returned value is : \" + value );\n }\n </script>\n </head>\n\n <body>\n <p>Click the button to see the result.</p>\n <br />\n\n <form id = \"example\" action = \"#\" onsubmit = \"return false\">\n <fieldset>\n <legend>User info</legend>\n <div>\n <label for = \"username\">Username:</label> \n <input name = \"username\" id = \"username\" value = \"Sai\" type = \"text\">\n </div>\n <div>\n <label for = \"age\">Age:</label> \n <input name = \"age\" id = \"age\" value = \"23\" size = \"3\" type = \"text\">\n </div>\n <div><label for = \"hobbies\">Your hobbies :</label>\n <select name = \"hobbies\" id = \"hobbies\" multiple = \"multiple\">\n <option>coding</option>\n <option>swimming</option>\n <option>hiking</option>\n <option>drawing</option>\n </select>\n </div>\n </fieldset>\n </form>\n \n <br />\n <input type = \"button\" value = \"Toggle\" onclick = \"showResult();\"/>\n </body>\n</html>"
},
{
"code": null,
"e": 3803,
"s": 3767,
"text": "Click the button to see the result."
},
{
"code": null,
"e": 3840,
"s": 3803,
"text": "\n 127 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 3862,
"s": 3840,
"text": " Aleksandar Cucukovic"
},
{
"code": null,
"e": 3869,
"s": 3862,
"text": " Print"
},
{
"code": null,
"e": 3880,
"s": 3869,
"text": " Add Notes"
}
]
|
HTML DOM MouseEvent clientX Property | The HTML DOM MouseEvent clientX property returns the horizontal (x) coordinate of the mouse pointer if a mouse event was triggered. Use with clientY to get the vertical coordinate as well.
Following is the syntax −
Returning reference to the clientX object
MouseEventObject.clientX
Let us see an example of MouseEvent clientX property −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>MouseEvent clientX</title>
<style>
* {
padding: 2px;
margin:5px;
}
form {
width:70%;
margin: 0 auto;
text-align: center;
}
#outer {
width:70%;
margin: 0 auto;
padding: 0;
text-align: center;
border:1px solid black;
height: 105px;
background-color: #28a745;
}
input[type="button"] {
border-radius: 10px;
}
#upper {
border-bottom: 1px solid black;
height: 40px;
margin: 0 0 15px 0;
background-color: #DC3545;
}
#lower {
border-top: 1px solid black;
height: 40px;
margin: 15px 0 0 0;
background-color: #DC3545;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>MouseEvent-clientX</legend>
<div id="outer">
<div id="upper"><h2>Danger</h2></div>
<div id="lower"><h2>Danger</h2></div>
</div>
<input type="button" id="start" value="Start" onclick="gameStart()">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById('divDisplay');
var gameDisplay = document.getElementById('outer');
function playGame(event) {
var x = event.clientX;
var y = event.clientY;
if(y > 95 && y < 110){
divDisplay.textContent = 'Keep Going!';
if(x === 439){
divDisplay.textContent = 'Congrats! You Did it!';
gameDisplay.removeEventListener('mousemove', playGame);
}
}
else{
divDisplay.textContent = 'You moved to DANGER area. You loose!';
gameDisplay.removeEventListener('mousemove', playGame);
}
}
function gameStart(){
gameDisplay.addEventListener('mousemove',playGame);
}
</script>
</body>
</html>
After clicking ‘Start’ button and cursor in green (safe) area −
After clicking ‘Start’ button and cursor at end of green (safe) area −
After clicking ‘Start’ button and cursor in red (danger) area − | [
{
"code": null,
"e": 1251,
"s": 1062,
"text": "The HTML DOM MouseEvent clientX property returns the horizontal (x) coordinate of the mouse pointer if a mouse event was triggered. Use with clientY to get the vertical coordinate as well."
},
{
"code": null,
"e": 1277,
"s": 1251,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1319,
"s": 1277,
"text": "Returning reference to the clientX object"
},
{
"code": null,
"e": 1344,
"s": 1319,
"text": "MouseEventObject.clientX"
},
{
"code": null,
"e": 1399,
"s": 1344,
"text": "Let us see an example of MouseEvent clientX property −"
},
{
"code": null,
"e": 1410,
"s": 1399,
"text": " Live Demo"
},
{
"code": null,
"e": 3223,
"s": 1410,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<title>MouseEvent clientX</title>\n<style>\n * {\n padding: 2px;\n margin:5px;\n }\n form {\n width:70%;\n margin: 0 auto;\n text-align: center;\n }\n #outer {\n width:70%;\n margin: 0 auto;\n padding: 0;\n text-align: center;\n border:1px solid black;\n height: 105px;\n background-color: #28a745;\n }\n input[type=\"button\"] {\n border-radius: 10px;\n }\n #upper {\n border-bottom: 1px solid black;\n height: 40px;\n margin: 0 0 15px 0;\n background-color: #DC3545;\n }\n #lower {\n border-top: 1px solid black;\n height: 40px;\n margin: 15px 0 0 0;\n background-color: #DC3545;\n }\n</style>\n</head>\n<body>\n <form>\n <fieldset>\n <legend>MouseEvent-clientX</legend>\n <div id=\"outer\">\n <div id=\"upper\"><h2>Danger</h2></div>\n <div id=\"lower\"><h2>Danger</h2></div>\n </div>\n <input type=\"button\" id=\"start\" value=\"Start\" onclick=\"gameStart()\">\n <div id=\"divDisplay\"></div>\n </fieldset>\n </form>\n<script>\n var divDisplay = document.getElementById('divDisplay');\n var gameDisplay = document.getElementById('outer');\n function playGame(event) {\n var x = event.clientX;\n var y = event.clientY;\n if(y > 95 && y < 110){\n divDisplay.textContent = 'Keep Going!';\n if(x === 439){\n divDisplay.textContent = 'Congrats! You Did it!';\n gameDisplay.removeEventListener('mousemove', playGame);\n }\n }\n else{\n divDisplay.textContent = 'You moved to DANGER area. You loose!';\n gameDisplay.removeEventListener('mousemove', playGame);\n }\n }\n function gameStart(){\n gameDisplay.addEventListener('mousemove',playGame);\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 3287,
"s": 3223,
"text": "After clicking ‘Start’ button and cursor in green (safe) area −"
},
{
"code": null,
"e": 3358,
"s": 3287,
"text": "After clicking ‘Start’ button and cursor at end of green (safe) area −"
},
{
"code": null,
"e": 3422,
"s": 3358,
"text": "After clicking ‘Start’ button and cursor in red (danger) area −"
}
]
|
Preorder Traversal | Practice | GeeksforGeeks | Given a binary tree, find its preorder traversal.
Example 1:
Input:
1
/
4
/ \
4 2
Output: 1 4 4 2
Example 2:
Input:
6
/ \
3 2
\ /
1 2
Output: 6 3 1 2 2
Your Task:
You just have to complete the function preorder() which takes the root node of the tree as input and returns an array containing the preorder traversal of the tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= Number of nodes <= 104
0 <= Data of a node <= 105
0
superrhitik4581 day ago
vector<int> vi;void pre(Node* root){ if(root!=NULL){ vi.push_back(root->data); pre(root->left); pre(root->right);} return;}vector <int> preorder(Node* root){ // Your code herepre(root); vector<int> res=vi;//v=vi;
vi.clear();// for(int i=0;i<v.size();i++)//cout<<v[i]<<" ";return res;}
0
itachinamikaze2211 week ago
JAVA
static ArrayList<Integer> preorder(Node root) { ArrayList<Integer> res= new ArrayList<>(); if(root==null) return res; Stack<Node> st= new Stack<Node>(); st.push(root); while(st.isEmpty()==false) { root=st.pop(); res.add(root.data); if(root.right!=null) st.push(root.right); if(root.left!=null) st.push(root.left); } return res;}
+1
singh.shobhit0071 week ago
If someone is wondering why there solution is not working when they are declaring a global vector, it cause there are multiple entries for being made in the vector for different testcases and the array is not being cleared, use array.clear to clean your array before using that assign the value of array to a temp vector and return the temp, it should work
for reference
vector<int> arr;void preOrder(Node *root){ if(root == nullptr) return; arr.push_back(root->data);; preOrder(root->left); preOrder(root->right); return;}
vector <int> preorder(Node* root){ // Your code here preOrder(root); vector<int> res = arr; arr.clear(); return res;}
0
harshscode1 week ago
void findpre(Node *root,vector<int> &v){ if(!root) return; v.push_back(root->data); findpre(root->left,v); findpre(root->right,v); }//Function to return a list containing the preorder traversal of the tree.vector <int> preorder(Node* root){ vector<int> v; findpre(root,v); return v; }
0
hharshit81182 weeks ago
vector<int> preorder(Node* root){vector<int> v;stack<Node*> st;st.push(root);while(st.empty() == false){ Node* curr = st.top(); st.pop(); v.push_back(curr->data); if(curr->right){ st.push(curr->right); } if(curr->left){ st.push(curr->left); }}return v;}
0
mangy007
This comment was deleted.
0
meanm0nst3r2 weeks ago
What's the error?someone please commentCode:vector <int> preorder(Node* root){ // Your code here Node* curr=root; vector<int> v; if(!curr) return v; v.push_back(curr->data); preorder(curr->left); preorder(curr->right); return v;}
0
sagrikasoni3 weeks ago
JAVA Solution
static ArrayList<Integer> preorder(Node root)
{
ArrayList<Integer> arr = new ArrayList<Integer>();
if(root==null) return arr;
Stack<Node> q = new Stack<Node>();
q.push(root);
while(!q.isEmpty()){
Node curr = q.pop();
arr.add(curr.data);
if(curr.right!=null)
q.push(curr.right);
if(curr.left!=null)
q.push(curr.left);
}
return arr;
}
0
talmeezahmed7863 weeks ago
#Iterative python solution, for more performance
#replace the queue with deque
def preorder(root):
# code here
result = []
# initialize our process queue
queue = []
size = 0
# push the root node to our queue
queue.append(root)
size = size + 1
while (size > 0):
# process the node at front of queue
currentNode = queue[0]
queue = queue[1:]
size = size - 1
# process the root first
if (currentNode.data != None):
result.append(currentNode.data)
# process the right node
if (currentNode.right and currentNode.right.data != None):
queue.insert(0, currentNode.right)
size = size + 1
# process the left node
if (currentNode.left and currentNode.left.data != None):
queue.insert(0, currentNode.left)
size = size + 1
return result
0
bsbh20is1 month ago
int arr[10000];
void pre(struct Node*node,int *i){ if(node==NULL) return; arr[(*i)]=node->data; (*i)=(*i)+1; pre(node->left,i); pre(node->right,i); }
int* preorder(struct Node* root){ //code here int ind=0; pre(root,&ind); return arr; //do not change the default values(i.e -1) in the unused array indices.}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 276,
"s": 226,
"text": "Given a binary tree, find its preorder traversal."
},
{
"code": null,
"e": 287,
"s": 276,
"text": "Example 1:"
},
{
"code": null,
"e": 378,
"s": 287,
"text": "Input:\n 1 \n / \n 4 \n / \\ \n4 2\nOutput: 1 4 4 2 \n"
},
{
"code": null,
"e": 389,
"s": 378,
"text": "Example 2:"
},
{
"code": null,
"e": 471,
"s": 389,
"text": "Input:\n 6\n / \\\n 3 2\n \\ / \n 1 2\nOutput: 6 3 1 2 2 \n\n"
},
{
"code": null,
"e": 647,
"s": 471,
"text": "Your Task:\nYou just have to complete the function preorder() which takes the root node of the tree as input and returns an array containing the preorder traversal of the tree."
},
{
"code": null,
"e": 711,
"s": 647,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)."
},
{
"code": null,
"e": 779,
"s": 711,
"text": "Constraints:\n1 <= Number of nodes <= 104\n0 <= Data of a node <= 105"
},
{
"code": null,
"e": 781,
"s": 779,
"text": "0"
},
{
"code": null,
"e": 805,
"s": 781,
"text": "superrhitik4581 day ago"
},
{
"code": null,
"e": 1029,
"s": 805,
"text": "vector<int> vi;void pre(Node* root){ if(root!=NULL){ vi.push_back(root->data); pre(root->left); pre(root->right);} return;}vector <int> preorder(Node* root){ // Your code herepre(root); vector<int> res=vi;//v=vi;"
},
{
"code": null,
"e": 1101,
"s": 1029,
"text": "vi.clear();// for(int i=0;i<v.size();i++)//cout<<v[i]<<\" \";return res;}"
},
{
"code": null,
"e": 1103,
"s": 1101,
"text": "0"
},
{
"code": null,
"e": 1131,
"s": 1103,
"text": "itachinamikaze2211 week ago"
},
{
"code": null,
"e": 1136,
"s": 1131,
"text": "JAVA"
},
{
"code": null,
"e": 1596,
"s": 1136,
"text": "static ArrayList<Integer> preorder(Node root) { ArrayList<Integer> res= new ArrayList<>(); if(root==null) return res; Stack<Node> st= new Stack<Node>(); st.push(root); while(st.isEmpty()==false) { root=st.pop(); res.add(root.data); if(root.right!=null) st.push(root.right); if(root.left!=null) st.push(root.left); } return res;}"
},
{
"code": null,
"e": 1599,
"s": 1596,
"text": "+1"
},
{
"code": null,
"e": 1626,
"s": 1599,
"text": "singh.shobhit0071 week ago"
},
{
"code": null,
"e": 1984,
"s": 1626,
"text": "If someone is wondering why there solution is not working when they are declaring a global vector, it cause there are multiple entries for being made in the vector for different testcases and the array is not being cleared, use array.clear to clean your array before using that assign the value of array to a temp vector and return the temp, it should work "
},
{
"code": null,
"e": 2000,
"s": 1986,
"text": "for reference"
},
{
"code": null,
"e": 2169,
"s": 2000,
"text": "vector<int> arr;void preOrder(Node *root){ if(root == nullptr) return; arr.push_back(root->data);; preOrder(root->left); preOrder(root->right); return;}"
},
{
"code": null,
"e": 2287,
"s": 2169,
"text": "vector <int> preorder(Node* root){ // Your code here preOrder(root); vector<int> res = arr; arr.clear(); return res;}"
},
{
"code": null,
"e": 2289,
"s": 2287,
"text": "0"
},
{
"code": null,
"e": 2310,
"s": 2289,
"text": "harshscode1 week ago"
},
{
"code": null,
"e": 2624,
"s": 2310,
"text": "void findpre(Node *root,vector<int> &v){ if(!root) return; v.push_back(root->data); findpre(root->left,v); findpre(root->right,v); }//Function to return a list containing the preorder traversal of the tree.vector <int> preorder(Node* root){ vector<int> v; findpre(root,v); return v; }"
},
{
"code": null,
"e": 2626,
"s": 2624,
"text": "0"
},
{
"code": null,
"e": 2650,
"s": 2626,
"text": "hharshit81182 weeks ago"
},
{
"code": null,
"e": 2930,
"s": 2650,
"text": "vector<int> preorder(Node* root){vector<int> v;stack<Node*> st;st.push(root);while(st.empty() == false){ Node* curr = st.top(); st.pop(); v.push_back(curr->data); if(curr->right){ st.push(curr->right); } if(curr->left){ st.push(curr->left); }}return v;}"
},
{
"code": null,
"e": 2932,
"s": 2930,
"text": "0"
},
{
"code": null,
"e": 2941,
"s": 2932,
"text": "mangy007"
},
{
"code": null,
"e": 2967,
"s": 2941,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2969,
"s": 2967,
"text": "0"
},
{
"code": null,
"e": 2992,
"s": 2969,
"text": "meanm0nst3r2 weeks ago"
},
{
"code": null,
"e": 3223,
"s": 2992,
"text": "What's the error?someone please commentCode:vector <int> preorder(Node* root){ // Your code here Node* curr=root; vector<int> v; if(!curr) return v; v.push_back(curr->data); preorder(curr->left); preorder(curr->right); return v;}"
},
{
"code": null,
"e": 3225,
"s": 3223,
"text": "0"
},
{
"code": null,
"e": 3248,
"s": 3225,
"text": "sagrikasoni3 weeks ago"
},
{
"code": null,
"e": 3262,
"s": 3248,
"text": "JAVA Solution"
},
{
"code": null,
"e": 3737,
"s": 3262,
"text": " static ArrayList<Integer> preorder(Node root)\n {\n ArrayList<Integer> arr = new ArrayList<Integer>();\n if(root==null) return arr;\n Stack<Node> q = new Stack<Node>();\n q.push(root);\n while(!q.isEmpty()){\n Node curr = q.pop();\n arr.add(curr.data);\n if(curr.right!=null)\n q.push(curr.right);\n if(curr.left!=null)\n q.push(curr.left);\n \n }\n \n return arr;\n }"
},
{
"code": null,
"e": 3739,
"s": 3737,
"text": "0"
},
{
"code": null,
"e": 3766,
"s": 3739,
"text": "talmeezahmed7863 weeks ago"
},
{
"code": null,
"e": 4718,
"s": 3766,
"text": "#Iterative python solution, for more performance \n#replace the queue with deque\n\ndef preorder(root):\n \n # code here\n result = []\n\n # initialize our process queue\n queue = []\n size = 0\n\n # push the root node to our queue\n queue.append(root)\n size = size + 1\n\n while (size > 0):\n\n # process the node at front of queue\n currentNode = queue[0]\n queue = queue[1:]\n size = size - 1\n\n # process the root first\n if (currentNode.data != None):\n result.append(currentNode.data)\n \n # process the right node\n if (currentNode.right and currentNode.right.data != None):\n queue.insert(0, currentNode.right)\n size = size + 1\n \n # process the left node\n if (currentNode.left and currentNode.left.data != None):\n queue.insert(0, currentNode.left)\n size = size + 1\n\n \n\n return result\n"
},
{
"code": null,
"e": 4720,
"s": 4718,
"text": "0"
},
{
"code": null,
"e": 4740,
"s": 4720,
"text": "bsbh20is1 month ago"
},
{
"code": null,
"e": 4756,
"s": 4740,
"text": "int arr[10000];"
},
{
"code": null,
"e": 4909,
"s": 4756,
"text": "void pre(struct Node*node,int *i){ if(node==NULL) return; arr[(*i)]=node->data; (*i)=(*i)+1; pre(node->left,i); pre(node->right,i); }"
},
{
"code": null,
"e": 5079,
"s": 4909,
"text": "int* preorder(struct Node* root){ //code here int ind=0; pre(root,&ind); return arr; //do not change the default values(i.e -1) in the unused array indices.}"
},
{
"code": null,
"e": 5225,
"s": 5079,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5261,
"s": 5225,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5271,
"s": 5261,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5281,
"s": 5271,
"text": "\nContest\n"
},
{
"code": null,
"e": 5344,
"s": 5281,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5492,
"s": 5344,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5700,
"s": 5492,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5806,
"s": 5700,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Detect Cycle in a an Undirected Graph | To detect if there is any cycle in the undirected graph or not, we will use the DFS traversal for the given graph. For every visited vertex v, when we have found any adjacent vertex u, such that u is already visited, and u is not the parent of vertex v. Then one cycle is detected.
We will assume that there are no parallel edges for any pair of vertices.
Input and Output:
Adjacency matrix
0 1 0 0 0
1 0 1 1 0
0 1 0 0 1
0 1 0 0 1
0 0 1 1 0
Output:
The graph has cycle.
dfs(vertex, visited, parent)
Input: The start vertex, the visited set, and the parent node of the vertex.Output: True a cycle is found.Begin
add vertex in the visited set
for all vertex v which is adjacent with vertex, do
if v = parent, then
return true
if v is not in the visited set, then
return true
if dfs(v, visited, vertex) is true, then
return true
done
return false
End hasCycle(graph)
Input: The given graph.
Output: True when a cycle has found.Begin
for all vertex v in the graph, do
if v is not in the visited set, then
go for next iteration
if dfs(v, visited, φ) is true, then //parent of v is null
return true
return false
done
End
Input: The start vertex, the visited set, and the parent node of the vertex.
#include<iostream>
#include<set>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {
{0, 1, 0, 0, 0},
{1, 0, 1, 1, 0},
{0, 1, 0, 0, 1},
{0, 1, 0, 0, 1},
{0, 0, 1, 1, 0}
};
bool dfs(int vertex, set<int>&visited, int parent) {
visited.insert(vertex);
for(int v = 0; v<NODE; v++) {
if(graph[vertex][v]) {
if(v == parent) //if v is the parent not move that direction
continue;
if(visited.find(v) != visited.end()) //if v is already visited
return true;
if(dfs(v, visited, vertex))
return true;
}
}
return false;
}
bool hasCycle() {
set<int> visited; //visited set
for(int v = 0; v<NODE; v++) {
if(visited.find(v) != visited.end()) //when visited holds v, jump to next iteration
continue;
if(dfs(v, visited, -1)) { //-1 as no parent of starting vertex
return true;
}
}
return false;
}
int main() {
bool res;
res = hasCycle();
if(res)
cout << "The graph has cycle." << endl;
else
cout << "The graph has no cycle." << endl;
}
The graph has cycle. | [
{
"code": null,
"e": 1345,
"s": 1062,
"text": "To detect if there is any cycle in the undirected graph or not, we will use the DFS traversal for the given graph. For every visited vertex v, when we have found any adjacent vertex u, such that u is already visited, and u is not the parent of vertex v. Then one cycle is detected. "
},
{
"code": null,
"e": 1419,
"s": 1345,
"text": "We will assume that there are no parallel edges for any pair of vertices."
},
{
"code": null,
"e": 1558,
"s": 1419,
"text": "Input and Output:\nAdjacency matrix\n \n 0 1 0 0 0\n 1 0 1 1 0\n 0 1 0 0 1\n 0 1 0 0 1\n 0 0 1 1 0\n\nOutput:\nThe graph has cycle."
},
{
"code": null,
"e": 2308,
"s": 1558,
"text": "dfs(vertex, visited, parent)\nInput: The start vertex, the visited set, and the parent node of the vertex.Output: True a cycle is found.Begin\n add vertex in the visited set\n for all vertex v which is adjacent with vertex, do\n if v = parent, then\n return true\n if v is not in the visited set, then\n return true\n if dfs(v, visited, vertex) is true, then\n return true\n done\n return false\nEnd hasCycle(graph)\n\nInput: The given graph.\n\nOutput: True when a cycle has found.Begin\n for all vertex v in the graph, do\n if v is not in the visited set, then\n go for next iteration\n if dfs(v, visited, φ) is true, then //parent of v is null\n return true\n return false\n done\nEnd"
},
{
"code": null,
"e": 2387,
"s": 2310,
"text": "Input: The start vertex, the visited set, and the parent node of the vertex."
},
{
"code": null,
"e": 3512,
"s": 2387,
"text": "#include<iostream>\n#include<set>\n#define NODE 5\nusing namespace std;\n\nint graph[NODE][NODE] = {\n {0, 1, 0, 0, 0},\n {1, 0, 1, 1, 0},\n {0, 1, 0, 0, 1},\n {0, 1, 0, 0, 1},\n {0, 0, 1, 1, 0}\n};\n\nbool dfs(int vertex, set<int>&visited, int parent) {\n visited.insert(vertex);\n for(int v = 0; v<NODE; v++) {\n if(graph[vertex][v]) {\n if(v == parent) //if v is the parent not move that direction\n continue;\n if(visited.find(v) != visited.end()) //if v is already visited\n return true;\n if(dfs(v, visited, vertex))\n return true;\n }\n }\n return false;\n}\n\nbool hasCycle() {\n set<int> visited; //visited set\n for(int v = 0; v<NODE; v++) {\n if(visited.find(v) != visited.end()) //when visited holds v, jump to next iteration\n continue;\n if(dfs(v, visited, -1)) { //-1 as no parent of starting vertex\n return true;\n }\n }\n return false;\n}\n\nint main() {\n bool res;\n res = hasCycle();\n if(res)\n cout << \"The graph has cycle.\" << endl;\n else\n cout << \"The graph has no cycle.\" << endl;\n}"
},
{
"code": null,
"e": 3533,
"s": 3512,
"text": "The graph has cycle."
}
]
|
How to delete the local group from the windows system using PowerShell? | To delete the local group from the windows system using PowerShell, you need to use the RemoveLocalGroup command as shown below.
Remove-LocalGroup -Name TestGroup
In the above example, the local group name TestGroup will be removed from the local system. To remove the local group from the remote systems, we can use Invoke-Command as shown in the below example.
Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock
{Remove-LocalGroup -Name TestGroup}
Remove-Localgroup command is supported from the PowerShell version 5.1 onwards and this command is a part of Microsoft.PowerShell.LocalAccounts module. If you have the PS version 5.1 or the local accounts module not available then you can use the cmd command.
net localgroup testgroup /delete
Similarly, you can run the above command on the remote system using Invoke-Command method.
Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{
net localgroup TestGroup /delete
} | [
{
"code": null,
"e": 1191,
"s": 1062,
"text": "To delete the local group from the windows system using PowerShell, you need to use the RemoveLocalGroup command as shown below."
},
{
"code": null,
"e": 1225,
"s": 1191,
"text": "Remove-LocalGroup -Name TestGroup"
},
{
"code": null,
"e": 1425,
"s": 1225,
"text": "In the above example, the local group name TestGroup will be removed from the local system. To remove the local group from the remote systems, we can use Invoke-Command as shown in the below example."
},
{
"code": null,
"e": 1531,
"s": 1425,
"text": "Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock\n{Remove-LocalGroup -Name TestGroup}"
},
{
"code": null,
"e": 1791,
"s": 1531,
"text": "Remove-Localgroup command is supported from the PowerShell version 5.1 onwards and this command is a part of Microsoft.PowerShell.LocalAccounts module. If you have the PS version 5.1 or the local accounts module not available then you can use the cmd command."
},
{
"code": null,
"e": 1824,
"s": 1791,
"text": "net localgroup testgroup /delete"
},
{
"code": null,
"e": 1915,
"s": 1824,
"text": "Similarly, you can run the above command on the remote system using Invoke-Command method."
},
{
"code": null,
"e": 2024,
"s": 1915,
"text": "Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{\n net localgroup TestGroup /delete\n}"
}
]
|
How to create a Number Input using jQuery Mobile ? - GeeksforGeeks | 14 Dec, 2020
jQuery Mobile is a web based technology used to make responsive content that can be accessed on all smartphones, tablets and desktops In this article, we will be creating a number input area using jQuery Mobile.
Approach: Add jQuery Mobile scripts needed for your project.
<link rel=”stylesheet” href=”http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css” />
<script src=”http://code.jquery.com/jquery-1.11.1.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js”></script>
Example: We will create a number input area using jQuery Mobile. We use type=”number” attribute to enter number only and use data-clear-btn=”true” attribute to clear the input text.
HTML
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" /> <script src="http://code.jquery.com/jquery-1.11.1.min.js"> </script> <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"> </script></head> <body> <center> <h1>GeeksforGeeks</h1> <h4> Design Number Input using jQuery Mobile </h4> <form style="width: 50%;"> <label for="numberInput1">Number Input Area:</label> <input type="number" data-clear-btn="false" name="numberInput1" id="numberInput1" value="" placeholder="Enter Number..."> <label for="numberInput2"> Number Input Area with clear button: </label> <input type="number" data-clear-btn="true" name="numberInput2" id="numberInput2" value="" placeholder="Enter Number..."> <label for="numberInput3"> Number and pattern Input Area: </label> <input type="number" data-clear-btn="false" name="numberInput3" pattern="[0-9]*" id="numberInput3" value="" placeholder="Enter Number and pattern..."> <label for="numberInput4"> Number and pattern Input Area with clear button: </label> <input type="number" data-clear-btn="true" name="numberInput4" pattern="[0-9]*" id="numberInput4" value="" placeholder="Enter Number and pattern..."> </form> </center></body> </html>
Output:
jQuery-Misc
jQuery-Mobile
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
How to get the value in an input text box using jQuery ?
jQuery | parent() & parents() with Examples
Difference Between JavaScript and jQuery
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
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 25755,
"s": 25727,
"text": "\n14 Dec, 2020"
},
{
"code": null,
"e": 25967,
"s": 25755,
"text": "jQuery Mobile is a web based technology used to make responsive content that can be accessed on all smartphones, tablets and desktops In this article, we will be creating a number input area using jQuery Mobile."
},
{
"code": null,
"e": 26028,
"s": 25967,
"text": "Approach: Add jQuery Mobile scripts needed for your project."
},
{
"code": null,
"e": 26125,
"s": 26028,
"text": "<link rel=”stylesheet” href=”http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css” />"
},
{
"code": null,
"e": 26193,
"s": 26125,
"text": "<script src=”http://code.jquery.com/jquery-1.11.1.min.js”></script>"
},
{
"code": null,
"e": 26280,
"s": 26193,
"text": "<script src=”http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js”></script>"
},
{
"code": null,
"e": 26462,
"s": 26280,
"text": "Example: We will create a number input area using jQuery Mobile. We use type=”number” attribute to enter number only and use data-clear-btn=”true” attribute to clear the input text."
},
{
"code": null,
"e": 26467,
"s": 26462,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css\" /> <script src=\"http://code.jquery.com/jquery-1.11.1.min.js\"> </script> <script src=\"http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js\"> </script></head> <body> <center> <h1>GeeksforGeeks</h1> <h4> Design Number Input using jQuery Mobile </h4> <form style=\"width: 50%;\"> <label for=\"numberInput1\">Number Input Area:</label> <input type=\"number\" data-clear-btn=\"false\" name=\"numberInput1\" id=\"numberInput1\" value=\"\" placeholder=\"Enter Number...\"> <label for=\"numberInput2\"> Number Input Area with clear button: </label> <input type=\"number\" data-clear-btn=\"true\" name=\"numberInput2\" id=\"numberInput2\" value=\"\" placeholder=\"Enter Number...\"> <label for=\"numberInput3\"> Number and pattern Input Area: </label> <input type=\"number\" data-clear-btn=\"false\" name=\"numberInput3\" pattern=\"[0-9]*\" id=\"numberInput3\" value=\"\" placeholder=\"Enter Number and pattern...\"> <label for=\"numberInput4\"> Number and pattern Input Area with clear button: </label> <input type=\"number\" data-clear-btn=\"true\" name=\"numberInput4\" pattern=\"[0-9]*\" id=\"numberInput4\" value=\"\" placeholder=\"Enter Number and pattern...\"> </form> </center></body> </html>",
"e": 28105,
"s": 26467,
"text": null
},
{
"code": null,
"e": 28113,
"s": 28105,
"text": "Output:"
},
{
"code": null,
"e": 28125,
"s": 28113,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 28139,
"s": 28125,
"text": "jQuery-Mobile"
},
{
"code": null,
"e": 28146,
"s": 28139,
"text": "JQuery"
},
{
"code": null,
"e": 28163,
"s": 28146,
"text": "Web Technologies"
},
{
"code": null,
"e": 28261,
"s": 28163,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28334,
"s": 28261,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 28357,
"s": 28334,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 28414,
"s": 28357,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 28458,
"s": 28414,
"text": "jQuery | parent() & parents() with Examples"
},
{
"code": null,
"e": 28499,
"s": 28458,
"text": "Difference Between JavaScript and jQuery"
},
{
"code": null,
"e": 28541,
"s": 28499,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28574,
"s": 28541,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28617,
"s": 28574,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28679,
"s": 28617,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
Stringize and Token-pasting operator in C | In this section we will see what are the Stringize operator and Token Pasting operator in C. The Stringize operator is a preprocessor operator. It sends commands to compiler to convert a token into string. We use this operator at the macro definition.
Using stringize operator we can convert some text into string without using any quotes.
#include<stdio.h>
#define STR_PRINT(x) #x
main() {
printf(STR_PRINT(This is a string without double quotes));
}
This is a string without double quotes
The Token Pasting operator is a preprocessor operator. It sends commands to compiler to add or concatenate two tokens into one string. We use this operator at the macro definition.
#include<stdio.h>
#define STR_CONCAT(x, y) x##y
main() {
printf("%d", STR_CONCAT(20, 50));
}
2050 | [
{
"code": null,
"e": 1314,
"s": 1062,
"text": "In this section we will see what are the Stringize operator and Token Pasting operator in C. The Stringize operator is a preprocessor operator. It sends commands to compiler to convert a token into string. We use this operator at the macro definition."
},
{
"code": null,
"e": 1402,
"s": 1314,
"text": "Using stringize operator we can convert some text into string without using any quotes."
},
{
"code": null,
"e": 1517,
"s": 1402,
"text": "#include<stdio.h>\n#define STR_PRINT(x) #x\nmain() {\n printf(STR_PRINT(This is a string without double quotes));\n}"
},
{
"code": null,
"e": 1556,
"s": 1517,
"text": "This is a string without double quotes"
},
{
"code": null,
"e": 1737,
"s": 1556,
"text": "The Token Pasting operator is a preprocessor operator. It sends commands to compiler to add or concatenate two tokens into one string. We use this operator at the macro definition."
},
{
"code": null,
"e": 1833,
"s": 1737,
"text": "#include<stdio.h>\n#define STR_CONCAT(x, y) x##y\nmain() {\n printf(\"%d\", STR_CONCAT(20, 50));\n}"
},
{
"code": null,
"e": 1838,
"s": 1833,
"text": "2050"
}
]
|
Dynamic ScrollView in Kotlin - GeeksforGeeks | 18 Feb, 2021
In Android ScrollView incorporates multiple views within itself and allows them to be scrolled.
In this article we will be discussing how to programmatically create a Scroll view in Kotlin .
Let’s start by first creating a project in Android Studio. To do so, follow these instructions:
Click on File, then New and then New Project and give name whatever you like
Then, select Kotlin language Support and click next button.
Select minimum SDK, whatever you need.
Select Empty activity and then click finish.
Second step is to design our layout page. Here, we will use the LinearLayout to get the Scroll View from the Kotlin file.
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/layout" tools:context=".MainActivity"> </LinearLayout>
Adding Images
We will be needing some images to be used in application. You can use the images that you like but the images need to be copied from our local computer path to app/res/drawable folder.
Open app/src/main/java/yourPackageName/MainActivity.kt. In this file, we declare a variable ScrollView to create the Scroll View widget like this:
val scrollView = ScrollView(this)
val layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT)
scrollView.layoutParams = layoutParams
then add the widget in layout using this
linearLayout1?.addView(scrollView)
package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundleimport android.view.Gravityimport android.view.ViewGroupimport android.widget.ImageViewimport android.widget.LinearLayoutimport android.widget.ScrollView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val scrollView = ScrollView(this) val layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) scrollView.layoutParams = layoutParams val linearLayout = LinearLayout(this) val linearParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) linearLayout.orientation = LinearLayout.VERTICAL linearLayout.layoutParams = linearParams scrollView.addView(linearLayout) val imageView1 = ImageView(this) val params1 = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) //setting margin params1.setMargins(0, 30, 0, 30) //aligning the layout to center of the screen params1.gravity = Gravity.CENTER imageView1.setLayoutParams(params1) //setting our own downloaded/custom image to the imageView imageView1.setImageResource(R.drawable.image1) linearLayout.addView(imageView1) val imageView2 = ImageView(this) val params2 = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) params2.setMargins(0, 0, 0, 30) params2.gravity = Gravity.CENTER imageView2.setLayoutParams(params2) imageView2.setImageResource(R.drawable.image2) linearLayout.addView(imageView2) val imageView3 = ImageView(this) val params3 = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) params3.setMargins(0, 0, 0, 30) params3.gravity = Gravity.CENTER imageView3.setLayoutParams(params3) imageView3.setImageResource(R.drawable.image3) linearLayout.addView(imageView3) val imageView4 = ImageView(this) val params4 = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) params4.setMargins(0, 0, 0, 30) params4.gravity = Gravity.CENTER imageView4.setLayoutParams(params4) imageView4.setImageResource(R.drawable.image4) linearLayout.addView(imageView4) val linearLayout1 = findViewById<LinearLayout>(R.id.layout) linearLayout1?.addView(scrollView) }}
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="i.apps.myapplication"> <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>
Android-View
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Services in Android with Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Services in Android with Example
Content Providers in Android with Example
Android UI Layouts
Android RecyclerView in Kotlin | [
{
"code": null,
"e": 24036,
"s": 24008,
"text": "\n18 Feb, 2021"
},
{
"code": null,
"e": 24132,
"s": 24036,
"text": "In Android ScrollView incorporates multiple views within itself and allows them to be scrolled."
},
{
"code": null,
"e": 24227,
"s": 24132,
"text": "In this article we will be discussing how to programmatically create a Scroll view in Kotlin ."
},
{
"code": null,
"e": 24323,
"s": 24227,
"text": "Let’s start by first creating a project in Android Studio. To do so, follow these instructions:"
},
{
"code": null,
"e": 24400,
"s": 24323,
"text": "Click on File, then New and then New Project and give name whatever you like"
},
{
"code": null,
"e": 24460,
"s": 24400,
"text": "Then, select Kotlin language Support and click next button."
},
{
"code": null,
"e": 24499,
"s": 24460,
"text": "Select minimum SDK, whatever you need."
},
{
"code": null,
"e": 24544,
"s": 24499,
"text": "Select Empty activity and then click finish."
},
{
"code": null,
"e": 24666,
"s": 24544,
"text": "Second step is to design our layout page. Here, we will use the LinearLayout to get the Scroll View from the Kotlin file."
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/layout\" tools:context=\".MainActivity\"> </LinearLayout>",
"e": 25075,
"s": 24666,
"text": null
},
{
"code": null,
"e": 25089,
"s": 25075,
"text": "Adding Images"
},
{
"code": null,
"e": 25274,
"s": 25089,
"text": "We will be needing some images to be used in application. You can use the images that you like but the images need to be copied from our local computer path to app/res/drawable folder."
},
{
"code": null,
"e": 25421,
"s": 25274,
"text": "Open app/src/main/java/yourPackageName/MainActivity.kt. In this file, we declare a variable ScrollView to create the Scroll View widget like this:"
},
{
"code": null,
"e": 25648,
"s": 25421,
"text": "val scrollView = ScrollView(this)\n val layoutParams = LinearLayout.LayoutParams(\n ViewGroup.LayoutParams.MATCH_PARENT, \n ViewGroup.LayoutParams.MATCH_PARENT)\n scrollView.layoutParams = layoutParams\n"
},
{
"code": null,
"e": 25689,
"s": 25648,
"text": "then add the widget in layout using this"
},
{
"code": null,
"e": 25724,
"s": 25689,
"text": "linearLayout1?.addView(scrollView)"
},
{
"code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundleimport android.view.Gravityimport android.view.ViewGroupimport android.widget.ImageViewimport android.widget.LinearLayoutimport android.widget.ScrollView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val scrollView = ScrollView(this) val layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) scrollView.layoutParams = layoutParams val linearLayout = LinearLayout(this) val linearParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) linearLayout.orientation = LinearLayout.VERTICAL linearLayout.layoutParams = linearParams scrollView.addView(linearLayout) val imageView1 = ImageView(this) val params1 = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) //setting margin params1.setMargins(0, 30, 0, 30) //aligning the layout to center of the screen params1.gravity = Gravity.CENTER imageView1.setLayoutParams(params1) //setting our own downloaded/custom image to the imageView imageView1.setImageResource(R.drawable.image1) linearLayout.addView(imageView1) val imageView2 = ImageView(this) val params2 = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) params2.setMargins(0, 0, 0, 30) params2.gravity = Gravity.CENTER imageView2.setLayoutParams(params2) imageView2.setImageResource(R.drawable.image2) linearLayout.addView(imageView2) val imageView3 = ImageView(this) val params3 = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) params3.setMargins(0, 0, 0, 30) params3.gravity = Gravity.CENTER imageView3.setLayoutParams(params3) imageView3.setImageResource(R.drawable.image3) linearLayout.addView(imageView3) val imageView4 = ImageView(this) val params4 = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) params4.setMargins(0, 0, 0, 30) params4.gravity = Gravity.CENTER imageView4.setLayoutParams(params4) imageView4.setImageResource(R.drawable.image4) linearLayout.addView(imageView4) val linearLayout1 = findViewById<LinearLayout>(R.id.layout) linearLayout1?.addView(scrollView) }}",
"e": 28629,
"s": 25724,
"text": null
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"i.apps.myapplication\"> <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>",
"e": 29358,
"s": 28629,
"text": null
},
{
"code": null,
"e": 29371,
"s": 29358,
"text": "Android-View"
},
{
"code": null,
"e": 29386,
"s": 29371,
"text": "Kotlin Android"
},
{
"code": null,
"e": 29393,
"s": 29386,
"text": "Picked"
},
{
"code": null,
"e": 29401,
"s": 29393,
"text": "Android"
},
{
"code": null,
"e": 29408,
"s": 29401,
"text": "Kotlin"
},
{
"code": null,
"e": 29416,
"s": 29408,
"text": "Android"
},
{
"code": null,
"e": 29514,
"s": 29416,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29572,
"s": 29514,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 29615,
"s": 29572,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 29648,
"s": 29615,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 29690,
"s": 29648,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 29721,
"s": 29690,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 29764,
"s": 29721,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 29797,
"s": 29764,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 29839,
"s": 29797,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 29858,
"s": 29839,
"text": "Android UI Layouts"
}
]
|
Java - The Collection Algorithms | The collections framework defines several algorithms that can be applied to collections and maps.
These algorithms are defined as static methods within the Collections class. Several of the methods can throw a ClassCastException, which occurs when an attempt is made to compare incompatible types, or an UnsupportedOperationException, which occurs when an attempt is made to modify an unmodifiable collection.
The methods defined in collection framework's algorithm are summarized in the following table −
static int binarySearch(List list, Object value, Comparator c)
Searches for value in the list ordered according to c. Returns the position of value in list, or -1 if value is not found.
static int binarySearch(List list, Object value)
Searches for value in the list. The list must be sorted. Returns the position of value in list, or -1 if value is not found.
static void copy(List list1, List list2)
Copies the elements of list2 to list1.
static Enumeration enumeration(Collection c)
Returns an enumeration over c.
static void fill(List list, Object obj)
Assigns obj to each element of the list.
static int indexOfSubList(List list, List subList)
Searches list for the first occurrence of subList. Returns the index of the first match, or .1 if no match is found.
static int lastIndexOfSubList(List list, List subList)
Searches list for the last occurrence of subList. Returns the index of the last match, or .1 if no match is found.
static ArrayList list(Enumeration enum)
Returns an ArrayList that contains the elements of enum.
static Object max(Collection c, Comparator comp)
Returns the maximum element in c as determined by comp.
static Object max(Collection c)
Returns the maximum element in c as determined by natural ordering. The collection need not be sorted.
static Object min(Collection c, Comparator comp)
Returns the minimum element in c as determined by comp. The collection need not be sorted.
static Object min(Collection c)
Returns the minimum element in c as determined by natural ordering.
static List nCopies(int num, Object obj)
Returns num copies of obj contained in an immutable list. num must be greater than or equal to zero.
static boolean replaceAll(List list, Object old, Object new)
Replaces all occurrences of old with new in the list. Returns true if at least one replacement occurred. Returns false, otherwise.
static void reverse(List list)
Reverses the sequence in list.
static Comparator reverseOrder( )
Returns a reverse comparator.
static void rotate(List list, int n)
Rotates list by n places to the right. To rotate left, use a negative value for n.
static void shuffle(List list, Random r)
Shuffles (i.e., randomizes) the elements in the list by using r as a source of random numbers.
static void shuffle(List list)
Shuffles (i.e., randomizes) the elements in list.
static Set singleton(Object obj)
Returns obj as an immutable set. This is an easy way to convert a single object into a set.
static List singletonList(Object obj)
Returns obj as an immutable list. This is an easy way to convert a single object into a list.
static Map singletonMap(Object k, Object v)
Returns the key/value pair k/v as an immutable map. This is an easy way to convert a single key/value pair into a map.
static void sort(List list, Comparator comp)
Sorts the elements of list as determined by comp.
static void sort(List list)
Sorts the elements of the list as determined by their natural ordering.
static void swap(List list, int idx1, int idx2)
Exchanges the elements in the list at the indices specified by idx1 and idx2.
static Collection synchronizedCollection(Collection c)
Returns a thread-safe collection backed by c.
static List synchronizedList(List list)
Returns a thread-safe list backed by list.
static Map synchronizedMap(Map m)
Returns a thread-safe map backed by m.
static Set synchronizedSet(Set s)
Returns a thread-safe set backed by s.
static SortedMap synchronizedSortedMap(SortedMap sm)
Returns a thread-safe sorted set backed by sm.
static SortedSet synchronizedSortedSet(SortedSet ss)
Returns a thread-safe set backed by ss.
static Collection unmodifiableCollection(Collection c)
Returns an unmodifiable collection backed by c.
static List unmodifiableList(List list)
Returns an unmodifiable list backed by the list.
static Map unmodifiableMap(Map m)
Returns an unmodifiable map backed by m.
static Set unmodifiableSet(Set s)
Returns an unmodifiable set backed by s.
static SortedMap unmodifiableSortedMap(SortedMap sm)
Returns an unmodifiable sorted map backed by sm.
static SortedSet unmodifiableSortedSet(SortedSet ss)
Returns an unmodifiable sorted set backed by ss.
Following is an example, which demonstrates various algorithms.
import java.util.*;
public class AlgorithmsDemo {
public static void main(String args[]) {
// Create and initialize linked list
LinkedList ll = new LinkedList();
ll.add(new Integer(-8));
ll.add(new Integer(20));
ll.add(new Integer(-20));
ll.add(new Integer(8));
// Create a reverse order comparator
Comparator r = Collections.reverseOrder();
// Sort list by using the comparator
Collections.sort(ll, r);
// Get iterator
Iterator li = ll.iterator();
System.out.print("List sorted in reverse: ");
while(li.hasNext()) {
System.out.print(li.next() + " ");
}
System.out.println();
Collections.shuffle(ll);
// display randomized list
li = ll.iterator();
System.out.print("List shuffled: ");
while(li.hasNext()) {
System.out.print(li.next() + " ");
}
System.out.println();
System.out.println("Minimum: " + Collections.min(ll));
System.out.println("Maximum: " + Collections.max(ll));
}
}
This will produce the following result −
List sorted in reverse: 20 8 -8 -20
List shuffled: 20 -20 8 -8
Minimum: -20
Maximum: 20
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2475,
"s": 2377,
"text": "The collections framework defines several algorithms that can be applied to collections and maps."
},
{
"code": null,
"e": 2787,
"s": 2475,
"text": "These algorithms are defined as static methods within the Collections class. Several of the methods can throw a ClassCastException, which occurs when an attempt is made to compare incompatible types, or an UnsupportedOperationException, which occurs when an attempt is made to modify an unmodifiable collection."
},
{
"code": null,
"e": 2883,
"s": 2787,
"text": "The methods defined in collection framework's algorithm are summarized in the following table −"
},
{
"code": null,
"e": 2946,
"s": 2883,
"text": "static int binarySearch(List list, Object value, Comparator c)"
},
{
"code": null,
"e": 3069,
"s": 2946,
"text": "Searches for value in the list ordered according to c. Returns the position of value in list, or -1 if value is not found."
},
{
"code": null,
"e": 3118,
"s": 3069,
"text": "static int binarySearch(List list, Object value)"
},
{
"code": null,
"e": 3243,
"s": 3118,
"text": "Searches for value in the list. The list must be sorted. Returns the position of value in list, or -1 if value is not found."
},
{
"code": null,
"e": 3284,
"s": 3243,
"text": "static void copy(List list1, List list2)"
},
{
"code": null,
"e": 3323,
"s": 3284,
"text": "Copies the elements of list2 to list1."
},
{
"code": null,
"e": 3368,
"s": 3323,
"text": "static Enumeration enumeration(Collection c)"
},
{
"code": null,
"e": 3399,
"s": 3368,
"text": "Returns an enumeration over c."
},
{
"code": null,
"e": 3439,
"s": 3399,
"text": "static void fill(List list, Object obj)"
},
{
"code": null,
"e": 3480,
"s": 3439,
"text": "Assigns obj to each element of the list."
},
{
"code": null,
"e": 3531,
"s": 3480,
"text": "static int indexOfSubList(List list, List subList)"
},
{
"code": null,
"e": 3648,
"s": 3531,
"text": "Searches list for the first occurrence of subList. Returns the index of the first match, or .1 if no match is found."
},
{
"code": null,
"e": 3703,
"s": 3648,
"text": "static int lastIndexOfSubList(List list, List subList)"
},
{
"code": null,
"e": 3818,
"s": 3703,
"text": "Searches list for the last occurrence of subList. Returns the index of the last match, or .1 if no match is found."
},
{
"code": null,
"e": 3858,
"s": 3818,
"text": "static ArrayList list(Enumeration enum)"
},
{
"code": null,
"e": 3915,
"s": 3858,
"text": "Returns an ArrayList that contains the elements of enum."
},
{
"code": null,
"e": 3964,
"s": 3915,
"text": "static Object max(Collection c, Comparator comp)"
},
{
"code": null,
"e": 4020,
"s": 3964,
"text": "Returns the maximum element in c as determined by comp."
},
{
"code": null,
"e": 4052,
"s": 4020,
"text": "static Object max(Collection c)"
},
{
"code": null,
"e": 4155,
"s": 4052,
"text": "Returns the maximum element in c as determined by natural ordering. The collection need not be sorted."
},
{
"code": null,
"e": 4204,
"s": 4155,
"text": "static Object min(Collection c, Comparator comp)"
},
{
"code": null,
"e": 4295,
"s": 4204,
"text": "Returns the minimum element in c as determined by comp. The collection need not be sorted."
},
{
"code": null,
"e": 4327,
"s": 4295,
"text": "static Object min(Collection c)"
},
{
"code": null,
"e": 4395,
"s": 4327,
"text": "Returns the minimum element in c as determined by natural ordering."
},
{
"code": null,
"e": 4436,
"s": 4395,
"text": "static List nCopies(int num, Object obj)"
},
{
"code": null,
"e": 4537,
"s": 4436,
"text": "Returns num copies of obj contained in an immutable list. num must be greater than or equal to zero."
},
{
"code": null,
"e": 4598,
"s": 4537,
"text": "static boolean replaceAll(List list, Object old, Object new)"
},
{
"code": null,
"e": 4729,
"s": 4598,
"text": "Replaces all occurrences of old with new in the list. Returns true if at least one replacement occurred. Returns false, otherwise."
},
{
"code": null,
"e": 4760,
"s": 4729,
"text": "static void reverse(List list)"
},
{
"code": null,
"e": 4791,
"s": 4760,
"text": "Reverses the sequence in list."
},
{
"code": null,
"e": 4825,
"s": 4791,
"text": "static Comparator reverseOrder( )"
},
{
"code": null,
"e": 4855,
"s": 4825,
"text": "Returns a reverse comparator."
},
{
"code": null,
"e": 4892,
"s": 4855,
"text": "static void rotate(List list, int n)"
},
{
"code": null,
"e": 4975,
"s": 4892,
"text": "Rotates list by n places to the right. To rotate left, use a negative value for n."
},
{
"code": null,
"e": 5016,
"s": 4975,
"text": "static void shuffle(List list, Random r)"
},
{
"code": null,
"e": 5111,
"s": 5016,
"text": "Shuffles (i.e., randomizes) the elements in the list by using r as a source of random numbers."
},
{
"code": null,
"e": 5142,
"s": 5111,
"text": "static void shuffle(List list)"
},
{
"code": null,
"e": 5192,
"s": 5142,
"text": "Shuffles (i.e., randomizes) the elements in list."
},
{
"code": null,
"e": 5225,
"s": 5192,
"text": "static Set singleton(Object obj)"
},
{
"code": null,
"e": 5317,
"s": 5225,
"text": "Returns obj as an immutable set. This is an easy way to convert a single object into a set."
},
{
"code": null,
"e": 5355,
"s": 5317,
"text": "static List singletonList(Object obj)"
},
{
"code": null,
"e": 5449,
"s": 5355,
"text": "Returns obj as an immutable list. This is an easy way to convert a single object into a list."
},
{
"code": null,
"e": 5493,
"s": 5449,
"text": "static Map singletonMap(Object k, Object v)"
},
{
"code": null,
"e": 5612,
"s": 5493,
"text": "Returns the key/value pair k/v as an immutable map. This is an easy way to convert a single key/value pair into a map."
},
{
"code": null,
"e": 5657,
"s": 5612,
"text": "static void sort(List list, Comparator comp)"
},
{
"code": null,
"e": 5707,
"s": 5657,
"text": "Sorts the elements of list as determined by comp."
},
{
"code": null,
"e": 5735,
"s": 5707,
"text": "static void sort(List list)"
},
{
"code": null,
"e": 5807,
"s": 5735,
"text": "Sorts the elements of the list as determined by their natural ordering."
},
{
"code": null,
"e": 5855,
"s": 5807,
"text": "static void swap(List list, int idx1, int idx2)"
},
{
"code": null,
"e": 5933,
"s": 5855,
"text": "Exchanges the elements in the list at the indices specified by idx1 and idx2."
},
{
"code": null,
"e": 5988,
"s": 5933,
"text": "static Collection synchronizedCollection(Collection c)"
},
{
"code": null,
"e": 6034,
"s": 5988,
"text": "Returns a thread-safe collection backed by c."
},
{
"code": null,
"e": 6074,
"s": 6034,
"text": "static List synchronizedList(List list)"
},
{
"code": null,
"e": 6117,
"s": 6074,
"text": "Returns a thread-safe list backed by list."
},
{
"code": null,
"e": 6151,
"s": 6117,
"text": "static Map synchronizedMap(Map m)"
},
{
"code": null,
"e": 6190,
"s": 6151,
"text": "Returns a thread-safe map backed by m."
},
{
"code": null,
"e": 6224,
"s": 6190,
"text": "static Set synchronizedSet(Set s)"
},
{
"code": null,
"e": 6263,
"s": 6224,
"text": "Returns a thread-safe set backed by s."
},
{
"code": null,
"e": 6316,
"s": 6263,
"text": "static SortedMap synchronizedSortedMap(SortedMap sm)"
},
{
"code": null,
"e": 6363,
"s": 6316,
"text": "Returns a thread-safe sorted set backed by sm."
},
{
"code": null,
"e": 6416,
"s": 6363,
"text": "static SortedSet synchronizedSortedSet(SortedSet ss)"
},
{
"code": null,
"e": 6456,
"s": 6416,
"text": "Returns a thread-safe set backed by ss."
},
{
"code": null,
"e": 6511,
"s": 6456,
"text": "static Collection unmodifiableCollection(Collection c)"
},
{
"code": null,
"e": 6559,
"s": 6511,
"text": "Returns an unmodifiable collection backed by c."
},
{
"code": null,
"e": 6599,
"s": 6559,
"text": "static List unmodifiableList(List list)"
},
{
"code": null,
"e": 6648,
"s": 6599,
"text": "Returns an unmodifiable list backed by the list."
},
{
"code": null,
"e": 6682,
"s": 6648,
"text": "static Map unmodifiableMap(Map m)"
},
{
"code": null,
"e": 6723,
"s": 6682,
"text": "Returns an unmodifiable map backed by m."
},
{
"code": null,
"e": 6757,
"s": 6723,
"text": "static Set unmodifiableSet(Set s)"
},
{
"code": null,
"e": 6798,
"s": 6757,
"text": "Returns an unmodifiable set backed by s."
},
{
"code": null,
"e": 6851,
"s": 6798,
"text": "static SortedMap unmodifiableSortedMap(SortedMap sm)"
},
{
"code": null,
"e": 6900,
"s": 6851,
"text": "Returns an unmodifiable sorted map backed by sm."
},
{
"code": null,
"e": 6953,
"s": 6900,
"text": "static SortedSet unmodifiableSortedSet(SortedSet ss)"
},
{
"code": null,
"e": 7002,
"s": 6953,
"text": "Returns an unmodifiable sorted set backed by ss."
},
{
"code": null,
"e": 7066,
"s": 7002,
"text": "Following is an example, which demonstrates various algorithms."
},
{
"code": null,
"e": 8171,
"s": 7066,
"text": "import java.util.*;\npublic class AlgorithmsDemo {\n\n public static void main(String args[]) {\n \n // Create and initialize linked list\n LinkedList ll = new LinkedList();\n ll.add(new Integer(-8));\n ll.add(new Integer(20));\n ll.add(new Integer(-20));\n ll.add(new Integer(8));\n \n // Create a reverse order comparator\n Comparator r = Collections.reverseOrder();\n \n // Sort list by using the comparator\n Collections.sort(ll, r);\n \n // Get iterator\n Iterator li = ll.iterator();\n System.out.print(\"List sorted in reverse: \");\n \n while(li.hasNext()) {\n System.out.print(li.next() + \" \");\n }\n System.out.println();\n Collections.shuffle(ll);\n \n // display randomized list\n li = ll.iterator();\n System.out.print(\"List shuffled: \");\n \n while(li.hasNext()) {\n System.out.print(li.next() + \" \");\n }\n\n System.out.println();\n System.out.println(\"Minimum: \" + Collections.min(ll));\n System.out.println(\"Maximum: \" + Collections.max(ll));\n }\n}"
},
{
"code": null,
"e": 8212,
"s": 8171,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 8301,
"s": 8212,
"text": "List sorted in reverse: 20 8 -8 -20\nList shuffled: 20 -20 8 -8\nMinimum: -20\nMaximum: 20\n"
},
{
"code": null,
"e": 8334,
"s": 8301,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8350,
"s": 8334,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8383,
"s": 8350,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8399,
"s": 8383,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8434,
"s": 8399,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8448,
"s": 8434,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8482,
"s": 8448,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8496,
"s": 8482,
"text": " Tushar Kale"
},
{
"code": null,
"e": 8533,
"s": 8496,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 8548,
"s": 8533,
"text": " Monica Mittal"
},
{
"code": null,
"e": 8581,
"s": 8548,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8600,
"s": 8581,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8607,
"s": 8600,
"text": " Print"
},
{
"code": null,
"e": 8618,
"s": 8607,
"text": " Add Notes"
}
]
|
Max Sum Subarray of size K | Practice | GeeksforGeeks | Given an array of integers Arr of size N and a number K. Return the maximum sum of a subarray of size K.
Example 1:
Input:
N = 4, K = 2
Arr = [100, 200, 300, 400]
Output:
700
Explanation:
Arr3 + Arr4 =700,
which is maximum.
Example 2:
Input:
N = 4, K = 4
Arr = [100, 200, 300, 400]
Output:
1000
Explanation:
Arr1 + Arr2 + Arr3
+ Arr4 =1000,
which is maximum.
Your Task:
You don't need to read input or print anything. Your task is to complete the function maximumSumSubarray() which takes the integer k, vector Arr with size N, containing the elements of the array and returns the maximum sum of a subarray of size K.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1<=N<=105
1<=K<=N
0
vickysah2 days ago
class Solution{ public: int maximumSumSubarray(int K, vector<int> &Arr , int N){ int temp=Arr[0]; Arr[0]=0; for(int i=1;i<N;i++) { int temp2=Arr[i]; Arr[i]=temp+Arr[i-1]; temp=temp2; } Arr.push_back(temp+Arr[i-1]); int a=0; for(int i=0;i<N-K+1;i++) { a=max(a , Arr[K+i]-Arr[i]); } return a; }};
+1
shahilsingh4562 weeks ago
EASIEST SOLUTION C++
int maximumSumSubarray(int K, vector<int> &Arr , int N){ // code here int sum=0; for(int i=0;i<K;i++) { sum+=Arr[i]; } int curr_sum=sum; for(int i=0;i<N-K;i++) { sum=sum-Arr[i]+Arr[i+K]; curr_sum=max(curr_sum,sum); } return curr_sum; }
+1
himanshu32492 weeks ago
class Solution{
public:
int maximumSumSubarray(int k, vector<int> &nums , int n){
// code here
int i(0), j(0), mx = 0, sum = 0;
while(j < n){
// first calculation to add the effect of the second pointer
sum += nums[j];
if(j - i + 1 == k){
mx = max(mx, sum);
// calculation to remove the effect of the first pointer
sum -= nums[i];
i++;
}
j++;
}
return mx;
}
};
0
19bcs13143 weeks ago
class Solution{
static int maximumSumSubarray(int k, ArrayList<Integer> arr,int n){
// code here
int i=0,j=0,sum=0,max=-1;
while(j<n){
sum+=arr.get(j);
if(j-i+1<k){
j++;
}else if(j-i+1==k){
max=Math.max(sum,max);
sum-=arr.get(i);
i++;j++;
}
}
return max;
}
}
+1
rajatgupta96963 weeks ago
// Using Sliding WIndow concept
int maximumSumSubarray(int K, vector<int> &Arr , int N){
int i=0,j=0;
int sum=0;
int maxSum = INT_MIN;
while(j<N){
sum+=Arr[j];
if(j-i+1<K)
{
j++;
}
else{
maxSum =max(maxSum,sum);
// reduce arr[i];
sum-=Arr[i];
i++;
j++;
}
}
return maxSum;
}
+1
shahabuddinbravo403 weeks ago
// int i=0,j=0,mx=INT_MIN,sum=0; // while(j<Arr.size()) // { // sum=sum+Arr[j]; // if((j-i+1)<K){ // j++; // } // else if((j-i+1)==K){ // mx=max(mx,sum); // sum=sum-Arr[i]; // i++; // j++; // } // } // return mx; int i=0,j=0,mx=INT_MIN,sum=0; for(int j=0;j<Arr.size();j++){ sum=sum+Arr[j]; if((j-i+1)==K){ mx=max(mx,sum); sum=sum-Arr[i]; i++; } } return mx; }
0
minturajmdb19991 month ago
int maximumSumSubarray(int K, vector<int> &Arr , int N) { int i=0,j=0; int sum=0,maxx=0; while(Arr.size()>j) { sum=sum+Arr[j]; if(j-i+1<K) j++; else if(j-i+1==K) { maxx=max(sum,maxx); sum=sum-Arr[i]; i++; j++; } } return maxx; }
+1
swastikp17111 month ago
Simple Java Solution using sliding window
Satisfies All Kind Of Test cases ( Standard Solution )
class Solution{
static int maximumSumSubarray(int k, ArrayList<Integer> arr,int n){
int sum=0;
int maxSum=Integer.MIN_VALUE;
for(int i=0;i<n;i++){
// Subtracting Element which is not present in window
if(i>=k){
sum-=arr.get(i-k);
}
//Adding element to sum(to slide window forward)
sum+=arr.get(i);
//condition to check whether sum is greater than maxSum or not
if(i>=k-1){
maxSum=Math.max(maxSum,sum);
}
}
return maxSum;
}
}
0
akashgahlot19261 month ago
nums[k]=max;k++;
0
zacksuhail1 month ago
EASIEST JAVA SOLUTION:
static int maximumSumSubarray(int K, ArrayList<Integer> Arr,int N){ // code here int max = 0; int sum = 0; int start = 0; for(int i = 0 ; i < N ; i++){ sum += Arr.get(i); if(i >= K){ sum -= Arr.get(start); start++; } max = Math.max(sum , max); } return max; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 343,
"s": 238,
"text": "Given an array of integers Arr of size N and a number K. Return the maximum sum of a subarray of size K."
},
{
"code": null,
"e": 356,
"s": 345,
"text": "Example 1:"
},
{
"code": null,
"e": 465,
"s": 356,
"text": "Input:\nN = 4, K = 2\nArr = [100, 200, 300, 400]\nOutput:\n700\nExplanation:\nArr3 + Arr4 =700,\nwhich is maximum."
},
{
"code": null,
"e": 478,
"s": 467,
"text": "Example 2:"
},
{
"code": null,
"e": 604,
"s": 478,
"text": "Input:\nN = 4, K = 4\nArr = [100, 200, 300, 400]\nOutput:\n1000\nExplanation:\nArr1 + Arr2 + Arr3 \n+ Arr4 =1000,\nwhich is maximum."
},
{
"code": null,
"e": 617,
"s": 606,
"text": "Your Task:"
},
{
"code": null,
"e": 865,
"s": 617,
"text": "You don't need to read input or print anything. Your task is to complete the function maximumSumSubarray() which takes the integer k, vector Arr with size N, containing the elements of the array and returns the maximum sum of a subarray of size K."
},
{
"code": null,
"e": 931,
"s": 867,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n "
},
{
"code": null,
"e": 965,
"s": 931,
"text": "\nConstraints:\n1<=N<=105\n1<=K<=N\n "
},
{
"code": null,
"e": 967,
"s": 965,
"text": "0"
},
{
"code": null,
"e": 986,
"s": 967,
"text": "vickysah2 days ago"
},
{
"code": null,
"e": 1428,
"s": 986,
"text": "class Solution{ public: int maximumSumSubarray(int K, vector<int> &Arr , int N){ int temp=Arr[0]; Arr[0]=0; for(int i=1;i<N;i++) { int temp2=Arr[i]; Arr[i]=temp+Arr[i-1]; temp=temp2; } Arr.push_back(temp+Arr[i-1]); int a=0; for(int i=0;i<N-K+1;i++) { a=max(a , Arr[K+i]-Arr[i]); } return a; }};"
},
{
"code": null,
"e": 1433,
"s": 1430,
"text": "+1"
},
{
"code": null,
"e": 1459,
"s": 1433,
"text": "shahilsingh4562 weeks ago"
},
{
"code": null,
"e": 1489,
"s": 1459,
"text": " EASIEST SOLUTION C++"
},
{
"code": null,
"e": 1832,
"s": 1491,
"text": " int maximumSumSubarray(int K, vector<int> &Arr , int N){ // code here int sum=0; for(int i=0;i<K;i++) { sum+=Arr[i]; } int curr_sum=sum; for(int i=0;i<N-K;i++) { sum=sum-Arr[i]+Arr[i+K]; curr_sum=max(curr_sum,sum); } return curr_sum; }"
},
{
"code": null,
"e": 1835,
"s": 1832,
"text": "+1"
},
{
"code": null,
"e": 1859,
"s": 1835,
"text": "himanshu32492 weeks ago"
},
{
"code": null,
"e": 2456,
"s": 1859,
"text": "class Solution{ \npublic:\n int maximumSumSubarray(int k, vector<int> &nums , int n){\n // code here\n int i(0), j(0), mx = 0, sum = 0;\n \n while(j < n){\n // first calculation to add the effect of the second pointer\n sum += nums[j];\n \n if(j - i + 1 == k){\n mx = max(mx, sum);\n \n // calculation to remove the effect of the first pointer\n sum -= nums[i];\n i++;\n }\n \n j++;\n }\n \n return mx;\n }\n};"
},
{
"code": null,
"e": 2458,
"s": 2456,
"text": "0"
},
{
"code": null,
"e": 2479,
"s": 2458,
"text": "19bcs13143 weeks ago"
},
{
"code": null,
"e": 2916,
"s": 2479,
"text": "class Solution{\n static int maximumSumSubarray(int k, ArrayList<Integer> arr,int n){\n // code here\n \n int i=0,j=0,sum=0,max=-1;\n \n while(j<n){\n sum+=arr.get(j);\n if(j-i+1<k){\n j++;\n }else if(j-i+1==k){\n max=Math.max(sum,max);\n sum-=arr.get(i);\n i++;j++;\n }\n }\n return max;\n }\n}"
},
{
"code": null,
"e": 2919,
"s": 2916,
"text": "+1"
},
{
"code": null,
"e": 2945,
"s": 2919,
"text": "rajatgupta96963 weeks ago"
},
{
"code": null,
"e": 3441,
"s": 2945,
"text": "// Using Sliding WIndow concept\n int maximumSumSubarray(int K, vector<int> &Arr , int N){\n int i=0,j=0;\n int sum=0;\n int maxSum = INT_MIN;\n while(j<N){\n sum+=Arr[j];\n if(j-i+1<K)\n {\n j++;\n }\n else{\n maxSum =max(maxSum,sum);\n \n // reduce arr[i];\n sum-=Arr[i];\n i++;\n j++;\n }\n }\n return maxSum;\n }"
},
{
"code": null,
"e": 3444,
"s": 3441,
"text": "+1"
},
{
"code": null,
"e": 3474,
"s": 3444,
"text": "shahabuddinbravo403 weeks ago"
},
{
"code": null,
"e": 4123,
"s": 3474,
"text": " // int i=0,j=0,mx=INT_MIN,sum=0; // while(j<Arr.size()) // { // sum=sum+Arr[j]; // if((j-i+1)<K){ // j++; // } // else if((j-i+1)==K){ // mx=max(mx,sum); // sum=sum-Arr[i]; // i++; // j++; // } // } // return mx; int i=0,j=0,mx=INT_MIN,sum=0; for(int j=0;j<Arr.size();j++){ sum=sum+Arr[j]; if((j-i+1)==K){ mx=max(mx,sum); sum=sum-Arr[i]; i++; } } return mx; }"
},
{
"code": null,
"e": 4125,
"s": 4123,
"text": "0"
},
{
"code": null,
"e": 4152,
"s": 4125,
"text": "minturajmdb19991 month ago"
},
{
"code": null,
"e": 4638,
"s": 4152,
"text": "int maximumSumSubarray(int K, vector<int> &Arr , int N) { int i=0,j=0; int sum=0,maxx=0; while(Arr.size()>j) { sum=sum+Arr[j]; if(j-i+1<K) j++; else if(j-i+1==K) { maxx=max(sum,maxx); sum=sum-Arr[i]; i++; j++; } } return maxx; }"
},
{
"code": null,
"e": 4641,
"s": 4638,
"text": "+1"
},
{
"code": null,
"e": 4665,
"s": 4641,
"text": "swastikp17111 month ago"
},
{
"code": null,
"e": 4707,
"s": 4665,
"text": "Simple Java Solution using sliding window"
},
{
"code": null,
"e": 4762,
"s": 4707,
"text": "Satisfies All Kind Of Test cases ( Standard Solution )"
},
{
"code": null,
"e": 5420,
"s": 4762,
"text": "class Solution{\n static int maximumSumSubarray(int k, ArrayList<Integer> arr,int n){\n \n int sum=0;\n int maxSum=Integer.MIN_VALUE;\n \n for(int i=0;i<n;i++){\n \n // Subtracting Element which is not present in window\n if(i>=k){\n sum-=arr.get(i-k);\n }\n \n //Adding element to sum(to slide window forward)\n sum+=arr.get(i);\n \n //condition to check whether sum is greater than maxSum or not\n if(i>=k-1){\n maxSum=Math.max(maxSum,sum);\n }\n }\n return maxSum;\n }\n}"
},
{
"code": null,
"e": 5422,
"s": 5420,
"text": "0"
},
{
"code": null,
"e": 5449,
"s": 5422,
"text": "akashgahlot19261 month ago"
},
{
"code": null,
"e": 5466,
"s": 5449,
"text": "nums[k]=max;k++;"
},
{
"code": null,
"e": 5468,
"s": 5466,
"text": "0"
},
{
"code": null,
"e": 5490,
"s": 5468,
"text": "zacksuhail1 month ago"
},
{
"code": null,
"e": 5513,
"s": 5490,
"text": "EASIEST JAVA SOLUTION:"
},
{
"code": null,
"e": 5897,
"s": 5513,
"text": " static int maximumSumSubarray(int K, ArrayList<Integer> Arr,int N){ // code here int max = 0; int sum = 0; int start = 0; for(int i = 0 ; i < N ; i++){ sum += Arr.get(i); if(i >= K){ sum -= Arr.get(start); start++; } max = Math.max(sum , max); } return max; }"
},
{
"code": null,
"e": 6043,
"s": 5897,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6079,
"s": 6043,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6089,
"s": 6079,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6099,
"s": 6089,
"text": "\nContest\n"
},
{
"code": null,
"e": 6162,
"s": 6099,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6310,
"s": 6162,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6518,
"s": 6310,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6624,
"s": 6518,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Rotating a 2-D (transposing a matrix) in JavaScript | The transpose of a matrix (2-D array) is simply a flipped version of the original matrix (2-D
array). We can transpose a matrix (2-D array) by switching its rows with its columns.
The code for this will be −
const arr = [
[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
];
const transpose = arr => {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < i; j++) {
const tmp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = tmp;
};
}
}
transpose(arr);
console.log(arr);
The output in the console −
[ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ] | [
{
"code": null,
"e": 1242,
"s": 1062,
"text": "The transpose of a matrix (2-D array) is simply a flipped version of the original matrix (2-D\narray). We can transpose a matrix (2-D array) by switching its rows with its columns."
},
{
"code": null,
"e": 1270,
"s": 1242,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1574,
"s": 1270,
"text": "const arr = [\n [1, 1, 1],\n [2, 2, 2],\n [3, 3, 3],\n];\nconst transpose = arr => {\n for (let i = 0; i < arr.length; i++) {\n for (let j = 0; j < i; j++) {\n const tmp = arr[i][j];\n arr[i][j] = arr[j][i];\n arr[j][i] = tmp;\n };\n }\n}\ntranspose(arr);\nconsole.log(arr);"
},
{
"code": null,
"e": 1602,
"s": 1574,
"text": "The output in the console −"
},
{
"code": null,
"e": 1644,
"s": 1602,
"text": "[ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ]"
}
]
|
How to edit the style of a heading in Treeview (Python ttk)? | Python Treeview widget is introduced for creating a Table look-like GUI in application. It includes many inbuilt features and functions which can be used to configure the properties. However, to configure the style of a tkinter widget, we generally refer to use ttk themed widget. This allows you to edit the style such as background color, foreground color, and other properties of the treeview widget as well.
In this example, we will create an instance of the ttk style widget and then configure the style of heading by passing 'Treeview.Heading' as the style parameter.
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame
win= Tk()
# Set the size of the tkinter window
win.geometry("700x350")
s = ttk.Style()
s.theme_use('clam')
# Configure the style of Heading in Treeview widget
s.configure('Treeview.Heading', background="green3")
# Add a Treeview widget
tree= ttk.Treeview(win, column=("c1", "c2"), show= 'headings', height= 8)
tree.column("# 1",anchor=CENTER)
tree.heading("# 1", text= "ID")
tree.column("# 2", anchor= CENTER)
tree.heading("# 2", text= "FName")
# Insert the data in Treeview widget
tree.insert('', 'end',text= "1",values=('1','Honda'))
tree.insert('', 'end',text= "2",values=('2', 'Hundayi'))
tree.insert('', 'end',text= "3",values=('3', 'Tesla'))
tree.insert('', 'end',text= "4",values=('4', 'Wolkswagon'))
tree.insert('', 'end',text= "5",values=('5', 'Tata'))
tree.insert('', 'end',text= "6",values=('6', 'Renault'))
tree.insert('', 'end',text= "7",values=('7', 'Audi'))
tree.insert('', 'end',text= "8",values=('8', 'BMW'))
tree.pack()
win.mainloop()
Executing the above code will display a window containing a table with a customized heading background color. | [
{
"code": null,
"e": 1474,
"s": 1062,
"text": "Python Treeview widget is introduced for creating a Table look-like GUI in application. It includes many inbuilt features and functions which can be used to configure the properties. However, to configure the style of a tkinter widget, we generally refer to use ttk themed widget. This allows you to edit the style such as background color, foreground color, and other properties of the treeview widget as well."
},
{
"code": null,
"e": 1636,
"s": 1474,
"text": "In this example, we will create an instance of the ttk style widget and then configure the style of heading by passing 'Treeview.Heading' as the style parameter."
},
{
"code": null,
"e": 2712,
"s": 1636,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame\nwin= Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\ns = ttk.Style()\ns.theme_use('clam')\n\n# Configure the style of Heading in Treeview widget\ns.configure('Treeview.Heading', background=\"green3\")\n\n# Add a Treeview widget\ntree= ttk.Treeview(win, column=(\"c1\", \"c2\"), show= 'headings', height= 8)\ntree.column(\"# 1\",anchor=CENTER)\ntree.heading(\"# 1\", text= \"ID\")\ntree.column(\"# 2\", anchor= CENTER)\ntree.heading(\"# 2\", text= \"FName\")\n\n# Insert the data in Treeview widget\ntree.insert('', 'end',text= \"1\",values=('1','Honda'))\ntree.insert('', 'end',text= \"2\",values=('2', 'Hundayi'))\ntree.insert('', 'end',text= \"3\",values=('3', 'Tesla'))\ntree.insert('', 'end',text= \"4\",values=('4', 'Wolkswagon'))\ntree.insert('', 'end',text= \"5\",values=('5', 'Tata'))\ntree.insert('', 'end',text= \"6\",values=('6', 'Renault'))\ntree.insert('', 'end',text= \"7\",values=('7', 'Audi'))\ntree.insert('', 'end',text= \"8\",values=('8', 'BMW'))\n\ntree.pack()\n\nwin.mainloop()"
},
{
"code": null,
"e": 2822,
"s": 2712,
"text": "Executing the above code will display a window containing a table with a customized heading background color."
}
]
|
wxPython - ListBox & ListCtrl Class | A wx.ListBox widget presents a vertically scrollable list of strings. By default, a single item in the list is selectable. However, it can be customized to be multi-select.
ListCtrl widget is a highly enhanced list display and selection tool. List of more than one column can be displayed in Report view, List view or Icon view.
ListBox constructor has the following definition −
Wx.ListBox(parent, id, pos, size, choices, style)
Choices parameter is the list of strings used to populate the list.
wx.ListBox object is customizable with the following style parameters −
wxLB_SINGLE
Single-selection list
wxLB_MULTIPLE
Multiple-selection list: the user can toggle multiple items on and off
wxLB_EXTENDED
Extended-selection list − the user can extend the selection by using SHIFT or CTRL keys together with the cursor movement keys or the mouse
wxLB_HSCROLL
Create horizontal scrollbar if contents are too wide
wxLB_ALWAYS_SB
Always show a vertical scrollbar
wxLB_NEEDED_SB
Only creates a vertical scrollbar if needed
wxLB_SORT
The listbox contents are sorted in an alphabetical order
wx.ListBox class methods −
DeSelect()
Deselects an item in the list box
InsertItem()
Inserts a given string at the specified position
SetFirstItem()
Sets a string at the given index as first in the list
IsSorted()
Returns true if wxzL?B_SORT style is used
GetString()
Returns the string at the selected index
SetString()
Sets the label for an item at the given index
EVT_LISTBOX binder triggers the handler when an item in the list is selected or when the selection changes programmatically. Handler function bound by EVT_LISTBOX_DCLICK is invoked when a double-click event on the list box item occurs.
In the following example, a ListBox control and a TextCtrl object are respectively placed in the left and the right portion of a horizontal box sizer. ListBox is populated with strings in languages[] list object.
languages = ['C', 'C++', 'Java', 'Python', 'Perl', 'JavaScript','PHP','VB.NET','C#']
self.text = wx.TextCtrl(panel,style = wx.TE_MULTILINE)
lst = wx.ListBox(panel, size = (100,-1), choices = languages, style = wx.LB_SINGLE)
Two objects are placed in a horizontal box sizer.
box = wx.BoxSizer(wx.HORIZONTAL)
box.Add(lst,0,wx.EXPAND)
box.Add(self.text, 1, wx.EXPAND)
ListBox control is linked to onListBox() handler with EVT_LISTBOX binder.
self.Bind(wx.EVT_LISTBOX, self.onListBox, lst)
The handler appends selected string into multiline TextCtrl on the right.
def onListBox(self, event):
self.text.AppendText( "Current selection: "+
event.GetEventObject().GetStringSelection() + "\n")
The complete code is as follows −
import wx
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title = title,size = (350,300))
panel = wx.Panel(self)
box = wx.BoxSizer(wx.HORIZONTAL)
self.text = wx.TextCtrl(panel,style = wx.TE_MULTILINE)
languages = ['C', 'C++', 'Java', 'Python', 'Perl', 'JavaScript', 'PHP', 'VB.NET','C#']
lst = wx.ListBox(panel, size = (100,-1), choices = languages, style = wx.LB_SINGLE)
box.Add(lst,0,wx.EXPAND)
box.Add(self.text, 1, wx.EXPAND)
panel.SetSizer(box)
panel.Fit()
self.Centre()
self.Bind(wx.EVT_LISTBOX, self.onListBox, lst)
self.Show(True)
def onListBox(self, event):
self.text.AppendText( "Current selection:
"+event.GetEventObject().GetStringSelection()+"\n")
ex = wx.App()
Mywin(None,'ListBox Demo')
ex.MainLoop()
The above code produces the following output −
wx.ListCtrl is an enhanced, and therefore, more complex widget. Where a ListBox shows only one column, ListCtrl can contain multiple columns. The appearance of ListCtrl widget is controlled by the following style parameters −
wx.LC_LIST
Multicolumn list view, with optional small icons. Columns are computed automatically
wx.LC_REPORT
Single or multicolumn report view, with optional header
wx.LC_VIRTUAL
The application provides items text on demand. May only be used with wxLC_REPORT
wx.LC_ICON
Large icon view, with optional labels
wx.LC_SMALL_ICON
Small icon view, with optional labels
wx.LC_ALIGN_LEFT
Icons align to the left
wx.LC_EDIT_LABELS
Labels are editable − the application will be notified when editing starts
wx.LC_NO_HEADER
No header in report mode
wx.LC_SORT_ASCENDING
Sort in ascending order
wx.LC_SORT_DESCENDING
Sort in descending order
wx.LC_HRULES
Draws light horizontal rules between the rows in report mode
wx.LC_VRULES
Draws light vertical rules between the columns in report mode
A ListCtrl widget in report view is constructed in the following example.
self.list = wx.ListCtrl(panel, -1, style = wx.LC_REPORT)
Header columns are created by InsertColumn() method which takes the column number, caption, style and width parameters.
self.list.InsertColumn(0, 'name', width = 100)
self.list.InsertColumn(1, 'runs', wx.LIST_FORMAT_RIGHT, 100)
self.list.InsertColumn(2, 'wkts', wx.LIST_FORMAT_RIGHT, 100)
A list of tuples, each containg three strings, called players[] stores the data which is used to populate columns of the ListCtrl object.
New row starts with InsertStringItem() method which returns the index of the current row. Use of sys.maxint gives the row number after the last row. Using the index, other columns are filled by SetStringItem() method.
for i in players:
index = self.list.InsertStringItem(sys.maxint, i[0])
self.list.SetStringItem(index, 1, i[1])
self.list.SetStringItem(index, 2, i[2])
The complete code for the example is −
import sys
import wx
players = [('Tendulkar', '15000', '100'), ('Dravid', '14000', '1'),
('Kumble', '1000', '700'), ('KapilDev', '5000', '400'),
('Ganguly', '8000', '50')]
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title = title)
panel = wx.Panel(self)
box = wx.BoxSizer(wx.HORIZONTAL)
self.list = wx.ListCtrl(panel, -1, style = wx.LC_REPORT)
self.list.InsertColumn(0, 'name', width = 100)
self.list.InsertColumn(1, 'runs', wx.LIST_FORMAT_RIGHT, 100)
self.list.InsertColumn(2, 'wkts', wx.LIST_FORMAT_RIGHT, 100)
for i in players:
index = self.list.InsertStringItem(sys.maxint, i[0])
self.list.SetStringItem(index, 1, i[1])
self.list.SetStringItem(index, 2, i[2])
box.Add(self.list,1,wx.EXPAND)
panel.SetSizer(box)
panel.Fit()
self.Centre()
self.Show(True)
ex = wx.App()
Mywin(None,'ListCtrl Demo')
ex.MainLoop()
The above code produces the following output. Players’ data is displayed in report view −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2055,
"s": 1882,
"text": "A wx.ListBox widget presents a vertically scrollable list of strings. By default, a single item in the list is selectable. However, it can be customized to be multi-select."
},
{
"code": null,
"e": 2211,
"s": 2055,
"text": "ListCtrl widget is a highly enhanced list display and selection tool. List of more than one column can be displayed in Report view, List view or Icon view."
},
{
"code": null,
"e": 2262,
"s": 2211,
"text": "ListBox constructor has the following definition −"
},
{
"code": null,
"e": 2313,
"s": 2262,
"text": "Wx.ListBox(parent, id, pos, size, choices, style)\n"
},
{
"code": null,
"e": 2381,
"s": 2313,
"text": "Choices parameter is the list of strings used to populate the list."
},
{
"code": null,
"e": 2453,
"s": 2381,
"text": "wx.ListBox object is customizable with the following style parameters −"
},
{
"code": null,
"e": 2465,
"s": 2453,
"text": "wxLB_SINGLE"
},
{
"code": null,
"e": 2487,
"s": 2465,
"text": "Single-selection list"
},
{
"code": null,
"e": 2501,
"s": 2487,
"text": "wxLB_MULTIPLE"
},
{
"code": null,
"e": 2572,
"s": 2501,
"text": "Multiple-selection list: the user can toggle multiple items on and off"
},
{
"code": null,
"e": 2586,
"s": 2572,
"text": "wxLB_EXTENDED"
},
{
"code": null,
"e": 2726,
"s": 2586,
"text": "Extended-selection list − the user can extend the selection by using SHIFT or CTRL keys together with the cursor movement keys or the mouse"
},
{
"code": null,
"e": 2739,
"s": 2726,
"text": "wxLB_HSCROLL"
},
{
"code": null,
"e": 2792,
"s": 2739,
"text": "Create horizontal scrollbar if contents are too wide"
},
{
"code": null,
"e": 2807,
"s": 2792,
"text": "wxLB_ALWAYS_SB"
},
{
"code": null,
"e": 2840,
"s": 2807,
"text": "Always show a vertical scrollbar"
},
{
"code": null,
"e": 2855,
"s": 2840,
"text": "wxLB_NEEDED_SB"
},
{
"code": null,
"e": 2899,
"s": 2855,
"text": "Only creates a vertical scrollbar if needed"
},
{
"code": null,
"e": 2909,
"s": 2899,
"text": "wxLB_SORT"
},
{
"code": null,
"e": 2966,
"s": 2909,
"text": "The listbox contents are sorted in an alphabetical order"
},
{
"code": null,
"e": 2993,
"s": 2966,
"text": "wx.ListBox class methods −"
},
{
"code": null,
"e": 3004,
"s": 2993,
"text": "DeSelect()"
},
{
"code": null,
"e": 3038,
"s": 3004,
"text": "Deselects an item in the list box"
},
{
"code": null,
"e": 3051,
"s": 3038,
"text": "InsertItem()"
},
{
"code": null,
"e": 3100,
"s": 3051,
"text": "Inserts a given string at the specified position"
},
{
"code": null,
"e": 3115,
"s": 3100,
"text": "SetFirstItem()"
},
{
"code": null,
"e": 3169,
"s": 3115,
"text": "Sets a string at the given index as first in the list"
},
{
"code": null,
"e": 3180,
"s": 3169,
"text": "IsSorted()"
},
{
"code": null,
"e": 3222,
"s": 3180,
"text": "Returns true if wxzL?B_SORT style is used"
},
{
"code": null,
"e": 3234,
"s": 3222,
"text": "GetString()"
},
{
"code": null,
"e": 3275,
"s": 3234,
"text": "Returns the string at the selected index"
},
{
"code": null,
"e": 3287,
"s": 3275,
"text": "SetString()"
},
{
"code": null,
"e": 3333,
"s": 3287,
"text": "Sets the label for an item at the given index"
},
{
"code": null,
"e": 3569,
"s": 3333,
"text": "EVT_LISTBOX binder triggers the handler when an item in the list is selected or when the selection changes programmatically. Handler function bound by EVT_LISTBOX_DCLICK is invoked when a double-click event on the list box item occurs."
},
{
"code": null,
"e": 3782,
"s": 3569,
"text": "In the following example, a ListBox control and a TextCtrl object are respectively placed in the left and the right portion of a horizontal box sizer. ListBox is populated with strings in languages[] list object."
},
{
"code": null,
"e": 4009,
"s": 3782,
"text": "languages = ['C', 'C++', 'Java', 'Python', 'Perl', 'JavaScript','PHP','VB.NET','C#'] \nself.text = wx.TextCtrl(panel,style = wx.TE_MULTILINE) \nlst = wx.ListBox(panel, size = (100,-1), choices = languages, style = wx.LB_SINGLE)\n"
},
{
"code": null,
"e": 4059,
"s": 4009,
"text": "Two objects are placed in a horizontal box sizer."
},
{
"code": null,
"e": 4152,
"s": 4059,
"text": "box = wx.BoxSizer(wx.HORIZONTAL) \nbox.Add(lst,0,wx.EXPAND) \nbox.Add(self.text, 1, wx.EXPAND)"
},
{
"code": null,
"e": 4226,
"s": 4152,
"text": "ListBox control is linked to onListBox() handler with EVT_LISTBOX binder."
},
{
"code": null,
"e": 4274,
"s": 4226,
"text": "self.Bind(wx.EVT_LISTBOX, self.onListBox, lst)\n"
},
{
"code": null,
"e": 4348,
"s": 4274,
"text": "The handler appends selected string into multiline TextCtrl on the right."
},
{
"code": null,
"e": 4484,
"s": 4348,
"text": "def onListBox(self, event): \n self.text.AppendText( \"Current selection: \"+ \n event.GetEventObject().GetStringSelection() + \"\\n\")"
},
{
"code": null,
"e": 4518,
"s": 4484,
"text": "The complete code is as follows −"
},
{
"code": null,
"e": 5444,
"s": 4518,
"text": "import wx \nclass Mywin(wx.Frame): \n \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title,size = (350,300))\n\t\t\n panel = wx.Panel(self) \n box = wx.BoxSizer(wx.HORIZONTAL) \n\t\t\n self.text = wx.TextCtrl(panel,style = wx.TE_MULTILINE) \n \n languages = ['C', 'C++', 'Java', 'Python', 'Perl', 'JavaScript', 'PHP', 'VB.NET','C#'] \n lst = wx.ListBox(panel, size = (100,-1), choices = languages, style = wx.LB_SINGLE)\n\t\t\n box.Add(lst,0,wx.EXPAND) \n box.Add(self.text, 1, wx.EXPAND) \n\t\t\n panel.SetSizer(box) \n panel.Fit() \n\t\t\n self.Centre() \n self.Bind(wx.EVT_LISTBOX, self.onListBox, lst) \n self.Show(True) \n\t\t\n def onListBox(self, event): \n self.text.AppendText( \"Current selection: \n \"+event.GetEventObject().GetStringSelection()+\"\\n\")\n\t\t\nex = wx.App() \nMywin(None,'ListBox Demo') \nex.MainLoop()"
},
{
"code": null,
"e": 5491,
"s": 5444,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 5717,
"s": 5491,
"text": "wx.ListCtrl is an enhanced, and therefore, more complex widget. Where a ListBox shows only one column, ListCtrl can contain multiple columns. The appearance of ListCtrl widget is controlled by the following style parameters −"
},
{
"code": null,
"e": 5728,
"s": 5717,
"text": "wx.LC_LIST"
},
{
"code": null,
"e": 5813,
"s": 5728,
"text": "Multicolumn list view, with optional small icons. Columns are computed automatically"
},
{
"code": null,
"e": 5826,
"s": 5813,
"text": "wx.LC_REPORT"
},
{
"code": null,
"e": 5882,
"s": 5826,
"text": "Single or multicolumn report view, with optional header"
},
{
"code": null,
"e": 5896,
"s": 5882,
"text": "wx.LC_VIRTUAL"
},
{
"code": null,
"e": 5977,
"s": 5896,
"text": "The application provides items text on demand. May only be used with wxLC_REPORT"
},
{
"code": null,
"e": 5988,
"s": 5977,
"text": "wx.LC_ICON"
},
{
"code": null,
"e": 6026,
"s": 5988,
"text": "Large icon view, with optional labels"
},
{
"code": null,
"e": 6043,
"s": 6026,
"text": "wx.LC_SMALL_ICON"
},
{
"code": null,
"e": 6081,
"s": 6043,
"text": "Small icon view, with optional labels"
},
{
"code": null,
"e": 6098,
"s": 6081,
"text": "wx.LC_ALIGN_LEFT"
},
{
"code": null,
"e": 6122,
"s": 6098,
"text": "Icons align to the left"
},
{
"code": null,
"e": 6140,
"s": 6122,
"text": "wx.LC_EDIT_LABELS"
},
{
"code": null,
"e": 6215,
"s": 6140,
"text": "Labels are editable − the application will be notified when editing starts"
},
{
"code": null,
"e": 6231,
"s": 6215,
"text": "wx.LC_NO_HEADER"
},
{
"code": null,
"e": 6256,
"s": 6231,
"text": "No header in report mode"
},
{
"code": null,
"e": 6277,
"s": 6256,
"text": "wx.LC_SORT_ASCENDING"
},
{
"code": null,
"e": 6301,
"s": 6277,
"text": "Sort in ascending order"
},
{
"code": null,
"e": 6323,
"s": 6301,
"text": "wx.LC_SORT_DESCENDING"
},
{
"code": null,
"e": 6348,
"s": 6323,
"text": "Sort in descending order"
},
{
"code": null,
"e": 6361,
"s": 6348,
"text": "wx.LC_HRULES"
},
{
"code": null,
"e": 6422,
"s": 6361,
"text": "Draws light horizontal rules between the rows in report mode"
},
{
"code": null,
"e": 6435,
"s": 6422,
"text": "wx.LC_VRULES"
},
{
"code": null,
"e": 6497,
"s": 6435,
"text": "Draws light vertical rules between the columns in report mode"
},
{
"code": null,
"e": 6571,
"s": 6497,
"text": "A ListCtrl widget in report view is constructed in the following example."
},
{
"code": null,
"e": 6629,
"s": 6571,
"text": "self.list = wx.ListCtrl(panel, -1, style = wx.LC_REPORT)\n"
},
{
"code": null,
"e": 6749,
"s": 6629,
"text": "Header columns are created by InsertColumn() method which takes the column number, caption, style and width parameters."
},
{
"code": null,
"e": 6921,
"s": 6749,
"text": "self.list.InsertColumn(0, 'name', width = 100) \nself.list.InsertColumn(1, 'runs', wx.LIST_FORMAT_RIGHT, 100) \nself.list.InsertColumn(2, 'wkts', wx.LIST_FORMAT_RIGHT, 100)\n"
},
{
"code": null,
"e": 7059,
"s": 6921,
"text": "A list of tuples, each containg three strings, called players[] stores the data which is used to populate columns of the ListCtrl object."
},
{
"code": null,
"e": 7277,
"s": 7059,
"text": "New row starts with InsertStringItem() method which returns the index of the current row. Use of sys.maxint gives the row number after the last row. Using the index, other columns are filled by SetStringItem() method."
},
{
"code": null,
"e": 7440,
"s": 7277,
"text": "for i in players: \n index = self.list.InsertStringItem(sys.maxint, i[0]) \n self.list.SetStringItem(index, 1, i[1]) \n self.list.SetStringItem(index, 2, i[2])"
},
{
"code": null,
"e": 7479,
"s": 7440,
"text": "The complete code for the example is −"
},
{
"code": null,
"e": 8534,
"s": 7479,
"text": "import sys \nimport wx \n\nplayers = [('Tendulkar', '15000', '100'), ('Dravid', '14000', '1'), \n ('Kumble', '1000', '700'), ('KapilDev', '5000', '400'), \n ('Ganguly', '8000', '50')] \n\t\nclass Mywin(wx.Frame): \n \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title) \n\t\t\n panel = wx.Panel(self) \n box = wx.BoxSizer(wx.HORIZONTAL)\n\t\t\n self.list = wx.ListCtrl(panel, -1, style = wx.LC_REPORT) \n self.list.InsertColumn(0, 'name', width = 100) \n self.list.InsertColumn(1, 'runs', wx.LIST_FORMAT_RIGHT, 100) \n self.list.InsertColumn(2, 'wkts', wx.LIST_FORMAT_RIGHT, 100) \n \n for i in players: \n index = self.list.InsertStringItem(sys.maxint, i[0]) \n self.list.SetStringItem(index, 1, i[1]) \n self.list.SetStringItem(index, 2, i[2]) \n\t\t\t\n box.Add(self.list,1,wx.EXPAND) \n panel.SetSizer(box) \n panel.Fit() \n self.Centre() \n \n self.Show(True) \n \nex = wx.App() \nMywin(None,'ListCtrl Demo') \nex.MainLoop()"
},
{
"code": null,
"e": 8624,
"s": 8534,
"text": "The above code produces the following output. Players’ data is displayed in report view −"
},
{
"code": null,
"e": 8631,
"s": 8624,
"text": " Print"
},
{
"code": null,
"e": 8642,
"s": 8631,
"text": " Add Notes"
}
]
|
Difference between One-way Binding and Two-way Binding - GeeksforGeeks | 22 Jul, 2021
In this article, we will learn the concept of data binding in Angular. We will also explore its types & examine the differences between one-way binding and two-way binding in angular.
Data binding is a way to synchronise the data between the model and view components automatically. AngularJS implements data-binding that treats the model as the single-source-of-truth in your application & for all the time, the view is a projection of the model. Unlike React, angular supports two-way binding. In this way, we can make the code more loosely coupled. Data binding can be categorized into 2 types, ie., One-way Binding & Two-way Binding.
One way binding:
In one-way binding, the data flow is one-directional.
This means that the flow of code is from typescript file to Html file.
In order to achieve a one-way binding, we used the property binding concept in Angular.
In property binding, we encapsulate the variable in Html with square brackets( [ ] ).
We will understand this concept through an example in order to make it more comprehensible.
app.component.ts
import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"],})export class AppComponent { title = "Displaying the content with one way binding";}
app.component.html
<h3>Displaying the content without one way binding</h3> <hr /> <h3 [textContent]="title"></h3>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser"; import { AppComponent } from "./app.component"; @NgModule({ imports: [BrowserModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
Output:
Two-way binding:
In a two-way binding, the data flow is bi-directional.
This means that the flow of code is from ts file to Html file as well as from Html file to ts file.
In order to achieve a two-way binding, we will use ngModel or banana in a box syntax.
To make sure the app doesn’t break, we need to import ‘FormsModule’ from ‘@angular/forms.
Any changes to the view are propagated to the component class. Also, any changes to the properties in the component class are reflected in the view.
To bind two properties in order to two-way binding works, declare the ngModel directive and set it equal to the name of the property.
We will understand the concept through an example in order to make it more comprehensible.
app.component.ts
import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html",})export class AppComponent { data = "Ram and Syam";}
app.component.html
<input [(ngModel)]="data" type="text"> <hr> <h3> Entered data is {{data}}</h3>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms"; import { AppComponent } from "./app.component"; @NgModule({ imports: [BrowserModule, FormsModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
Output:
One-way binding
Two-way binding
In one-way binding, the flow is one-directional.
In a two-way binding, the flow is two-directional.
This means that the flow of code is from ts file to Html file.
This means that the flow of code is from ts file to Html file as well as from Html file to ts file.
In order to achieve one-way binding, we used the property binding concept in Angular.
In order to achieve a two-way binding, we will use ngModel or banana in a box syntax.
In property binding, we encapsulate the variable in html with square brackets( [ ] ).
To make sure the app doesn’t break, we need to import ‘FormsModule’ from ‘@angular/forms’. Using ngModel, we will bind a variable from Html to ts file and from ts file to Html file.
AngularJS-Questions
Picked
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
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
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? | [
{
"code": null,
"e": 25197,
"s": 25169,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 25382,
"s": 25197,
"text": "In this article, we will learn the concept of data binding in Angular. We will also explore its types & examine the differences between one-way binding and two-way binding in angular. "
},
{
"code": null,
"e": 25836,
"s": 25382,
"text": "Data binding is a way to synchronise the data between the model and view components automatically. AngularJS implements data-binding that treats the model as the single-source-of-truth in your application & for all the time, the view is a projection of the model. Unlike React, angular supports two-way binding. In this way, we can make the code more loosely coupled. Data binding can be categorized into 2 types, ie., One-way Binding & Two-way Binding."
},
{
"code": null,
"e": 25853,
"s": 25836,
"text": "One way binding:"
},
{
"code": null,
"e": 25907,
"s": 25853,
"text": "In one-way binding, the data flow is one-directional."
},
{
"code": null,
"e": 25978,
"s": 25907,
"text": "This means that the flow of code is from typescript file to Html file."
},
{
"code": null,
"e": 26066,
"s": 25978,
"text": "In order to achieve a one-way binding, we used the property binding concept in Angular."
},
{
"code": null,
"e": 26152,
"s": 26066,
"text": "In property binding, we encapsulate the variable in Html with square brackets( [ ] )."
},
{
"code": null,
"e": 26244,
"s": 26152,
"text": "We will understand this concept through an example in order to make it more comprehensible."
},
{
"code": null,
"e": 26261,
"s": 26244,
"text": "app.component.ts"
},
{
"code": "import { Component } from \"@angular/core\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\", styleUrls: [\"./app.component.css\"],})export class AppComponent { title = \"Displaying the content with one way binding\";}",
"e": 26500,
"s": 26261,
"text": null
},
{
"code": null,
"e": 26521,
"s": 26502,
"text": "app.component.html"
},
{
"code": "<h3>Displaying the content without one way binding</h3> <hr /> <h3 [textContent]=\"title\"></h3>",
"e": 26618,
"s": 26521,
"text": null
},
{
"code": null,
"e": 26632,
"s": 26618,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\"; import { AppComponent } from \"./app.component\"; @NgModule({ imports: [BrowserModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}",
"e": 26907,
"s": 26632,
"text": null
},
{
"code": null,
"e": 26915,
"s": 26907,
"text": "Output:"
},
{
"code": null,
"e": 26932,
"s": 26915,
"text": "Two-way binding:"
},
{
"code": null,
"e": 26987,
"s": 26932,
"text": "In a two-way binding, the data flow is bi-directional."
},
{
"code": null,
"e": 27087,
"s": 26987,
"text": "This means that the flow of code is from ts file to Html file as well as from Html file to ts file."
},
{
"code": null,
"e": 27173,
"s": 27087,
"text": "In order to achieve a two-way binding, we will use ngModel or banana in a box syntax."
},
{
"code": null,
"e": 27263,
"s": 27173,
"text": "To make sure the app doesn’t break, we need to import ‘FormsModule’ from ‘@angular/forms."
},
{
"code": null,
"e": 27412,
"s": 27263,
"text": "Any changes to the view are propagated to the component class. Also, any changes to the properties in the component class are reflected in the view."
},
{
"code": null,
"e": 27546,
"s": 27412,
"text": "To bind two properties in order to two-way binding works, declare the ngModel directive and set it equal to the name of the property."
},
{
"code": null,
"e": 27637,
"s": 27546,
"text": "We will understand the concept through an example in order to make it more comprehensible."
},
{
"code": null,
"e": 27654,
"s": 27637,
"text": "app.component.ts"
},
{
"code": "import { Component } from \"@angular/core\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\",})export class AppComponent { data = \"Ram and Syam\";}",
"e": 27824,
"s": 27654,
"text": null
},
{
"code": null,
"e": 27843,
"s": 27824,
"text": "app.component.html"
},
{
"code": "<input [(ngModel)]=\"data\" type=\"text\"> <hr> <h3> Entered data is {{data}}</h3>",
"e": 27926,
"s": 27843,
"text": null
},
{
"code": null,
"e": 27942,
"s": 27928,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\"; import { AppComponent } from \"./app.component\"; @NgModule({ imports: [BrowserModule, FormsModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}",
"e": 28275,
"s": 27942,
"text": null
},
{
"code": null,
"e": 28283,
"s": 28275,
"text": "Output:"
},
{
"code": null,
"e": 28300,
"s": 28283,
"text": "One-way binding "
},
{
"code": null,
"e": 28317,
"s": 28300,
"text": "Two-way binding "
},
{
"code": null,
"e": 28366,
"s": 28317,
"text": "In one-way binding, the flow is one-directional."
},
{
"code": null,
"e": 28417,
"s": 28366,
"text": "In a two-way binding, the flow is two-directional."
},
{
"code": null,
"e": 28481,
"s": 28417,
"text": "This means that the flow of code is from ts file to Html file."
},
{
"code": null,
"e": 28581,
"s": 28481,
"text": "This means that the flow of code is from ts file to Html file as well as from Html file to ts file."
},
{
"code": null,
"e": 28667,
"s": 28581,
"text": "In order to achieve one-way binding, we used the property binding concept in Angular."
},
{
"code": null,
"e": 28753,
"s": 28667,
"text": "In order to achieve a two-way binding, we will use ngModel or banana in a box syntax."
},
{
"code": null,
"e": 28840,
"s": 28753,
"text": "In property binding, we encapsulate the variable in html with square brackets( [ ] )."
},
{
"code": null,
"e": 29022,
"s": 28840,
"text": "To make sure the app doesn’t break, we need to import ‘FormsModule’ from ‘@angular/forms’. Using ngModel, we will bind a variable from Html to ts file and from ts file to Html file."
},
{
"code": null,
"e": 29042,
"s": 29022,
"text": "AngularJS-Questions"
},
{
"code": null,
"e": 29049,
"s": 29042,
"text": "Picked"
},
{
"code": null,
"e": 29059,
"s": 29049,
"text": "AngularJS"
},
{
"code": null,
"e": 29076,
"s": 29059,
"text": "Web Technologies"
},
{
"code": null,
"e": 29174,
"s": 29076,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29183,
"s": 29174,
"text": "Comments"
},
{
"code": null,
"e": 29196,
"s": 29183,
"text": "Old Comments"
},
{
"code": null,
"e": 29240,
"s": 29196,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 29271,
"s": 29240,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 29313,
"s": 29271,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 29377,
"s": 29313,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 29430,
"s": 29377,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 29472,
"s": 29430,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29505,
"s": 29472,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29548,
"s": 29505,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29610,
"s": 29548,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
ES6 - constructor () | Javascript Boolean constructor() method returns a reference to the Boolean function that created the instance's prototype.
Use the following syntax to create a Boolean constructor() method. It returns the function that created this object's instance.
boolean.constructor()
<html>
<head>
<title>JavaScript constructor() Method</title>
</head>
<body>
<script type="text/javascript">
var bool = new Boolean( );
document.write("bool.constructor() is : " + bool.constructor);
</script>
</body>
</html>
The following output is displayed on successful execution of the above code.
bool.constructor() is : function Boolean() { [native code] }
32 Lectures
3.5 hours
Sharad Kumar
40 Lectures
5 hours
Richa Maheshwari
16 Lectures
1 hours
Anadi Sharma
50 Lectures
6.5 hours
Gowthami Swarna
14 Lectures
1 hours
Deepti Trivedi
31 Lectures
1.5 hours
Shweta
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2400,
"s": 2277,
"text": "Javascript Boolean constructor() method returns a reference to the Boolean function that created the instance's prototype."
},
{
"code": null,
"e": 2528,
"s": 2400,
"text": "Use the following syntax to create a Boolean constructor() method. It returns the function that created this object's instance."
},
{
"code": null,
"e": 2551,
"s": 2528,
"text": "boolean.constructor()\n"
},
{
"code": null,
"e": 2823,
"s": 2551,
"text": "<html>\n <head>\n <title>JavaScript constructor() Method</title>\n </head>\n <body>\n <script type=\"text/javascript\">\n var bool = new Boolean( );\n document.write(\"bool.constructor() is : \" + bool.constructor);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 2900,
"s": 2823,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 2962,
"s": 2900,
"text": "bool.constructor() is : function Boolean() { [native code] }\n"
},
{
"code": null,
"e": 2997,
"s": 2962,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3011,
"s": 2997,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 3044,
"s": 3011,
"text": "\n 40 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3062,
"s": 3044,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3095,
"s": 3062,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3109,
"s": 3095,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3144,
"s": 3109,
"text": "\n 50 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3161,
"s": 3144,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 3194,
"s": 3161,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3210,
"s": 3194,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 3245,
"s": 3210,
"text": "\n 31 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3253,
"s": 3245,
"text": " Shweta"
},
{
"code": null,
"e": 3260,
"s": 3253,
"text": " Print"
},
{
"code": null,
"e": 3271,
"s": 3260,
"text": " Add Notes"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.