title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Using OpenCV with Tkinter
|
Open CV is a Python library that is used to work with Computer Vision and other artificial artifacts. Open CV has inbuilt functions and methods which provide access to work with Computer Vision in Artificial Intelligence and Machine Learning. Some of the examples of Open CV are: face detection, object detection, X-ray and other industrial uses.
Using Tkinter Library, we can create an interactive application that uses OpenCV as the essential part of the application.
To create the application, you are required to install OpenCV in your local machine and make sure that Python Pillow package is pre-installed. You can install these packages by typing the following commands in the notebook.
pip install open-cv
pip install Pillow
Once the installation is complete, we can start creating the structure and GUI of the application. The basic functionality of our application would be to open the web camera (if possible) using OpenCV. So, to display each and every captured frame, we can use Python Pillow (PIL) package which converts the frame into an Image. The Image now can be used in a Label widget that iteratively displays every captured frame in the window.
# Import required Libraries
from tkinter import *
from PIL import Image, ImageTk
import cv2
# Create an instance of TKinter Window or frame
win= Tk()
# Set the size of the window
win.geometry("700x350")# Create a Label to capture the Video frames
label =Label(win)
label.grid(row=0, column=0)
cap= cv2.VideoCapture(0)
# Define function to show frame
def show_frames():
# Get the latest frame and convert into Image
cv2image= cv2.cvtColor(cap.read()[1],cv2.COLOR_BGR2RGB)
img = Image.fromarray(cv2image)
# Convert image to PhotoImage
imgtk = ImageTk.PhotoImage(image = img)
label.imgtk = imgtk
label.configure(image=imgtk)
# Repeat after an interval to capture continiously
label.after(20, show_frames)
show_frames()
win.mainloop()
When we execute the above code, it will display a window that opens the user camera to capture the frames.
|
[
{
"code": null,
"e": 1409,
"s": 1062,
"text": "Open CV is a Python library that is used to work with Computer Vision and other artificial artifacts. Open CV has inbuilt functions and methods which provide access to work with Computer Vision in Artificial Intelligence and Machine Learning. Some of the examples of Open CV are: face detection, object detection, X-ray and other industrial uses."
},
{
"code": null,
"e": 1532,
"s": 1409,
"text": "Using Tkinter Library, we can create an interactive application that uses OpenCV as the essential part of the application."
},
{
"code": null,
"e": 1756,
"s": 1532,
"text": "To create the application, you are required to install OpenCV in your local machine and make sure that Python Pillow package is pre-installed. You can install these packages by typing the following commands in the notebook."
},
{
"code": null,
"e": 1795,
"s": 1756,
"text": "pip install open-cv\npip install Pillow"
},
{
"code": null,
"e": 2228,
"s": 1795,
"text": "Once the installation is complete, we can start creating the structure and GUI of the application. The basic functionality of our application would be to open the web camera (if possible) using OpenCV. So, to display each and every captured frame, we can use Python Pillow (PIL) package which converts the frame into an Image. The Image now can be used in a Label widget that iteratively displays every captured frame in the window."
},
{
"code": null,
"e": 3010,
"s": 2228,
"text": "# Import required Libraries\nfrom tkinter import *\nfrom PIL import Image, ImageTk\nimport cv2\n\n# Create an instance of TKinter Window or frame\nwin= Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")# Create a Label to capture the Video frames\nlabel =Label(win)\nlabel.grid(row=0, column=0)\ncap= cv2.VideoCapture(0)\n\n# Define function to show frame\n def show_frames():\n # Get the latest frame and convert into Image\n cv2image= cv2.cvtColor(cap.read()[1],cv2.COLOR_BGR2RGB)\n img = Image.fromarray(cv2image)\n\n # Convert image to PhotoImage\n imgtk = ImageTk.PhotoImage(image = img)\n label.imgtk = imgtk\n label.configure(image=imgtk)\n\n# Repeat after an interval to capture continiously\nlabel.after(20, show_frames)\n\nshow_frames()\nwin.mainloop()"
},
{
"code": null,
"e": 3117,
"s": 3010,
"text": "When we execute the above code, it will display a window that opens the user camera to capture the frames."
}
] |
VBA - CDate Function
|
The Function converts a valid date and time expression to type date.
cdate(date)
Add a button and add the following function.
Private Sub Constant_demo_Click()
Dim a as Variant
Dim b as Variant
a = cdate("Jan 01 2020")
msgbox("The Value of a : " & a)
b = cdate("31 Dec 2050")
msgbox("The Value of b : " & b)
End Sub
When you execute the function, it produces the following output.
The Value of a : 1/01/2020
The Value of b : 31/12/2050
101 Lectures
6 hours
Pavan Lalwani
41 Lectures
3 hours
Arnold Higuit
80 Lectures
5.5 hours
Prashant Panchal
25 Lectures
2 hours
Prashant Panchal
26 Lectures
2 hours
Arnold Higuit
92 Lectures
10.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2004,
"s": 1935,
"text": "The Function converts a valid date and time expression to type date."
},
{
"code": null,
"e": 2017,
"s": 2004,
"text": "cdate(date)\n"
},
{
"code": null,
"e": 2062,
"s": 2017,
"text": "Add a button and add the following function."
},
{
"code": null,
"e": 2278,
"s": 2062,
"text": "Private Sub Constant_demo_Click()\n Dim a as Variant\n Dim b as Variant\n \n a = cdate(\"Jan 01 2020\")\n msgbox(\"The Value of a : \" & a)\n \n b = cdate(\"31 Dec 2050\")\n msgbox(\"The Value of b : \" & b)\nEnd Sub"
},
{
"code": null,
"e": 2343,
"s": 2278,
"text": "When you execute the function, it produces the following output."
},
{
"code": null,
"e": 2400,
"s": 2343,
"text": "The Value of a : 1/01/2020\nThe Value of b : 31/12/2050 \n"
},
{
"code": null,
"e": 2434,
"s": 2400,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2449,
"s": 2434,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 2482,
"s": 2449,
"text": "\n 41 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2497,
"s": 2482,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 2532,
"s": 2497,
"text": "\n 80 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2550,
"s": 2532,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 2583,
"s": 2550,
"text": "\n 25 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2601,
"s": 2583,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 2634,
"s": 2601,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2649,
"s": 2634,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 2685,
"s": 2649,
"text": "\n 92 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 2713,
"s": 2685,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 2720,
"s": 2713,
"text": " Print"
},
{
"code": null,
"e": 2731,
"s": 2720,
"text": " Add Notes"
}
] |
Java NIO - Datagram Channel
|
Java NIO Datagram is used as channel which can send and receive UDP packets over a connection less protocol.By default datagram channel is blocking while it can be use in non blocking mode.In order to make it non-blocking we can use the configureBlocking(false) method.DataGram channel can be open by calling its one of the static method named as open() which can also take IP address as parameter so that it can be used for multi casting.
Datagram channel alike of FileChannel do not connected by default in order to make it connected we have to explicitly call its connect() method.However datagram channel need not be connected in order for the send and receive methods to be used while it must be connected in order to use the read and write methods, since those methods do not accept or return socket addresses.
We can check the connection status of datagram channel by calling its isConnected() method.Once connected, a datagram channel remains connected until it is disconnected or closed.Datagram channels are thread safe and supports multi-threading and concurrency simultaneously.
bind(SocketAddress local) − This method is used to bind the datagram channel's socket to the local address which is provided as the parameter to this method.
bind(SocketAddress local) − This method is used to bind the datagram channel's socket to the local address which is provided as the parameter to this method.
connect(SocketAddress remote) − This method is used to connect the socket to the remote address.
connect(SocketAddress remote) − This method is used to connect the socket to the remote address.
disconnect() − This method is used to disconnect the socket to the remote address.
disconnect() − This method is used to disconnect the socket to the remote address.
getRemoteAddress() − This method return the address of remote location to which the channel's socket is connected.
getRemoteAddress() − This method return the address of remote location to which the channel's socket is connected.
isConnected() − As already mentioned this method returns the status of connection of datagram channel i.e whether it is connected or not.
isConnected() − As already mentioned this method returns the status of connection of datagram channel i.e whether it is connected or not.
open() and open(ProtocolFamily family) − Open method is used open a datagram channel for single address while parametrized open method open channel for multiple addresses represented as protocol family.
open() and open(ProtocolFamily family) − Open method is used open a datagram channel for single address while parametrized open method open channel for multiple addresses represented as protocol family.
read(ByteBuffer dst) − This method is used to read data from the given buffer through datagram channel.
read(ByteBuffer dst) − This method is used to read data from the given buffer through datagram channel.
receive(ByteBuffer dst) − This method is used to receive datagram via this channel.
receive(ByteBuffer dst) − This method is used to receive datagram via this channel.
send(ByteBuffer src, SocketAddress target) − This method is used to send datagram via this channel.
send(ByteBuffer src, SocketAddress target) − This method is used to send datagram via this channel.
The following example shows the how to send data from Java NIO DataGramChannel.
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
public class DatagramChannelServer {
public static void main(String[] args) throws IOException {
DatagramChannel server = DatagramChannel.open();
InetSocketAddress iAdd = new InetSocketAddress("localhost", 8989);
server.bind(iAdd);
System.out.println("Server Started: " + iAdd);
ByteBuffer buffer = ByteBuffer.allocate(1024);
//receive buffer from client.
SocketAddress remoteAdd = server.receive(buffer);
//change mode of buffer
buffer.flip();
int limits = buffer.limit();
byte bytes[] = new byte[limits];
buffer.get(bytes, 0, limits);
String msg = new String(bytes);
System.out.println("Client at " + remoteAdd + " sent: " + msg);
server.send(buffer,remoteAdd);
server.close();
}
}
Server Started: localhost/127.0.0.1:8989
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
public class DatagramChannelClient {
public static void main(String[] args) throws IOException {
DatagramChannel client = null;
client = DatagramChannel.open();
client.bind(null);
String msg = "Hello World!";
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
InetSocketAddress serverAddress = new InetSocketAddress("localhost",
8989);
client.send(buffer, serverAddress);
buffer.clear();
client.receive(buffer);
buffer.flip();
client.close();
}
}
Running the client will print the following output on server.
Server Started: localhost/127.0.0.1:8989
Client at /127.0.0.1:64857 sent: Hello World!
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": 2424,
"s": 1984,
"text": "Java NIO Datagram is used as channel which can send and receive UDP packets over a connection less protocol.By default datagram channel is blocking while it can be use in non blocking mode.In order to make it non-blocking we can use the configureBlocking(false) method.DataGram channel can be open by calling its one of the static method named as open() which can also take IP address as parameter so that it can be used for multi casting."
},
{
"code": null,
"e": 2801,
"s": 2424,
"text": "Datagram channel alike of FileChannel do not connected by default in order to make it connected we have to explicitly call its connect() method.However datagram channel need not be connected in order for the send and receive methods to be used while it must be connected in order to use the read and write methods, since those methods do not accept or return socket addresses."
},
{
"code": null,
"e": 3075,
"s": 2801,
"text": "We can check the connection status of datagram channel by calling its isConnected() method.Once connected, a datagram channel remains connected until it is disconnected or closed.Datagram channels are thread safe and supports multi-threading and concurrency simultaneously."
},
{
"code": null,
"e": 3233,
"s": 3075,
"text": "bind(SocketAddress local) − This method is used to bind the datagram channel's socket to the local address which is provided as the parameter to this method."
},
{
"code": null,
"e": 3391,
"s": 3233,
"text": "bind(SocketAddress local) − This method is used to bind the datagram channel's socket to the local address which is provided as the parameter to this method."
},
{
"code": null,
"e": 3488,
"s": 3391,
"text": "connect(SocketAddress remote) − This method is used to connect the socket to the remote address."
},
{
"code": null,
"e": 3585,
"s": 3488,
"text": "connect(SocketAddress remote) − This method is used to connect the socket to the remote address."
},
{
"code": null,
"e": 3668,
"s": 3585,
"text": "disconnect() − This method is used to disconnect the socket to the remote address."
},
{
"code": null,
"e": 3751,
"s": 3668,
"text": "disconnect() − This method is used to disconnect the socket to the remote address."
},
{
"code": null,
"e": 3866,
"s": 3751,
"text": "getRemoteAddress() − This method return the address of remote location to which the channel's socket is connected."
},
{
"code": null,
"e": 3981,
"s": 3866,
"text": "getRemoteAddress() − This method return the address of remote location to which the channel's socket is connected."
},
{
"code": null,
"e": 4119,
"s": 3981,
"text": "isConnected() − As already mentioned this method returns the status of connection of datagram channel i.e whether it is connected or not."
},
{
"code": null,
"e": 4257,
"s": 4119,
"text": "isConnected() − As already mentioned this method returns the status of connection of datagram channel i.e whether it is connected or not."
},
{
"code": null,
"e": 4460,
"s": 4257,
"text": "open() and open(ProtocolFamily family) − Open method is used open a datagram channel for single address while parametrized open method open channel for multiple addresses represented as protocol family."
},
{
"code": null,
"e": 4663,
"s": 4460,
"text": "open() and open(ProtocolFamily family) − Open method is used open a datagram channel for single address while parametrized open method open channel for multiple addresses represented as protocol family."
},
{
"code": null,
"e": 4767,
"s": 4663,
"text": "read(ByteBuffer dst) − This method is used to read data from the given buffer through datagram channel."
},
{
"code": null,
"e": 4871,
"s": 4767,
"text": "read(ByteBuffer dst) − This method is used to read data from the given buffer through datagram channel."
},
{
"code": null,
"e": 4955,
"s": 4871,
"text": "receive(ByteBuffer dst) − This method is used to receive datagram via this channel."
},
{
"code": null,
"e": 5039,
"s": 4955,
"text": "receive(ByteBuffer dst) − This method is used to receive datagram via this channel."
},
{
"code": null,
"e": 5139,
"s": 5039,
"text": "send(ByteBuffer src, SocketAddress target) − This method is used to send datagram via this channel."
},
{
"code": null,
"e": 5239,
"s": 5139,
"text": "send(ByteBuffer src, SocketAddress target) − This method is used to send datagram via this channel."
},
{
"code": null,
"e": 5319,
"s": 5239,
"text": "The following example shows the how to send data from Java NIO DataGramChannel."
},
{
"code": null,
"e": 6271,
"s": 5319,
"text": "import java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.SocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.DatagramChannel;\n\npublic class DatagramChannelServer {\n public static void main(String[] args) throws IOException {\n DatagramChannel server = DatagramChannel.open();\n InetSocketAddress iAdd = new InetSocketAddress(\"localhost\", 8989);\n server.bind(iAdd);\n System.out.println(\"Server Started: \" + iAdd);\n ByteBuffer buffer = ByteBuffer.allocate(1024);\n //receive buffer from client.\n SocketAddress remoteAdd = server.receive(buffer);\n //change mode of buffer\n buffer.flip();\n int limits = buffer.limit();\n byte bytes[] = new byte[limits];\n buffer.get(bytes, 0, limits);\n String msg = new String(bytes);\n System.out.println(\"Client at \" + remoteAdd + \" sent: \" + msg);\n server.send(buffer,remoteAdd);\n server.close();\n }\n}"
},
{
"code": null,
"e": 6313,
"s": 6271,
"text": "Server Started: localhost/127.0.0.1:8989\n"
},
{
"code": null,
"e": 7015,
"s": 6313,
"text": "import java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.SocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.DatagramChannel;\n\npublic class DatagramChannelClient {\n public static void main(String[] args) throws IOException {\n DatagramChannel client = null;\n client = DatagramChannel.open();\n\n client.bind(null);\n\n String msg = \"Hello World!\";\n ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());\n InetSocketAddress serverAddress = new InetSocketAddress(\"localhost\",\n 8989);\n\n client.send(buffer, serverAddress);\n buffer.clear();\n client.receive(buffer);\n buffer.flip();\n \n client.close();\n }\n}"
},
{
"code": null,
"e": 7077,
"s": 7015,
"text": "Running the client will print the following output on server."
},
{
"code": null,
"e": 7166,
"s": 7077,
"text": "Server Started: localhost/127.0.0.1:8989\nClient at /127.0.0.1:64857 sent: Hello World!\n"
},
{
"code": null,
"e": 7199,
"s": 7166,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7215,
"s": 7199,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7248,
"s": 7215,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7264,
"s": 7248,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7299,
"s": 7264,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7313,
"s": 7299,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7347,
"s": 7313,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7361,
"s": 7347,
"text": " Tushar Kale"
},
{
"code": null,
"e": 7398,
"s": 7361,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7413,
"s": 7398,
"text": " Monica Mittal"
},
{
"code": null,
"e": 7446,
"s": 7413,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7465,
"s": 7446,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7472,
"s": 7465,
"text": " Print"
},
{
"code": null,
"e": 7483,
"s": 7472,
"text": " Add Notes"
}
] |
Bootstrap Glyphicons
|
Bootstrap provides 260 glyphicons from the Glyphicons
Halflings set.
Glyphicons can be used in text, buttons, toolbars, navigation, forms, etc.
Here are some examples of glyphicons:
Envelope glyphicon:
Print glyphicon:
Search glyphicon:
Download glyphicon:
A glyphicon is inserted with the following syntax:
The name part in the syntax above must be replaced with the proper name of the glyphicon.
The following example shows different ways to use glyphicons:
Use a Glyphicon class value to make the span display as a "search" icon.
<span class=""></span>
Start the Exercise
For a complete reference of all glyphicons, go to our complete
Bootstrap Glyphicon Reference.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 69,
"s": 0,
"text": "Bootstrap provides 260 glyphicons from the Glyphicons\nHalflings set."
},
{
"code": null,
"e": 144,
"s": 69,
"text": "Glyphicons can be used in text, buttons, toolbars, navigation, forms, etc."
},
{
"code": null,
"e": 182,
"s": 144,
"text": "Here are some examples of glyphicons:"
},
{
"code": null,
"e": 203,
"s": 182,
"text": "Envelope glyphicon: "
},
{
"code": null,
"e": 221,
"s": 203,
"text": "Print glyphicon: "
},
{
"code": null,
"e": 240,
"s": 221,
"text": "Search glyphicon: "
},
{
"code": null,
"e": 261,
"s": 240,
"text": "Download glyphicon: "
},
{
"code": null,
"e": 312,
"s": 261,
"text": "A glyphicon is inserted with the following syntax:"
},
{
"code": null,
"e": 402,
"s": 312,
"text": "The name part in the syntax above must be replaced with the proper name of the glyphicon."
},
{
"code": null,
"e": 464,
"s": 402,
"text": "The following example shows different ways to use glyphicons:"
},
{
"code": null,
"e": 537,
"s": 464,
"text": "Use a Glyphicon class value to make the span display as a \"search\" icon."
},
{
"code": null,
"e": 561,
"s": 537,
"text": "<span class=\"\"></span>\n"
},
{
"code": null,
"e": 580,
"s": 561,
"text": "Start the Exercise"
},
{
"code": null,
"e": 674,
"s": 580,
"text": "For a complete reference of all glyphicons, go to our complete\nBootstrap Glyphicon Reference."
},
{
"code": null,
"e": 707,
"s": 674,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 749,
"s": 707,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 856,
"s": 749,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 875,
"s": 856,
"text": "help@w3schools.com"
}
] |
4 Reasons Why You Should Use Google Colab for Your Next Project | by Orhan G. Yalçın | Towards Data Science
|
Colaboratory, or Colab for short, is a Google Research product, which allows developers to write and execute Python code through their browser. Google Colab is an excellent tool for deep learning tasks. It is a hosted Jupyter notebook that requires no setup and has an excellent free version, which gives free access to Google computing resources such as GPUs and TPUs.
In this post, we will cover three topics:
1 — Interactive Python Programming Environments: Python, Jupyter Notebook, and Google Colab;
2–4 Additional Features of Google Colab over Jupyter Notebook; and
3 — How to Create a Google Colab Notebook in 5 Easy Steps.
Since Google Colab is built on top of vanilla Jupyter Notebook, which is built on top of Python kernel, let’s look at these technologies before diving into why we should and how we can use Google Colab.
Please note that this is not a sponsored post. I am sharing my views on a product that I have been using for years.
There are several tools used in Python interactive programming environments. The central technology making interaction possible is iPython. IPython is an improved shell and read–eval–print loop (REPL) for Python.
A read–eval–print loop (REPL) is a simple interactive computer programming environment that takes single user inputs, executes them, and returns the result to the user; a program written in a REPL environment is executed piecewise.
“iPython Notebook” is a product developed with iPython accessed as a “notebook” via a web browser. IPython handles two fundamental roles:
The Terminal IPython as a REPL; and
The IPython kernel, which provides computation and communication with the frontend interfaces such as iPython notebook.
Developers can write codes, take notes, and upload media to their iPython notebook. The growth of the iPython notebook project led to Project Jupyter, which contains the notebook tool and the other interactive tools for multiple languages (Julia, Python, and R). Jupyter Notebook and its flexible interface extend the notebook beyond code to visualization, multimedia, collaboration, and many other features, which creates a comfortable environment for data scientists and machine learning experts.
Let’s get into a more detailed analysis of iPython, Jupyter Notebook, and Google Colab.
iPython is a command shell and a kernel, which powers interactive Python notebooks. iPython allows programmers to run their code in a notebook environment quickly. The features that iPython provides can be summarized as follows:
Interactive shells (Terminal and Qt Console).
A web-based notebook interface with support for code, text, and media.
Support for interactive data visualization and GUI toolkits.
Flexible and embeddable interpreters to load into projects.
Parallel computing toolkits.
iPython Project has grown beyond running Python scripts and is on its way to becoming a language-agnostic tool. As of iPython 4.0, the language-agnostic parts are gathered under a new Project, named Project Jupyter. The name Jupyter is a reference to core programming languages supported by Jupyter, which are Julia, Python, and R. As of the implementation of this spin-off decision, iPython, now only focuses on interactive Python whereas Jupyter focuses on tools like the notebook format, message protocol, QT Console, notebook web application.
Project Jupyter is a spin-off open-source project born out of the iPython Project in 2014. Jupyter is forever free for all to use, and it is developed through the consensus of the Jupyter community. Several useful tools are released as part of the Jupyter Project, such as Jupyter Notebook, JupyterLab, Jupyter Hub, and Voilà. While all these tools may be used simultaneously for accompanying purposes, installing Jupyter Notebook suffices the environmental requirements for a basic machine learning project.
On the other hand, as an open-source project, Jupyter tools may be integrated into different toolsets and bundles. Instead of installing Jupyter Notebook through Terminal (for macOS and Linux) or Command Prompt (for Windows), you can use the Anaconda distribution, which will also take care of the environment installation on local machines.
If you want to take your development experience to the next level, Google Colab, which is a cloud-based Jupyter Notebook environment, is the ultimate tool.
Let’s see why:
There are several reasons to opt to use Google Colab instead of a plain Jupyter Notebook instance:
Pre-Installed Libraries
Saved on the Cloud
Collaboration
Free GPU and TPU Use
Let’s see these advantages in more detail:
Anaconda distribution of Jupyter Notebook shipped with several pre-installed data libraries, such as Pandas, NumPy, Matplotlib, which is awesome. Google Colab, on the other hand, provides even more pre-installed machine learning libraries such as Keras, TensorFlow, and PyTorch.
When you opt to use a plain Jupyter notebook as your development environment, everything is saved in your local machine. If you are cautious about privacy, this may be a preferred feature for you. However, if you want your notebooks to be accessible to you from any device with a simple Google log-in, then Google Colab is the way to go. All of your Google Colab notebooks are saved under your Google Drive account, just like your Google Docs and Google Sheets files.
Another great feature that Google Colab offers is the collaboration feature. If you are working with multiple developers on a project, it is great to use Google Colab notebook. Just like collaborating on a Google Docs document, you can co-code with multiple developers using a Google Colab notebook. Besides, you can also share your completed work with other developers.
For me this is a great option since I share all my Colab notebooks with my subscribers thanks to this feature. Subscribe today to get them!
I think this is an absolute no brainer to choose Google Colab instead of a local Jupyter notebook. Google Research lets you use their dedicated GPUs and TPUs for your personal machine learning projects. Speaking from experience, for some projects, the GPU and TPU acceleration make a huge difference even for some small projects. This is one of the main reasons for me to code all my educational projects on Google Colab. Besides, since it uses Google resources, the neural network optimization operations do not mess with my processors, and my cooling fan doesn’t go crazy.
Google Colab is just a specialized version of the Jupyter Notebook, which runs on the cloud and offers free computing resources. The relationship between iPython, Jupyter Notebook, and Google Colab is shown in Figure 3.
So, I assume that you are now convinced that you will use Google Colab for your next project. How are you going to set it up?
It’s fairly simple:
The Google Setup process is relatively easy and can be completed with the following steps across all devices:
Visit the Google Colab page, which will direct you to the Google Colaboratory Welcome Page.
Visit the Google Colab page, which will direct you to the Google Colaboratory Welcome Page.
2. Click the Sign in button on the right top.
3. Sign in with your Gmail account. Create one if you don’t have a Gmail account.
4. As soon as you complete the sign-in process, you are ready to use Google Colab.
5. You may easily create a new Colab notebook on this page by clicking File> New notebook.
You have successfully created a Google Colab notebook within minutes. Now you can start working on your machine learning project.
In this post, we talked about three complementary interactive programming environments. iPython provides a useful kernel to run interactive codes. Jupyter Notebook provides a beautiful notebook with cells that you can add code, media, and text. Finally, Google Colab adds collaboration, free GPU and TPU, cloud features, and additional pre-installed ML libraries.
I can think of two scenarios where you should opt for a local Jupyter Notebook instance:
1 — If you care about privacy and want to keep your code hidden, stay away from Google Colab; or
2 — If you have an incredibly powerful local machine with access to GPUs and TPUs, also local Jupyter Notebook is the way to go.
But, for almost all the other scenarios, I’d recommend Google Colab. I hope this post was helpful in understanding the relationship between iPython, Jupyter Notebook, and Google Colab notebook.
Besides my latest content, I also share my Google Colab notebooks with my subscribers, containing full codes for every post I published.
If you liked this post, consider subscribing to the Newsletter! ✉️
Subscribe Now
Since you are reading this article, I am sure that we share similar interests and are/will be in similar industries. So let’s connect via Linkedin! Please do not hesitate to send a contact request! Orhan G. Yalçın — Linkedin
|
[
{
"code": null,
"e": 542,
"s": 172,
"text": "Colaboratory, or Colab for short, is a Google Research product, which allows developers to write and execute Python code through their browser. Google Colab is an excellent tool for deep learning tasks. It is a hosted Jupyter notebook that requires no setup and has an excellent free version, which gives free access to Google computing resources such as GPUs and TPUs."
},
{
"code": null,
"e": 584,
"s": 542,
"text": "In this post, we will cover three topics:"
},
{
"code": null,
"e": 677,
"s": 584,
"text": "1 — Interactive Python Programming Environments: Python, Jupyter Notebook, and Google Colab;"
},
{
"code": null,
"e": 744,
"s": 677,
"text": "2–4 Additional Features of Google Colab over Jupyter Notebook; and"
},
{
"code": null,
"e": 803,
"s": 744,
"text": "3 — How to Create a Google Colab Notebook in 5 Easy Steps."
},
{
"code": null,
"e": 1006,
"s": 803,
"text": "Since Google Colab is built on top of vanilla Jupyter Notebook, which is built on top of Python kernel, let’s look at these technologies before diving into why we should and how we can use Google Colab."
},
{
"code": null,
"e": 1122,
"s": 1006,
"text": "Please note that this is not a sponsored post. I am sharing my views on a product that I have been using for years."
},
{
"code": null,
"e": 1335,
"s": 1122,
"text": "There are several tools used in Python interactive programming environments. The central technology making interaction possible is iPython. IPython is an improved shell and read–eval–print loop (REPL) for Python."
},
{
"code": null,
"e": 1567,
"s": 1335,
"text": "A read–eval–print loop (REPL) is a simple interactive computer programming environment that takes single user inputs, executes them, and returns the result to the user; a program written in a REPL environment is executed piecewise."
},
{
"code": null,
"e": 1705,
"s": 1567,
"text": "“iPython Notebook” is a product developed with iPython accessed as a “notebook” via a web browser. IPython handles two fundamental roles:"
},
{
"code": null,
"e": 1741,
"s": 1705,
"text": "The Terminal IPython as a REPL; and"
},
{
"code": null,
"e": 1861,
"s": 1741,
"text": "The IPython kernel, which provides computation and communication with the frontend interfaces such as iPython notebook."
},
{
"code": null,
"e": 2360,
"s": 1861,
"text": "Developers can write codes, take notes, and upload media to their iPython notebook. The growth of the iPython notebook project led to Project Jupyter, which contains the notebook tool and the other interactive tools for multiple languages (Julia, Python, and R). Jupyter Notebook and its flexible interface extend the notebook beyond code to visualization, multimedia, collaboration, and many other features, which creates a comfortable environment for data scientists and machine learning experts."
},
{
"code": null,
"e": 2448,
"s": 2360,
"text": "Let’s get into a more detailed analysis of iPython, Jupyter Notebook, and Google Colab."
},
{
"code": null,
"e": 2677,
"s": 2448,
"text": "iPython is a command shell and a kernel, which powers interactive Python notebooks. iPython allows programmers to run their code in a notebook environment quickly. The features that iPython provides can be summarized as follows:"
},
{
"code": null,
"e": 2723,
"s": 2677,
"text": "Interactive shells (Terminal and Qt Console)."
},
{
"code": null,
"e": 2794,
"s": 2723,
"text": "A web-based notebook interface with support for code, text, and media."
},
{
"code": null,
"e": 2855,
"s": 2794,
"text": "Support for interactive data visualization and GUI toolkits."
},
{
"code": null,
"e": 2915,
"s": 2855,
"text": "Flexible and embeddable interpreters to load into projects."
},
{
"code": null,
"e": 2944,
"s": 2915,
"text": "Parallel computing toolkits."
},
{
"code": null,
"e": 3491,
"s": 2944,
"text": "iPython Project has grown beyond running Python scripts and is on its way to becoming a language-agnostic tool. As of iPython 4.0, the language-agnostic parts are gathered under a new Project, named Project Jupyter. The name Jupyter is a reference to core programming languages supported by Jupyter, which are Julia, Python, and R. As of the implementation of this spin-off decision, iPython, now only focuses on interactive Python whereas Jupyter focuses on tools like the notebook format, message protocol, QT Console, notebook web application."
},
{
"code": null,
"e": 4001,
"s": 3491,
"text": "Project Jupyter is a spin-off open-source project born out of the iPython Project in 2014. Jupyter is forever free for all to use, and it is developed through the consensus of the Jupyter community. Several useful tools are released as part of the Jupyter Project, such as Jupyter Notebook, JupyterLab, Jupyter Hub, and Voilà. While all these tools may be used simultaneously for accompanying purposes, installing Jupyter Notebook suffices the environmental requirements for a basic machine learning project."
},
{
"code": null,
"e": 4343,
"s": 4001,
"text": "On the other hand, as an open-source project, Jupyter tools may be integrated into different toolsets and bundles. Instead of installing Jupyter Notebook through Terminal (for macOS and Linux) or Command Prompt (for Windows), you can use the Anaconda distribution, which will also take care of the environment installation on local machines."
},
{
"code": null,
"e": 4499,
"s": 4343,
"text": "If you want to take your development experience to the next level, Google Colab, which is a cloud-based Jupyter Notebook environment, is the ultimate tool."
},
{
"code": null,
"e": 4514,
"s": 4499,
"text": "Let’s see why:"
},
{
"code": null,
"e": 4613,
"s": 4514,
"text": "There are several reasons to opt to use Google Colab instead of a plain Jupyter Notebook instance:"
},
{
"code": null,
"e": 4637,
"s": 4613,
"text": "Pre-Installed Libraries"
},
{
"code": null,
"e": 4656,
"s": 4637,
"text": "Saved on the Cloud"
},
{
"code": null,
"e": 4670,
"s": 4656,
"text": "Collaboration"
},
{
"code": null,
"e": 4691,
"s": 4670,
"text": "Free GPU and TPU Use"
},
{
"code": null,
"e": 4734,
"s": 4691,
"text": "Let’s see these advantages in more detail:"
},
{
"code": null,
"e": 5013,
"s": 4734,
"text": "Anaconda distribution of Jupyter Notebook shipped with several pre-installed data libraries, such as Pandas, NumPy, Matplotlib, which is awesome. Google Colab, on the other hand, provides even more pre-installed machine learning libraries such as Keras, TensorFlow, and PyTorch."
},
{
"code": null,
"e": 5481,
"s": 5013,
"text": "When you opt to use a plain Jupyter notebook as your development environment, everything is saved in your local machine. If you are cautious about privacy, this may be a preferred feature for you. However, if you want your notebooks to be accessible to you from any device with a simple Google log-in, then Google Colab is the way to go. All of your Google Colab notebooks are saved under your Google Drive account, just like your Google Docs and Google Sheets files."
},
{
"code": null,
"e": 5852,
"s": 5481,
"text": "Another great feature that Google Colab offers is the collaboration feature. If you are working with multiple developers on a project, it is great to use Google Colab notebook. Just like collaborating on a Google Docs document, you can co-code with multiple developers using a Google Colab notebook. Besides, you can also share your completed work with other developers."
},
{
"code": null,
"e": 5992,
"s": 5852,
"text": "For me this is a great option since I share all my Colab notebooks with my subscribers thanks to this feature. Subscribe today to get them!"
},
{
"code": null,
"e": 6567,
"s": 5992,
"text": "I think this is an absolute no brainer to choose Google Colab instead of a local Jupyter notebook. Google Research lets you use their dedicated GPUs and TPUs for your personal machine learning projects. Speaking from experience, for some projects, the GPU and TPU acceleration make a huge difference even for some small projects. This is one of the main reasons for me to code all my educational projects on Google Colab. Besides, since it uses Google resources, the neural network optimization operations do not mess with my processors, and my cooling fan doesn’t go crazy."
},
{
"code": null,
"e": 6787,
"s": 6567,
"text": "Google Colab is just a specialized version of the Jupyter Notebook, which runs on the cloud and offers free computing resources. The relationship between iPython, Jupyter Notebook, and Google Colab is shown in Figure 3."
},
{
"code": null,
"e": 6913,
"s": 6787,
"text": "So, I assume that you are now convinced that you will use Google Colab for your next project. How are you going to set it up?"
},
{
"code": null,
"e": 6933,
"s": 6913,
"text": "It’s fairly simple:"
},
{
"code": null,
"e": 7043,
"s": 6933,
"text": "The Google Setup process is relatively easy and can be completed with the following steps across all devices:"
},
{
"code": null,
"e": 7135,
"s": 7043,
"text": "Visit the Google Colab page, which will direct you to the Google Colaboratory Welcome Page."
},
{
"code": null,
"e": 7227,
"s": 7135,
"text": "Visit the Google Colab page, which will direct you to the Google Colaboratory Welcome Page."
},
{
"code": null,
"e": 7273,
"s": 7227,
"text": "2. Click the Sign in button on the right top."
},
{
"code": null,
"e": 7355,
"s": 7273,
"text": "3. Sign in with your Gmail account. Create one if you don’t have a Gmail account."
},
{
"code": null,
"e": 7438,
"s": 7355,
"text": "4. As soon as you complete the sign-in process, you are ready to use Google Colab."
},
{
"code": null,
"e": 7529,
"s": 7438,
"text": "5. You may easily create a new Colab notebook on this page by clicking File> New notebook."
},
{
"code": null,
"e": 7659,
"s": 7529,
"text": "You have successfully created a Google Colab notebook within minutes. Now you can start working on your machine learning project."
},
{
"code": null,
"e": 8023,
"s": 7659,
"text": "In this post, we talked about three complementary interactive programming environments. iPython provides a useful kernel to run interactive codes. Jupyter Notebook provides a beautiful notebook with cells that you can add code, media, and text. Finally, Google Colab adds collaboration, free GPU and TPU, cloud features, and additional pre-installed ML libraries."
},
{
"code": null,
"e": 8112,
"s": 8023,
"text": "I can think of two scenarios where you should opt for a local Jupyter Notebook instance:"
},
{
"code": null,
"e": 8209,
"s": 8112,
"text": "1 — If you care about privacy and want to keep your code hidden, stay away from Google Colab; or"
},
{
"code": null,
"e": 8338,
"s": 8209,
"text": "2 — If you have an incredibly powerful local machine with access to GPUs and TPUs, also local Jupyter Notebook is the way to go."
},
{
"code": null,
"e": 8532,
"s": 8338,
"text": "But, for almost all the other scenarios, I’d recommend Google Colab. I hope this post was helpful in understanding the relationship between iPython, Jupyter Notebook, and Google Colab notebook."
},
{
"code": null,
"e": 8669,
"s": 8532,
"text": "Besides my latest content, I also share my Google Colab notebooks with my subscribers, containing full codes for every post I published."
},
{
"code": null,
"e": 8736,
"s": 8669,
"text": "If you liked this post, consider subscribing to the Newsletter! ✉️"
},
{
"code": null,
"e": 8750,
"s": 8736,
"text": "Subscribe Now"
}
] |
How to display regression slope using model in a plot created by ggplot2 in R?
|
To display regression slope using model in a plot created by ggplot2, we can follow the below steps −
First of all, create the data frame.
Use annotate function of ggplot2 to create the scatterplot with regression slope displayed on the plot.
Check the regression slope.
Let's create a data frame as shown below −
Live Demo
x<-rnorm(25)
y<-rnorm(25)
df<-data.frame(x,y)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x y
1 -0.3344355 -1.107060779
2 0.9164450 -2.499279489
3 -1.2110213 -1.232242802
4 -0.2469611 -0.002048849
5 0.8153152 0.096430178
6 1.5256898 0.366641036
7 0.2477990 -0.887210596
8 -0.5315179 1.594046357
9 -0.3118217 -0.059540798
10 -2.3218482 -0.578005944
11 -0.2519221 -1.470768208
12 0.8210061 -0.252782378
13 0.3679411 0.907479636
14 -1.1653608 -1.645537248
15 -2.7027016 -0.543878325
16 -0.2973516 0.217316266
17 0.1234872 0.749658413
18 1.1059414 0.204091591
19 0.6868014 0.976441196
20 -1.2037182 0.560449928
21 0.1567828 -0.799122836
22 0.5292457 -2.364608009
23 -0.9377216 0.347594404
24 0.5401030 -1.615585141
25 -0.5440631 0.637820747
Creating the scatterplot with regression line and slope of the model displayed on the plot −
Live Demo
x<-rnorm(25)
y<-rnorm(25)
df<-data.frame(x,y)
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()+stat_smooth(method="lm",se=F)+annotate("text",x=-
2,y=1,label=(paste0("slope==",coef(lm(df$y~df$x))[2])),parse=TRUE)
`geom_smooth()` using formula 'y ~ x'
Use coeff function to find the slope of the model and check if it matches with the one displayed in the plot −
x<-rnorm(25)
y<-rnorm(25)
df<-data.frame(x,y)
coef(lm(df$y~df$x))[2]
df$x
0.01180069
|
[
{
"code": null,
"e": 1164,
"s": 1062,
"text": "To display regression slope using model in a plot created by ggplot2, we can follow the below steps −"
},
{
"code": null,
"e": 1201,
"s": 1164,
"text": "First of all, create the data frame."
},
{
"code": null,
"e": 1305,
"s": 1201,
"text": "Use annotate function of ggplot2 to create the scatterplot with regression slope displayed on the plot."
},
{
"code": null,
"e": 1333,
"s": 1305,
"text": "Check the regression slope."
},
{
"code": null,
"e": 1376,
"s": 1333,
"text": "Let's create a data frame as shown below −"
},
{
"code": null,
"e": 1387,
"s": 1376,
"text": " Live Demo"
},
{
"code": null,
"e": 1436,
"s": 1387,
"text": "x<-rnorm(25)\ny<-rnorm(25)\ndf<-data.frame(x,y)\ndf"
},
{
"code": null,
"e": 1555,
"s": 1436,
"text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −"
},
{
"code": null,
"e": 2217,
"s": 1555,
"text": " x y\n1 -0.3344355 -1.107060779\n2 0.9164450 -2.499279489\n3 -1.2110213 -1.232242802\n4 -0.2469611 -0.002048849\n5 0.8153152 0.096430178\n6 1.5256898 0.366641036\n7 0.2477990 -0.887210596\n8 -0.5315179 1.594046357\n9 -0.3118217 -0.059540798\n10 -2.3218482 -0.578005944\n11 -0.2519221 -1.470768208\n12 0.8210061 -0.252782378\n13 0.3679411 0.907479636\n14 -1.1653608 -1.645537248\n15 -2.7027016 -0.543878325\n16 -0.2973516 0.217316266\n17 0.1234872 0.749658413\n18 1.1059414 0.204091591\n19 0.6868014 0.976441196\n20 -1.2037182 0.560449928\n21 0.1567828 -0.799122836\n22 0.5292457 -2.364608009\n23 -0.9377216 0.347594404\n24 0.5401030 -1.615585141\n25 -0.5440631 0.637820747"
},
{
"code": null,
"e": 2310,
"s": 2217,
"text": "Creating the scatterplot with regression line and slope of the model displayed on the plot −"
},
{
"code": null,
"e": 2321,
"s": 2310,
"text": " Live Demo"
},
{
"code": null,
"e": 2572,
"s": 2321,
"text": "x<-rnorm(25)\ny<-rnorm(25)\ndf<-data.frame(x,y)\nlibrary(ggplot2)\nggplot(df,aes(x,y))+geom_point()+stat_smooth(method=\"lm\",se=F)+annotate(\"text\",x=-\n2,y=1,label=(paste0(\"slope==\",coef(lm(df$y~df$x))[2])),parse=TRUE)\n`geom_smooth()` using formula 'y ~ x'"
},
{
"code": null,
"e": 2683,
"s": 2572,
"text": "Use coeff function to find the slope of the model and check if it matches with the one displayed in the plot −"
},
{
"code": null,
"e": 2752,
"s": 2683,
"text": "x<-rnorm(25)\ny<-rnorm(25)\ndf<-data.frame(x,y)\ncoef(lm(df$y~df$x))[2]"
},
{
"code": null,
"e": 2768,
"s": 2752,
"text": "df$x\n0.01180069"
}
] |
DAX Math & Trigonometric - ROUND function
|
Rounds a number to the specified number of digits.
ROUND (<number>, <num_digits>)
number
The number you want to round.
num_digits
The number of digits to which you want to round.
A decimal number.
If num_digits > 0, then the number is rounded to the specified number of decimal places.
If num_digits > 0, then the number is rounded to the specified number of decimal places.
If num_digits = 0, the number is rounded to the nearest integer.
If num_digits = 0, the number is rounded to the nearest integer.
If num_digits < 0, the number is rounded to the left of the decimal point.
If num_digits < 0, the number is rounded to the left of the decimal point.
You can also use the following DAX functions in specific instances −
DAX ROUNDUP function to always round up (away from zero).
DAX ROUNDUP function to always round up (away from zero).
DAX ROUNDDOWN function to always round down (toward zero).
DAX ROUNDDOWN function to always round down (toward zero).
DAX MROUND function to round a number to a specific multiple.
DAX MROUND function to round a number to a specific multiple.
DAX TRUNC and INT functions to obtain the integer portion of the number.
DAX TRUNC and INT functions to obtain the integer portion of the number.
= ROUND (5.5555555,2) returns 5.56.
= ROUND (5.5555555,0) returns 6.
= ROUND (5.5555555, -1) returns 10.
= ROUND (5.5555555, -2) returns 0.
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2052,
"s": 2001,
"text": "Rounds a number to the specified number of digits."
},
{
"code": null,
"e": 2085,
"s": 2052,
"text": "ROUND (<number>, <num_digits>) \n"
},
{
"code": null,
"e": 2092,
"s": 2085,
"text": "number"
},
{
"code": null,
"e": 2122,
"s": 2092,
"text": "The number you want to round."
},
{
"code": null,
"e": 2133,
"s": 2122,
"text": "num_digits"
},
{
"code": null,
"e": 2182,
"s": 2133,
"text": "The number of digits to which you want to round."
},
{
"code": null,
"e": 2200,
"s": 2182,
"text": "A decimal number."
},
{
"code": null,
"e": 2289,
"s": 2200,
"text": "If num_digits > 0, then the number is rounded to the specified number of decimal places."
},
{
"code": null,
"e": 2378,
"s": 2289,
"text": "If num_digits > 0, then the number is rounded to the specified number of decimal places."
},
{
"code": null,
"e": 2443,
"s": 2378,
"text": "If num_digits = 0, the number is rounded to the nearest integer."
},
{
"code": null,
"e": 2508,
"s": 2443,
"text": "If num_digits = 0, the number is rounded to the nearest integer."
},
{
"code": null,
"e": 2583,
"s": 2508,
"text": "If num_digits < 0, the number is rounded to the left of the decimal point."
},
{
"code": null,
"e": 2658,
"s": 2583,
"text": "If num_digits < 0, the number is rounded to the left of the decimal point."
},
{
"code": null,
"e": 2727,
"s": 2658,
"text": "You can also use the following DAX functions in specific instances −"
},
{
"code": null,
"e": 2785,
"s": 2727,
"text": "DAX ROUNDUP function to always round up (away from zero)."
},
{
"code": null,
"e": 2843,
"s": 2785,
"text": "DAX ROUNDUP function to always round up (away from zero)."
},
{
"code": null,
"e": 2902,
"s": 2843,
"text": "DAX ROUNDDOWN function to always round down (toward zero)."
},
{
"code": null,
"e": 2961,
"s": 2902,
"text": "DAX ROUNDDOWN function to always round down (toward zero)."
},
{
"code": null,
"e": 3023,
"s": 2961,
"text": "DAX MROUND function to round a number to a specific multiple."
},
{
"code": null,
"e": 3085,
"s": 3023,
"text": "DAX MROUND function to round a number to a specific multiple."
},
{
"code": null,
"e": 3158,
"s": 3085,
"text": "DAX TRUNC and INT functions to obtain the integer portion of the number."
},
{
"code": null,
"e": 3231,
"s": 3158,
"text": "DAX TRUNC and INT functions to obtain the integer portion of the number."
},
{
"code": null,
"e": 3375,
"s": 3231,
"text": "= ROUND (5.5555555,2) returns 5.56. \n= ROUND (5.5555555,0) returns 6. \n= ROUND (5.5555555, -1) returns 10. \n= ROUND (5.5555555, -2) returns 0. "
},
{
"code": null,
"e": 3410,
"s": 3375,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3424,
"s": 3410,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3457,
"s": 3424,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3471,
"s": 3457,
"text": " Randy Minder"
},
{
"code": null,
"e": 3506,
"s": 3471,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3520,
"s": 3506,
"text": " Randy Minder"
},
{
"code": null,
"e": 3527,
"s": 3520,
"text": " Print"
},
{
"code": null,
"e": 3538,
"s": 3527,
"text": " Add Notes"
}
] |
Program for product of array
|
26 May, 2022
Given an array, find a product of all array elements.Examples :
Input : ar[] = {1, 2, 3, 4, 5}
Output : 120
Product of array elements is 1 x 2
x 3 x 4 x 5 = 120.
Input : ar[] = {1, 6, 3}
Output : 18
C
Java
Python3
C#
PHP
Javascript
// C program to find product of array// elements.#include <stdio.h> int product(int ar[], int n){ int result = 1; for (int i = 0; i < n; i++) result = result * ar[i]; return result;} // driver code for the above programint main(){ int ar[] = { 1, 2, 3, 4, 5 }; int n = sizeof(ar) / sizeof(ar[0]); printf("%d", product(a, n)); return 0;}
// Java program to find product of array// elements.class GFG{ static int product(int ar[], int n) { int result = 1; for (int i = 0; i < n; i++) result = result * ar[i]; return result; } // driver code for the above program public static void main(String[] args) { int ar[] = { 1, 2, 3, 4, 5 }; int n = ar.length; System.out.printf("%d", product(ar, n)); }} // This code is contributed by Smitha Dinesh Semwal
# Python3 program to find# product of array elements.def product(ar, n): result = 1 for i in range(0, n): result = result * ar[i] return result # Driver Codear = [ 1, 2, 3, 4, 5 ]n = len(ar) print(product(ar, n)) # This code is contributed by Smitha Dinesh Semwal.
// C# program to find product of array// elements.using System; class GFG { static int product(int []ar, int n) { int result = 1; for (int i = 0; i < n; i++) result = result * ar[i]; return result; } // driver code for the above program public static void Main() { int []ar = { 1, 2, 3, 4, 5 }; int n = ar.Length; Console.WriteLine(product(ar, n)); }} // This code is contributed by vt_m.
<?php// PHP program to find product// of array elements. function product($ar, $n){ $result = 1; for ($i = 0; $i < $n; $i++) $result = $result * $ar[$i]; return $result;} // Driver Code$ar = array( 1, 2, 3, 4, 5 );$n = count($ar);print((int)product($ar, $n)); // This code is contributed by Sam007?>
<script> // Javascript program to find product of array// elements.function product(ar,n) { let result = 1; for (let i = 0; i < n; i++) result = result * ar[i]; return result; } // driver code for the above program let ar = [ 1, 2, 3, 4, 5 ]; let n = ar.length; document.write(parseInt(product(ar, n))); // This code is Contributed by sravan kumar </script>
Output :
120
Time Complexity : O(n)
Auxiliary Space : O(1) The above code may cause overflow. Therefore, it is always desired to compute product under modulo. The reason for its working is the simple distributive property of modulo.
( a * b) % c = ( ( a % c ) * ( b % c ) ) % c
Below is a program to find and print the product of all the number in this array of Modulo (10^9 +7).
C
Java
Python3
C#
PHP
Javascript
// C code for above program to find product// under modulo.#include <stdio.h> const int MOD = 1000000007; int product(int ar[], int n){ int result = 1; for (int i = 0; i < n; i++) result = (result * ar[i]) % MOD; return result;} // driver code for the above programint main(){ int ar[] = { 1, 2, 3, 4, 5 }; int n = sizeof(ar) / sizeof(ar[0]); printf("%d", product(ar, n)); return 0;}
// Java code for above program to find product// under modulo.class GFG { static final int MOD = 1000000007; static int product(int ar[], int n) { int result = 1; for (int i = 0; i < n; i++) result = (result * ar[i]) % MOD; return result; } // driver code for the above program public static void main(String[] args) { int ar[] = { 1, 2, 3, 4, 5 }; int n = ar.length; System.out.printf("%d", product(ar, n)); }} // This code is contributed by Smitha Dinesh Semwal.
# Python 3 code for above# program to find product# under modulo. MOD = 1000000007 def product(ar, n): result = 1 for i in range(0, n): result = (result * ar[i]) % MOD return result # driver code for the# above programar = [1, 2, 3, 4, 5]n = len(ar) print(product(ar, n)) # This code is contributed by# Smitha Dinesh Semwal
// C# code for above program to find product// under modulo.using System;class GFG { static int MOD = 1000000007; static int product(int []ar, int n) { int result = 1; for (int i = 0; i < n; i++) result = (result * ar[i]) % MOD; return result; } // driver code for the above program public static void Main() { int []ar = { 1, 2, 3, 4, 5 }; int n = ar.Length; Console.WriteLine(product(ar, n)); }} // This code is contributed by vt_m.
<?php// PHP code for above program// to find product under modulo. function product($ar, $n){ $result = 1; for ($i = 0; $i < $n; $i++) $result = ($result * $ar[$i]) % 1000000007; return $result;} // Driver Code$ar = array( 1, 2, 3, 4, 5 );$n = count($ar);print(product($ar, $n)); // This code is contributed by Sam007?>
<script> // Javascript code for above program to find product under modulo. let MOD = 1000000007; function product(ar, n) { let result = 1; for (let i = 0; i < n; i++) result = (result * ar[i]) % MOD; return result; } let ar = [ 1, 2, 3, 4, 5 ]; let n = ar.length; document.write(product(ar, n)); </script>
Output :
120
Time Complexity : O(n)
Auxiliary Space : O(1) This article is contributed by Shivani Baghel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
vt_m
Sam007
sravankumar8128
divyesh072019
rohitmishra051000
Modular Arithmetic
Arrays
School Programming
Arrays
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
Python Dictionary
Reverse a string in Java
Introduction To PYTHON
Interfaces in Java
Inheritance in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 May, 2022"
},
{
"code": null,
"e": 118,
"s": 52,
"text": "Given an array, find a product of all array elements.Examples : "
},
{
"code": null,
"e": 256,
"s": 118,
"text": "Input : ar[] = {1, 2, 3, 4, 5}\nOutput : 120\nProduct of array elements is 1 x 2\nx 3 x 4 x 5 = 120.\n\nInput : ar[] = {1, 6, 3}\nOutput : 18"
},
{
"code": null,
"e": 262,
"s": 260,
"text": "C"
},
{
"code": null,
"e": 267,
"s": 262,
"text": "Java"
},
{
"code": null,
"e": 275,
"s": 267,
"text": "Python3"
},
{
"code": null,
"e": 278,
"s": 275,
"text": "C#"
},
{
"code": null,
"e": 282,
"s": 278,
"text": "PHP"
},
{
"code": null,
"e": 293,
"s": 282,
"text": "Javascript"
},
{
"code": "// C program to find product of array// elements.#include <stdio.h> int product(int ar[], int n){ int result = 1; for (int i = 0; i < n; i++) result = result * ar[i]; return result;} // driver code for the above programint main(){ int ar[] = { 1, 2, 3, 4, 5 }; int n = sizeof(ar) / sizeof(ar[0]); printf(\"%d\", product(a, n)); return 0;}",
"e": 658,
"s": 293,
"text": null
},
{
"code": "// Java program to find product of array// elements.class GFG{ static int product(int ar[], int n) { int result = 1; for (int i = 0; i < n; i++) result = result * ar[i]; return result; } // driver code for the above program public static void main(String[] args) { int ar[] = { 1, 2, 3, 4, 5 }; int n = ar.length; System.out.printf(\"%d\", product(ar, n)); }} // This code is contributed by Smitha Dinesh Semwal",
"e": 1149,
"s": 658,
"text": null
},
{
"code": "# Python3 program to find# product of array elements.def product(ar, n): result = 1 for i in range(0, n): result = result * ar[i] return result # Driver Codear = [ 1, 2, 3, 4, 5 ]n = len(ar) print(product(ar, n)) # This code is contributed by Smitha Dinesh Semwal.",
"e": 1432,
"s": 1149,
"text": null
},
{
"code": "// C# program to find product of array// elements.using System; class GFG { static int product(int []ar, int n) { int result = 1; for (int i = 0; i < n; i++) result = result * ar[i]; return result; } // driver code for the above program public static void Main() { int []ar = { 1, 2, 3, 4, 5 }; int n = ar.Length; Console.WriteLine(product(ar, n)); }} // This code is contributed by vt_m.",
"e": 1932,
"s": 1432,
"text": null
},
{
"code": "<?php// PHP program to find product// of array elements. function product($ar, $n){ $result = 1; for ($i = 0; $i < $n; $i++) $result = $result * $ar[$i]; return $result;} // Driver Code$ar = array( 1, 2, 3, 4, 5 );$n = count($ar);print((int)product($ar, $n)); // This code is contributed by Sam007?>",
"e": 2248,
"s": 1932,
"text": null
},
{
"code": "<script> // Javascript program to find product of array// elements.function product(ar,n) { let result = 1; for (let i = 0; i < n; i++) result = result * ar[i]; return result; } // driver code for the above program let ar = [ 1, 2, 3, 4, 5 ]; let n = ar.length; document.write(parseInt(product(ar, n))); // This code is Contributed by sravan kumar </script>",
"e": 2692,
"s": 2248,
"text": null
},
{
"code": null,
"e": 2702,
"s": 2692,
"text": "Output : "
},
{
"code": null,
"e": 2706,
"s": 2702,
"text": "120"
},
{
"code": null,
"e": 2729,
"s": 2706,
"text": "Time Complexity : O(n)"
},
{
"code": null,
"e": 2928,
"s": 2729,
"text": "Auxiliary Space : O(1) The above code may cause overflow. Therefore, it is always desired to compute product under modulo. The reason for its working is the simple distributive property of modulo. "
},
{
"code": null,
"e": 2973,
"s": 2928,
"text": "( a * b) % c = ( ( a % c ) * ( b % c ) ) % c"
},
{
"code": null,
"e": 3077,
"s": 2973,
"text": "Below is a program to find and print the product of all the number in this array of Modulo (10^9 +7). "
},
{
"code": null,
"e": 3079,
"s": 3077,
"text": "C"
},
{
"code": null,
"e": 3084,
"s": 3079,
"text": "Java"
},
{
"code": null,
"e": 3092,
"s": 3084,
"text": "Python3"
},
{
"code": null,
"e": 3095,
"s": 3092,
"text": "C#"
},
{
"code": null,
"e": 3099,
"s": 3095,
"text": "PHP"
},
{
"code": null,
"e": 3110,
"s": 3099,
"text": "Javascript"
},
{
"code": "// C code for above program to find product// under modulo.#include <stdio.h> const int MOD = 1000000007; int product(int ar[], int n){ int result = 1; for (int i = 0; i < n; i++) result = (result * ar[i]) % MOD; return result;} // driver code for the above programint main(){ int ar[] = { 1, 2, 3, 4, 5 }; int n = sizeof(ar) / sizeof(ar[0]); printf(\"%d\", product(ar, n)); return 0;}",
"e": 3522,
"s": 3110,
"text": null
},
{
"code": "// Java code for above program to find product// under modulo.class GFG { static final int MOD = 1000000007; static int product(int ar[], int n) { int result = 1; for (int i = 0; i < n; i++) result = (result * ar[i]) % MOD; return result; } // driver code for the above program public static void main(String[] args) { int ar[] = { 1, 2, 3, 4, 5 }; int n = ar.length; System.out.printf(\"%d\", product(ar, n)); }} // This code is contributed by Smitha Dinesh Semwal.",
"e": 4094,
"s": 3522,
"text": null
},
{
"code": "# Python 3 code for above# program to find product# under modulo. MOD = 1000000007 def product(ar, n): result = 1 for i in range(0, n): result = (result * ar[i]) % MOD return result # driver code for the# above programar = [1, 2, 3, 4, 5]n = len(ar) print(product(ar, n)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 4436,
"s": 4094,
"text": null
},
{
"code": " // C# code for above program to find product// under modulo.using System;class GFG { static int MOD = 1000000007; static int product(int []ar, int n) { int result = 1; for (int i = 0; i < n; i++) result = (result * ar[i]) % MOD; return result; } // driver code for the above program public static void Main() { int []ar = { 1, 2, 3, 4, 5 }; int n = ar.Length; Console.WriteLine(product(ar, n)); }} // This code is contributed by vt_m.",
"e": 4980,
"s": 4436,
"text": null
},
{
"code": "<?php// PHP code for above program// to find product under modulo. function product($ar, $n){ $result = 1; for ($i = 0; $i < $n; $i++) $result = ($result * $ar[$i]) % 1000000007; return $result;} // Driver Code$ar = array( 1, 2, 3, 4, 5 );$n = count($ar);print(product($ar, $n)); // This code is contributed by Sam007?>",
"e": 5334,
"s": 4980,
"text": null
},
{
"code": "<script> // Javascript code for above program to find product under modulo. let MOD = 1000000007; function product(ar, n) { let result = 1; for (let i = 0; i < n; i++) result = (result * ar[i]) % MOD; return result; } let ar = [ 1, 2, 3, 4, 5 ]; let n = ar.length; document.write(product(ar, n)); </script>",
"e": 5733,
"s": 5334,
"text": null
},
{
"code": null,
"e": 5743,
"s": 5733,
"text": "Output : "
},
{
"code": null,
"e": 5747,
"s": 5743,
"text": "120"
},
{
"code": null,
"e": 5770,
"s": 5747,
"text": "Time Complexity : O(n)"
},
{
"code": null,
"e": 6216,
"s": 5770,
"text": "Auxiliary Space : O(1) This article is contributed by Shivani Baghel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 6221,
"s": 6216,
"text": "vt_m"
},
{
"code": null,
"e": 6228,
"s": 6221,
"text": "Sam007"
},
{
"code": null,
"e": 6244,
"s": 6228,
"text": "sravankumar8128"
},
{
"code": null,
"e": 6258,
"s": 6244,
"text": "divyesh072019"
},
{
"code": null,
"e": 6276,
"s": 6258,
"text": "rohitmishra051000"
},
{
"code": null,
"e": 6295,
"s": 6276,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 6302,
"s": 6295,
"text": "Arrays"
},
{
"code": null,
"e": 6321,
"s": 6302,
"text": "School Programming"
},
{
"code": null,
"e": 6328,
"s": 6321,
"text": "Arrays"
},
{
"code": null,
"e": 6347,
"s": 6328,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 6445,
"s": 6347,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6477,
"s": 6445,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 6524,
"s": 6477,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 6549,
"s": 6524,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 6580,
"s": 6549,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 6638,
"s": 6580,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 6656,
"s": 6638,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6681,
"s": 6656,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 6704,
"s": 6681,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 6723,
"s": 6704,
"text": "Interfaces in Java"
}
] |
Java String Class indent() Method With Examples
|
13 Apr, 2021
JDK 12 introduced indent() method in Java.lang.String class. This method is useful to add or remove white spaces from the beginning of the line to adjust indentation for each string line.
Syntax:
public String indent(int n)
Parameter: It takes integer n as input and does indentation accordingly.
Also, each line is suffixed with “\n” (a newline character).
Procedure:
When a string is provided to indent() method,
It calls lines() functionThen, for each line, does indentation based on integer value provided as per user cases discussed below:If n>0 (Positive)Then n white spaces are added at the starting of each line and each line is suffixed with “\n”.If n==0Then the indentation remains as it is, only line is suffixed with “\n”.If n<0 (Negative), thenIf (+n) > leading white spaces availableThen all leading white spaces are removed for each line and each line is suffixed with “\n”If (+n) < leading white spaces availableThen (+n) leading white spaces are removed for each line and each line is suffixed with “\n”Then, suffix each line with “\n”.Then, concatenates resulting string lines and returns
It calls lines() function
Then, for each line, does indentation based on integer value provided as per user cases discussed below:If n>0 (Positive)Then n white spaces are added at the starting of each line and each line is suffixed with “\n”.If n==0Then the indentation remains as it is, only line is suffixed with “\n”.If n<0 (Negative), thenIf (+n) > leading white spaces availableThen all leading white spaces are removed for each line and each line is suffixed with “\n”If (+n) < leading white spaces availableThen (+n) leading white spaces are removed for each line and each line is suffixed with “\n”
If n>0 (Positive)Then n white spaces are added at the starting of each line and each line is suffixed with “\n”.
Then n white spaces are added at the starting of each line and each line is suffixed with “\n”.
If n==0Then the indentation remains as it is, only line is suffixed with “\n”.
Then the indentation remains as it is, only line is suffixed with “\n”.
If n<0 (Negative), thenIf (+n) > leading white spaces availableThen all leading white spaces are removed for each line and each line is suffixed with “\n”If (+n) < leading white spaces availableThen (+n) leading white spaces are removed for each line and each line is suffixed with “\n”
If (+n) > leading white spaces availableThen all leading white spaces are removed for each line and each line is suffixed with “\n”
Then all leading white spaces are removed for each line and each line is suffixed with “\n”
If (+n) < leading white spaces availableThen (+n) leading white spaces are removed for each line and each line is suffixed with “\n”
Then (+n) leading white spaces are removed for each line and each line is suffixed with “\n”
Then, suffix each line with “\n”.
Then, concatenates resulting string lines and returns
Implementation:
Example 1
Java
// Java Program to illustrate indent() method of// String class // Importing basic librariesimport java.io.*;import java.util.*; // Class for indent() methodpublic class GFG { // Main driver method public static void main(String args[]) { // Custom input string String input = "GeeksforGeeks\nA Computer Science portal for geeks."; // Print and display the input string System.out.println(input); // Print the above string length // using standard length() method System.out.println("Input String length: " + input.length()); // Now, calling the indent() method // for random value of N // Case 1: N>0 | Positive // Say N = 5 which is positive // so as per procedural algorithm // 5 white spaces are added // at the starting of each line String output = input.indent(5); // Print and display output string System.out.println(output); // Print the new string length // again using the length() method System.out.println("New String length: " + output.length()); // Case 2: N=0 | Zero // Call indent method with n=0 String output1 = input.indent(0); System.out.println(output1); System.out.println("New String length: " + output1.length()); // Case 3: N < 0 | Negative // Call indent method with n=-3 (negative) String output2 = input.indent(-3); // Print the output string System.out.println(output); // Print output(new) string length System.out.println("New String length: " + output2.length()); }}
Output:
GeeksforGeeks
A Computer Science portal for geeks.
Input String length: 50
GeeksforGeeks
A Computer Science portal for geeks.
New String length: 61
GeeksforGeeks
A Computer Science portal for geeks.
New String length: 51
GeeksforGeeks
A Computer Science portal for geeks.
New String length: 51
Example 2:
Java
// Java Program to illustrate indent() method of// String class // Importing basic librariesimport java.util.*;import java.io.*; // Class for indent() methodpublic class GFG { // Main driver method public static void main(String args[]) { // Input string String input = "GeeksforGeeks"; System.out.println(input); System.out.println("Input String length: " + input.length()); // Call indent method on input string with n=5 // (positive) String output = input.indent(5); System.out.println(output); System.out.println("New String length: " + output.length()); // Call indent method on output string with n=0 String output1 = output.indent(0); System.out.println(output1); System.out.println("New String length: " + output1.length()); // Call indent method on output1 string with n=-3 // (negative) String output2 = output.indent(-3); System.out.println(output2); System.out.println("New String length: " + output2.length()); }}
Output:
GeeksforGeeks
Input String length: 13
GeeksforGeeks
New String length: 19
GeeksforGeeks
New String length: 19
GeeksforGeeks
New String length: 16
simmytarika5
Java-Strings
Picked
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 216,
"s": 28,
"text": "JDK 12 introduced indent() method in Java.lang.String class. This method is useful to add or remove white spaces from the beginning of the line to adjust indentation for each string line."
},
{
"code": null,
"e": 224,
"s": 216,
"text": "Syntax:"
},
{
"code": null,
"e": 252,
"s": 224,
"text": "public String indent(int n)"
},
{
"code": null,
"e": 326,
"s": 252,
"text": "Parameter: It takes integer n as input and does indentation accordingly. "
},
{
"code": null,
"e": 387,
"s": 326,
"text": "Also, each line is suffixed with “\\n” (a newline character)."
},
{
"code": null,
"e": 399,
"s": 387,
"text": "Procedure: "
},
{
"code": null,
"e": 446,
"s": 399,
"text": "When a string is provided to indent() method, "
},
{
"code": null,
"e": 1138,
"s": 446,
"text": "It calls lines() functionThen, for each line, does indentation based on integer value provided as per user cases discussed below:If n>0 (Positive)Then n white spaces are added at the starting of each line and each line is suffixed with “\\n”.If n==0Then the indentation remains as it is, only line is suffixed with “\\n”.If n<0 (Negative), thenIf (+n) > leading white spaces availableThen all leading white spaces are removed for each line and each line is suffixed with “\\n”If (+n) < leading white spaces availableThen (+n) leading white spaces are removed for each line and each line is suffixed with “\\n”Then, suffix each line with “\\n”.Then, concatenates resulting string lines and returns"
},
{
"code": null,
"e": 1164,
"s": 1138,
"text": "It calls lines() function"
},
{
"code": null,
"e": 1745,
"s": 1164,
"text": "Then, for each line, does indentation based on integer value provided as per user cases discussed below:If n>0 (Positive)Then n white spaces are added at the starting of each line and each line is suffixed with “\\n”.If n==0Then the indentation remains as it is, only line is suffixed with “\\n”.If n<0 (Negative), thenIf (+n) > leading white spaces availableThen all leading white spaces are removed for each line and each line is suffixed with “\\n”If (+n) < leading white spaces availableThen (+n) leading white spaces are removed for each line and each line is suffixed with “\\n”"
},
{
"code": null,
"e": 1858,
"s": 1745,
"text": "If n>0 (Positive)Then n white spaces are added at the starting of each line and each line is suffixed with “\\n”."
},
{
"code": null,
"e": 1954,
"s": 1858,
"text": "Then n white spaces are added at the starting of each line and each line is suffixed with “\\n”."
},
{
"code": null,
"e": 2033,
"s": 1954,
"text": "If n==0Then the indentation remains as it is, only line is suffixed with “\\n”."
},
{
"code": null,
"e": 2105,
"s": 2033,
"text": "Then the indentation remains as it is, only line is suffixed with “\\n”."
},
{
"code": null,
"e": 2392,
"s": 2105,
"text": "If n<0 (Negative), thenIf (+n) > leading white spaces availableThen all leading white spaces are removed for each line and each line is suffixed with “\\n”If (+n) < leading white spaces availableThen (+n) leading white spaces are removed for each line and each line is suffixed with “\\n”"
},
{
"code": null,
"e": 2524,
"s": 2392,
"text": "If (+n) > leading white spaces availableThen all leading white spaces are removed for each line and each line is suffixed with “\\n”"
},
{
"code": null,
"e": 2616,
"s": 2524,
"text": "Then all leading white spaces are removed for each line and each line is suffixed with “\\n”"
},
{
"code": null,
"e": 2749,
"s": 2616,
"text": "If (+n) < leading white spaces availableThen (+n) leading white spaces are removed for each line and each line is suffixed with “\\n”"
},
{
"code": null,
"e": 2842,
"s": 2749,
"text": "Then (+n) leading white spaces are removed for each line and each line is suffixed with “\\n”"
},
{
"code": null,
"e": 2876,
"s": 2842,
"text": "Then, suffix each line with “\\n”."
},
{
"code": null,
"e": 2930,
"s": 2876,
"text": "Then, concatenates resulting string lines and returns"
},
{
"code": null,
"e": 2946,
"s": 2930,
"text": "Implementation:"
},
{
"code": null,
"e": 2956,
"s": 2946,
"text": "Example 1"
},
{
"code": null,
"e": 2961,
"s": 2956,
"text": "Java"
},
{
"code": "// Java Program to illustrate indent() method of// String class // Importing basic librariesimport java.io.*;import java.util.*; // Class for indent() methodpublic class GFG { // Main driver method public static void main(String args[]) { // Custom input string String input = \"GeeksforGeeks\\nA Computer Science portal for geeks.\"; // Print and display the input string System.out.println(input); // Print the above string length // using standard length() method System.out.println(\"Input String length: \" + input.length()); // Now, calling the indent() method // for random value of N // Case 1: N>0 | Positive // Say N = 5 which is positive // so as per procedural algorithm // 5 white spaces are added // at the starting of each line String output = input.indent(5); // Print and display output string System.out.println(output); // Print the new string length // again using the length() method System.out.println(\"New String length: \" + output.length()); // Case 2: N=0 | Zero // Call indent method with n=0 String output1 = input.indent(0); System.out.println(output1); System.out.println(\"New String length: \" + output1.length()); // Case 3: N < 0 | Negative // Call indent method with n=-3 (negative) String output2 = input.indent(-3); // Print the output string System.out.println(output); // Print output(new) string length System.out.println(\"New String length: \" + output2.length()); }}",
"e": 4723,
"s": 2961,
"text": null
},
{
"code": null,
"e": 4731,
"s": 4723,
"text": "Output:"
},
{
"code": null,
"e": 5036,
"s": 4731,
"text": "GeeksforGeeks\nA Computer Science portal for geeks.\nInput String length: 50\n GeeksforGeeks\n A Computer Science portal for geeks.\n\nNew String length: 61\nGeeksforGeeks\nA Computer Science portal for geeks.\n\nNew String length: 51\nGeeksforGeeks\nA Computer Science portal for geeks.\n\nNew String length: 51"
},
{
"code": null,
"e": 5047,
"s": 5036,
"text": "Example 2:"
},
{
"code": null,
"e": 5052,
"s": 5047,
"text": "Java"
},
{
"code": "// Java Program to illustrate indent() method of// String class // Importing basic librariesimport java.util.*;import java.io.*; // Class for indent() methodpublic class GFG { // Main driver method public static void main(String args[]) { // Input string String input = \"GeeksforGeeks\"; System.out.println(input); System.out.println(\"Input String length: \" + input.length()); // Call indent method on input string with n=5 // (positive) String output = input.indent(5); System.out.println(output); System.out.println(\"New String length: \" + output.length()); // Call indent method on output string with n=0 String output1 = output.indent(0); System.out.println(output1); System.out.println(\"New String length: \" + output1.length()); // Call indent method on output1 string with n=-3 // (negative) String output2 = output.indent(-3); System.out.println(output2); System.out.println(\"New String length: \" + output2.length()); }}",
"e": 6225,
"s": 5052,
"text": null
},
{
"code": null,
"e": 6237,
"s": 6229,
"text": "Output:"
},
{
"code": null,
"e": 6397,
"s": 6239,
"text": "GeeksforGeeks\nInput String length: 13\n GeeksforGeeks\n\nNew String length: 19\n GeeksforGeeks\n\nNew String length: 19\n GeeksforGeeks\n\nNew String length: 16"
},
{
"code": null,
"e": 6412,
"s": 6399,
"text": "simmytarika5"
},
{
"code": null,
"e": 6425,
"s": 6412,
"text": "Java-Strings"
},
{
"code": null,
"e": 6432,
"s": 6425,
"text": "Picked"
},
{
"code": null,
"e": 6437,
"s": 6432,
"text": "Java"
},
{
"code": null,
"e": 6450,
"s": 6437,
"text": "Java-Strings"
},
{
"code": null,
"e": 6455,
"s": 6450,
"text": "Java"
},
{
"code": null,
"e": 6553,
"s": 6455,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6568,
"s": 6553,
"text": "Stream In Java"
},
{
"code": null,
"e": 6589,
"s": 6568,
"text": "Introduction to Java"
},
{
"code": null,
"e": 6610,
"s": 6589,
"text": "Constructors in Java"
},
{
"code": null,
"e": 6629,
"s": 6610,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 6646,
"s": 6629,
"text": "Generics in Java"
},
{
"code": null,
"e": 6676,
"s": 6646,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 6702,
"s": 6676,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 6718,
"s": 6702,
"text": "Strings in Java"
},
{
"code": null,
"e": 6755,
"s": 6718,
"text": "Differences between JDK, JRE and JVM"
}
] |
Lexicographically smallest permutation with distinct elements using minimum replacements
|
28 Apr, 2021
Given an array of n positive integers such that each element of an integer is from 1 to n. Find the lexicographically permutation that can be obtained by replacing minimum number of elements in array such that every element of array occurs exactly once in the entire array. First, print the minimum number of replacements required and then print the final lexicographical array. Examples:
Input arr[] = {2, 3, 4, 3, 2}
Output 2
1 3 4 5 2
Explanation
Replace number '2' at position 1st with number
'1' and '3' at position 4th with number '5'.
The array that we obtain is [1, 3, 4, 5, 2]
which is lexicographically smallest among all
the possible suitable.
Input arr[] = {2, 1, 2, 1, 2}
Output 3
2 1 3 4 5
Naive approach is to generate all the permutation from 1 to n and pick the smallest one which renders the minimum replacements. Time complexity of this approach is O(n!) which will definitely time out for a large value of n.Efficient approach is to pick desired elements greedily. Firstly initialize the cnt[] array which will contain the frequency of elements occurring in the array. For each element of array(ai), occurred more than once in an array, add the numbers in ascending order because of getting lexicographically minimal permutation. For instance, Iterate the array over all elements. Let the current number of array is ai. If count of ai is equaled to 1 then move to the next number of array. If count of ai is greater than 1 then replace the number ai with element ele(the smallest number which does not occur in array) only if ele < ai. Meanwhile, decrease the count of ai in cnt[] array. If ele > ai then mark the number ai so that we can replace it in the next iteration. This step this need because we need to make smallest lexicographically permutation.
For example, let’s suppose the arr[] = {1, 5, 4, 5, 3, 7, 3} In first iteration ‘5’ occurs two times in array(indexing 1), therefore we have to replace ‘5’ at position ‘2’ with ‘2’(2 < 5). Now the updated array = {1, 2, 4, 5, 3, 7, 3} In next iteration, ‘3’ would be consider as it occurs two times in array. But this time the next element of replacement would be equals to 6 which is greater than 3. Therefore visit element 3 in boolean array vis[] and iterate over other elements. Now again ‘3’ occurred at position 7th, this time replace it with number ‘6’. Final array is arr[] = {1, 2, 4, 5, 3, 7, 6}
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print lexicographically// permutation array by replacing minimum// element of array#include <bits/stdc++.h>using namespace std; // Function to calculate lexicographically permutation// in arrayvoid lexicoSmallestPermuatation(int arr[], int n){ // Calculate frequency of array elements int cnt[n + 1]; memset(cnt, 0, sizeof(cnt)); for (int i = 0; i < n; ++i) ++cnt[arr[i]]; int ele = 1, replacement = 0; bool vis[n + 1]; memset(vis, 0, sizeof(vis)); for (int i = 0; i < n; ++i) { // If count of element is 1, no // need to replace if (cnt[arr[i]] == 1) continue; // Find the element that has not // occurred in array while (cnt[ele]) ++ele; // If replacement element is greater // than current arr[i] then visit // that element for next iteration if (ele > arr[i] && !vis[arr[i]]) vis[arr[i]] = 1; else { // Decrement count and assign the element // to array --cnt[arr[i]]; arr[i] = ele; // Increment the replacement count ++replacement; // Increment element after assigning // to the array ++ele; } } cout << replacement << "\n"; for (int i = 0; i < n; ++i) cout << arr[i] << " ";} // Driver codeint main(){ int arr[] = { 2, 3, 4, 3, 2 }; int sz = sizeof(arr) / sizeof(arr[0]); lexicoSmallestPermuatation(arr, sz); return 0;}
// Java program to print lexicographically// permutation array by replacing minimum// element of array class GFG { // Function to calculate lexicographically permutation// in array static void lexicoSmallestPermuatation(int arr[], int n) { // Calculate frequency of array elements int cnt[] = new int[n + 1]; for (int i = 0; i < n; ++i) { ++cnt[arr[i]]; } int ele = 1, replacement = 0; boolean vis[] = new boolean[n + 1]; for (int i = 0; i < n; ++i) { // If count of element is 1, no // need to replace if (cnt[arr[i]] == 1) { continue; } // Find the element that has not // occurred in array while (cnt[ele]>0) { ++ele; } // If replacement element is greater // than current arr[i] then visit // that element for next iteration if (ele > arr[i] && !vis[arr[i]]) { vis[arr[i]] = true; } else { // Decrement count and assign the element // to array --cnt[arr[i]]; arr[i] = ele; // Increment the replacement count ++replacement; // Increment element after assigning // to the array ++ele; } } System.out.print(replacement + "\n"); for (int i = 0; i < n; ++i) { System.out.print(arr[i] + " "); } } // Driver code public static void main(String[] args) { int arr[] = {2, 3, 4, 3, 2}; int sz = arr.length; lexicoSmallestPermuatation(arr, sz); }} // This code is contributed by 29AjayKumar
# Python 3 program to print lexicographically# permutation array by replacing minimum# element of array # Function to calculate lexicographically# permutation in arraydef lexicoSmallestPermuatation(arr, n): # Calculate frequency of array elements cnt = [0 for i in range(n + 1)] for i in range(n): cnt[arr[i]] += 1 ele = 1 replacement = 0 vis = [0 for i in range(n + 1)] for i in range(n): # If count of element is 1, no # need to replace if (cnt[arr[i]] == 1): continue # Find the element that has not # occurred in array while (cnt[ele]): ele += 1 # If replacement element is greater # than current arr[i] then visit # that element for next iteration if (ele > arr[i] and vis[arr[i]] == 0): vis[arr[i]] = 1; else: # Decrement count and assign # the element to array cnt[arr[i]] -= 1 arr[i] = ele # Increment the replacement count replacement += 1 # Increment element after assigning # to the array ele += 1 print(replacement) for i in range(n): print(arr[i], end = " ") # Driver codeif __name__ == '__main__': arr = [2, 3, 4, 3, 2] sz = len(arr) lexicoSmallestPermuatation(arr, sz) # This code is contributed by# Shashank_Sharma
// C# program to print lexicographically// permutation array by replacing minimum// element of array using System;public class GFG { // Function to calculate lexicographically permutation// in array static void lexicoSmallestPermuatation(int []arr, int n) { // Calculate frequency of array elements int []cnt= new int[n + 1]; for (int i = 0; i < n; ++i) { ++cnt[arr[i]]; } int ele = 1, replacement = 0; bool []vis = new bool[n + 1]; for (int i = 0; i < n; ++i) { // If count of element is 1, no // need to replace if (cnt[arr[i]] == 1) { continue; } // Find the element that has not // occurred in array while (cnt[ele]>0) { ++ele; } // If replacement element is greater // than current arr[i] then visit // that element for next iteration if (ele > arr[i] && !vis[arr[i]]) { vis[arr[i]] = true; } else { // Decrement count and assign the element // to array --cnt[arr[i]]; arr[i] = ele; // Increment the replacement count ++replacement; // Increment element after assigning // to the array ++ele; } } Console.Write(replacement + "\n"); for (int i = 0; i < n; ++i) { Console.Write(arr[i] + " "); } } // Driver code public static void Main() { int []arr = {2, 3, 4, 3, 2}; int sz = arr.Length; lexicoSmallestPermuatation(arr, sz); }} // This code is contributed by Rajput-Ji//
<?php// PHP program to print lexicographically// permutation array by replacing minimum// element of array // Function to calculate lexicographically// permutation in arrayfunction lexicoSmallestPermuatation(&$arr, $n){ // Calculate frequency of array elements $cnt = array_fill(0, $n + 1, NULL); for ($i = 0; $i < $n; ++$i) ++$cnt[$arr[$i]]; $ele = 1; $replacement = 0; $vis = array_fill(0, $n + 1, NULL); for ($i = 0; $i < $n; ++$i) { // If count of element is 1, no // need to replace if ($cnt[$arr[$i]] == 1) continue; // Find the element that has not // occurred in array while ($cnt[$ele]) ++$ele; // If replacement element is greater // than current arr[i] then visit // that element for next iteration if ($ele > $arr[$i] && !$vis[$arr[$i]]) $vis[$arr[$i]] = 1; else { // Decrement count and assign the // element to array --$cnt[$arr[$i]]; $arr[$i] = $ele; // Increment the replacement count ++$replacement; // Increment element after assigning // to the array ++$ele; } } echo $replacement. "\n"; for ($i = 0; $i < $n; ++$i) echo $arr[$i] . " ";} // Driver code$arr = array(2, 3, 4, 3, 2 );$sz = sizeof($arr);lexicoSmallestPermuatation($arr, $sz); // This code is contributed by ita_c?>
<script> // Javascript program to// print lexicographically// permutation array by// replacing minimum// element of array // Function to calculate// lexicographically permutation// in array function lexicoSmallestPermuatation(arr, n) { // Calculate frequency of // array elements let cnt = Array.from({length: n + 1}, (_, i) => 0); for (let i = 0; i < n; ++i) { ++cnt[arr[i]]; } let ele = 1, replacement = 0; let vis = Array.from({length: n + 1}, (_, i) => 0); for (let i = 0; i < n; ++i) { // If count of element is 1, no // need to replace if (cnt[arr[i]] == 1) { continue; } // Find the element that has not // occurred in array while (cnt[ele]>0) { ++ele; } // If replacement element is greater // than current arr[i] then visit // that element for next iteration if (ele > arr[i] && !vis[arr[i]]) { vis[arr[i]] = true; } else { // Decrement count and // assign the element // to array --cnt[arr[i]]; arr[i] = ele; // Increment the // replacement count ++replacement; // Increment element // after assigning // to the array ++ele; } } document.write(replacement + "<br/>"); for (let i = 0; i < n; ++i) { document.write(arr[i] + " "); } } // driver program let arr = [2, 3, 4, 3, 2]; let sz = arr.length; lexicoSmallestPermuatation(arr, sz); </script>
Output
2
1 3 4 5 2
Time complexity: O(n)This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
29AjayKumar
Rajput-Ji
Shashank_Sharma
ukasp
nidhi_biet
sanjoy_62
lexicographic-ordering
Arrays
Combinatorial
Arrays
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Write a program to print all permutations of a given string
Permutation and Combination in Python
Factorial of a large number
Count of subsets with sum equal to X
itertools.combinations() module in Python to print all possible combinations
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 443,
"s": 52,
"text": "Given an array of n positive integers such that each element of an integer is from 1 to n. Find the lexicographically permutation that can be obtained by replacing minimum number of elements in array such that every element of array occurs exactly once in the entire array. First, print the minimum number of replacements required and then print the final lexicographical array. Examples: "
},
{
"code": null,
"e": 785,
"s": 443,
"text": "Input arr[] = {2, 3, 4, 3, 2}\nOutput 2\n 1 3 4 5 2\nExplanation\nReplace number '2' at position 1st with number \n'1' and '3' at position 4th with number '5'. \nThe array that we obtain is [1, 3, 4, 5, 2]\nwhich is lexicographically smallest among all \nthe possible suitable.\n\nInput arr[] = {2, 1, 2, 1, 2}\nOutput 3\n 2 1 3 4 5 "
},
{
"code": null,
"e": 1861,
"s": 787,
"text": "Naive approach is to generate all the permutation from 1 to n and pick the smallest one which renders the minimum replacements. Time complexity of this approach is O(n!) which will definitely time out for a large value of n.Efficient approach is to pick desired elements greedily. Firstly initialize the cnt[] array which will contain the frequency of elements occurring in the array. For each element of array(ai), occurred more than once in an array, add the numbers in ascending order because of getting lexicographically minimal permutation. For instance, Iterate the array over all elements. Let the current number of array is ai. If count of ai is equaled to 1 then move to the next number of array. If count of ai is greater than 1 then replace the number ai with element ele(the smallest number which does not occur in array) only if ele < ai. Meanwhile, decrease the count of ai in cnt[] array. If ele > ai then mark the number ai so that we can replace it in the next iteration. This step this need because we need to make smallest lexicographically permutation. "
},
{
"code": null,
"e": 2469,
"s": 1861,
"text": "For example, let’s suppose the arr[] = {1, 5, 4, 5, 3, 7, 3} In first iteration ‘5’ occurs two times in array(indexing 1), therefore we have to replace ‘5’ at position ‘2’ with ‘2’(2 < 5). Now the updated array = {1, 2, 4, 5, 3, 7, 3} In next iteration, ‘3’ would be consider as it occurs two times in array. But this time the next element of replacement would be equals to 6 which is greater than 3. Therefore visit element 3 in boolean array vis[] and iterate over other elements. Now again ‘3’ occurred at position 7th, this time replace it with number ‘6’. Final array is arr[] = {1, 2, 4, 5, 3, 7, 6} "
},
{
"code": null,
"e": 2475,
"s": 2471,
"text": "C++"
},
{
"code": null,
"e": 2480,
"s": 2475,
"text": "Java"
},
{
"code": null,
"e": 2488,
"s": 2480,
"text": "Python3"
},
{
"code": null,
"e": 2491,
"s": 2488,
"text": "C#"
},
{
"code": null,
"e": 2495,
"s": 2491,
"text": "PHP"
},
{
"code": null,
"e": 2506,
"s": 2495,
"text": "Javascript"
},
{
"code": "// C++ program to print lexicographically// permutation array by replacing minimum// element of array#include <bits/stdc++.h>using namespace std; // Function to calculate lexicographically permutation// in arrayvoid lexicoSmallestPermuatation(int arr[], int n){ // Calculate frequency of array elements int cnt[n + 1]; memset(cnt, 0, sizeof(cnt)); for (int i = 0; i < n; ++i) ++cnt[arr[i]]; int ele = 1, replacement = 0; bool vis[n + 1]; memset(vis, 0, sizeof(vis)); for (int i = 0; i < n; ++i) { // If count of element is 1, no // need to replace if (cnt[arr[i]] == 1) continue; // Find the element that has not // occurred in array while (cnt[ele]) ++ele; // If replacement element is greater // than current arr[i] then visit // that element for next iteration if (ele > arr[i] && !vis[arr[i]]) vis[arr[i]] = 1; else { // Decrement count and assign the element // to array --cnt[arr[i]]; arr[i] = ele; // Increment the replacement count ++replacement; // Increment element after assigning // to the array ++ele; } } cout << replacement << \"\\n\"; for (int i = 0; i < n; ++i) cout << arr[i] << \" \";} // Driver codeint main(){ int arr[] = { 2, 3, 4, 3, 2 }; int sz = sizeof(arr) / sizeof(arr[0]); lexicoSmallestPermuatation(arr, sz); return 0;}",
"e": 4034,
"s": 2506,
"text": null
},
{
"code": "// Java program to print lexicographically// permutation array by replacing minimum// element of array class GFG { // Function to calculate lexicographically permutation// in array static void lexicoSmallestPermuatation(int arr[], int n) { // Calculate frequency of array elements int cnt[] = new int[n + 1]; for (int i = 0; i < n; ++i) { ++cnt[arr[i]]; } int ele = 1, replacement = 0; boolean vis[] = new boolean[n + 1]; for (int i = 0; i < n; ++i) { // If count of element is 1, no // need to replace if (cnt[arr[i]] == 1) { continue; } // Find the element that has not // occurred in array while (cnt[ele]>0) { ++ele; } // If replacement element is greater // than current arr[i] then visit // that element for next iteration if (ele > arr[i] && !vis[arr[i]]) { vis[arr[i]] = true; } else { // Decrement count and assign the element // to array --cnt[arr[i]]; arr[i] = ele; // Increment the replacement count ++replacement; // Increment element after assigning // to the array ++ele; } } System.out.print(replacement + \"\\n\"); for (int i = 0; i < n; ++i) { System.out.print(arr[i] + \" \"); } } // Driver code public static void main(String[] args) { int arr[] = {2, 3, 4, 3, 2}; int sz = arr.length; lexicoSmallestPermuatation(arr, sz); }} // This code is contributed by 29AjayKumar",
"e": 5793,
"s": 4034,
"text": null
},
{
"code": "# Python 3 program to print lexicographically# permutation array by replacing minimum# element of array # Function to calculate lexicographically# permutation in arraydef lexicoSmallestPermuatation(arr, n): # Calculate frequency of array elements cnt = [0 for i in range(n + 1)] for i in range(n): cnt[arr[i]] += 1 ele = 1 replacement = 0 vis = [0 for i in range(n + 1)] for i in range(n): # If count of element is 1, no # need to replace if (cnt[arr[i]] == 1): continue # Find the element that has not # occurred in array while (cnt[ele]): ele += 1 # If replacement element is greater # than current arr[i] then visit # that element for next iteration if (ele > arr[i] and vis[arr[i]] == 0): vis[arr[i]] = 1; else: # Decrement count and assign # the element to array cnt[arr[i]] -= 1 arr[i] = ele # Increment the replacement count replacement += 1 # Increment element after assigning # to the array ele += 1 print(replacement) for i in range(n): print(arr[i], end = \" \") # Driver codeif __name__ == '__main__': arr = [2, 3, 4, 3, 2] sz = len(arr) lexicoSmallestPermuatation(arr, sz) # This code is contributed by# Shashank_Sharma",
"e": 7225,
"s": 5793,
"text": null
},
{
"code": " // C# program to print lexicographically// permutation array by replacing minimum// element of array using System;public class GFG { // Function to calculate lexicographically permutation// in array static void lexicoSmallestPermuatation(int []arr, int n) { // Calculate frequency of array elements int []cnt= new int[n + 1]; for (int i = 0; i < n; ++i) { ++cnt[arr[i]]; } int ele = 1, replacement = 0; bool []vis = new bool[n + 1]; for (int i = 0; i < n; ++i) { // If count of element is 1, no // need to replace if (cnt[arr[i]] == 1) { continue; } // Find the element that has not // occurred in array while (cnt[ele]>0) { ++ele; } // If replacement element is greater // than current arr[i] then visit // that element for next iteration if (ele > arr[i] && !vis[arr[i]]) { vis[arr[i]] = true; } else { // Decrement count and assign the element // to array --cnt[arr[i]]; arr[i] = ele; // Increment the replacement count ++replacement; // Increment element after assigning // to the array ++ele; } } Console.Write(replacement + \"\\n\"); for (int i = 0; i < n; ++i) { Console.Write(arr[i] + \" \"); } } // Driver code public static void Main() { int []arr = {2, 3, 4, 3, 2}; int sz = arr.Length; lexicoSmallestPermuatation(arr, sz); }} // This code is contributed by Rajput-Ji//",
"e": 8981,
"s": 7225,
"text": null
},
{
"code": "<?php// PHP program to print lexicographically// permutation array by replacing minimum// element of array // Function to calculate lexicographically// permutation in arrayfunction lexicoSmallestPermuatation(&$arr, $n){ // Calculate frequency of array elements $cnt = array_fill(0, $n + 1, NULL); for ($i = 0; $i < $n; ++$i) ++$cnt[$arr[$i]]; $ele = 1; $replacement = 0; $vis = array_fill(0, $n + 1, NULL); for ($i = 0; $i < $n; ++$i) { // If count of element is 1, no // need to replace if ($cnt[$arr[$i]] == 1) continue; // Find the element that has not // occurred in array while ($cnt[$ele]) ++$ele; // If replacement element is greater // than current arr[i] then visit // that element for next iteration if ($ele > $arr[$i] && !$vis[$arr[$i]]) $vis[$arr[$i]] = 1; else { // Decrement count and assign the // element to array --$cnt[$arr[$i]]; $arr[$i] = $ele; // Increment the replacement count ++$replacement; // Increment element after assigning // to the array ++$ele; } } echo $replacement. \"\\n\"; for ($i = 0; $i < $n; ++$i) echo $arr[$i] . \" \";} // Driver code$arr = array(2, 3, 4, 3, 2 );$sz = sizeof($arr);lexicoSmallestPermuatation($arr, $sz); // This code is contributed by ita_c?>",
"e": 10457,
"s": 8981,
"text": null
},
{
"code": "<script> // Javascript program to// print lexicographically// permutation array by// replacing minimum// element of array // Function to calculate// lexicographically permutation// in array function lexicoSmallestPermuatation(arr, n) { // Calculate frequency of // array elements let cnt = Array.from({length: n + 1}, (_, i) => 0); for (let i = 0; i < n; ++i) { ++cnt[arr[i]]; } let ele = 1, replacement = 0; let vis = Array.from({length: n + 1}, (_, i) => 0); for (let i = 0; i < n; ++i) { // If count of element is 1, no // need to replace if (cnt[arr[i]] == 1) { continue; } // Find the element that has not // occurred in array while (cnt[ele]>0) { ++ele; } // If replacement element is greater // than current arr[i] then visit // that element for next iteration if (ele > arr[i] && !vis[arr[i]]) { vis[arr[i]] = true; } else { // Decrement count and // assign the element // to array --cnt[arr[i]]; arr[i] = ele; // Increment the // replacement count ++replacement; // Increment element // after assigning // to the array ++ele; } } document.write(replacement + \"<br/>\"); for (let i = 0; i < n; ++i) { document.write(arr[i] + \" \"); } } // driver program let arr = [2, 3, 4, 3, 2]; let sz = arr.length; lexicoSmallestPermuatation(arr, sz); </script>",
"e": 12294,
"s": 10457,
"text": null
},
{
"code": null,
"e": 12303,
"s": 12294,
"text": "Output "
},
{
"code": null,
"e": 12316,
"s": 12303,
"text": "2\n1 3 4 5 2 "
},
{
"code": null,
"e": 12640,
"s": 12316,
"text": "Time complexity: O(n)This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 12652,
"s": 12640,
"text": "29AjayKumar"
},
{
"code": null,
"e": 12662,
"s": 12652,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 12678,
"s": 12662,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 12684,
"s": 12678,
"text": "ukasp"
},
{
"code": null,
"e": 12695,
"s": 12684,
"text": "nidhi_biet"
},
{
"code": null,
"e": 12705,
"s": 12695,
"text": "sanjoy_62"
},
{
"code": null,
"e": 12728,
"s": 12705,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 12735,
"s": 12728,
"text": "Arrays"
},
{
"code": null,
"e": 12749,
"s": 12735,
"text": "Combinatorial"
},
{
"code": null,
"e": 12756,
"s": 12749,
"text": "Arrays"
},
{
"code": null,
"e": 12770,
"s": 12756,
"text": "Combinatorial"
},
{
"code": null,
"e": 12868,
"s": 12770,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12900,
"s": 12868,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 12914,
"s": 12900,
"text": "Linear Search"
},
{
"code": null,
"e": 12999,
"s": 12914,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 13022,
"s": 12999,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 13078,
"s": 13022,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 13138,
"s": 13078,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 13176,
"s": 13138,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 13204,
"s": 13176,
"text": "Factorial of a large number"
},
{
"code": null,
"e": 13241,
"s": 13204,
"text": "Count of subsets with sum equal to X"
}
] |
Wand implode() function – Python
|
25 Aug, 2021
The implode() function is an inbuilt function in the Python Wand ImageMagick library which is used to create a “imploding” effect by pulling pixels towards the center of the image.
Syntax:
implode(amount, method)
Parameters: This function accepts two parameters as mentioned above and defined below:
amount: This parameter stores the normalized degree of effect between 0.0 & 1.0.
method: This parameter stores the interpolation method.
Return Value: This function returns the Wand ImageMagick object.
Original Image:
Example 1:
Python3
# Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as implode: # Invoke implode function implode.implode(0.5, "blend") # Save the image implode.save(filename ='implode1.jpg')
Output:
Example 2:
Python3
# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke implode function pic.implode(0.7, "catrom") # Save the image pic.save(filename ='implode2.jpg')
Output:
sagartomar9927
Image-Processing
Python-wand
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
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": "\n25 Aug, 2021"
},
{
"code": null,
"e": 210,
"s": 28,
"text": "The implode() function is an inbuilt function in the Python Wand ImageMagick library which is used to create a “imploding” effect by pulling pixels towards the center of the image. "
},
{
"code": null,
"e": 219,
"s": 210,
"text": "Syntax: "
},
{
"code": null,
"e": 243,
"s": 219,
"text": "implode(amount, method)"
},
{
"code": null,
"e": 331,
"s": 243,
"text": "Parameters: This function accepts two parameters as mentioned above and defined below: "
},
{
"code": null,
"e": 412,
"s": 331,
"text": "amount: This parameter stores the normalized degree of effect between 0.0 & 1.0."
},
{
"code": null,
"e": 468,
"s": 412,
"text": "method: This parameter stores the interpolation method."
},
{
"code": null,
"e": 533,
"s": 468,
"text": "Return Value: This function returns the Wand ImageMagick object."
},
{
"code": null,
"e": 551,
"s": 533,
"text": "Original Image: "
},
{
"code": null,
"e": 563,
"s": 551,
"text": "Example 1: "
},
{
"code": null,
"e": 571,
"s": 563,
"text": "Python3"
},
{
"code": "# Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as implode: # Invoke implode function implode.implode(0.5, \"blend\") # Save the image implode.save(filename ='implode1.jpg')",
"e": 915,
"s": 571,
"text": null
},
{
"code": null,
"e": 924,
"s": 915,
"text": "Output: "
},
{
"code": null,
"e": 936,
"s": 924,
"text": "Example 2: "
},
{
"code": null,
"e": 944,
"s": 936,
"text": "Python3"
},
{
"code": "# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke implode function pic.implode(0.7, \"catrom\") # Save the image pic.save(filename ='implode2.jpg')",
"e": 1945,
"s": 944,
"text": null
},
{
"code": null,
"e": 1954,
"s": 1945,
"text": "Output: "
},
{
"code": null,
"e": 1971,
"s": 1956,
"text": "sagartomar9927"
},
{
"code": null,
"e": 1988,
"s": 1971,
"text": "Image-Processing"
},
{
"code": null,
"e": 2000,
"s": 1988,
"text": "Python-wand"
},
{
"code": null,
"e": 2007,
"s": 2000,
"text": "Python"
},
{
"code": null,
"e": 2105,
"s": 2007,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2137,
"s": 2105,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2164,
"s": 2137,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2185,
"s": 2164,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2208,
"s": 2185,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2264,
"s": 2208,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2295,
"s": 2264,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2337,
"s": 2295,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2379,
"s": 2337,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2418,
"s": 2379,
"text": "Python | datetime.timedelta() function"
}
] |
Upsert in MongoDB
|
30 Jun, 2022
In MongoDB, upsert is an option that is used for update operation e.g. update(), findAndModify(), etc. Or in other words, upsert is a combination of update and insert (update + insert = upsert). If the value of this option is set to true and the document or documents found that match the specified query, then the update operation will update the matched document or documents. Or if the value of this option is set to true and no document or documents matches the specified document, then this option inserts a new document in the collection and this new document have the fields that indicate in the operation. By default, the value of the upsert option is false. If the value of upsert in a sharded collection is true then you have to include the full shard key in the filter.
Syntax:
upsert: <boolean>
The value of upsert option is either true or false.
Now we will learn the usage of the upsert option:
We can use upsert option with findAndModify() method. In this method, the default value of this option is false. If we set the value of this option is true, then the method performs one of the following operation:
If a document or documents found that matches the given query criteria, then the findAndModify() method updates the document/documents.
If no document/documents match the given query criteria, then the findAndModify() method inserts a new document in the collection.
Syntax:
db.Collection_name.findAndModify(
{
selection_criteria:<document>,
sort: <document>,
remove: <boolean>,
update: <document>,
new: <boolean>,
fields: <document>,
upsert: <boolean>,
bypassDocumentValidation: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
})
For example:
In this example we are working with
Database: gfg
Collection: employee
Database: three documents that contains details of employees
Now we are going to insert a new document in employee collection by setting the value of upsert option to true.
db.employee.findAndModify({query:{name:"Ram"},
update:{$set:{department:"Development"}},
upsert:true})
Here, no document matches the name “Ram”, so the findAndModify() method inserts a new document that contains two fields(i.e., name: “Ram” and department: “Development”) because the value of the upsert option is set to true.
We can use upsert option with update() method. In this method, the default value of this option is false. If we set the value of this option is true, then the method performs one of the following operations:
If a document or documents found that matches the given query criteria, then the update() method updates the document/documents.
If no document/documents match the given query criteria, then the update() method inserts a new document in the collection.
Note: To prevent MongoDB from inserting the same document more than once, create a unique index on the name field. With a unique index, if multiple documents want the same update with upsert: true, only one update operation successfully inserts a new document.
Syntax:
db.Collection_name.update({Selection_criteria}, {$set:{Update_data}}, {
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>
})
For example:
In this example, we are working with
Database: gfg
Collection: employee
Database: three documents that contains details of employees
Now we are going to insert a new document in employee collection by setting the value of upsert option to true.
db.employee.update({name:"Priya"}, {$set: {department: "HR"}},{upsert:true})
Here, no document matches the name “Priya”, so the update() method inserts a new document that contains two fields(i.e., name: “Priya” and department: “HR”) because the value of the upsert option is set to true.
If no document matches the filter from the given collection and the update parameter is a document that contains update operators, also the value of upsert option is set to true, then the update operation creates new documents from the equality clauses in the given query parameter and applies the expressions from the update parameter. Or in other words, when the value of upsert option is true and no document matches the given filter, then the update operation inserts a new document in the given collection, and the fields inserted in this new document are the fields that specify in the query and update documents.
Example:
In this example, we are working with
Database: gfg
Collection: example
Database: five documents that contains details of students
Now we are going to insert a new document in the example collection by setting the value of the upsert option to true.
db.example.update({Name: "Rekha"}, // Query parameter
{$set: {Phone: '7841235468 '}, // Update document
$setOnInsert: {Gender: 'Female'}},
{upsert: true})
Here, the update() method creates a new document with field “Name: Rekha” from the query condition and then applies the $set and $setOnInsert operations to this document.
If no document matches the filter from the given collection and the update parameter contains a replacement document, also the value of upsert document is set to true, the update operation inserts a new document in the collection and the fields inserted in this new document are the fields that specify in the replacement document. Here, if the replacement document contains an _id field then MongoDB does not create a new _id field for the new document. Or if the replacement document does not contain an _id field then MongoDB does create a new _id field for the new document.
Note: You are not allowed to specify different _id field values in the query parameter and replacement document. If you do, then you will get errors.
Example:
In this example, we are working with
Database: gfg
Collection: example
Database: four documents that contains details of students
Now we are going to insert a new document in the example collection by setting the value of the upsert option to true.
db.example.update({Name:"Hema"}, // Query parameter
{Name:"Hema", Phone:8332564578}, // Replacement document
{upsert:true})
The aggregation pipeline is a multi-stage pipeline, so in each state, the documents taken as input and produce the resultant set of documents now in the next stage(id available) the resultant documents taken as input and produce output, this process is going on till the last stage. The pipeline can have 1 to n number of stagers
If no document matches the given filter and the update parameter contains aggregation pipeline, also the value of upsert option is set to true then update operation inserts a new document in the collection. This new document is created from the equality clause present in the query parameter and after that applies the pipeline to the document to create the document to insert.
Example:
In this example, we are working with
Database: gfg
Collection: employee
Database: three documents that contains details of employees
Now we are going to insert a new document in the employee collection by setting the value of the upsert option to true.
db.employee.update({name:”Ram”}, [{$set: {department: “HR”, age:30}}],{upsert:true})
Till now, we have studied that the update() method can modify data in the collection based on the query and if any matching document is not found with help of upsert option new field can be added to the collection. But upsert with a dotted _id query is an exception and if you attempt to insert a document in this way MongoDB will show you an error.
Example:
Consider the following update operation. Since the update operation specifies upsert:true and the query specifies conditions on the _id field using dot notation, then the update will result in an error when constructing the document to insert.
db.employee.update({“_id.name”:”Roma”, “_id.uid”:0},{age:20}, {upsert:true})
khushb99
MongoDB
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 810,
"s": 28,
"text": "In MongoDB, upsert is an option that is used for update operation e.g. update(), findAndModify(), etc. Or in other words, upsert is a combination of update and insert (update + insert = upsert). If the value of this option is set to true and the document or documents found that match the specified query, then the update operation will update the matched document or documents. Or if the value of this option is set to true and no document or documents matches the specified document, then this option inserts a new document in the collection and this new document have the fields that indicate in the operation. By default, the value of the upsert option is false. If the value of upsert in a sharded collection is true then you have to include the full shard key in the filter. "
},
{
"code": null,
"e": 818,
"s": 810,
"text": "Syntax:"
},
{
"code": null,
"e": 836,
"s": 818,
"text": "upsert: <boolean>"
},
{
"code": null,
"e": 888,
"s": 836,
"text": "The value of upsert option is either true or false."
},
{
"code": null,
"e": 938,
"s": 888,
"text": "Now we will learn the usage of the upsert option:"
},
{
"code": null,
"e": 1152,
"s": 938,
"text": "We can use upsert option with findAndModify() method. In this method, the default value of this option is false. If we set the value of this option is true, then the method performs one of the following operation:"
},
{
"code": null,
"e": 1288,
"s": 1152,
"text": "If a document or documents found that matches the given query criteria, then the findAndModify() method updates the document/documents."
},
{
"code": null,
"e": 1419,
"s": 1288,
"text": "If no document/documents match the given query criteria, then the findAndModify() method inserts a new document in the collection."
},
{
"code": null,
"e": 1427,
"s": 1419,
"text": "Syntax:"
},
{
"code": null,
"e": 1461,
"s": 1427,
"text": "db.Collection_name.findAndModify("
},
{
"code": null,
"e": 1463,
"s": 1461,
"text": "{"
},
{
"code": null,
"e": 1498,
"s": 1463,
"text": " selection_criteria:<document>,"
},
{
"code": null,
"e": 1520,
"s": 1498,
"text": " sort: <document>,"
},
{
"code": null,
"e": 1543,
"s": 1520,
"text": " remove: <boolean>,"
},
{
"code": null,
"e": 1567,
"s": 1543,
"text": " update: <document>,"
},
{
"code": null,
"e": 1587,
"s": 1567,
"text": " new: <boolean>,"
},
{
"code": null,
"e": 1611,
"s": 1587,
"text": " fields: <document>,"
},
{
"code": null,
"e": 1634,
"s": 1611,
"text": " upsert: <boolean>,"
},
{
"code": null,
"e": 1675,
"s": 1634,
"text": " bypassDocumentValidation: <boolean>,"
},
{
"code": null,
"e": 1705,
"s": 1675,
"text": " writeConcern: <document>,"
},
{
"code": null,
"e": 1732,
"s": 1705,
"text": " collation: <document>,"
},
{
"code": null,
"e": 1777,
"s": 1732,
"text": " arrayFilters: [ <filterdocument1>, ... ]"
},
{
"code": null,
"e": 1780,
"s": 1777,
"text": "})"
},
{
"code": null,
"e": 1793,
"s": 1780,
"text": "For example:"
},
{
"code": null,
"e": 1830,
"s": 1793,
"text": "In this example we are working with "
},
{
"code": null,
"e": 1844,
"s": 1830,
"text": "Database: gfg"
},
{
"code": null,
"e": 1865,
"s": 1844,
"text": "Collection: employee"
},
{
"code": null,
"e": 1926,
"s": 1865,
"text": "Database: three documents that contains details of employees"
},
{
"code": null,
"e": 2038,
"s": 1926,
"text": "Now we are going to insert a new document in employee collection by setting the value of upsert option to true."
},
{
"code": null,
"e": 2199,
"s": 2038,
"text": " db.employee.findAndModify({query:{name:\"Ram\"}, \n update:{$set:{department:\"Development\"}},\n upsert:true})"
},
{
"code": null,
"e": 2423,
"s": 2199,
"text": "Here, no document matches the name “Ram”, so the findAndModify() method inserts a new document that contains two fields(i.e., name: “Ram” and department: “Development”) because the value of the upsert option is set to true."
},
{
"code": null,
"e": 2631,
"s": 2423,
"text": "We can use upsert option with update() method. In this method, the default value of this option is false. If we set the value of this option is true, then the method performs one of the following operations:"
},
{
"code": null,
"e": 2760,
"s": 2631,
"text": "If a document or documents found that matches the given query criteria, then the update() method updates the document/documents."
},
{
"code": null,
"e": 2884,
"s": 2760,
"text": "If no document/documents match the given query criteria, then the update() method inserts a new document in the collection."
},
{
"code": null,
"e": 3145,
"s": 2884,
"text": "Note: To prevent MongoDB from inserting the same document more than once, create a unique index on the name field. With a unique index, if multiple documents want the same update with upsert: true, only one update operation successfully inserts a new document."
},
{
"code": null,
"e": 3153,
"s": 3145,
"text": "Syntax:"
},
{
"code": null,
"e": 3225,
"s": 3153,
"text": "db.Collection_name.update({Selection_criteria}, {$set:{Update_data}}, {"
},
{
"code": null,
"e": 3249,
"s": 3225,
"text": " upsert: <boolean>,"
},
{
"code": null,
"e": 3272,
"s": 3249,
"text": " multi: <boolean>,"
},
{
"code": null,
"e": 3303,
"s": 3272,
"text": " writeConcern: <document>,"
},
{
"code": null,
"e": 3331,
"s": 3303,
"text": " collation: <document>,"
},
{
"code": null,
"e": 3378,
"s": 3331,
"text": " arrayFilters: [ <filterdocument1>, ... ],"
},
{
"code": null,
"e": 3416,
"s": 3378,
"text": " hint: <document|string> "
},
{
"code": null,
"e": 3422,
"s": 3416,
"text": " })"
},
{
"code": null,
"e": 3435,
"s": 3422,
"text": "For example:"
},
{
"code": null,
"e": 3473,
"s": 3435,
"text": "In this example, we are working with "
},
{
"code": null,
"e": 3487,
"s": 3473,
"text": "Database: gfg"
},
{
"code": null,
"e": 3508,
"s": 3487,
"text": "Collection: employee"
},
{
"code": null,
"e": 3569,
"s": 3508,
"text": "Database: three documents that contains details of employees"
},
{
"code": null,
"e": 3681,
"s": 3569,
"text": "Now we are going to insert a new document in employee collection by setting the value of upsert option to true."
},
{
"code": null,
"e": 3758,
"s": 3681,
"text": "db.employee.update({name:\"Priya\"}, {$set: {department: \"HR\"}},{upsert:true})"
},
{
"code": null,
"e": 3970,
"s": 3758,
"text": "Here, no document matches the name “Priya”, so the update() method inserts a new document that contains two fields(i.e., name: “Priya” and department: “HR”) because the value of the upsert option is set to true."
},
{
"code": null,
"e": 4591,
"s": 3970,
"text": "If no document matches the filter from the given collection and the update parameter is a document that contains update operators, also the value of upsert option is set to true, then the update operation creates new documents from the equality clauses in the given query parameter and applies the expressions from the update parameter. Or in other words, when the value of upsert option is true and no document matches the given filter, then the update operation inserts a new document in the given collection, and the fields inserted in this new document are the fields that specify in the query and update documents. "
},
{
"code": null,
"e": 4600,
"s": 4591,
"text": "Example:"
},
{
"code": null,
"e": 4638,
"s": 4600,
"text": "In this example, we are working with "
},
{
"code": null,
"e": 4652,
"s": 4638,
"text": "Database: gfg"
},
{
"code": null,
"e": 4672,
"s": 4652,
"text": "Collection: example"
},
{
"code": null,
"e": 4731,
"s": 4672,
"text": "Database: five documents that contains details of students"
},
{
"code": null,
"e": 4850,
"s": 4731,
"text": "Now we are going to insert a new document in the example collection by setting the value of the upsert option to true."
},
{
"code": null,
"e": 5064,
"s": 4850,
"text": "db.example.update({Name: \"Rekha\"}, // Query parameter \n {$set: {Phone: '7841235468 '}, // Update document\n $setOnInsert: {Gender: 'Female'}},\n {upsert: true})"
},
{
"code": null,
"e": 5235,
"s": 5064,
"text": "Here, the update() method creates a new document with field “Name: Rekha” from the query condition and then applies the $set and $setOnInsert operations to this document."
},
{
"code": null,
"e": 5815,
"s": 5235,
"text": "If no document matches the filter from the given collection and the update parameter contains a replacement document, also the value of upsert document is set to true, the update operation inserts a new document in the collection and the fields inserted in this new document are the fields that specify in the replacement document. Here, if the replacement document contains an _id field then MongoDB does not create a new _id field for the new document. Or if the replacement document does not contain an _id field then MongoDB does create a new _id field for the new document. "
},
{
"code": null,
"e": 5965,
"s": 5815,
"text": "Note: You are not allowed to specify different _id field values in the query parameter and replacement document. If you do, then you will get errors."
},
{
"code": null,
"e": 5974,
"s": 5965,
"text": "Example:"
},
{
"code": null,
"e": 6012,
"s": 5974,
"text": "In this example, we are working with "
},
{
"code": null,
"e": 6026,
"s": 6012,
"text": "Database: gfg"
},
{
"code": null,
"e": 6046,
"s": 6026,
"text": "Collection: example"
},
{
"code": null,
"e": 6105,
"s": 6046,
"text": "Database: four documents that contains details of students"
},
{
"code": null,
"e": 6224,
"s": 6105,
"text": "Now we are going to insert a new document in the example collection by setting the value of the upsert option to true."
},
{
"code": null,
"e": 6384,
"s": 6224,
"text": "db.example.update({Name:\"Hema\"}, // Query parameter\n {Name:\"Hema\", Phone:8332564578}, // Replacement document\n {upsert:true})"
},
{
"code": null,
"e": 6714,
"s": 6384,
"text": "The aggregation pipeline is a multi-stage pipeline, so in each state, the documents taken as input and produce the resultant set of documents now in the next stage(id available) the resultant documents taken as input and produce output, this process is going on till the last stage. The pipeline can have 1 to n number of stagers"
},
{
"code": null,
"e": 7092,
"s": 6714,
"text": "If no document matches the given filter and the update parameter contains aggregation pipeline, also the value of upsert option is set to true then update operation inserts a new document in the collection. This new document is created from the equality clause present in the query parameter and after that applies the pipeline to the document to create the document to insert."
},
{
"code": null,
"e": 7101,
"s": 7092,
"text": "Example:"
},
{
"code": null,
"e": 7139,
"s": 7101,
"text": "In this example, we are working with "
},
{
"code": null,
"e": 7153,
"s": 7139,
"text": "Database: gfg"
},
{
"code": null,
"e": 7174,
"s": 7153,
"text": "Collection: employee"
},
{
"code": null,
"e": 7235,
"s": 7174,
"text": "Database: three documents that contains details of employees"
},
{
"code": null,
"e": 7355,
"s": 7235,
"text": "Now we are going to insert a new document in the employee collection by setting the value of the upsert option to true."
},
{
"code": null,
"e": 7440,
"s": 7355,
"text": "db.employee.update({name:”Ram”}, [{$set: {department: “HR”, age:30}}],{upsert:true})"
},
{
"code": null,
"e": 7790,
"s": 7440,
"text": "Till now, we have studied that the update() method can modify data in the collection based on the query and if any matching document is not found with help of upsert option new field can be added to the collection. But upsert with a dotted _id query is an exception and if you attempt to insert a document in this way MongoDB will show you an error."
},
{
"code": null,
"e": 7799,
"s": 7790,
"text": "Example:"
},
{
"code": null,
"e": 8043,
"s": 7799,
"text": "Consider the following update operation. Since the update operation specifies upsert:true and the query specifies conditions on the _id field using dot notation, then the update will result in an error when constructing the document to insert."
},
{
"code": null,
"e": 8120,
"s": 8043,
"text": "db.employee.update({“_id.name”:”Roma”, “_id.uid”:0},{age:20}, {upsert:true})"
},
{
"code": null,
"e": 8129,
"s": 8120,
"text": "khushb99"
},
{
"code": null,
"e": 8137,
"s": 8129,
"text": "MongoDB"
},
{
"code": null,
"e": 8144,
"s": 8137,
"text": "Picked"
},
{
"code": null,
"e": 8152,
"s": 8144,
"text": "MongoDB"
}
] |
Rename the column name in R using Dplyr
|
21 Jul, 2021
In this article, we are going to rename the column name using dplyr package in the R programming language.
Dataset in use:
This method is used to rename the columns in the dataframe
Syntax:
rename(dataframe,new_columnname=old_column,.............,name,new_columnname=old_columnname)
Where dataframe is the input dataframe, new_columnname is the newname of the column and old_columnname is the old name of the column.
Example: R program to rename single column
R
# load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # rename the name column with first_namedata1=rename(data1,first_name=name)print(data1)print("====================") # rename the address column with cityrename(data1,city=address)
Output:
Example: R program to rename multiple columns
R
# load the librarylibrary(dplyr) # create dataframe with 3 columns id,name# and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # rename multiple columns# name with first_name# id with roll_no# address with streetrename(data1,first_name=name,roll_no=id,street=address)
Output:
rename_with() is used to change the case of the column.
uppercase: To convert to uppercase, the name of the dataframe along with the toupper is passed to the function which tells the function to convert the case to upper.
Syntax:
rename_with(dataframe,toupper)
Where, dataframe is the input dataframe and toupper is a keyword that converts all columns to upper
lowercase: To convert to lowercase, the name of the dataframe along with the tolower is passed to the function which tells the function to convert the case to lower.
Syntax:
rename_with(dataframe,tolower)
where dataframe is the input dataframe and tolower is a keyword that converts all columns to lower.
Example: R program to convert columns to upper and lower
R
# load the librarylibrary(dplyr) # create dataframe with 3 columns id,name # and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # convert all columns to upperrename_with(data1,toupper)print("==============") # convert all columns to lowerrename_with(data1,tolower)
Output:
We can rename multiple columns at once using a vector that is by passing columns to vector.
Syntax:
rename(dataframe,c(newcolumn1=oldcolumn1,newcolumn2=oldcolumn2...,,newcolumn n=oldcolumn n))
Example: R program to rename multiple columns at once
R
# load the librarylibrary(dplyr) # create dataframe with 3 columns id,name # and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # rename multiple columns# name with first_name# id with roll_no# address with streetrename(data1,c(first_name=name,roll_no=id,street=address))
Output:
Picked
R Dplyr
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 135,
"s": 28,
"text": "In this article, we are going to rename the column name using dplyr package in the R programming language."
},
{
"code": null,
"e": 151,
"s": 135,
"text": "Dataset in use:"
},
{
"code": null,
"e": 210,
"s": 151,
"text": "This method is used to rename the columns in the dataframe"
},
{
"code": null,
"e": 218,
"s": 210,
"text": "Syntax:"
},
{
"code": null,
"e": 311,
"s": 218,
"text": "rename(dataframe,new_columnname=old_column,.............,name,new_columnname=old_columnname)"
},
{
"code": null,
"e": 445,
"s": 311,
"text": "Where dataframe is the input dataframe, new_columnname is the newname of the column and old_columnname is the old name of the column."
},
{
"code": null,
"e": 488,
"s": 445,
"text": "Example: R program to rename single column"
},
{
"code": null,
"e": 490,
"s": 488,
"text": "R"
},
{
"code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # rename the name column with first_namedata1=rename(data1,first_name=name)print(data1)print(\"====================\") # rename the address column with cityrename(data1,city=address)",
"e": 1200,
"s": 490,
"text": null
},
{
"code": null,
"e": 1208,
"s": 1200,
"text": "Output:"
},
{
"code": null,
"e": 1254,
"s": 1208,
"text": "Example: R program to rename multiple columns"
},
{
"code": null,
"e": 1256,
"s": 1254,
"text": "R"
},
{
"code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns id,name# and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # rename multiple columns# name with first_name# id with roll_no# address with streetrename(data1,first_name=name,roll_no=id,street=address)",
"e": 1925,
"s": 1256,
"text": null
},
{
"code": null,
"e": 1933,
"s": 1925,
"text": "Output:"
},
{
"code": null,
"e": 1990,
"s": 1933,
"text": "rename_with() is used to change the case of the column. "
},
{
"code": null,
"e": 2156,
"s": 1990,
"text": "uppercase: To convert to uppercase, the name of the dataframe along with the toupper is passed to the function which tells the function to convert the case to upper."
},
{
"code": null,
"e": 2164,
"s": 2156,
"text": "Syntax:"
},
{
"code": null,
"e": 2195,
"s": 2164,
"text": "rename_with(dataframe,toupper)"
},
{
"code": null,
"e": 2295,
"s": 2195,
"text": "Where, dataframe is the input dataframe and toupper is a keyword that converts all columns to upper"
},
{
"code": null,
"e": 2461,
"s": 2295,
"text": "lowercase: To convert to lowercase, the name of the dataframe along with the tolower is passed to the function which tells the function to convert the case to lower."
},
{
"code": null,
"e": 2469,
"s": 2461,
"text": "Syntax:"
},
{
"code": null,
"e": 2500,
"s": 2469,
"text": "rename_with(dataframe,tolower)"
},
{
"code": null,
"e": 2600,
"s": 2500,
"text": "where dataframe is the input dataframe and tolower is a keyword that converts all columns to lower."
},
{
"code": null,
"e": 2657,
"s": 2600,
"text": "Example: R program to convert columns to upper and lower"
},
{
"code": null,
"e": 2659,
"s": 2657,
"text": "R"
},
{
"code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns id,name # and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # convert all columns to upperrename_with(data1,toupper)print(\"==============\") # convert all columns to lowerrename_with(data1,tolower)",
"e": 3326,
"s": 2659,
"text": null
},
{
"code": null,
"e": 3334,
"s": 3326,
"text": "Output:"
},
{
"code": null,
"e": 3426,
"s": 3334,
"text": "We can rename multiple columns at once using a vector that is by passing columns to vector."
},
{
"code": null,
"e": 3434,
"s": 3426,
"text": "Syntax:"
},
{
"code": null,
"e": 3527,
"s": 3434,
"text": "rename(dataframe,c(newcolumn1=oldcolumn1,newcolumn2=oldcolumn2...,,newcolumn n=oldcolumn n))"
},
{
"code": null,
"e": 3581,
"s": 3527,
"text": "Example: R program to rename multiple columns at once"
},
{
"code": null,
"e": 3583,
"s": 3581,
"text": "R"
},
{
"code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns id,name # and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # rename multiple columns# name with first_name# id with roll_no# address with streetrename(data1,c(first_name=name,roll_no=id,street=address))",
"e": 4256,
"s": 3583,
"text": null
},
{
"code": null,
"e": 4264,
"s": 4256,
"text": "Output:"
},
{
"code": null,
"e": 4271,
"s": 4264,
"text": "Picked"
},
{
"code": null,
"e": 4279,
"s": 4271,
"text": "R Dplyr"
},
{
"code": null,
"e": 4290,
"s": 4279,
"text": "R Language"
}
] |
Dijkstra’s shortest path with minimum edges
|
16 May, 2022
Prerequisite: Dijkstra’s shortest path algorithm Given an adjacency matrix graph representing paths between the nodes in the given graph. The task is to find the shortest path with minimum edges i.e. if there a multiple short paths with same cost then choose the one with the minimum number of edges.Consider the graph given below:
There are two paths from vertex 0 to vertex 3 with the weight of 12:
0 -> 1 -> 2 -> 30 -> 4 -> 3
0 -> 1 -> 2 -> 3
0 -> 4 -> 3
Since, Dijkstra’s algorithm is a greedy algorithm that seeks the minimum weighted vertex on every iteration, so the original Dijkstra’s algorithm will output the first path but the result should be the second path as it contains minimum number of edges.Examples:
Input: graph[][] = { {0, 1, INFINITY, INFINITY, 10}, {1, 0, 4, INFINITY, INFINITY}, {INFINITY, 4, 0, 7, INFINITY}, {INFINITY, INFINITY, 7, 0, 2}, {10, INFINITY, INFINITY, 2, 0} }; Output: 0->4->3 INFINITY here shows that u and v are not neighborsInput: graph[][] = { {0, 5, INFINITY, INFINITY}, {5, 0, 5, 10}, {INFINITY, 5, 0, 5}, {INFINITY, 10, 5, 0} }; Output: 0->1->3
Approach: The idea of the algorithm is to use the original Dijkstra’s algorithm, but also to keep track on the length of the paths by an array that stores the length of the paths from the source vertex, so if we find a shorter path with the same weight, then we will take it.Let’s follow the upper example iteration by iteration: Consider we want to find the shortest path from vertex 0 to vertex 3Initial state: The distance and the parent of all vertices are Infinity and NILL respectively, as usual. But now, we have one more array called pathlength[] that stores the length of the path from the source vertex to all of the vertices. Initially, we set all the elements of pathlength[] to 0.
First iteration: First we seek the vertex which contains the minimum distance which is vertex 0, as shown in the image above. Then, we traverse all its neighbors which are not blackened, which are 1 and 4. Since, the distance of vertex 1 and 4 are infinity, then we reduce their weights to 1 and 10 respectively. Update the parents, and set the pathlength[] for each vertex (1 and 4) to 1 because they can be reached from source vertex by 1 edge. After that, we blacken the vertex as the original Dijkstra’s algorithm does.
Second iteration: We continue to seek the non-blakened vertex which contains the minimum distance, which is vertex 1, and after that we reduce its neighbor’s weight to 1 + 4 = 5 and update its parent as the original Dijkstra’s algorithm does, and set its pathlength[] to 2, because it is two edges away from the source vertex. Finally, we blacken vertex 1.
Third iteration: Again, the non-blackened vertex which contains the minimum distance is vertex 2, so we update the non-blackened neighbors. It has one non-blackened neighbor which is vertex 3. So, we update its weight from Infinity to 5 + 7 = 12 then we set its parent to 2 and set its pathlength[] to 3 because it is 3 edges sway from the source vertex. Finally, we blacken vertex 2.
Fourth iteration: In this iteration, the algorithm acts different from the original Dijkstra’s algorithm. We seek the non-blackened vertex which contains the minimum distance which is 4. Since, the distance to vertex 3 from the source vertex is 12 (0->1->2->3) and the distance of vertex 4 plus the edge (4, 3) is 12, it means that we just found a new path to vertex 3 from the source vertex with the same weight. Then, we check if the new path is shorter (in edges) than the existing one and we take the one with the minimum edges. Finally, we blacken vertex 4.
Since V-1 vertices are blackened, the algorithm ends.Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ program to find the shortest path// with minimum edges in a graph#include <iostream>using namespace std;#define INFINITY 9999#define n 5#define s 0#define d 3#define NILL -1int MinDistance(int*, int*);void PrintPath(int*, int); // Function to find the shortest path// with minimum edges in a graphvoid Dijkstra(int Graph[n][n], int _n, int _s, int _d){ int i, u, v, count; int dist[n]; int Blackened[n] = { 0 }; int pathlength[n] = { 0 }; int parent[n]; // The parent Of the source vertex is always equal to nill parent[_s] = NILL; // first, we initialize all distances to infinity. for (i = 0; i < n; i++) dist[i] = INFINITY; dist[_s] = 0; for (count = 0; count < n - 1; count++) { u = MinDistance(dist, Blackened); // if MinDistance() returns INFINITY, then the graph is not // connected and we have traversed all of the vertices in the // connected component of the source vertex, so it can reduce // the time complexity sometimes // In a directed graph, it means that the source vertex // is not a root if (u == INFINITY) break; else { // Mark the vertex as Blackened Blackened[u] = 1; for (v = 0; v < n; v++) { //distance to v via u should be smaller and the path length should be minimum if (!Blackened[v] && Graph[u][v] && dist[u] + Graph[u][v] <= dist[v] && pathlength[u] + 1 < pathlength[v]) { parent[v] = u; pathlength[v] = pathlength[u] + 1; } } } } // Printing the path if (dist[_d] != INFINITY) PrintPath(parent, _d); else cout << "There is no path between vertex " << _s << "to vertex " << _d;} int MinDistance(int* dist, int* Blackened){ int min = INFINITY, min_index, v; for (v = 0; v < n; v++) if (!Blackened[v] && dist[v] < min) { min = dist[v]; min_index = v; } return min == INFINITY ? INFINITY : min_index;} // Function to print the pathvoid PrintPath(int* parent, int _d){ if (parent[_d] == NILL) { cout << _d; return; } PrintPath(parent, parent[_d]); cout << "->" << _d;} // Driver codeint main(){ // INFINITY means that u and v are not neighbors. int Graph[n][n] = { { 0, 1, INFINITY, INFINITY, 10 }, { 1, 0, 4, INFINITY, INFINITY }, { INFINITY, 4, 0, 7, INFINITY }, { INFINITY, INFINITY, 7, 0, 2 }, { 10, INFINITY, INFINITY, 2, 0 } }; Dijkstra(Graph, n, s, d); return 0;}
// Java program to find the shortest path// with minimum edges in a graphimport java.io.*;import java.util.*; class GFG{ static int INFINITY = 9999, n = 5, s = 0, d = 3, NILL = -1; // Function to find the shortest path // with minimum edges in a graph static void Dijkstra(int[][] Graph, int _n, int _s, int _d) { int i, u, v, count; int[] dist = new int[n]; int[] Blackened = new int[n]; int[] pathlength = new int[n]; int[] parent = new int[n]; // The parent Of the source vertex is always equal to nill parent[_s] = NILL; // first, we initialize all distances to infinity. for (i = 0; i < n; i++) dist[i] = INFINITY; dist[_s] = 0; for (count = 0; count < n - 1; count++) { u = MinDistance(dist, Blackened); // if MinDistance() returns INFINITY, then the graph is not // connected and we have traversed all of the vertices in the // connected component of the source vertex, so it can reduce // the time complexity sometimes // In a directed graph, it means that the source vertex // is not a root if (u == INFINITY) break; else { // Mark the vertex as Blackened Blackened[u] = 1; for (v = 0; v < n; v++) { if (Blackened[v] == 0 && Graph[u][v] != 0 && dist[u] + Graph[u][v] < dist[v]) { parent[v] = u; pathlength[v] = pathlength[parent[v]] + 1; dist[v] = dist[u] + Graph[u][v]; } else if (Blackened[v] == 0 && Graph[u][v] != 0 && dist[u] + Graph[u][v] == dist[v] && pathlength[u] + 1 < pathlength[v]) { parent[v] = u; pathlength[v] = pathlength[u] + 1; } } } } // Printing the path if (dist[_d] != INFINITY) PrintPath(parent, _d); else System.out.println("There is not path between vertex " + _s + " to vertex " + _d); } static int MinDistance(int[] dist, int[] Blackened) { int min = INFINITY, min_index = -1, v; for (v = 0; v < n; v++) if (Blackened[v] == 0 && dist[v] < min) { min = dist[v]; min_index = v; } return min == INFINITY ? INFINITY : min_index; } // Function to print the path static void PrintPath(int[] parent, int _d) { if (parent[_d] == NILL) { System.out.print(_d); return; } PrintPath(parent, parent[_d]); System.out.print("->" + _d); } // Driver Code public static void main(String[] args) { // INFINITY means that u and v are not neighbors. int[][] Graph = { { 0, 1, INFINITY, INFINITY, 10 }, { 1, 0, 4, INFINITY, INFINITY }, { INFINITY, 4, 0, 7, INFINITY }, { INFINITY, INFINITY, 7, 0, 2 }, { 10, INFINITY, INFINITY, 2, 0 } }; Dijkstra(Graph, n, s, d); }} // This code is contributed by// sanjeev2552
# Python program to find the shortest path# with minimum edges in a graphdef Dijkstra(Graph, _s, _d): row = len(Graph) col = len(Graph[0]) dist = [float("Inf")] * row Blackened =[0] * row pathlength =[0] * row parent = [-1] * row dist[_s]= 0 for count in range(row-1): u = MinDistance(dist, Blackened) # if MinDistance() returns INFINITY, then the graph is not # connected and we have traversed all of the vertices in the # connected component of the source vertex, so it can reduce # the time complexity sometimes # In a directed graph, it means that the source vertex # is not a root if u == float("Inf"): break else: # Mark the vertex as Blackened Blackened[u]= 1 for v in range(row): if Blackened[v]== 0 and Graph[u][v] and dist[u]+Graph[u][v]<dist[v]: parent[v]= u pathlength[v]= pathlength[parent[v]]+1 dist[v]= dist[u]+Graph[u][v] elif Blackened[v]== 0 and Graph[u][v] and dist[u]+Graph[u][v]== dist[v] and pathlength[u]+1<pathlength[v]: parent[v]= u pathlength[v] = pathlength[u] + 1 if dist[_d]!= float("Inf"): # Printing the path PrintPath(parent, _d) else: print("There is no path between vertex ", _s, "to vertex ", _d) # Function to print the pathdef PrintPath(parent, _d): if parent[_d]==-1: print(_d,end='') return PrintPath(parent, parent[_d]) print("->", _d,end='')def MinDistance(dist, Blackened): min = float("Inf") for v in range(len(dist)): if not Blackened[v] and dist[v]<min: min = dist[v] Min_index = v return float("Inf") if min == float("Inf") else Min_index # Driver code# float("Inf") means that u and v are not neighborsGraph =[[0, 1, float("Inf"), float("Inf"), 10], [1, 0, 4, float("Inf"), float("Inf")], [float("Inf"), 4, 0, 7, float("Inf")], [float("Inf"), float("Inf"), 7, 0, 2], [10, float("Inf"), float("Inf"), 2, 0]]Dijkstra(Graph, 0, 3)
// C# program to find the shortest path// with minimum edges in a graphusing System;class GFG{ static int INFINITY = 9999, n = 5, s = 0, d = 3, NILL = -1; // Function to find the shortest path // with minimum edges in a graph static void Dijkstra(int [,] Graph, int _n, int _s, int _d) { int i, u, v, count; int[] dist = new int[n]; int[] Blackened = new int[n]; int[] pathlength = new int[n]; int[] parent = new int[n]; // The parent Of the source vertex is always equal to nill parent[_s] = NILL; // first, we initialize all distances to infinity. for (i = 0; i < n; i++) dist[i] = INFINITY; dist[_s] = 0; for (count = 0; count < n - 1; count++) { u = MinDistance(dist, Blackened); // if MinDistance() returns INFINITY, then the graph is not // connected and we have traversed all of the vertices in the // connected component of the source vertex, so it can reduce // the time complexity sometimes // In a directed graph, it means that the source vertex // is not a root if (u == INFINITY) break; else { // Mark the vertex as Blackened Blackened[u] = 1; for (v = 0; v < n; v++) { if (Blackened[v] == 0 && Graph[u,v] != 0 && dist[u] + Graph[u,v] < dist[v]) { parent[v] = u; pathlength[v] = pathlength[parent[v]] + 1; dist[v] = dist[u] + Graph[u,v]; } else if (Blackened[v] == 0 && Graph[u,v] != 0 && dist[u] + Graph[u,v] == dist[v] && pathlength[u] + 1 < pathlength[v]) { parent[v] = u; pathlength[v] = pathlength[u] + 1; } } } } // Printing the path if (dist[_d] != INFINITY) PrintPath(parent, _d); else Console.Write("There is not path between vertex " + _s + " to vertex " + _d); } static int MinDistance(int[] dist, int[] Blackened) { int min = INFINITY, min_index = -1, v; for (v = 0; v < n; v++) if (Blackened[v] == 0 && dist[v] < min) { min = dist[v]; min_index = v; } return min == INFINITY ? INFINITY : min_index; } // Function to print the path static void PrintPath(int[] parent, int _d) { if (parent[_d] == NILL) { Console.Write(_d); return; } PrintPath(parent, parent[_d]); Console.Write("->" + _d); } // Driver Code public static void Main() { // INFINITY means that u and v are not neighbors. int [,] Graph = { { 0, 1, INFINITY, INFINITY, 10 }, { 1, 0, 4, INFINITY, INFINITY }, { INFINITY, 4, 0, 7, INFINITY }, { INFINITY, INFINITY, 7, 0, 2 }, { 10, INFINITY, INFINITY, 2, 0 } }; Dijkstra(Graph, n, s, d); }} // This code is contributed by jana_sayantan.
0->4->3
Time Complexity: O(V^2) where V is the number of vertices and E is the number of edges.Auxiliary Space: O(V + E)
sanjeev2552
pankajsharmagfg
amartyaghoshgfg
abhishekdutta
sweetyty
jana_sayantan
Dijkstra
Shortest Path
Algorithms
Graph
Greedy
Greedy
Graph
Shortest Path
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
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
Graph and its representations
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 May, 2022"
},
{
"code": null,
"e": 386,
"s": 52,
"text": "Prerequisite: Dijkstra’s shortest path algorithm Given an adjacency matrix graph representing paths between the nodes in the given graph. The task is to find the shortest path with minimum edges i.e. if there a multiple short paths with same cost then choose the one with the minimum number of edges.Consider the graph given below: "
},
{
"code": null,
"e": 457,
"s": 386,
"text": "There are two paths from vertex 0 to vertex 3 with the weight of 12: "
},
{
"code": null,
"e": 485,
"s": 457,
"text": "0 -> 1 -> 2 -> 30 -> 4 -> 3"
},
{
"code": null,
"e": 502,
"s": 485,
"text": "0 -> 1 -> 2 -> 3"
},
{
"code": null,
"e": 514,
"s": 502,
"text": "0 -> 4 -> 3"
},
{
"code": null,
"e": 779,
"s": 514,
"text": "Since, Dijkstra’s algorithm is a greedy algorithm that seeks the minimum weighted vertex on every iteration, so the original Dijkstra’s algorithm will output the first path but the result should be the second path as it contains minimum number of edges.Examples: "
},
{
"code": null,
"e": 1152,
"s": 779,
"text": "Input: graph[][] = { {0, 1, INFINITY, INFINITY, 10}, {1, 0, 4, INFINITY, INFINITY}, {INFINITY, 4, 0, 7, INFINITY}, {INFINITY, INFINITY, 7, 0, 2}, {10, INFINITY, INFINITY, 2, 0} }; Output: 0->4->3 INFINITY here shows that u and v are not neighborsInput: graph[][] = { {0, 5, INFINITY, INFINITY}, {5, 0, 5, 10}, {INFINITY, 5, 0, 5}, {INFINITY, 10, 5, 0} }; Output: 0->1->3 "
},
{
"code": null,
"e": 1850,
"s": 1154,
"text": "Approach: The idea of the algorithm is to use the original Dijkstra’s algorithm, but also to keep track on the length of the paths by an array that stores the length of the paths from the source vertex, so if we find a shorter path with the same weight, then we will take it.Let’s follow the upper example iteration by iteration: Consider we want to find the shortest path from vertex 0 to vertex 3Initial state: The distance and the parent of all vertices are Infinity and NILL respectively, as usual. But now, we have one more array called pathlength[] that stores the length of the path from the source vertex to all of the vertices. Initially, we set all the elements of pathlength[] to 0. "
},
{
"code": null,
"e": 2376,
"s": 1850,
"text": "First iteration: First we seek the vertex which contains the minimum distance which is vertex 0, as shown in the image above. Then, we traverse all its neighbors which are not blackened, which are 1 and 4. Since, the distance of vertex 1 and 4 are infinity, then we reduce their weights to 1 and 10 respectively. Update the parents, and set the pathlength[] for each vertex (1 and 4) to 1 because they can be reached from source vertex by 1 edge. After that, we blacken the vertex as the original Dijkstra’s algorithm does. "
},
{
"code": null,
"e": 2735,
"s": 2376,
"text": "Second iteration: We continue to seek the non-blakened vertex which contains the minimum distance, which is vertex 1, and after that we reduce its neighbor’s weight to 1 + 4 = 5 and update its parent as the original Dijkstra’s algorithm does, and set its pathlength[] to 2, because it is two edges away from the source vertex. Finally, we blacken vertex 1. "
},
{
"code": null,
"e": 3122,
"s": 2735,
"text": "Third iteration: Again, the non-blackened vertex which contains the minimum distance is vertex 2, so we update the non-blackened neighbors. It has one non-blackened neighbor which is vertex 3. So, we update its weight from Infinity to 5 + 7 = 12 then we set its parent to 2 and set its pathlength[] to 3 because it is 3 edges sway from the source vertex. Finally, we blacken vertex 2. "
},
{
"code": null,
"e": 3687,
"s": 3122,
"text": "Fourth iteration: In this iteration, the algorithm acts different from the original Dijkstra’s algorithm. We seek the non-blackened vertex which contains the minimum distance which is 4. Since, the distance to vertex 3 from the source vertex is 12 (0->1->2->3) and the distance of vertex 4 plus the edge (4, 3) is 12, it means that we just found a new path to vertex 3 from the source vertex with the same weight. Then, we check if the new path is shorter (in edges) than the existing one and we take the one with the minimum edges. Finally, we blacken vertex 4. "
},
{
"code": null,
"e": 3792,
"s": 3687,
"text": "Since V-1 vertices are blackened, the algorithm ends.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 3796,
"s": 3792,
"text": "C++"
},
{
"code": null,
"e": 3801,
"s": 3796,
"text": "Java"
},
{
"code": null,
"e": 3809,
"s": 3801,
"text": "Python3"
},
{
"code": null,
"e": 3812,
"s": 3809,
"text": "C#"
},
{
"code": "// C++ program to find the shortest path// with minimum edges in a graph#include <iostream>using namespace std;#define INFINITY 9999#define n 5#define s 0#define d 3#define NILL -1int MinDistance(int*, int*);void PrintPath(int*, int); // Function to find the shortest path// with minimum edges in a graphvoid Dijkstra(int Graph[n][n], int _n, int _s, int _d){ int i, u, v, count; int dist[n]; int Blackened[n] = { 0 }; int pathlength[n] = { 0 }; int parent[n]; // The parent Of the source vertex is always equal to nill parent[_s] = NILL; // first, we initialize all distances to infinity. for (i = 0; i < n; i++) dist[i] = INFINITY; dist[_s] = 0; for (count = 0; count < n - 1; count++) { u = MinDistance(dist, Blackened); // if MinDistance() returns INFINITY, then the graph is not // connected and we have traversed all of the vertices in the // connected component of the source vertex, so it can reduce // the time complexity sometimes // In a directed graph, it means that the source vertex // is not a root if (u == INFINITY) break; else { // Mark the vertex as Blackened Blackened[u] = 1; for (v = 0; v < n; v++) { //distance to v via u should be smaller and the path length should be minimum if (!Blackened[v] && Graph[u][v] && dist[u] + Graph[u][v] <= dist[v] && pathlength[u] + 1 < pathlength[v]) { parent[v] = u; pathlength[v] = pathlength[u] + 1; } } } } // Printing the path if (dist[_d] != INFINITY) PrintPath(parent, _d); else cout << \"There is no path between vertex \" << _s << \"to vertex \" << _d;} int MinDistance(int* dist, int* Blackened){ int min = INFINITY, min_index, v; for (v = 0; v < n; v++) if (!Blackened[v] && dist[v] < min) { min = dist[v]; min_index = v; } return min == INFINITY ? INFINITY : min_index;} // Function to print the pathvoid PrintPath(int* parent, int _d){ if (parent[_d] == NILL) { cout << _d; return; } PrintPath(parent, parent[_d]); cout << \"->\" << _d;} // Driver codeint main(){ // INFINITY means that u and v are not neighbors. int Graph[n][n] = { { 0, 1, INFINITY, INFINITY, 10 }, { 1, 0, 4, INFINITY, INFINITY }, { INFINITY, 4, 0, 7, INFINITY }, { INFINITY, INFINITY, 7, 0, 2 }, { 10, INFINITY, INFINITY, 2, 0 } }; Dijkstra(Graph, n, s, d); return 0;}",
"e": 6530,
"s": 3812,
"text": null
},
{
"code": "// Java program to find the shortest path// with minimum edges in a graphimport java.io.*;import java.util.*; class GFG{ static int INFINITY = 9999, n = 5, s = 0, d = 3, NILL = -1; // Function to find the shortest path // with minimum edges in a graph static void Dijkstra(int[][] Graph, int _n, int _s, int _d) { int i, u, v, count; int[] dist = new int[n]; int[] Blackened = new int[n]; int[] pathlength = new int[n]; int[] parent = new int[n]; // The parent Of the source vertex is always equal to nill parent[_s] = NILL; // first, we initialize all distances to infinity. for (i = 0; i < n; i++) dist[i] = INFINITY; dist[_s] = 0; for (count = 0; count < n - 1; count++) { u = MinDistance(dist, Blackened); // if MinDistance() returns INFINITY, then the graph is not // connected and we have traversed all of the vertices in the // connected component of the source vertex, so it can reduce // the time complexity sometimes // In a directed graph, it means that the source vertex // is not a root if (u == INFINITY) break; else { // Mark the vertex as Blackened Blackened[u] = 1; for (v = 0; v < n; v++) { if (Blackened[v] == 0 && Graph[u][v] != 0 && dist[u] + Graph[u][v] < dist[v]) { parent[v] = u; pathlength[v] = pathlength[parent[v]] + 1; dist[v] = dist[u] + Graph[u][v]; } else if (Blackened[v] == 0 && Graph[u][v] != 0 && dist[u] + Graph[u][v] == dist[v] && pathlength[u] + 1 < pathlength[v]) { parent[v] = u; pathlength[v] = pathlength[u] + 1; } } } } // Printing the path if (dist[_d] != INFINITY) PrintPath(parent, _d); else System.out.println(\"There is not path between vertex \" + _s + \" to vertex \" + _d); } static int MinDistance(int[] dist, int[] Blackened) { int min = INFINITY, min_index = -1, v; for (v = 0; v < n; v++) if (Blackened[v] == 0 && dist[v] < min) { min = dist[v]; min_index = v; } return min == INFINITY ? INFINITY : min_index; } // Function to print the path static void PrintPath(int[] parent, int _d) { if (parent[_d] == NILL) { System.out.print(_d); return; } PrintPath(parent, parent[_d]); System.out.print(\"->\" + _d); } // Driver Code public static void main(String[] args) { // INFINITY means that u and v are not neighbors. int[][] Graph = { { 0, 1, INFINITY, INFINITY, 10 }, { 1, 0, 4, INFINITY, INFINITY }, { INFINITY, 4, 0, 7, INFINITY }, { INFINITY, INFINITY, 7, 0, 2 }, { 10, INFINITY, INFINITY, 2, 0 } }; Dijkstra(Graph, n, s, d); }} // This code is contributed by// sanjeev2552",
"e": 9967,
"s": 6530,
"text": null
},
{
"code": "# Python program to find the shortest path# with minimum edges in a graphdef Dijkstra(Graph, _s, _d): row = len(Graph) col = len(Graph[0]) dist = [float(\"Inf\")] * row Blackened =[0] * row pathlength =[0] * row parent = [-1] * row dist[_s]= 0 for count in range(row-1): u = MinDistance(dist, Blackened) # if MinDistance() returns INFINITY, then the graph is not # connected and we have traversed all of the vertices in the # connected component of the source vertex, so it can reduce # the time complexity sometimes # In a directed graph, it means that the source vertex # is not a root if u == float(\"Inf\"): break else: # Mark the vertex as Blackened Blackened[u]= 1 for v in range(row): if Blackened[v]== 0 and Graph[u][v] and dist[u]+Graph[u][v]<dist[v]: parent[v]= u pathlength[v]= pathlength[parent[v]]+1 dist[v]= dist[u]+Graph[u][v] elif Blackened[v]== 0 and Graph[u][v] and dist[u]+Graph[u][v]== dist[v] and pathlength[u]+1<pathlength[v]: parent[v]= u pathlength[v] = pathlength[u] + 1 if dist[_d]!= float(\"Inf\"): # Printing the path PrintPath(parent, _d) else: print(\"There is no path between vertex \", _s, \"to vertex \", _d) # Function to print the pathdef PrintPath(parent, _d): if parent[_d]==-1: print(_d,end='') return PrintPath(parent, parent[_d]) print(\"->\", _d,end='')def MinDistance(dist, Blackened): min = float(\"Inf\") for v in range(len(dist)): if not Blackened[v] and dist[v]<min: min = dist[v] Min_index = v return float(\"Inf\") if min == float(\"Inf\") else Min_index # Driver code# float(\"Inf\") means that u and v are not neighborsGraph =[[0, 1, float(\"Inf\"), float(\"Inf\"), 10], [1, 0, 4, float(\"Inf\"), float(\"Inf\")], [float(\"Inf\"), 4, 0, 7, float(\"Inf\")], [float(\"Inf\"), float(\"Inf\"), 7, 0, 2], [10, float(\"Inf\"), float(\"Inf\"), 2, 0]]Dijkstra(Graph, 0, 3)",
"e": 12081,
"s": 9967,
"text": null
},
{
"code": "// C# program to find the shortest path// with minimum edges in a graphusing System;class GFG{ static int INFINITY = 9999, n = 5, s = 0, d = 3, NILL = -1; // Function to find the shortest path // with minimum edges in a graph static void Dijkstra(int [,] Graph, int _n, int _s, int _d) { int i, u, v, count; int[] dist = new int[n]; int[] Blackened = new int[n]; int[] pathlength = new int[n]; int[] parent = new int[n]; // The parent Of the source vertex is always equal to nill parent[_s] = NILL; // first, we initialize all distances to infinity. for (i = 0; i < n; i++) dist[i] = INFINITY; dist[_s] = 0; for (count = 0; count < n - 1; count++) { u = MinDistance(dist, Blackened); // if MinDistance() returns INFINITY, then the graph is not // connected and we have traversed all of the vertices in the // connected component of the source vertex, so it can reduce // the time complexity sometimes // In a directed graph, it means that the source vertex // is not a root if (u == INFINITY) break; else { // Mark the vertex as Blackened Blackened[u] = 1; for (v = 0; v < n; v++) { if (Blackened[v] == 0 && Graph[u,v] != 0 && dist[u] + Graph[u,v] < dist[v]) { parent[v] = u; pathlength[v] = pathlength[parent[v]] + 1; dist[v] = dist[u] + Graph[u,v]; } else if (Blackened[v] == 0 && Graph[u,v] != 0 && dist[u] + Graph[u,v] == dist[v] && pathlength[u] + 1 < pathlength[v]) { parent[v] = u; pathlength[v] = pathlength[u] + 1; } } } } // Printing the path if (dist[_d] != INFINITY) PrintPath(parent, _d); else Console.Write(\"There is not path between vertex \" + _s + \" to vertex \" + _d); } static int MinDistance(int[] dist, int[] Blackened) { int min = INFINITY, min_index = -1, v; for (v = 0; v < n; v++) if (Blackened[v] == 0 && dist[v] < min) { min = dist[v]; min_index = v; } return min == INFINITY ? INFINITY : min_index; } // Function to print the path static void PrintPath(int[] parent, int _d) { if (parent[_d] == NILL) { Console.Write(_d); return; } PrintPath(parent, parent[_d]); Console.Write(\"->\" + _d); } // Driver Code public static void Main() { // INFINITY means that u and v are not neighbors. int [,] Graph = { { 0, 1, INFINITY, INFINITY, 10 }, { 1, 0, 4, INFINITY, INFINITY }, { INFINITY, 4, 0, 7, INFINITY }, { INFINITY, INFINITY, 7, 0, 2 }, { 10, INFINITY, INFINITY, 2, 0 } }; Dijkstra(Graph, n, s, d); }} // This code is contributed by jana_sayantan.",
"e": 14972,
"s": 12081,
"text": null
},
{
"code": null,
"e": 14980,
"s": 14972,
"text": "0->4->3"
},
{
"code": null,
"e": 15096,
"s": 14982,
"text": "Time Complexity: O(V^2) where V is the number of vertices and E is the number of edges.Auxiliary Space: O(V + E) "
},
{
"code": null,
"e": 15108,
"s": 15096,
"text": "sanjeev2552"
},
{
"code": null,
"e": 15124,
"s": 15108,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 15140,
"s": 15124,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 15154,
"s": 15140,
"text": "abhishekdutta"
},
{
"code": null,
"e": 15163,
"s": 15154,
"text": "sweetyty"
},
{
"code": null,
"e": 15177,
"s": 15163,
"text": "jana_sayantan"
},
{
"code": null,
"e": 15186,
"s": 15177,
"text": "Dijkstra"
},
{
"code": null,
"e": 15200,
"s": 15186,
"text": "Shortest Path"
},
{
"code": null,
"e": 15211,
"s": 15200,
"text": "Algorithms"
},
{
"code": null,
"e": 15217,
"s": 15211,
"text": "Graph"
},
{
"code": null,
"e": 15224,
"s": 15217,
"text": "Greedy"
},
{
"code": null,
"e": 15231,
"s": 15224,
"text": "Greedy"
},
{
"code": null,
"e": 15237,
"s": 15231,
"text": "Graph"
},
{
"code": null,
"e": 15251,
"s": 15237,
"text": "Shortest Path"
},
{
"code": null,
"e": 15262,
"s": 15251,
"text": "Algorithms"
},
{
"code": null,
"e": 15360,
"s": 15262,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15398,
"s": 15360,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 15466,
"s": 15398,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 15493,
"s": 15466,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 15536,
"s": 15493,
"text": "Complete Roadmap To Learn DSA From Scratch"
},
{
"code": null,
"e": 15603,
"s": 15536,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 15643,
"s": 15603,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 15681,
"s": 15643,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 15732,
"s": 15681,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 15783,
"s": 15732,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
}
] |
REST API (Introduction)
|
08 Jun, 2022
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing.
REST technology is generally preferred to the more robust Simple Object Access Protocol (SOAP) technology because REST uses less bandwidth, simple and flexible making it more suitable for internet usage. It’s used to fetch or give some information from a web service. All communication done via REST API uses only HTTP request.
Working: A request is sent from client to server in the form of a web URL as HTTP GET or POST or PUT or DELETE request. After that, a response comes back from the server in the form of a resource which can be anything like HTML, XML, Image, or JSON. But now JSON is the most popular format being used in Web Services.
In HTTP there are five methods that are commonly used in a REST-based Architecture i.e., POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations respectively. There are other methods which are less frequently used like OPTIONS and HEAD.
GET: The HTTP GET method is used to read (or retrieve) a representation of a resource. In the safe path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).
POST: The POST verb is most often utilized to create new resources. In particular, it’s used to create subordinate resources. That is, subordinate to some other (e.g. parent) resource. On successful creation, return HTTP status 201, returning a Location header with a link to the newly-created resource with the 201 HTTP status.
NOTE: POST is neither safe nor idempotent.
PUT: It is used for updating the capabilities. However, PUT can also be used to create a resource in the case where the resource ID is chosen by the client instead of by the server. In other words, if the PUT is to a URI that contains the value of a non-existent resource ID. On successful update, return 200 (or 204 if not returning any content in the body) from a PUT. If using PUT for create, return HTTP status 201 on successful creation. PUT is not safe operation but it’s idempotent.
PATCH: It is used to modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource. This resembles PUT, but the body contains a set of instructions describing how a resource currently residing on the server should be modified to produce a new version. This means that the PATCH body should not just be a modified part of the resource, but in some kind of patch language like JSON Patch or XML Patch. PATCH is neither safe nor idempotent.
DELETE: It is used to delete a resource identified by a URI. On successful deletion, return HTTP status 200 (OK) along with a response body.
Idempotence: An idempotent HTTP method is a HTTP method that can be called many times without different outcomes. It would not matter if the method is called only once, or ten times over. The result should be the same. Again, this only applies to the result, not the resource itself.
Example:
C
1. a = 4 // It is Idempotence, as final value(a = 4) // would not change after executing it multiple // times. 2. a++ // It is not Idempotence because the final value // will depend upon the number of times the // statement is executed.
Now we will see how request and response work for different HTTP methods. Let’s assume we have an API(https://www.geeksforgeeks.org/api/students) for all students data of gfg.
GET: Request for all Students.
POST: Request for Posting/Creating/Inserting Data
Request
POST:/api/students
{“name”:”Raj”}
PUT or PATCH: Request for Updating Data at id=1
Request
PUT or PATCH:/api/students/1
{“name”:”Raj”}
DELETE: Request for Deleting Data of id=1
RESTful web services are very popular because they are light weight, highly scalable and maintainable and are very commonly used to create APIs for web-based applications.
pranshulrs
isha307
Web technologies
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 293,
"s": 52,
"text": "Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing."
},
{
"code": null,
"e": 622,
"s": 293,
"text": "REST technology is generally preferred to the more robust Simple Object Access Protocol (SOAP) technology because REST uses less bandwidth, simple and flexible making it more suitable for internet usage. It’s used to fetch or give some information from a web service. All communication done via REST API uses only HTTP request. "
},
{
"code": null,
"e": 942,
"s": 622,
"text": "Working: A request is sent from client to server in the form of a web URL as HTTP GET or POST or PUT or DELETE request. After that, a response comes back from the server in the form of a resource which can be anything like HTML, XML, Image, or JSON. But now JSON is the most popular format being used in Web Services. "
},
{
"code": null,
"e": 1234,
"s": 942,
"text": "In HTTP there are five methods that are commonly used in a REST-based Architecture i.e., POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations respectively. There are other methods which are less frequently used like OPTIONS and HEAD. "
},
{
"code": null,
"e": 1504,
"s": 1234,
"text": "GET: The HTTP GET method is used to read (or retrieve) a representation of a resource. In the safe path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST). "
},
{
"code": null,
"e": 1834,
"s": 1504,
"text": "POST: The POST verb is most often utilized to create new resources. In particular, it’s used to create subordinate resources. That is, subordinate to some other (e.g. parent) resource. On successful creation, return HTTP status 201, returning a Location header with a link to the newly-created resource with the 201 HTTP status. "
},
{
"code": null,
"e": 1878,
"s": 1834,
"text": "NOTE: POST is neither safe nor idempotent. "
},
{
"code": null,
"e": 2369,
"s": 1878,
"text": "PUT: It is used for updating the capabilities. However, PUT can also be used to create a resource in the case where the resource ID is chosen by the client instead of by the server. In other words, if the PUT is to a URI that contains the value of a non-existent resource ID. On successful update, return 200 (or 204 if not returning any content in the body) from a PUT. If using PUT for create, return HTTP status 201 on successful creation. PUT is not safe operation but it’s idempotent. "
},
{
"code": null,
"e": 2862,
"s": 2369,
"text": "PATCH: It is used to modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource. This resembles PUT, but the body contains a set of instructions describing how a resource currently residing on the server should be modified to produce a new version. This means that the PATCH body should not just be a modified part of the resource, but in some kind of patch language like JSON Patch or XML Patch. PATCH is neither safe nor idempotent. "
},
{
"code": null,
"e": 3004,
"s": 2862,
"text": "DELETE: It is used to delete a resource identified by a URI. On successful deletion, return HTTP status 200 (OK) along with a response body. "
},
{
"code": null,
"e": 3289,
"s": 3004,
"text": "Idempotence: An idempotent HTTP method is a HTTP method that can be called many times without different outcomes. It would not matter if the method is called only once, or ten times over. The result should be the same. Again, this only applies to the result, not the resource itself. "
},
{
"code": null,
"e": 3298,
"s": 3289,
"text": "Example:"
},
{
"code": null,
"e": 3300,
"s": 3298,
"text": "C"
},
{
"code": "1. a = 4 // It is Idempotence, as final value(a = 4) // would not change after executing it multiple // times. 2. a++ // It is not Idempotence because the final value // will depend upon the number of times the // statement is executed.",
"e": 3559,
"s": 3300,
"text": null
},
{
"code": null,
"e": 3735,
"s": 3559,
"text": "Now we will see how request and response work for different HTTP methods. Let’s assume we have an API(https://www.geeksforgeeks.org/api/students) for all students data of gfg."
},
{
"code": null,
"e": 3766,
"s": 3735,
"text": "GET: Request for all Students."
},
{
"code": null,
"e": 3816,
"s": 3766,
"text": "POST: Request for Posting/Creating/Inserting Data"
},
{
"code": null,
"e": 3824,
"s": 3816,
"text": "Request"
},
{
"code": null,
"e": 3843,
"s": 3824,
"text": "POST:/api/students"
},
{
"code": null,
"e": 3858,
"s": 3843,
"text": "{“name”:”Raj”}"
},
{
"code": null,
"e": 3906,
"s": 3858,
"text": "PUT or PATCH: Request for Updating Data at id=1"
},
{
"code": null,
"e": 3914,
"s": 3906,
"text": "Request"
},
{
"code": null,
"e": 3943,
"s": 3914,
"text": "PUT or PATCH:/api/students/1"
},
{
"code": null,
"e": 3958,
"s": 3943,
"text": "{“name”:”Raj”}"
},
{
"code": null,
"e": 4000,
"s": 3958,
"text": "DELETE: Request for Deleting Data of id=1"
},
{
"code": null,
"e": 4172,
"s": 4000,
"text": "RESTful web services are very popular because they are light weight, highly scalable and maintainable and are very commonly used to create APIs for web-based applications."
},
{
"code": null,
"e": 4183,
"s": 4172,
"text": "pranshulrs"
},
{
"code": null,
"e": 4191,
"s": 4183,
"text": "isha307"
},
{
"code": null,
"e": 4208,
"s": 4191,
"text": "Web technologies"
},
{
"code": null,
"e": 4213,
"s": 4208,
"text": "HTML"
},
{
"code": null,
"e": 4230,
"s": 4213,
"text": "Web Technologies"
},
{
"code": null,
"e": 4235,
"s": 4230,
"text": "HTML"
}
] |
Python – The new generation Language
|
29 Jun, 2022
Python designed by Guido van Rossum at CWI has become a widely used general-purpose, high-level programming language.
Prerequisites:
Knowledge of any programming language can be a plus.
Reason for increasing popularity
Emphasis on code readability, shorter codes, ease of writingProgrammers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java.Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural.There exists inbuilt functions for almost all of the frequently used concepts.Philosophy is “Simplicity is the best”.
Emphasis on code readability, shorter codes, ease of writing
Programmers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java.
Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural.
There exists inbuilt functions for almost all of the frequently used concepts.
Philosophy is “Simplicity is the best”.
LANGUAGE FEATURES
InterpretedThere are no separate compilation and execution steps like C and C++.Directly run the program from the source code.Internally, Python converts the source code into an intermediate form called bytecodes which is then translated into native language of specific computer to run it.No need to worry about linking and loading with libraries, etc.
There are no separate compilation and execution steps like C and C++.
Directly run the program from the source code.
Internally, Python converts the source code into an intermediate form called bytecodes which is then translated into native language of specific computer to run it.
No need to worry about linking and loading with libraries, etc.
Platform IndependentPython programs can be developed and executed on multiple operating system platforms.Python can be used on Linux, Windows, Macintosh, Solaris and many more.
Python programs can be developed and executed on multiple operating system platforms.
Python can be used on Linux, Windows, Macintosh, Solaris and many more.
Free and Open Source; Redistributable
High-level LanguageIn Python, no need to take care about low-level details such as managing the memory used by the program.
In Python, no need to take care about low-level details such as managing the memory used by the program.
SimpleCloser to English language;Easy to LearnMore emphasis on the solution to the problem rather than the syntax
Closer to English language;Easy to Learn
More emphasis on the solution to the problem rather than the syntax
EmbeddablePython can be used within C/C++ program to give scripting capabilities for the program’s users.
Python can be used within C/C++ program to give scripting capabilities for the program’s users.
Robust:Exceptional handling featuresMemory management techniques in built
Exceptional handling features
Memory management techniques in built
Rich Library SupportThe Python Standard Library is vary vast.Known as the “batteries included” philosophy of Python ;It can help do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more.Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library.
The Python Standard Library is vary vast.
Known as the “batteries included” philosophy of Python ;It can help do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more.
Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library.
Python vs JAVA
The classical Hello World program illustrating the relative verbosity of a Java Program and Python ProgramJava Code
public class HelloWorld{ public static void main (String[] args) { System.out.println("Hello, world!"); }}
Python Code
print("Hello, world!")
Similarity with Java
Require some form of runtime on your system (JVM/Python runtime)
Can probably be compiled to executables without the runtime (this is situational, none of them are designed to work this way)
LOOK and FEEL of the Python
GUI
Command Line interface
Softwares making use of Python
Python has been successfully embedded in a number of software products as a scripting language.
GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers.Python has also been used in artificial intelligencePython is often used for natural language processing tasks.
GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers.
Python has also been used in artificial intelligence
Python is often used for natural language processing tasks.
Current Applications of Python
A number of Linux distributions use installers written in Python example in Ubuntu we have the UbiquityPython has seen extensive use in the information security industry, including in exploit development.Raspberry Pi– single board computer uses Python as its principal user-programming language.Python is now being used Game Development areas also.
A number of Linux distributions use installers written in Python example in Ubuntu we have the Ubiquity
Python has seen extensive use in the information security industry, including in exploit development.
Raspberry Pi– single board computer uses Python as its principal user-programming language.
Python is now being used Game Development areas also.
Pros:
Ease of useMulti-paradigm Approach
Ease of use
Multi-paradigm Approach
Cons:
Slow speed of execution compared to C,C++Absence from mobile computing and browsersFor the C,C++ programmers switching to python can be irritating as the language requires proper indentation of code. Certain variable names commonly used like sum are functions in python. So C, C++ programmers have to look out for these.
Slow speed of execution compared to C,C++
Absence from mobile computing and browsers
For the C,C++ programmers switching to python can be irritating as the language requires proper indentation of code. Certain variable names commonly used like sum are functions in python. So C, C++ programmers have to look out for these.
Industrial Importance
Most of the companies are now looking for candidates who know about Python Programming. Those having the knowledge of python may have more chances of impressing the interviewing panel. So I would suggest that beginners should start learning python and excel in it.
GeeksforGeeks is very soon going to introduce programming in Python too.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Article By Mudit Maheshwari:
A 3rd-year B.Tech IT student from VIT University, Vellore having a keen interest in coding, learning about new technology, and developing software. Besides being passionate about coding, he also loves playing guitar and singing. Currently staying in Chennai. You can reach him at mudit94@gmail.com.
If you also wish to showcase your blog here,please see GBlog for guest blog writing on GeeksforGeeks.
sagar utekar
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 171,
"s": 53,
"text": "Python designed by Guido van Rossum at CWI has become a widely used general-purpose, high-level programming language."
},
{
"code": null,
"e": 186,
"s": 171,
"text": "Prerequisites:"
},
{
"code": null,
"e": 239,
"s": 186,
"text": "Knowledge of any programming language can be a plus."
},
{
"code": null,
"e": 272,
"s": 239,
"text": "Reason for increasing popularity"
},
{
"code": null,
"e": 683,
"s": 272,
"text": "Emphasis on code readability, shorter codes, ease of writingProgrammers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java.Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural.There exists inbuilt functions for almost all of the frequently used concepts.Philosophy is “Simplicity is the best”."
},
{
"code": null,
"e": 744,
"s": 683,
"text": "Emphasis on code readability, shorter codes, ease of writing"
},
{
"code": null,
"e": 856,
"s": 744,
"text": "Programmers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java."
},
{
"code": null,
"e": 979,
"s": 856,
"text": "Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural."
},
{
"code": null,
"e": 1058,
"s": 979,
"text": "There exists inbuilt functions for almost all of the frequently used concepts."
},
{
"code": null,
"e": 1098,
"s": 1058,
"text": "Philosophy is “Simplicity is the best”."
},
{
"code": null,
"e": 1116,
"s": 1098,
"text": "LANGUAGE FEATURES"
},
{
"code": null,
"e": 1470,
"s": 1116,
"text": "InterpretedThere are no separate compilation and execution steps like C and C++.Directly run the program from the source code.Internally, Python converts the source code into an intermediate form called bytecodes which is then translated into native language of specific computer to run it.No need to worry about linking and loading with libraries, etc."
},
{
"code": null,
"e": 1540,
"s": 1470,
"text": "There are no separate compilation and execution steps like C and C++."
},
{
"code": null,
"e": 1587,
"s": 1540,
"text": "Directly run the program from the source code."
},
{
"code": null,
"e": 1752,
"s": 1587,
"text": "Internally, Python converts the source code into an intermediate form called bytecodes which is then translated into native language of specific computer to run it."
},
{
"code": null,
"e": 1816,
"s": 1752,
"text": "No need to worry about linking and loading with libraries, etc."
},
{
"code": null,
"e": 1993,
"s": 1816,
"text": "Platform IndependentPython programs can be developed and executed on multiple operating system platforms.Python can be used on Linux, Windows, Macintosh, Solaris and many more."
},
{
"code": null,
"e": 2079,
"s": 1993,
"text": "Python programs can be developed and executed on multiple operating system platforms."
},
{
"code": null,
"e": 2151,
"s": 2079,
"text": "Python can be used on Linux, Windows, Macintosh, Solaris and many more."
},
{
"code": null,
"e": 2189,
"s": 2151,
"text": "Free and Open Source; Redistributable"
},
{
"code": null,
"e": 2313,
"s": 2189,
"text": "High-level LanguageIn Python, no need to take care about low-level details such as managing the memory used by the program."
},
{
"code": null,
"e": 2418,
"s": 2313,
"text": "In Python, no need to take care about low-level details such as managing the memory used by the program."
},
{
"code": null,
"e": 2532,
"s": 2418,
"text": "SimpleCloser to English language;Easy to LearnMore emphasis on the solution to the problem rather than the syntax"
},
{
"code": null,
"e": 2573,
"s": 2532,
"text": "Closer to English language;Easy to Learn"
},
{
"code": null,
"e": 2641,
"s": 2573,
"text": "More emphasis on the solution to the problem rather than the syntax"
},
{
"code": null,
"e": 2747,
"s": 2641,
"text": "EmbeddablePython can be used within C/C++ program to give scripting capabilities for the program’s users."
},
{
"code": null,
"e": 2843,
"s": 2747,
"text": "Python can be used within C/C++ program to give scripting capabilities for the program’s users."
},
{
"code": null,
"e": 2917,
"s": 2843,
"text": "Robust:Exceptional handling featuresMemory management techniques in built"
},
{
"code": null,
"e": 2947,
"s": 2917,
"text": "Exceptional handling features"
},
{
"code": null,
"e": 2985,
"s": 2947,
"text": "Memory management techniques in built"
},
{
"code": null,
"e": 3474,
"s": 2985,
"text": "Rich Library SupportThe Python Standard Library is vary vast.Known as the “batteries included” philosophy of Python ;It can help do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more.Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library."
},
{
"code": null,
"e": 3516,
"s": 3474,
"text": "The Python Standard Library is vary vast."
},
{
"code": null,
"e": 3776,
"s": 3516,
"text": "Known as the “batteries included” philosophy of Python ;It can help do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more."
},
{
"code": null,
"e": 3945,
"s": 3776,
"text": "Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library."
},
{
"code": null,
"e": 3960,
"s": 3945,
"text": "Python vs JAVA"
},
{
"code": null,
"e": 4076,
"s": 3960,
"text": "The classical Hello World program illustrating the relative verbosity of a Java Program and Python ProgramJava Code"
},
{
"code": "public class HelloWorld{ public static void main (String[] args) { System.out.println(\"Hello, world!\"); }}",
"e": 4194,
"s": 4076,
"text": null
},
{
"code": null,
"e": 4206,
"s": 4194,
"text": "Python Code"
},
{
"code": "print(\"Hello, world!\")",
"e": 4229,
"s": 4206,
"text": null
},
{
"code": null,
"e": 4250,
"s": 4229,
"text": "Similarity with Java"
},
{
"code": null,
"e": 4315,
"s": 4250,
"text": "Require some form of runtime on your system (JVM/Python runtime)"
},
{
"code": null,
"e": 4441,
"s": 4315,
"text": "Can probably be compiled to executables without the runtime (this is situational, none of them are designed to work this way)"
},
{
"code": null,
"e": 4469,
"s": 4441,
"text": "LOOK and FEEL of the Python"
},
{
"code": null,
"e": 4473,
"s": 4469,
"text": "GUI"
},
{
"code": null,
"e": 4496,
"s": 4473,
"text": "Command Line interface"
},
{
"code": null,
"e": 4527,
"s": 4496,
"text": "Softwares making use of Python"
},
{
"code": null,
"e": 4623,
"s": 4527,
"text": "Python has been successfully embedded in a number of software products as a scripting language."
},
{
"code": null,
"e": 4830,
"s": 4623,
"text": "GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers.Python has also been used in artificial intelligencePython is often used for natural language processing tasks."
},
{
"code": null,
"e": 4926,
"s": 4830,
"text": "GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers."
},
{
"code": null,
"e": 4979,
"s": 4926,
"text": "Python has also been used in artificial intelligence"
},
{
"code": null,
"e": 5039,
"s": 4979,
"text": "Python is often used for natural language processing tasks."
},
{
"code": null,
"e": 5070,
"s": 5039,
"text": "Current Applications of Python"
},
{
"code": null,
"e": 5419,
"s": 5070,
"text": "A number of Linux distributions use installers written in Python example in Ubuntu we have the UbiquityPython has seen extensive use in the information security industry, including in exploit development.Raspberry Pi– single board computer uses Python as its principal user-programming language.Python is now being used Game Development areas also."
},
{
"code": null,
"e": 5523,
"s": 5419,
"text": "A number of Linux distributions use installers written in Python example in Ubuntu we have the Ubiquity"
},
{
"code": null,
"e": 5625,
"s": 5523,
"text": "Python has seen extensive use in the information security industry, including in exploit development."
},
{
"code": null,
"e": 5717,
"s": 5625,
"text": "Raspberry Pi– single board computer uses Python as its principal user-programming language."
},
{
"code": null,
"e": 5771,
"s": 5717,
"text": "Python is now being used Game Development areas also."
},
{
"code": null,
"e": 5777,
"s": 5771,
"text": "Pros:"
},
{
"code": null,
"e": 5812,
"s": 5777,
"text": "Ease of useMulti-paradigm Approach"
},
{
"code": null,
"e": 5824,
"s": 5812,
"text": "Ease of use"
},
{
"code": null,
"e": 5848,
"s": 5824,
"text": "Multi-paradigm Approach"
},
{
"code": null,
"e": 5854,
"s": 5848,
"text": "Cons:"
},
{
"code": null,
"e": 6175,
"s": 5854,
"text": "Slow speed of execution compared to C,C++Absence from mobile computing and browsersFor the C,C++ programmers switching to python can be irritating as the language requires proper indentation of code. Certain variable names commonly used like sum are functions in python. So C, C++ programmers have to look out for these."
},
{
"code": null,
"e": 6217,
"s": 6175,
"text": "Slow speed of execution compared to C,C++"
},
{
"code": null,
"e": 6260,
"s": 6217,
"text": "Absence from mobile computing and browsers"
},
{
"code": null,
"e": 6498,
"s": 6260,
"text": "For the C,C++ programmers switching to python can be irritating as the language requires proper indentation of code. Certain variable names commonly used like sum are functions in python. So C, C++ programmers have to look out for these."
},
{
"code": null,
"e": 6520,
"s": 6498,
"text": "Industrial Importance"
},
{
"code": null,
"e": 6785,
"s": 6520,
"text": "Most of the companies are now looking for candidates who know about Python Programming. Those having the knowledge of python may have more chances of impressing the interviewing panel. So I would suggest that beginners should start learning python and excel in it."
},
{
"code": null,
"e": 6858,
"s": 6785,
"text": "GeeksforGeeks is very soon going to introduce programming in Python too."
},
{
"code": null,
"e": 6983,
"s": 6858,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 7012,
"s": 6983,
"text": "Article By Mudit Maheshwari:"
},
{
"code": null,
"e": 7311,
"s": 7012,
"text": "A 3rd-year B.Tech IT student from VIT University, Vellore having a keen interest in coding, learning about new technology, and developing software. Besides being passionate about coding, he also loves playing guitar and singing. Currently staying in Chennai. You can reach him at mudit94@gmail.com."
},
{
"code": null,
"e": 7413,
"s": 7311,
"text": "If you also wish to showcase your blog here,please see GBlog for guest blog writing on GeeksforGeeks."
},
{
"code": null,
"e": 7428,
"s": 7415,
"text": "sagar utekar"
},
{
"code": null,
"e": 7435,
"s": 7428,
"text": "Python"
},
{
"code": null,
"e": 7454,
"s": 7435,
"text": "School Programming"
}
] |
Creating a REST API Backend using Node.js, Express and Postgres
|
09 May, 2022
JavaScript Backend can be developed using Node.js, Express, and Postgres. This backend can do Query operations on the PostgreSQL database and provide the status or data on the REST API.
Installation Requirement:
Node.js:Install the Node.js on WindowsInstall the Node.js on LinuxPostgreSQL:Install Postgres on WindowsInstall Postgres on LinuxInstall Postgres on Mac
Node.js:Install the Node.js on WindowsInstall the Node.js on Linux
Install the Node.js on Windows
Install the Node.js on Linux
PostgreSQL:Install Postgres on WindowsInstall Postgres on LinuxInstall Postgres on Mac
Install Postgres on Windows
Install Postgres on Linux
Install Postgres on Mac
Testing for Successful Installation:
Node.js:Open Command Prompt or Terminal and type:node -v The output must show some version number example:v12.14.0 Note: If it shows command not found then node.js is not installed successfully.Postgres:Windows : Search for SQL Shell, if found the Installation is successful.Linux or Mac: Type the command below: which psql Note: If output present then it is installed successfully.
Node.js:Open Command Prompt or Terminal and type:node -v The output must show some version number example:v12.14.0 Note: If it shows command not found then node.js is not installed successfully.
Open Command Prompt or Terminal and type:node -v The output must show some version number example:v12.14.0 Note: If it shows command not found then node.js is not installed successfully.
node -v
The output must show some version number example:
v12.14.0
Note: If it shows command not found then node.js is not installed successfully.
Postgres:Windows : Search for SQL Shell, if found the Installation is successful.Linux or Mac: Type the command below: which psql Note: If output present then it is installed successfully.
Windows : Search for SQL Shell, if found the Installation is successful.
Linux or Mac: Type the command below: which psql Note: If output present then it is installed successfully.
which psql
Note: If output present then it is installed successfully.
Steps to Setup Database:
Open the PostgresSQL Shell
Type the Database Credentials for local Setup or press enter in case you want to go with default values as shown below:
Create the database using:create database gfgbackend;
create database gfgbackend;
Switch to this database using:\c gfgbackend;
\c gfgbackend;
Create a test table using:create table test(id int not null);
create table test(id int not null);
Insert values into test table using:insert into test values(1);
insert into test values(2);
insert into test values(1);
insert into test values(2);
Now try to validate whether the data is inserted into table using:select * from test;
select * from test;
Steps to Create a Backend:
Go to the Directory where you want to create project
Initialize the Node Project using:npm init
npm init
Type the name of Project and Other Details or Press Enter if you want to go with Default
Install express using npmnpm install --save express
npm install --save express
Install the node-postgres Client using npmnpm install --save pg
npm install --save pg
Install the postgres module for serializing and de-serializing JSON data in to hstore format using npm. npm install --save pg-hstore
npm install --save pg-hstore
Create a file index.js as entry point to the backend.
Now Install body-parser using npmnpm install --save body-parser
npm install --save body-parser
Now add the below code to index.js file which initiates the express server, creates a pool connection and also creates a REST API ‘/testdata’. Don’t forget to add your Password while pool creation in the below code.// Entry Point of the API Server const express = require('express'); /* Creates an Express application. The express() function is a top-level function exported by the express module.*/const app = express();const Pool = require('pg').Pool; const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'gfgbackend', password: 'postgres', dialect: 'postgres', port: 5432}); /* To handle the HTTP Methods Body Parser is used, Generally used to extract the entire body portion of an incoming request stream and exposes it on req.body */const bodyParser = require('body-parser');app.use(bodyParser.json())app.use(bodyParser.urlencoded({ extended: false })); pool.connect((err, client, release) => { if (err) { return console.error( 'Error acquiring client', err.stack) } client.query('SELECT NOW()', (err, result) => { release() if (err) { return console.error( 'Error executing query', err.stack) } console.log("Connected to Database !") })}) app.get('/testdata', (req, res, next) => { console.log("TEST DATA :"); pool.query('Select * from test') .then(testData => { console.log(testData); res.send(testData.rows); })}) // Require the Routes API // Create a Server and run it on the port 3000const server = app.listen(3000, function () { let host = server.address().address let port = server.address().port // Starting the Server at the port 3000})
// Entry Point of the API Server const express = require('express'); /* Creates an Express application. The express() function is a top-level function exported by the express module.*/const app = express();const Pool = require('pg').Pool; const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'gfgbackend', password: 'postgres', dialect: 'postgres', port: 5432}); /* To handle the HTTP Methods Body Parser is used, Generally used to extract the entire body portion of an incoming request stream and exposes it on req.body */const bodyParser = require('body-parser');app.use(bodyParser.json())app.use(bodyParser.urlencoded({ extended: false })); pool.connect((err, client, release) => { if (err) { return console.error( 'Error acquiring client', err.stack) } client.query('SELECT NOW()', (err, result) => { release() if (err) { return console.error( 'Error executing query', err.stack) } console.log("Connected to Database !") })}) app.get('/testdata', (req, res, next) => { console.log("TEST DATA :"); pool.query('Select * from test') .then(testData => { console.log(testData); res.send(testData.rows); })}) // Require the Routes API // Create a Server and run it on the port 3000const server = app.listen(3000, function () { let host = server.address().address let port = server.address().port // Starting the Server at the port 3000})
Now, start the backend server using:node index.js
node index.js
Open Browser and try to router to:http://localhost:3000/testdataNow, you can see the data from test table as follows:
http://localhost:3000/testdata
Now, you can see the data from test table as follows:
kimoji
JavaScript-Misc
Node.js-Misc
JavaScript
Node.js
PostgreSQL
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 214,
"s": 28,
"text": "JavaScript Backend can be developed using Node.js, Express, and Postgres. This backend can do Query operations on the PostgreSQL database and provide the status or data on the REST API."
},
{
"code": null,
"e": 240,
"s": 214,
"text": "Installation Requirement:"
},
{
"code": null,
"e": 393,
"s": 240,
"text": "Node.js:Install the Node.js on WindowsInstall the Node.js on LinuxPostgreSQL:Install Postgres on WindowsInstall Postgres on LinuxInstall Postgres on Mac"
},
{
"code": null,
"e": 460,
"s": 393,
"text": "Node.js:Install the Node.js on WindowsInstall the Node.js on Linux"
},
{
"code": null,
"e": 491,
"s": 460,
"text": "Install the Node.js on Windows"
},
{
"code": null,
"e": 520,
"s": 491,
"text": "Install the Node.js on Linux"
},
{
"code": null,
"e": 607,
"s": 520,
"text": "PostgreSQL:Install Postgres on WindowsInstall Postgres on LinuxInstall Postgres on Mac"
},
{
"code": null,
"e": 635,
"s": 607,
"text": "Install Postgres on Windows"
},
{
"code": null,
"e": 661,
"s": 635,
"text": "Install Postgres on Linux"
},
{
"code": null,
"e": 685,
"s": 661,
"text": "Install Postgres on Mac"
},
{
"code": null,
"e": 722,
"s": 685,
"text": "Testing for Successful Installation:"
},
{
"code": null,
"e": 1105,
"s": 722,
"text": "Node.js:Open Command Prompt or Terminal and type:node -v The output must show some version number example:v12.14.0 Note: If it shows command not found then node.js is not installed successfully.Postgres:Windows : Search for SQL Shell, if found the Installation is successful.Linux or Mac: Type the command below: which psql Note: If output present then it is installed successfully."
},
{
"code": null,
"e": 1300,
"s": 1105,
"text": "Node.js:Open Command Prompt or Terminal and type:node -v The output must show some version number example:v12.14.0 Note: If it shows command not found then node.js is not installed successfully."
},
{
"code": null,
"e": 1487,
"s": 1300,
"text": "Open Command Prompt or Terminal and type:node -v The output must show some version number example:v12.14.0 Note: If it shows command not found then node.js is not installed successfully."
},
{
"code": null,
"e": 1496,
"s": 1487,
"text": "node -v "
},
{
"code": null,
"e": 1546,
"s": 1496,
"text": "The output must show some version number example:"
},
{
"code": null,
"e": 1556,
"s": 1546,
"text": "v12.14.0 "
},
{
"code": null,
"e": 1636,
"s": 1556,
"text": "Note: If it shows command not found then node.js is not installed successfully."
},
{
"code": null,
"e": 1825,
"s": 1636,
"text": "Postgres:Windows : Search for SQL Shell, if found the Installation is successful.Linux or Mac: Type the command below: which psql Note: If output present then it is installed successfully."
},
{
"code": null,
"e": 1898,
"s": 1825,
"text": "Windows : Search for SQL Shell, if found the Installation is successful."
},
{
"code": null,
"e": 2006,
"s": 1898,
"text": "Linux or Mac: Type the command below: which psql Note: If output present then it is installed successfully."
},
{
"code": null,
"e": 2019,
"s": 2006,
"text": " which psql "
},
{
"code": null,
"e": 2078,
"s": 2019,
"text": "Note: If output present then it is installed successfully."
},
{
"code": null,
"e": 2103,
"s": 2078,
"text": "Steps to Setup Database:"
},
{
"code": null,
"e": 2130,
"s": 2103,
"text": "Open the PostgresSQL Shell"
},
{
"code": null,
"e": 2250,
"s": 2130,
"text": "Type the Database Credentials for local Setup or press enter in case you want to go with default values as shown below:"
},
{
"code": null,
"e": 2309,
"s": 2250,
"text": "Create the database using:create database gfgbackend; "
},
{
"code": null,
"e": 2342,
"s": 2309,
"text": "create database gfgbackend; "
},
{
"code": null,
"e": 2387,
"s": 2342,
"text": "Switch to this database using:\\c gfgbackend;"
},
{
"code": null,
"e": 2402,
"s": 2387,
"text": "\\c gfgbackend;"
},
{
"code": null,
"e": 2465,
"s": 2402,
"text": "Create a test table using:create table test(id int not null); "
},
{
"code": null,
"e": 2502,
"s": 2465,
"text": "create table test(id int not null); "
},
{
"code": null,
"e": 2596,
"s": 2502,
"text": "Insert values into test table using:insert into test values(1); \ninsert into test values(2);"
},
{
"code": null,
"e": 2654,
"s": 2596,
"text": "insert into test values(1); \ninsert into test values(2);"
},
{
"code": null,
"e": 2740,
"s": 2654,
"text": "Now try to validate whether the data is inserted into table using:select * from test;"
},
{
"code": null,
"e": 2760,
"s": 2740,
"text": "select * from test;"
},
{
"code": null,
"e": 2787,
"s": 2760,
"text": "Steps to Create a Backend:"
},
{
"code": null,
"e": 2840,
"s": 2787,
"text": "Go to the Directory where you want to create project"
},
{
"code": null,
"e": 2883,
"s": 2840,
"text": "Initialize the Node Project using:npm init"
},
{
"code": null,
"e": 2892,
"s": 2883,
"text": "npm init"
},
{
"code": null,
"e": 2981,
"s": 2892,
"text": "Type the name of Project and Other Details or Press Enter if you want to go with Default"
},
{
"code": null,
"e": 3033,
"s": 2981,
"text": "Install express using npmnpm install --save express"
},
{
"code": null,
"e": 3060,
"s": 3033,
"text": "npm install --save express"
},
{
"code": null,
"e": 3124,
"s": 3060,
"text": "Install the node-postgres Client using npmnpm install --save pg"
},
{
"code": null,
"e": 3146,
"s": 3124,
"text": "npm install --save pg"
},
{
"code": null,
"e": 3283,
"s": 3146,
"text": "Install the postgres module for serializing and de-serializing JSON data in to hstore format using npm. npm install --save pg-hstore "
},
{
"code": null,
"e": 3317,
"s": 3283,
"text": " npm install --save pg-hstore "
},
{
"code": null,
"e": 3371,
"s": 3317,
"text": "Create a file index.js as entry point to the backend."
},
{
"code": null,
"e": 3435,
"s": 3371,
"text": "Now Install body-parser using npmnpm install --save body-parser"
},
{
"code": null,
"e": 3466,
"s": 3435,
"text": "npm install --save body-parser"
},
{
"code": null,
"e": 5216,
"s": 3466,
"text": "Now add the below code to index.js file which initiates the express server, creates a pool connection and also creates a REST API ‘/testdata’. Don’t forget to add your Password while pool creation in the below code.// Entry Point of the API Server const express = require('express'); /* Creates an Express application. The express() function is a top-level function exported by the express module.*/const app = express();const Pool = require('pg').Pool; const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'gfgbackend', password: 'postgres', dialect: 'postgres', port: 5432}); /* To handle the HTTP Methods Body Parser is used, Generally used to extract the entire body portion of an incoming request stream and exposes it on req.body */const bodyParser = require('body-parser');app.use(bodyParser.json())app.use(bodyParser.urlencoded({ extended: false })); pool.connect((err, client, release) => { if (err) { return console.error( 'Error acquiring client', err.stack) } client.query('SELECT NOW()', (err, result) => { release() if (err) { return console.error( 'Error executing query', err.stack) } console.log(\"Connected to Database !\") })}) app.get('/testdata', (req, res, next) => { console.log(\"TEST DATA :\"); pool.query('Select * from test') .then(testData => { console.log(testData); res.send(testData.rows); })}) // Require the Routes API // Create a Server and run it on the port 3000const server = app.listen(3000, function () { let host = server.address().address let port = server.address().port // Starting the Server at the port 3000})"
},
{
"code": "// Entry Point of the API Server const express = require('express'); /* Creates an Express application. The express() function is a top-level function exported by the express module.*/const app = express();const Pool = require('pg').Pool; const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'gfgbackend', password: 'postgres', dialect: 'postgres', port: 5432}); /* To handle the HTTP Methods Body Parser is used, Generally used to extract the entire body portion of an incoming request stream and exposes it on req.body */const bodyParser = require('body-parser');app.use(bodyParser.json())app.use(bodyParser.urlencoded({ extended: false })); pool.connect((err, client, release) => { if (err) { return console.error( 'Error acquiring client', err.stack) } client.query('SELECT NOW()', (err, result) => { release() if (err) { return console.error( 'Error executing query', err.stack) } console.log(\"Connected to Database !\") })}) app.get('/testdata', (req, res, next) => { console.log(\"TEST DATA :\"); pool.query('Select * from test') .then(testData => { console.log(testData); res.send(testData.rows); })}) // Require the Routes API // Create a Server and run it on the port 3000const server = app.listen(3000, function () { let host = server.address().address let port = server.address().port // Starting the Server at the port 3000})",
"e": 6751,
"s": 5216,
"text": null
},
{
"code": null,
"e": 6801,
"s": 6751,
"text": "Now, start the backend server using:node index.js"
},
{
"code": null,
"e": 6815,
"s": 6801,
"text": "node index.js"
},
{
"code": null,
"e": 6933,
"s": 6815,
"text": "Open Browser and try to router to:http://localhost:3000/testdataNow, you can see the data from test table as follows:"
},
{
"code": null,
"e": 6964,
"s": 6933,
"text": "http://localhost:3000/testdata"
},
{
"code": null,
"e": 7018,
"s": 6964,
"text": "Now, you can see the data from test table as follows:"
},
{
"code": null,
"e": 7025,
"s": 7018,
"text": "kimoji"
},
{
"code": null,
"e": 7041,
"s": 7025,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 7054,
"s": 7041,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 7065,
"s": 7054,
"text": "JavaScript"
},
{
"code": null,
"e": 7073,
"s": 7065,
"text": "Node.js"
},
{
"code": null,
"e": 7084,
"s": 7073,
"text": "PostgreSQL"
},
{
"code": null,
"e": 7101,
"s": 7084,
"text": "Web Technologies"
},
{
"code": null,
"e": 7128,
"s": 7101,
"text": "Web technologies Questions"
}
] |
How to join the elements of the byte slice in Golang?
|
26 Aug, 2019
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.In the Go slice of bytes, you are allowed to join the elements of the byte slice with the help of Join() function. Or in other words, Join function is used to concatenate the elements of the slice and return a new slice of bytes which contain all these joined elements separated by the given separator. It is defined under the bytes package so, you have to import bytes package in your program for accessing Join function.
Syntax:
func Join(slice_1 [][]byte, sep []byte) []byte
Here, sep is the separator placed between the elements of the resulting slice. Let us discuss this concept with the help of the examples:
Example 1:
// Simple Go program to illustrate// how to join a slice of bytespackage main import ( "bytes" "fmt") // Main functionfunc main() { // Creating and initializing // slices of bytes // Using shorthand declaration name := [][]byte{[]byte("Sumit"), []byte("Kumar"), []byte("Singh")} sep := []byte("-") // displaying name of the student in parts fmt.Printf("First Name: %s", name[0]) fmt.Printf("\nMiddle Name: %s", name[1]) fmt.Printf("\nLast Name: %s", name[2]) // Join the first, middle, and // last name of the student // Using Join function full_name := bytes.Join(name, sep) // Displaying the name of the student fmt.Printf("\n\nFull name of the student: %s", full_name) }
Output:
First Name: Sumit
Middle Name: Kumar
Last Name: Singh
Full name of the student: Sumit-Kumar-Singh
Example 2:
// Go program to illustrate how to// join the slices of bytespackage main import ( "bytes" "fmt") // Main functionfunc main() { // Creating and initializing slices of bytes // Using shorthand declaration slice_1 := [][]byte{[]byte("Geeks"), []byte("for"), []byte("Geeks")} slice_2 := [][]byte{[]byte("Hello"), []byte("My"), []byte("name"), []byte("is"), []byte("Bongo")} // Displaying slices fmt.Println("Slice(Before):") fmt.Printf("Slice 1: %s ", slice_1) fmt.Printf("\nSlice 2: %s", slice_2) // Joining the elements of the slice // Using Join function res1 := bytes.Join(slice_1, []byte(" , ")) res2 := bytes.Join(slice_2, []byte(" * ")) res3 := bytes.Join([][]byte{[]byte("Hey"), []byte("I"), []byte("am"), []byte("Apple")}, []byte("+")) // Displaying results fmt.Println("\n\nSlice(after):") fmt.Printf("New Slice_1: %s ", res1) fmt.Printf("\nNew Slice_2: %s", res2) fmt.Printf("\nNew Slice_3: %s", res3) }
Output:
Slice(Before):
Slice 1: [Geeks for Geeks]
Slice 2: [Hello My name is Bongo]
Slice(after):
New Slice_1: Geeks , for , Geeks
New Slice_2: Hello * My * name * is * Bongo
New Slice_3: Hey+I+am+Apple
Golang
Golang-Slices
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Constants- Go Language
Time Durations in Golang
How to iterate over an Array using for loop in Golang?
Structures in Golang
Loops in Go Language
Go Variables
Strings in Golang
time.Parse() Function in Golang With Examples
Class and Object in Golang
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 718,
"s": 28,
"text": "In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.In the Go slice of bytes, you are allowed to join the elements of the byte slice with the help of Join() function. Or in other words, Join function is used to concatenate the elements of the slice and return a new slice of bytes which contain all these joined elements separated by the given separator. It is defined under the bytes package so, you have to import bytes package in your program for accessing Join function."
},
{
"code": null,
"e": 726,
"s": 718,
"text": "Syntax:"
},
{
"code": null,
"e": 773,
"s": 726,
"text": "func Join(slice_1 [][]byte, sep []byte) []byte"
},
{
"code": null,
"e": 911,
"s": 773,
"text": "Here, sep is the separator placed between the elements of the resulting slice. Let us discuss this concept with the help of the examples:"
},
{
"code": null,
"e": 922,
"s": 911,
"text": "Example 1:"
},
{
"code": "// Simple Go program to illustrate// how to join a slice of bytespackage main import ( \"bytes\" \"fmt\") // Main functionfunc main() { // Creating and initializing // slices of bytes // Using shorthand declaration name := [][]byte{[]byte(\"Sumit\"), []byte(\"Kumar\"), []byte(\"Singh\")} sep := []byte(\"-\") // displaying name of the student in parts fmt.Printf(\"First Name: %s\", name[0]) fmt.Printf(\"\\nMiddle Name: %s\", name[1]) fmt.Printf(\"\\nLast Name: %s\", name[2]) // Join the first, middle, and // last name of the student // Using Join function full_name := bytes.Join(name, sep) // Displaying the name of the student fmt.Printf(\"\\n\\nFull name of the student: %s\", full_name) }",
"e": 1700,
"s": 922,
"text": null
},
{
"code": null,
"e": 1708,
"s": 1700,
"text": "Output:"
},
{
"code": null,
"e": 1808,
"s": 1708,
"text": "First Name: Sumit\nMiddle Name: Kumar\nLast Name: Singh\n\nFull name of the student: Sumit-Kumar-Singh\n"
},
{
"code": null,
"e": 1819,
"s": 1808,
"text": "Example 2:"
},
{
"code": "// Go program to illustrate how to// join the slices of bytespackage main import ( \"bytes\" \"fmt\") // Main functionfunc main() { // Creating and initializing slices of bytes // Using shorthand declaration slice_1 := [][]byte{[]byte(\"Geeks\"), []byte(\"for\"), []byte(\"Geeks\")} slice_2 := [][]byte{[]byte(\"Hello\"), []byte(\"My\"), []byte(\"name\"), []byte(\"is\"), []byte(\"Bongo\")} // Displaying slices fmt.Println(\"Slice(Before):\") fmt.Printf(\"Slice 1: %s \", slice_1) fmt.Printf(\"\\nSlice 2: %s\", slice_2) // Joining the elements of the slice // Using Join function res1 := bytes.Join(slice_1, []byte(\" , \")) res2 := bytes.Join(slice_2, []byte(\" * \")) res3 := bytes.Join([][]byte{[]byte(\"Hey\"), []byte(\"I\"), []byte(\"am\"), []byte(\"Apple\")}, []byte(\"+\")) // Displaying results fmt.Println(\"\\n\\nSlice(after):\") fmt.Printf(\"New Slice_1: %s \", res1) fmt.Printf(\"\\nNew Slice_2: %s\", res2) fmt.Printf(\"\\nNew Slice_3: %s\", res3) }",
"e": 2829,
"s": 1819,
"text": null
},
{
"code": null,
"e": 2837,
"s": 2829,
"text": "Output:"
},
{
"code": null,
"e": 3036,
"s": 2837,
"text": "Slice(Before):\nSlice 1: [Geeks for Geeks] \nSlice 2: [Hello My name is Bongo]\n\nSlice(after):\nNew Slice_1: Geeks , for , Geeks \nNew Slice_2: Hello * My * name * is * Bongo\nNew Slice_3: Hey+I+am+Apple\n"
},
{
"code": null,
"e": 3043,
"s": 3036,
"text": "Golang"
},
{
"code": null,
"e": 3057,
"s": 3043,
"text": "Golang-Slices"
},
{
"code": null,
"e": 3069,
"s": 3057,
"text": "Go Language"
},
{
"code": null,
"e": 3167,
"s": 3069,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3196,
"s": 3167,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 3219,
"s": 3196,
"text": "Constants- Go Language"
},
{
"code": null,
"e": 3244,
"s": 3219,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 3299,
"s": 3244,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 3320,
"s": 3299,
"text": "Structures in Golang"
},
{
"code": null,
"e": 3341,
"s": 3320,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 3354,
"s": 3341,
"text": "Go Variables"
},
{
"code": null,
"e": 3372,
"s": 3354,
"text": "Strings in Golang"
},
{
"code": null,
"e": 3418,
"s": 3372,
"text": "time.Parse() Function in Golang With Examples"
}
] |
reflect.TypeOf() Function in Golang with Examples
|
28 Apr, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package.The reflect.TypeOf() Function in Golang is used to get the reflection Type that represents the dynamic type of i. To access this function, one needs to imports the reflect package in the program.
Syntax:
func TypeOf(i interface{}) Type
Parameters: This function takes only one parameters of interface( i ).
Return Value: This function returns the reflection Type.
Below examples illustrate the use of above method in Golang:
Example 1:
// Golang program to illustrate// reflect.TypeOf() Function package main import ( "fmt" "reflect") // Main functionfunc main() { tst1 := "string" tst2 := 10 tst3 := 1.2 tst4 := true tst5 := []string{"foo", "bar", "baz"} tst6 := map[string]int{"apple": 23, "tomato": 13} // use of TypeOf method fmt.Println(reflect.TypeOf(tst1)) fmt.Println(reflect.TypeOf(tst2)) fmt.Println(reflect.TypeOf(tst3)) fmt.Println(reflect.TypeOf(tst4)) fmt.Println(reflect.TypeOf(tst5)) fmt.Println(reflect.TypeOf(tst6)) }
Output:
string
int
float64
bool
[]string
map[string]int
Example 2:
// Golang program to illustrate// reflect.TypeOf() Function package main import ( "fmt" "io" "os" "reflect") // Main functionfunc main() { // use of TypeOf method tt := reflect.TypeOf((*io.Writer)(nil)).Elem() fileType := reflect.TypeOf((*os.File)(nil)) fmt.Println(fileType.Implements(tt)) }
Output:
true
Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Data Types in Go
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Apr, 2020"
},
{
"code": null,
"e": 398,
"s": 28,
"text": "Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package.The reflect.TypeOf() Function in Golang is used to get the reflection Type that represents the dynamic type of i. To access this function, one needs to imports the reflect package in the program."
},
{
"code": null,
"e": 406,
"s": 398,
"text": "Syntax:"
},
{
"code": null,
"e": 439,
"s": 406,
"text": "func TypeOf(i interface{}) Type\n"
},
{
"code": null,
"e": 510,
"s": 439,
"text": "Parameters: This function takes only one parameters of interface( i )."
},
{
"code": null,
"e": 567,
"s": 510,
"text": "Return Value: This function returns the reflection Type."
},
{
"code": null,
"e": 628,
"s": 567,
"text": "Below examples illustrate the use of above method in Golang:"
},
{
"code": null,
"e": 639,
"s": 628,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate// reflect.TypeOf() Function package main import ( \"fmt\" \"reflect\") // Main functionfunc main() { tst1 := \"string\" tst2 := 10 tst3 := 1.2 tst4 := true tst5 := []string{\"foo\", \"bar\", \"baz\"} tst6 := map[string]int{\"apple\": 23, \"tomato\": 13} // use of TypeOf method fmt.Println(reflect.TypeOf(tst1)) fmt.Println(reflect.TypeOf(tst2)) fmt.Println(reflect.TypeOf(tst3)) fmt.Println(reflect.TypeOf(tst4)) fmt.Println(reflect.TypeOf(tst5)) fmt.Println(reflect.TypeOf(tst6)) }",
"e": 1209,
"s": 639,
"text": null
},
{
"code": null,
"e": 1217,
"s": 1209,
"text": "Output:"
},
{
"code": null,
"e": 1266,
"s": 1217,
"text": "string\nint\nfloat64\nbool\n[]string\nmap[string]int\n"
},
{
"code": null,
"e": 1277,
"s": 1266,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate// reflect.TypeOf() Function package main import ( \"fmt\" \"io\" \"os\" \"reflect\") // Main functionfunc main() { // use of TypeOf method tt := reflect.TypeOf((*io.Writer)(nil)).Elem() fileType := reflect.TypeOf((*os.File)(nil)) fmt.Println(fileType.Implements(tt)) }",
"e": 1607,
"s": 1277,
"text": null
},
{
"code": null,
"e": 1615,
"s": 1607,
"text": "Output:"
},
{
"code": null,
"e": 1621,
"s": 1615,
"text": "true\n"
},
{
"code": null,
"e": 1636,
"s": 1621,
"text": "Golang-reflect"
},
{
"code": null,
"e": 1648,
"s": 1636,
"text": "Go Language"
},
{
"code": null,
"e": 1746,
"s": 1648,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1797,
"s": 1746,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 1844,
"s": 1797,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 1857,
"s": 1844,
"text": "Arrays in Go"
},
{
"code": null,
"e": 1869,
"s": 1857,
"text": "Golang Maps"
},
{
"code": null,
"e": 1902,
"s": 1869,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 1923,
"s": 1902,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 1940,
"s": 1923,
"text": "Data Types in Go"
},
{
"code": null,
"e": 1957,
"s": 1940,
"text": "Slices in Golang"
},
{
"code": null,
"e": 2011,
"s": 1957,
"text": "Different Ways to Find the Type of Variable in Golang"
}
] |
How to loop through input elements in jQuery ?
|
01 Apr, 2021
In this article, we will learn how to loop through input elements and display their current values in jQuery. This can be done using two approaches:
Approach 1: In this approach, we will iterate over every input type which is of text type by using input[type=text] as the selector. Next, we will use the each() method to iterate over the inputs to display the values or perform any operation as needed.
Syntax:
$("#id input[type=text]").each(function() {
//... your code
});
Example:
HTML
<html><head> <!-- Include jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.js"> </script> <script> $(document).ready(function () { // Bind the click event to the function $("#buttonId").click(function () { // Select all the elements with the // type of text $("#formId input[type=text]") .each(function () { // Print the value currently in // the input box console.log(this.value); }); }) }); </script></head><body> <!-- Define the form and the inputs --> <form action="" id="formId"> <label>enter email</label> <input type="text" placeholder="email"><br> <label>enter name</label> <input type="text" placeholder="name"><br> <label>enter city</label> <input type="text" placeholder="city"><br><br> <button type="button" id="buttonId"> Loop Through </button> </form></body></html>
Output:
Approach 2: In this approach, we will try to iterate over all possible input types. We will select the form using the form id and iterate over every input type using the filter() method in jQuery. The inputs can be filtered by specifying the :input selector in jQuery that selects every type of input on the element it is used. Next, we will use the each() method to iterate over the inputs to display the values or perform any operation as needed.
Syntax:
$('#id *').filter(':input').each(function () {
//..your code
});
Example:
HTML
<html><head> <!-- Include jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.js"> </script> <script> $(document).ready(function () { // Bind the click event to the function $("#buttonId").click(function () { // Select all the elements // which is of the type of input $('#formId *').filter(':input') .each(function () { // Print the value currently in // the input element console.log($(this).val()); }); }) }) </script></head><body> <!-- Define the form and the inputs --> <form action="" id="formId"> <label>enter email</label> <input type="email" placeholder="email"><br> <label>enter password</label> <input type="password" placeholder="password"><br> <label>enter city</label> <input type="text" placeholder="city"> <br><br> <button type="button" id="buttonId"> Loop Through </button> </form></body></html>
Output:
jQuery-Methods
jQuery-Questions
jQuery-Selectors
Picked
JQuery
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": "\n01 Apr, 2021"
},
{
"code": null,
"e": 177,
"s": 28,
"text": "In this article, we will learn how to loop through input elements and display their current values in jQuery. This can be done using two approaches:"
},
{
"code": null,
"e": 431,
"s": 177,
"text": "Approach 1: In this approach, we will iterate over every input type which is of text type by using input[type=text] as the selector. Next, we will use the each() method to iterate over the inputs to display the values or perform any operation as needed."
},
{
"code": null,
"e": 439,
"s": 431,
"text": "Syntax:"
},
{
"code": null,
"e": 507,
"s": 439,
"text": "$(\"#id input[type=text]\").each(function() {\n //... your code\n});"
},
{
"code": null,
"e": 516,
"s": 507,
"text": "Example:"
},
{
"code": null,
"e": 521,
"s": 516,
"text": "HTML"
},
{
"code": "<html><head> <!-- Include jQuery --> <script src=\"https://code.jquery.com/jquery-3.6.0.js\"> </script> <script> $(document).ready(function () { // Bind the click event to the function $(\"#buttonId\").click(function () { // Select all the elements with the // type of text $(\"#formId input[type=text]\") .each(function () { // Print the value currently in // the input box console.log(this.value); }); }) }); </script></head><body> <!-- Define the form and the inputs --> <form action=\"\" id=\"formId\"> <label>enter email</label> <input type=\"text\" placeholder=\"email\"><br> <label>enter name</label> <input type=\"text\" placeholder=\"name\"><br> <label>enter city</label> <input type=\"text\" placeholder=\"city\"><br><br> <button type=\"button\" id=\"buttonId\"> Loop Through </button> </form></body></html>",
"e": 1497,
"s": 521,
"text": null
},
{
"code": null,
"e": 1505,
"s": 1497,
"text": "Output:"
},
{
"code": null,
"e": 1954,
"s": 1505,
"text": "Approach 2: In this approach, we will try to iterate over all possible input types. We will select the form using the form id and iterate over every input type using the filter() method in jQuery. The inputs can be filtered by specifying the :input selector in jQuery that selects every type of input on the element it is used. Next, we will use the each() method to iterate over the inputs to display the values or perform any operation as needed."
},
{
"code": null,
"e": 1962,
"s": 1954,
"text": "Syntax:"
},
{
"code": null,
"e": 2032,
"s": 1962,
"text": "$('#id *').filter(':input').each(function () {\n //..your code\n});"
},
{
"code": null,
"e": 2041,
"s": 2032,
"text": "Example:"
},
{
"code": null,
"e": 2046,
"s": 2041,
"text": "HTML"
},
{
"code": "<html><head> <!-- Include jQuery --> <script src=\"https://code.jquery.com/jquery-3.6.0.js\"> </script> <script> $(document).ready(function () { // Bind the click event to the function $(\"#buttonId\").click(function () { // Select all the elements // which is of the type of input $('#formId *').filter(':input') .each(function () { // Print the value currently in // the input element console.log($(this).val()); }); }) }) </script></head><body> <!-- Define the form and the inputs --> <form action=\"\" id=\"formId\"> <label>enter email</label> <input type=\"email\" placeholder=\"email\"><br> <label>enter password</label> <input type=\"password\" placeholder=\"password\"><br> <label>enter city</label> <input type=\"text\" placeholder=\"city\"> <br><br> <button type=\"button\" id=\"buttonId\"> Loop Through </button> </form></body></html>",
"e": 3057,
"s": 2046,
"text": null
},
{
"code": null,
"e": 3065,
"s": 3057,
"text": "Output:"
},
{
"code": null,
"e": 3080,
"s": 3065,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 3097,
"s": 3080,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 3114,
"s": 3097,
"text": "jQuery-Selectors"
},
{
"code": null,
"e": 3121,
"s": 3114,
"text": "Picked"
},
{
"code": null,
"e": 3128,
"s": 3121,
"text": "JQuery"
},
{
"code": null,
"e": 3145,
"s": 3128,
"text": "Web Technologies"
}
] |
GATE | GATE-CS-2016 (Set 1) | Question 29
|
16 Sep, 2021
Consider the following code segment.
x = u - t;
y = x * v;
x = y + w;
y = t - z;
y = x * y;
The minimum number of total variables required to convert the above code segment to static single assignment form is
Note : This question was asked as Numerical Answer Type.(A) 6(B) 8(C) 9(D) 10Answer: (D)Explanation: Static Single Assignment is used for intermediate code in compiler design. In Static Single Assignment form(SSA) each assignment to a variable should be specified with distinct names. We use subscripts to distinguish each definition of variables.
In the given code segment, there are two assignments of the variable x
x = u - t;
x = y + w;
and three assignments of the variable y.
y = x * v;
y = t - z;
y = x * y
So we use two variables x1, x2 for specifying distinct assignments of x and y1, y2 and y3 each assignment of y. So, total number of variables is 10 (x1, x2, y1, y2, y3, t, u, v, w, z).Static Single Assignment form(SSA) of the given code segment is:
x1 = u - t;
y1 = x1 * v;
x2 = y1 + w;
y2 = t - z;
y3 = x2 * y2;
Please refer below link for detailshttps://www.cs.cmu.edu/~fp/courses/15411-f08/lectures/09-ssa.pdf
GATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE | - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersGATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE |Watch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0023:59 / 59:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4ab8S2Qs7h8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2016 (Set 1)
GATE-GATE-CS-2016 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Sep, 2021"
},
{
"code": null,
"e": 65,
"s": 28,
"text": "Consider the following code segment."
},
{
"code": null,
"e": 121,
"s": 65,
"text": "x = u - t;\ny = x * v;\nx = y + w;\ny = t - z;\ny = x * y; "
},
{
"code": null,
"e": 238,
"s": 121,
"text": "The minimum number of total variables required to convert the above code segment to static single assignment form is"
},
{
"code": null,
"e": 587,
"s": 238,
"text": " Note : This question was asked as Numerical Answer Type.(A) 6(B) 8(C) 9(D) 10Answer: (D)Explanation: Static Single Assignment is used for intermediate code in compiler design. In Static Single Assignment form(SSA) each assignment to a variable should be specified with distinct names. We use subscripts to distinguish each definition of variables."
},
{
"code": null,
"e": 658,
"s": 587,
"text": "In the given code segment, there are two assignments of the variable x"
},
{
"code": null,
"e": 681,
"s": 658,
"text": "x = u - t;\nx = y + w;\n"
},
{
"code": null,
"e": 722,
"s": 681,
"text": "and three assignments of the variable y."
},
{
"code": null,
"e": 755,
"s": 722,
"text": "y = x * v;\ny = t - z;\ny = x * y "
},
{
"code": null,
"e": 1004,
"s": 755,
"text": "So we use two variables x1, x2 for specifying distinct assignments of x and y1, y2 and y3 each assignment of y. So, total number of variables is 10 (x1, x2, y1, y2, y3, t, u, v, w, z).Static Single Assignment form(SSA) of the given code segment is:"
},
{
"code": null,
"e": 1068,
"s": 1004,
"text": "x1 = u - t;\ny1 = x1 * v;\nx2 = y1 + w;\ny2 = t - z;\ny3 = x2 * y2;"
},
{
"code": null,
"e": 1168,
"s": 1068,
"text": "Please refer below link for detailshttps://www.cs.cmu.edu/~fp/courses/15411-f08/lectures/09-ssa.pdf"
},
{
"code": null,
"e": 2172,
"s": 1168,
"text": "GATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE | - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersGATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE |Watch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0023:59 / 59:20•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=4ab8S2Qs7h8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 2193,
"s": 2172,
"text": "GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 2219,
"s": 2193,
"text": "GATE-GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 2224,
"s": 2219,
"text": "GATE"
}
] |
PHP | Converting string to Date and DateTime
|
31 Jul, 2021
Converting the string to Date and DateTime uses several functions/methods like strtotime(), getDate(). We will see what these functions do.strtotime() – This is basically a function which returns the number of seconds passed since Jan 1, 1970, just like a linux machine timestamp. It returns the number of seconds passed according to the parameter passed to the function.Syntax
strtotime(parameter);
Parameter
Time/Date
now(optional)
Return Type Returns the number of seconds passed since Jan 1, 1970.
getDate() This function return the date/time information of the passed parameter(date/time);Syntax
getDate(parameter);
Parameter The parameter is optional as it takes the current local time as default parameter.Return Type It returns the information of the date, day, year, month etc in an array.
Code for converting a string to date
<?php$time_input = strtotime("2011/05/21"); $date_input = getDate($time_input); print_r($date_input); ?>
Array
(
[seconds] => 0
[minutes] => 0
[hours] => 0
[mday] => 21
[wday] => 6
[mon] => 5
[year] => 2011
[yday] => 140
[weekday] => Saturday
[month] => May
[0] => 1305936000
)
Code for converting a string to dateTime
<?php$input = '06/10/2011 19:00:02';$date = strtotime($input);echo date('d/M/Y h:i:s', $date);?>
10/Jun/2011 07:00:02
Note1 We can use “D” in the place of “d” for getting the day in the output
<?php$input = '05/10/2011 15:00:02';$date = strtotime($input);echo date('D/M/Y h:i:s', $date);?>
Tue/May/2011 03:00:02
Note 2 We can use “H” in the place of “h” for getting the time in 24 Hour format in the output
<?php$input = '05/10/2011 15:00:02';$date = strtotime($input);echo date('D/M/Y H:i:s', $date);?>
Tue/May/2011 15:00:02
Similarly, the “i” and “s” could also be changed to uppercase to find different outputs, it is possible but not of much use.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
date-time-program
PHP-date-time
PHP-string
Picked
Technical Scripter 2018
PHP
Technical Scripter
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
Split a comma delimited string into an array in PHP
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 406,
"s": 28,
"text": "Converting the string to Date and DateTime uses several functions/methods like strtotime(), getDate(). We will see what these functions do.strtotime() – This is basically a function which returns the number of seconds passed since Jan 1, 1970, just like a linux machine timestamp. It returns the number of seconds passed according to the parameter passed to the function.Syntax"
},
{
"code": null,
"e": 429,
"s": 406,
"text": " strtotime(parameter);"
},
{
"code": null,
"e": 439,
"s": 429,
"text": "Parameter"
},
{
"code": null,
"e": 449,
"s": 439,
"text": "Time/Date"
},
{
"code": null,
"e": 463,
"s": 449,
"text": "now(optional)"
},
{
"code": null,
"e": 531,
"s": 463,
"text": "Return Type Returns the number of seconds passed since Jan 1, 1970."
},
{
"code": null,
"e": 630,
"s": 531,
"text": "getDate() This function return the date/time information of the passed parameter(date/time);Syntax"
},
{
"code": null,
"e": 650,
"s": 630,
"text": "getDate(parameter);"
},
{
"code": null,
"e": 828,
"s": 650,
"text": "Parameter The parameter is optional as it takes the current local time as default parameter.Return Type It returns the information of the date, day, year, month etc in an array."
},
{
"code": null,
"e": 865,
"s": 828,
"text": "Code for converting a string to date"
},
{
"code": "<?php$time_input = strtotime(\"2011/05/21\"); $date_input = getDate($time_input); print_r($date_input); ?>",
"e": 985,
"s": 865,
"text": null
},
{
"code": null,
"e": 1203,
"s": 985,
"text": "Array\n(\n [seconds] => 0\n [minutes] => 0\n [hours] => 0\n [mday] => 21\n [wday] => 6\n [mon] => 5\n [year] => 2011\n [yday] => 140\n [weekday] => Saturday\n [month] => May\n [0] => 1305936000\n)\n"
},
{
"code": null,
"e": 1244,
"s": 1203,
"text": "Code for converting a string to dateTime"
},
{
"code": "<?php$input = '06/10/2011 19:00:02';$date = strtotime($input);echo date('d/M/Y h:i:s', $date);?>",
"e": 1341,
"s": 1244,
"text": null
},
{
"code": null,
"e": 1363,
"s": 1341,
"text": "10/Jun/2011 07:00:02\n"
},
{
"code": null,
"e": 1438,
"s": 1363,
"text": "Note1 We can use “D” in the place of “d” for getting the day in the output"
},
{
"code": "<?php$input = '05/10/2011 15:00:02';$date = strtotime($input);echo date('D/M/Y h:i:s', $date);?>",
"e": 1535,
"s": 1438,
"text": null
},
{
"code": null,
"e": 1558,
"s": 1535,
"text": "Tue/May/2011 03:00:02\n"
},
{
"code": null,
"e": 1653,
"s": 1558,
"text": "Note 2 We can use “H” in the place of “h” for getting the time in 24 Hour format in the output"
},
{
"code": "<?php$input = '05/10/2011 15:00:02';$date = strtotime($input);echo date('D/M/Y H:i:s', $date);?>",
"e": 1750,
"s": 1653,
"text": null
},
{
"code": null,
"e": 1773,
"s": 1750,
"text": "Tue/May/2011 15:00:02\n"
},
{
"code": null,
"e": 1898,
"s": 1773,
"text": "Similarly, the “i” and “s” could also be changed to uppercase to find different outputs, it is possible but not of much use."
},
{
"code": null,
"e": 2067,
"s": 1898,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 2085,
"s": 2067,
"text": "date-time-program"
},
{
"code": null,
"e": 2099,
"s": 2085,
"text": "PHP-date-time"
},
{
"code": null,
"e": 2110,
"s": 2099,
"text": "PHP-string"
},
{
"code": null,
"e": 2117,
"s": 2110,
"text": "Picked"
},
{
"code": null,
"e": 2141,
"s": 2117,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 2145,
"s": 2141,
"text": "PHP"
},
{
"code": null,
"e": 2164,
"s": 2145,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2168,
"s": 2164,
"text": "PHP"
},
{
"code": null,
"e": 2266,
"s": 2168,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2311,
"s": 2266,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 2361,
"s": 2311,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2385,
"s": 2361,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 2437,
"s": 2385,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 2477,
"s": 2437,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2521,
"s": 2477,
"text": "How to pop an alert message box using PHP ?"
},
{
"code": null,
"e": 2582,
"s": 2521,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2632,
"s": 2582,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 2659,
"s": 2632,
"text": "Comparing two dates in PHP"
}
] |
Data Structures and Algorithms | Set 35
|
03 Dec, 2015
Following questions have been asked in GATE CS 2014 exam.
1) The number of distinct minimum spanning trees for the weighted graph below is ____
Answer: 6Highlighted (in green) are the edges picked to make a MST. In the right side of MST, we could either pick edge ‘a’ or ‘b’. In the left side, we could either pick ‘c’ or ‘d’ or ‘e’ in MST.There are 2 options for one edge to be picked and 3 options for another edge to be picked. Therefore, total 2*3 possible MSTs.
2) Consider the following rooted tree with the vertex P labeled as rootThe order in which the nodes are visited during in-order traversal is(A) SQPTRWUV(B) SQPTURWV(C) SQPTWUVR(D) SQPTRUWV
Answer: (A)The only confusion in this question is, there are 3 children of R. So when should R appear – after U or after R? There are two possibilities: SQPTRWUV and SQPTWURV. Only 1st possibility is present as an option A, the IInd possibility is not there. Therefore option A is the right answer.
3) Let A be a square matrix of size n x n. Consider the following program. What is the expected output?
C = 100for i = 1 to n do for j = 1 to n do { Temp = A[i][j] + C A[i][j] = A[j][i] A[j][i] = Temp - C }for i = 1 to n do for j = 1 to n do Output(A[i][j]);
(A) The matrix A itself(B) Transpose of matrix A(C) Adding 100 to the upper diagonal elements and subtracting 100 from diagonal elements of A(D) None of the above
Answer: AIf we take look at the inner statements of first loops, we can notice that the statements swap A[i][j] and A[j][i] for all i and j.Since the loop runs for all elements, every element A[l][m] would be swapped twice, once for i = l and j = m and then for i = m and j = l. Swapping twice means the matrix doesn’t change.
4) The minimum number of arithmetic operations required to evaluate the polynomial P(X) = X5 + 4X3 + 6X + 5 for a given value of X using only one temporary variable.(A) 6(B) 7(C) 8(D) 9
Answer: BWe can parenthesize the polynomial to minimize the number of operations (See Horner’s Method). We get X(X2(X2 + 4) + 6) + 5 after parenthesization.
Following is sequence of operations to be used.
Note that we are allowed to use only one variable.
res = X*X
res = res + 4
res = X*res
res = X*res
res = res + 6
res = X*res
res = res + 5
5) You have an array of n elements. Suppose you implement quicksort by always choosing the central element of the array as the pivot. Then the tightest upper bound for the worst case performance is(A) O(n2)(B) O(nLogn)(C) Θ(nLogn)(D) O(n3)
Answer: (A)The middle element may always be an extreme element (minimum or maximum) in sorted order, therefore time complexity in worst case becomes O(n2)
See GATE Corner for all previous year paper/solutions/explanations, Syllabus, Important dates, Notes, etc.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
GATE-CS-2014
GATE-CS-DS-&-Algo
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operating Systems | Set 1
Practice questions on Height balanced/AVL Tree
Data Structures and Algorithms | Set 11
Computer Networks | Set 2
Computer Networks | Set 1
Database Management Systems | Set 1
Data Structures and Algorithms | Set 16
Data Structures and Algorithms | Set 10
Database Management Systems | Set 2
Computer Networks | Set 3
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Dec, 2015"
},
{
"code": null,
"e": 110,
"s": 52,
"text": "Following questions have been asked in GATE CS 2014 exam."
},
{
"code": null,
"e": 196,
"s": 110,
"text": "1) The number of distinct minimum spanning trees for the weighted graph below is ____"
},
{
"code": null,
"e": 519,
"s": 196,
"text": "Answer: 6Highlighted (in green) are the edges picked to make a MST. In the right side of MST, we could either pick edge ‘a’ or ‘b’. In the left side, we could either pick ‘c’ or ‘d’ or ‘e’ in MST.There are 2 options for one edge to be picked and 3 options for another edge to be picked. Therefore, total 2*3 possible MSTs."
},
{
"code": null,
"e": 708,
"s": 519,
"text": "2) Consider the following rooted tree with the vertex P labeled as rootThe order in which the nodes are visited during in-order traversal is(A) SQPTRWUV(B) SQPTURWV(C) SQPTWUVR(D) SQPTRUWV"
},
{
"code": null,
"e": 1007,
"s": 708,
"text": "Answer: (A)The only confusion in this question is, there are 3 children of R. So when should R appear – after U or after R? There are two possibilities: SQPTRWUV and SQPTWURV. Only 1st possibility is present as an option A, the IInd possibility is not there. Therefore option A is the right answer."
},
{
"code": null,
"e": 1111,
"s": 1007,
"text": "3) Let A be a square matrix of size n x n. Consider the following program. What is the expected output?"
},
{
"code": "C = 100for i = 1 to n do for j = 1 to n do { Temp = A[i][j] + C A[i][j] = A[j][i] A[j][i] = Temp - C }for i = 1 to n do for j = 1 to n do Output(A[i][j]);",
"e": 1306,
"s": 1111,
"text": null
},
{
"code": null,
"e": 1469,
"s": 1306,
"text": "(A) The matrix A itself(B) Transpose of matrix A(C) Adding 100 to the upper diagonal elements and subtracting 100 from diagonal elements of A(D) None of the above"
},
{
"code": null,
"e": 1796,
"s": 1469,
"text": "Answer: AIf we take look at the inner statements of first loops, we can notice that the statements swap A[i][j] and A[j][i] for all i and j.Since the loop runs for all elements, every element A[l][m] would be swapped twice, once for i = l and j = m and then for i = m and j = l. Swapping twice means the matrix doesn’t change."
},
{
"code": null,
"e": 1982,
"s": 1796,
"text": "4) The minimum number of arithmetic operations required to evaluate the polynomial P(X) = X5 + 4X3 + 6X + 5 for a given value of X using only one temporary variable.(A) 6(B) 7(C) 8(D) 9"
},
{
"code": null,
"e": 2139,
"s": 1982,
"text": "Answer: BWe can parenthesize the polynomial to minimize the number of operations (See Horner’s Method). We get X(X2(X2 + 4) + 6) + 5 after parenthesization."
},
{
"code": null,
"e": 2326,
"s": 2139,
"text": "Following is sequence of operations to be used.\nNote that we are allowed to use only one variable.\nres = X*X\nres = res + 4\nres = X*res\nres = X*res\nres = res + 6\nres = X*res\nres = res + 5"
},
{
"code": null,
"e": 2566,
"s": 2326,
"text": "5) You have an array of n elements. Suppose you implement quicksort by always choosing the central element of the array as the pivot. Then the tightest upper bound for the worst case performance is(A) O(n2)(B) O(nLogn)(C) Θ(nLogn)(D) O(n3)"
},
{
"code": null,
"e": 2721,
"s": 2566,
"text": "Answer: (A)The middle element may always be an extreme element (minimum or maximum) in sorted order, therefore time complexity in worst case becomes O(n2)"
},
{
"code": null,
"e": 2828,
"s": 2721,
"text": "See GATE Corner for all previous year paper/solutions/explanations, Syllabus, Important dates, Notes, etc."
},
{
"code": null,
"e": 2952,
"s": 2828,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 2965,
"s": 2952,
"text": "GATE-CS-2014"
},
{
"code": null,
"e": 2983,
"s": 2965,
"text": "GATE-CS-DS-&-Algo"
},
{
"code": null,
"e": 2987,
"s": 2983,
"text": "MCQ"
},
{
"code": null,
"e": 3085,
"s": 2987,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3111,
"s": 3085,
"text": "Operating Systems | Set 1"
},
{
"code": null,
"e": 3158,
"s": 3111,
"text": "Practice questions on Height balanced/AVL Tree"
},
{
"code": null,
"e": 3198,
"s": 3158,
"text": "Data Structures and Algorithms | Set 11"
},
{
"code": null,
"e": 3224,
"s": 3198,
"text": "Computer Networks | Set 2"
},
{
"code": null,
"e": 3250,
"s": 3224,
"text": "Computer Networks | Set 1"
},
{
"code": null,
"e": 3286,
"s": 3250,
"text": "Database Management Systems | Set 1"
},
{
"code": null,
"e": 3326,
"s": 3286,
"text": "Data Structures and Algorithms | Set 16"
},
{
"code": null,
"e": 3366,
"s": 3326,
"text": "Data Structures and Algorithms | Set 10"
},
{
"code": null,
"e": 3402,
"s": 3366,
"text": "Database Management Systems | Set 2"
}
] |
JavaFX | HBox Class
|
07 Sep, 2018
HBox is a part of JavaFX. HBox lays out its children in form of horizontal columns. If the HBox has a border and/or padding set, then the contents will be layed out within those insets. HBox class extends Pane class.
Constructors of the class:
HBox(): Creates an HBox object with no nodes.
HBox(double s): Creates an HBox with spacing in between nodes.
Commonly Used Methods:
Below programs illustrate the use of HBox class:
Java Program to create a HBox and add it to the stage: In this program we will create a HBox named hbox. Now create a label and add it to the hbox. We will also create some buttons and add them to the HBox using the getChildren().add() function. Now create a scene and add the hbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a HBox// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class HBOX_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("HBox"); // create a HBox HBox hbox = new HBox(); // create a label Label label = new Label("this is HBox example"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 10; i++) { hbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a HBox, add spaces between its elements and add it to the stage: In this program we will create a HBox named hbox. Set the spacing by passing a double value of space as an argument to the constructor. Now create a label and add it to the hbox. To add some buttons to the HBox use the getChildren().add() function. Finally, create a scene and add the hbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a HBox, add// spaces between its elements and add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class HBOX_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("HBox"); // create a HBox HBox hbox = new HBox(10); // create a label Label label = new Label("this is HBox example"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 5; i++) { hbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a HBox, add spaces between its elements, set an alignment and add it to the stage: In this program we will create a HBox named hbox. Set the spacing by passing a double value of space as an argument to the constructor. Set the alignment of the HBox using the setAlignment() function. Then create a label and add it to the hbox. Add some buttons to the HBox using the getChildren().add() function. Finally, create a scene and add the hbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a HBox, add spaces// between its elements, set an alignment// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.geometry.*; public class HBOX_3 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("HBox"); // create a HBox HBox hbox = new HBox(10); // setAlignment hbox.setAlignment(Pos.CENTER); // create a label Label label = new Label("this is HBox example"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 5; i++) { hbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
Java Program to create a HBox and add it to the stage: In this program we will create a HBox named hbox. Now create a label and add it to the hbox. We will also create some buttons and add them to the HBox using the getChildren().add() function. Now create a scene and add the hbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a HBox// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class HBOX_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("HBox"); // create a HBox HBox hbox = new HBox(); // create a label Label label = new Label("this is HBox example"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 10; i++) { hbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create a HBox// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class HBOX_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("HBox"); // create a HBox HBox hbox = new HBox(); // create a label Label label = new Label("this is HBox example"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 10; i++) { hbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Java Program to create a HBox, add spaces between its elements and add it to the stage: In this program we will create a HBox named hbox. Set the spacing by passing a double value of space as an argument to the constructor. Now create a label and add it to the hbox. To add some buttons to the HBox use the getChildren().add() function. Finally, create a scene and add the hbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a HBox, add// spaces between its elements and add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class HBOX_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("HBox"); // create a HBox HBox hbox = new HBox(10); // create a label Label label = new Label("this is HBox example"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 5; i++) { hbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create a HBox, add// spaces between its elements and add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class HBOX_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("HBox"); // create a HBox HBox hbox = new HBox(10); // create a label Label label = new Label("this is HBox example"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 5; i++) { hbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Java Program to create a HBox, add spaces between its elements, set an alignment and add it to the stage: In this program we will create a HBox named hbox. Set the spacing by passing a double value of space as an argument to the constructor. Set the alignment of the HBox using the setAlignment() function. Then create a label and add it to the hbox. Add some buttons to the HBox using the getChildren().add() function. Finally, create a scene and add the hbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a HBox, add spaces// between its elements, set an alignment// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.geometry.*; public class HBOX_3 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("HBox"); // create a HBox HBox hbox = new HBox(10); // setAlignment hbox.setAlignment(Pos.CENTER); // create a label Label label = new Label("this is HBox example"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 5; i++) { hbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create a HBox, add spaces// between its elements, set an alignment// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.geometry.*; public class HBOX_3 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("HBox"); // create a HBox HBox hbox = new HBox(10); // setAlignment hbox.setAlignment(Pos.CENTER); // create a label Label label = new Label("this is HBox example"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 5; i++) { hbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Note: The above programs might not run in an online IDE please use an offline compiler.
Reference: https://docs.oracle.com/javafx/2/api/javafx/scene/layout/HBox.html
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Collections in Java
Set in Java
Introduction to Java
Constructors in Java
Initializing a List in Java
Multithreading in Java
LinkedList in Java
Exceptions in Java
Queue Interface In Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Sep, 2018"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "HBox is a part of JavaFX. HBox lays out its children in form of horizontal columns. If the HBox has a border and/or padding set, then the contents will be layed out within those insets. HBox class extends Pane class."
},
{
"code": null,
"e": 272,
"s": 245,
"text": "Constructors of the class:"
},
{
"code": null,
"e": 318,
"s": 272,
"text": "HBox(): Creates an HBox object with no nodes."
},
{
"code": null,
"e": 381,
"s": 318,
"text": "HBox(double s): Creates an HBox with spacing in between nodes."
},
{
"code": null,
"e": 404,
"s": 381,
"text": "Commonly Used Methods:"
},
{
"code": null,
"e": 453,
"s": 404,
"text": "Below programs illustrate the use of HBox class:"
},
{
"code": null,
"e": 6325,
"s": 453,
"text": "Java Program to create a HBox and add it to the stage: In this program we will create a HBox named hbox. Now create a label and add it to the hbox. We will also create some buttons and add them to the HBox using the getChildren().add() function. Now create a scene and add the hbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a HBox// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class HBOX_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"HBox\"); // create a HBox HBox hbox = new HBox(); // create a label Label label = new Label(\"this is HBox example\"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 10; i++) { hbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a HBox, add spaces between its elements and add it to the stage: In this program we will create a HBox named hbox. Set the spacing by passing a double value of space as an argument to the constructor. Now create a label and add it to the hbox. To add some buttons to the HBox use the getChildren().add() function. Finally, create a scene and add the hbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a HBox, add// spaces between its elements and add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class HBOX_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"HBox\"); // create a HBox HBox hbox = new HBox(10); // create a label Label label = new Label(\"this is HBox example\"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 5; i++) { hbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a HBox, add spaces between its elements, set an alignment and add it to the stage: In this program we will create a HBox named hbox. Set the spacing by passing a double value of space as an argument to the constructor. Set the alignment of the HBox using the setAlignment() function. Then create a label and add it to the hbox. Add some buttons to the HBox using the getChildren().add() function. Finally, create a scene and add the hbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a HBox, add spaces// between its elements, set an alignment// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.geometry.*; public class HBOX_3 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"HBox\"); // create a HBox HBox hbox = new HBox(10); // setAlignment hbox.setAlignment(Pos.CENTER); // create a label Label label = new Label(\"this is HBox example\"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 5; i++) { hbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": null,
"e": 8130,
"s": 6325,
"text": "Java Program to create a HBox and add it to the stage: In this program we will create a HBox named hbox. Now create a label and add it to the hbox. We will also create some buttons and add them to the HBox using the getChildren().add() function. Now create a scene and add the hbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a HBox// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class HBOX_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"HBox\"); // create a HBox HBox hbox = new HBox(); // create a label Label label = new Label(\"this is HBox example\"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 10; i++) { hbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java Program to create a HBox// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class HBOX_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"HBox\"); // create a HBox HBox hbox = new HBox(); // create a label Label label = new Label(\"this is HBox example\"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 10; i++) { hbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 9548,
"s": 8130,
"text": null
},
{
"code": null,
"e": 9556,
"s": 9548,
"text": "Output:"
},
{
"code": null,
"e": 11492,
"s": 9556,
"text": "Java Program to create a HBox, add spaces between its elements and add it to the stage: In this program we will create a HBox named hbox. Set the spacing by passing a double value of space as an argument to the constructor. Now create a label and add it to the hbox. To add some buttons to the HBox use the getChildren().add() function. Finally, create a scene and add the hbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a HBox, add// spaces between its elements and add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class HBOX_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"HBox\"); // create a HBox HBox hbox = new HBox(10); // create a label Label label = new Label(\"this is HBox example\"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 5; i++) { hbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java Program to create a HBox, add// spaces between its elements and add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class HBOX_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"HBox\"); // create a HBox HBox hbox = new HBox(10); // create a label Label label = new Label(\"this is HBox example\"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 5; i++) { hbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 12945,
"s": 11492,
"text": null
},
{
"code": null,
"e": 12953,
"s": 12945,
"text": "Output:"
},
{
"code": null,
"e": 15086,
"s": 12953,
"text": "Java Program to create a HBox, add spaces between its elements, set an alignment and add it to the stage: In this program we will create a HBox named hbox. Set the spacing by passing a double value of space as an argument to the constructor. Set the alignment of the HBox using the setAlignment() function. Then create a label and add it to the hbox. Add some buttons to the HBox using the getChildren().add() function. Finally, create a scene and add the hbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a HBox, add spaces// between its elements, set an alignment// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.geometry.*; public class HBOX_3 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"HBox\"); // create a HBox HBox hbox = new HBox(10); // setAlignment hbox.setAlignment(Pos.CENTER); // create a label Label label = new Label(\"this is HBox example\"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 5; i++) { hbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java Program to create a HBox, add spaces// between its elements, set an alignment// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group;import javafx.geometry.*; public class HBOX_3 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"HBox\"); // create a HBox HBox hbox = new HBox(10); // setAlignment hbox.setAlignment(Pos.CENTER); // create a label Label label = new Label(\"this is HBox example\"); // add label to hbox hbox.getChildren().add(label); // add buttons to HBox for (int i = 0; i < 5; i++) { hbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(hbox, 800, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 16653,
"s": 15086,
"text": null
},
{
"code": null,
"e": 16661,
"s": 16653,
"text": "Output:"
},
{
"code": null,
"e": 16749,
"s": 16661,
"text": "Note: The above programs might not run in an online IDE please use an offline compiler."
},
{
"code": null,
"e": 16827,
"s": 16749,
"text": "Reference: https://docs.oracle.com/javafx/2/api/javafx/scene/layout/HBox.html"
},
{
"code": null,
"e": 16834,
"s": 16827,
"text": "JavaFX"
},
{
"code": null,
"e": 16839,
"s": 16834,
"text": "Java"
},
{
"code": null,
"e": 16844,
"s": 16839,
"text": "Java"
},
{
"code": null,
"e": 16942,
"s": 16844,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16957,
"s": 16942,
"text": "Stream In Java"
},
{
"code": null,
"e": 16977,
"s": 16957,
"text": "Collections in Java"
},
{
"code": null,
"e": 16989,
"s": 16977,
"text": "Set in Java"
},
{
"code": null,
"e": 17010,
"s": 16989,
"text": "Introduction to Java"
},
{
"code": null,
"e": 17031,
"s": 17010,
"text": "Constructors in Java"
},
{
"code": null,
"e": 17059,
"s": 17031,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 17082,
"s": 17059,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 17101,
"s": 17082,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 17120,
"s": 17101,
"text": "Exceptions in Java"
}
] |
Insightful Loan Default Analysis. Exploring and crunching out the driving... | by Sparsh Gupta | Towards Data Science
|
Lending Club is the largest online loan marketplace, facilitating personal loans, business loans, and financing of medical procedures. Borrowers can easily access lower interest rate loans through a fast online interface.
Like most other lending companies, lending loans to ‘risky’ applicants is the largest source of financial loss (called credit loss). The credit loss is the amount of money lost by the lender when the borrower refuses to pay or runs away with the money owed. In other words, borrowers who default cause the largest amount of loss to the lenders.
Therefore, using Data Science, Exploratory Data Analysis and public data from Lending Club, we will be exploring and crunching out the driving factors that exists behind the loan default, i.e. the variables which are strong indicators of default. Further, the company can utilise this knowledge for its portfolio and risk assessment.
The dataset contains complete loan data for all loans issued through the 2007–2011, including the current loan status (Current, Charged-off, Fully Paid) and latest payment information. Additional features include credit scores, number of finance inquiries, and collections among others. The file is a matrix of about 39 thousand observations and 111 variables. A Data Dictionary is provided in a separate file in the dataset. The dataset can be downloaded here on Kaggle.
What set of loan data are we working with?
What types of features do we have?
Do we need to treat missing values?
What is the distribution of Loan Status?
What is the distribution of Loan Default with other features?
What all plots we can draw for inferring the relation with Loan Default?
Majorly, what are the driving features that describes the Loan Default?
Loan Characteristics such as loan amount, term, purpose which shows the information about the loan that will help us in finding loan default.
Demographic Variables such as age, employment status, relationship status which shows the information about the borrower profile which is not useful for us.
Behavioural Variables such as next payment date, EMI, delinquency which shows the information which is updated after providing the loan which in our case is not useful as we need to decide whether we should approve the loan or not by default analysis.
Here is a quick overview of things we are going to see in this article:
Dataset Overview (Distribution of Loans)
Data Cleaning (Missing Values, Standardize Data, Outlier Treatment)
Metrics Derivation (Binning)
Univariate Analysis (Categorical/Continuous Features)
Bivariate Analysis (Box Plots, Scatter Plots, Violin Plots)
Multivariate Analysis (Correlation Heatmap)
# import required librariesimport numpy as npprint('numpy version:',np.__version__)import pandas as pdprint('pandas version:',pd.__version__)import matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinesns.set(style="whitegrid")plt.style.use('ggplot')plt.rcParams['figure.figsize'] = (12, 8)pd.options.mode.chained_assignment = Nonepd.options.display.float_format = '{:.2f}'.formatpd.set_option('display.max_columns', 200)pd.set_option('display.width', 400)# file path variablecase_data = "/kaggle/input/lending-club-loan-dataset-2007-2011/loan.csv"loan = pd.read_csv(case_data, low_memory=False)
Data set has 111 columns and 39717 rows
# plotting pie chart for different types of loan_statuschargedOffLoans = loan.loc[(loan["loan_status"] == "Charged Off")]currentLoans = loan.loc[(loan["loan_status"] == "Current")]fullyPaidLoans = loan.loc[(loan["loan_status"]== "Fully Paid")]data = [{"Charged Off": chargedOffLoans["funded_amnt_inv"].sum(), "Fully Paid":fullyPaidLoans["funded_amnt_inv"].sum(), "Current":currentLoans["funded_amnt_inv"].sum()}]investment_sum = pd.DataFrame(data) chargedOffTotalSum = float(investment_sum["Charged Off"])fullyPaidTotalSum = float(investment_sum["Fully Paid"])currentTotalSum = float(investment_sum["Current"])loan_status = [chargedOffTotalSum,fullyPaidTotalSum,currentTotalSum]loan_status_labels = 'Charged Off','Fully Paid','Current'plt.pie(loan_status,labels=loan_status_labels,autopct='%1.1f%%')plt.title('Loan Status Aggregate Information')plt.axis('equal')plt.legend(loan_status,title="Loan Amount",loc="center left",bbox_to_anchor=(1, 0, 0.5, 1))plt.show()
# plotting pie chart for different types of purposeloans_purpose = loan.groupby(['purpose'])['funded_amnt_inv'].sum().reset_index()plt.figure(figsize=(14, 10))plt.pie(loans_purpose["funded_amnt_inv"],labels=loans_purpose["purpose"],autopct='%1.1f%%')plt.title('Loan purpose Aggregate Information')plt.axis('equal')plt.legend(loan_status,title="Loan purpose",loc="center left",bbox_to_anchor=(1, 0, 0.5, 1))plt.show()
# in dataset, we can see around half of the columns are null# completely, hence remove all columns having no valuesloan = loan.dropna(axis=1, how="all")print("Looking into remaining columns info:")print(loan.info(max_cols=200))
We are left with following columns:
Looking into remaining columns info:<class 'pandas.core.frame.DataFrame'>RangeIndex: 39717 entries, 0 to 39716Data columns (total 57 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 39717 non-null int64 1 member_id 39717 non-null int64 2 loan_amnt 39717 non-null int64 3 funded_amnt 39717 non-null int64 4 funded_amnt_inv 39717 non-null float64 5 term 39717 non-null object 6 int_rate 39717 non-null object 7 installment 39717 non-null float64 8 grade 39717 non-null object 9 sub_grade 39717 non-null object 10 emp_title 37258 non-null object 11 emp_length 38642 non-null object 12 home_ownership 39717 non-null object 13 annual_inc 39717 non-null float64 14 verification_status 39717 non-null object 15 issue_d 39717 non-null object 16 loan_status 39717 non-null object 17 pymnt_plan 39717 non-null object 18 url 39717 non-null object 19 desc 26777 non-null object 20 purpose 39717 non-null object 21 title 39706 non-null object 22 zip_code 39717 non-null object 23 addr_state 39717 non-null object 24 dti 39717 non-null float64 25 delinq_2yrs 39717 non-null int64 26 earliest_cr_line 39717 non-null object 27 inq_last_6mths 39717 non-null int64 28 mths_since_last_delinq 14035 non-null float64 29 mths_since_last_record 2786 non-null float64 30 open_acc 39717 non-null int64 31 pub_rec 39717 non-null int64 32 revol_bal 39717 non-null int64 33 revol_util 39667 non-null object 34 total_acc 39717 non-null int64 35 initial_list_status 39717 non-null object 36 out_prncp 39717 non-null float64 37 out_prncp_inv 39717 non-null float64 38 total_pymnt 39717 non-null float64 39 total_pymnt_inv 39717 non-null float64 40 total_rec_prncp 39717 non-null float64 41 total_rec_int 39717 non-null float64 42 total_rec_late_fee 39717 non-null float64 43 recoveries 39717 non-null float64 44 collection_recovery_fee 39717 non-null float64 45 last_pymnt_d 39646 non-null object 46 last_pymnt_amnt 39717 non-null float64 47 next_pymnt_d 1140 non-null object 48 last_credit_pull_d 39715 non-null object 49 collections_12_mths_ex_med 39661 non-null float64 50 policy_code 39717 non-null int64 51 application_type 39717 non-null object 52 acc_now_delinq 39717 non-null int64 53 chargeoff_within_12_mths 39661 non-null float64 54 delinq_amnt 39717 non-null int64 55 pub_rec_bankruptcies 39020 non-null float64 56 tax_liens 39678 non-null float64dtypes: float64(20), int64(13), object(24)memory usage: 17.3+ MB
Now, we will remove all the Demographic and Customer Behavioural features which is of no use for default analysis for credit approval.
# remove non-required columns# id - not required# member_id - not required# acc_now_delinq - empty# funded_amnt - not useful, funded_amnt_inv is useful which is funded to person# emp_title - brand names not useful# pymnt_plan - fixed value as n for all# url - not useful# desc - can be applied some NLP but not for EDA# title - too many distinct values not useful# zip_code - complete zip is not available# delinq_2yrs - post approval feature# mths_since_last_delinq - only half values are there, not much information# mths_since_last_record - only 10% values are there# revol_bal - post/behavioural feature# initial_list_status - fixed value as f for all# out_prncp - post approval feature# out_prncp_inv - not useful as its for investors# total_pymnt - post approval feature# total_pymnt_inv - not useful as it is for investors# total_rec_prncp - post approval feature# total_rec_int - post approval feature# total_rec_late_fee - post approval feature# recoveries - post approval feature# collection_recovery_fee - post approval feature# last_pymnt_d - post approval feature# last_credit_pull_d - irrelevant for approval# last_pymnt_amnt - post feature# next_pymnt_d - post feature# collections_12_mths_ex_med - only 1 value # policy_code - only 1 value# acc_now_delinq - single valued# chargeoff_within_12_mths - post feature# delinq_amnt - single valued# tax_liens - single valued# application_type - single# pub_rec_bankruptcies - single valued for more than 99%# addr_state - may not depend on location as its in financial domaincolsToDrop = ["id", "member_id", "funded_amnt", "emp_title", "pymnt_plan", "url", "desc", "title", "zip_code", "delinq_2yrs", "mths_since_last_delinq", "mths_since_last_record", "revol_bal", "initial_list_status", "out_prncp", "out_prncp_inv", "total_pymnt", "total_pymnt_inv", "total_rec_prncp", "total_rec_int", "total_rec_late_fee", "recoveries", "collection_recovery_fee", "last_pymnt_d", "last_pymnt_amnt", "next_pymnt_d", "last_credit_pull_d", "collections_12_mths_ex_med", "policy_code", "acc_now_delinq", "chargeoff_within_12_mths", "delinq_amnt", "tax_liens", "application_type", "pub_rec_bankruptcies", "addr_state"]loan.drop(colsToDrop, axis=1, inplace=True)print("Features we are left with",list(loan.columns))
We are left with [‘loan_amnt’, ‘funded_amnt_inv’, ‘term’, ‘int_rate’, ‘installment’, ‘grade’, ‘sub_grade’, ‘emp_length’, ‘home_ownership’, ‘annual_inc’, ‘verification_status’, ‘issue_d’, ‘loan_status’, ‘purpose’, ‘dti’, ‘earliest_cr_line’, ‘inq_last_6mths’, ‘open_acc’, ‘pub_rec’, ‘revol_util’, ‘total_acc’]
Now, dealing with missing values by removing/imputing:
# in 12 unique values we have 10+ years the most for emp_length, # but it is highly dependent variable so we will not impute# but remove the rows with null values which is around 2.5%loan.dropna(axis=0, subset=["emp_length"], inplace=True)# remove NA rows for revol_util as its dependent and is around 0.1%loan.dropna(axis=0, subset=["revol_util"], inplace=True)
Now, we standardize some feature columns to make data compatible for analysis:
# update int_rate, revol_util without % sign and as numeric typeloan["int_rate"] = pd.to_numeric(loan["int_rate"].apply(lambda x:x.split('%')[0]))loan["revol_util"] = pd.to_numeric(loan["revol_util"].apply(lambda x:x.split('%')[0]))# remove text data from term feature and store as numericalloan["term"] = pd.to_numeric(loan["term"].apply(lambda x:x.split()[0]))
Removing records with loan status as “Current”, as the loan is currently running and we can’t infer any information regarding default from such loans.
# remove the rows with loan_status as "Current"loan = loan[loan["loan_status"].apply(lambda x:False if x == "Current" else True)]# update loan_status as Fully Paid to 0 and Charged Off to 1loan["loan_status"] = loan["loan_status"].apply(lambda x: 0 if x == "Fully Paid" else 1)# update emp_length feature with continuous values as int# where (< 1 year) is assumed as 0 and 10+ years is assumed as 10 and rest are stored as their magnitudeloan["emp_length"] = pd.to_numeric(loan["emp_length"].apply(lambda x:0 if "<" in x else (x.split('+')[0] if "+" in x else x.split()[0])))# look through the purpose value countsloan_purpose_values = loan["purpose"].value_counts()*100/loan.shape[0]# remove rows with less than 1% of value counts in paricular purpose loan_purpose_delete = loan_purpose_values[loan_purpose_values<1].index.valuesloan = loan[[False if p in loan_purpose_delete else True for p in loan["purpose"]]]
Looking upon the quantile values of each features, we will treat outliers for the some features.
# for annual_inc, the highest value is 6000000 where 75% quantile value is 83000, and is 100 times the mean# we need to remomve outliers from annual_inc i.e. 99 to 100%annual_inc_q = loan["annual_inc"].quantile(0.99)loan = loan[loan["annual_inc"] < annual_inc_q]# for open_acc, the highest value is 44 where 75% quantile value is 12, and is 5 times the mean# we need to remomve outliers from open_acc i.e. 99.9 to 100%open_acc_q = loan["open_acc"].quantile(0.999)loan = loan[loan["open_acc"] < open_acc_q]# for total_acc, the highest value is 90 where 75% quantile value is 29, and is 4 times the mean# we need to remomve outliers from total_acc i.e. 98 to 100%total_acc_q = loan["total_acc"].quantile(0.98)loan = loan[loan["total_acc"] < total_acc_q]# for pub_rec, the highest value is 4 where 75% quantile value is 0, and is 4 times the mean# we need to remomve outliers from pub_rec i.e. 99.5 to 100%pub_rec_q = loan["pub_rec"].quantile(0.995)loan = loan[loan["pub_rec"] <= pub_rec_q]
Now this is how our data looks after cleaning and standardizing the features:
Issue date is not in the standard format also we can split the date into two columns with month and the year which will make it easy for analysis
Year in the datetime requires year between 00 to 99 and in some cases year is single digit number i.e. 9 writing a function which will convert such dates to avoid exception in date conversion.
def standerdisedate(date): year = date.split("-")[0] if(len(year) == 1): date = "0"+date return datefrom datetime import datetimeloan['issue_d'] = loan['issue_d'].apply(lambda x:standerdisedate(x))loan['issue_d'] = loan['issue_d'].apply(lambda x: datetime.strptime(x, '%b-%y'))# extracting month and year from issue_dateloan['month'] = loan['issue_d'].apply(lambda x: x.month)loan['year'] = loan['issue_d'].apply(lambda x: x.year)# get year from issue_d and replace the sameloan["earliest_cr_line"] = pd.to_numeric(loan["earliest_cr_line"].apply(lambda x:x.split('-')[1]))
Binning Continuous features:
# create bins for loan_amnt rangebins = [0, 5000, 10000, 15000, 20000, 25000, 36000]bucket_l = ['0-5000', '5000-10000', '10000-15000', '15000-20000', '20000-25000','25000+']loan['loan_amnt_range'] = pd.cut(loan['loan_amnt'], bins, labels=bucket_l)# create bins for int_rate rangebins = [0, 7.5, 10, 12.5, 15, 100]bucket_l = ['0-7.5', '7.5-10', '10-12.5', '12.5-15', '15+']loan['int_rate_range'] = pd.cut(loan['int_rate'], bins, labels=bucket_l)# create bins for annual_inc rangebins = [0, 25000, 50000, 75000, 100000, 1000000]bucket_l = ['0-25000', '25000-50000', '50000-75000', '75000-100000', '100000+']loan['annual_inc_range'] = pd.cut(loan['annual_inc'], bins, labels=bucket_l)# create bins for installment rangedef installment(n): if n <= 200: return 'low' elif n > 200 and n <=500: return 'medium' elif n > 500 and n <=800: return 'high' else: return 'very high'loan['installment'] = loan['installment'].apply(lambda x: installment(x))# create bins for dti rangebins = [-1, 5.00, 10.00, 15.00, 20.00, 25.00, 50.00]bucket_l = ['0-5%', '5-10%', '10-15%', '15-20%', '20-25%', '25%+']loan['dti_range'] = pd.cut(loan['dti'], bins, labels=bucket_l)
The following bins are created:
# check for amount of defaults in the data using countplotplt.figure(figsize=(14,5))sns.countplot(y="loan_status", data=loan)plt.show()
From above plot we can see that around 16% i.e. 5062 people are defaulters in total 35152 records.
# function for plotting the count plot features wrt default ratiodef plotUnivariateRatioBar(feature, data=loan, figsize=(10,5), rsorted=True): plt.figure(figsize=figsize) if rsorted: feature_dimension = sorted(data[feature].unique()) else: feature_dimension = data[feature].unique() feature_values = [] for fd in feature_dimension: feature_filter = data[data[feature]==fd] feature_count = len(feature_filter[feature_filter["loan_status"]==1]) feature_values.append(feature_count*100/feature_filter["loan_status"].count()) plt.bar(feature_dimension, feature_values, color='orange', edgecolor='white') plt.title("Loan Defaults wrt "+str(feature)+" feature - countplot") plt.xlabel(feature, fontsize=16) plt.ylabel("defaulter %", fontsize=16) plt.show()# function to plot univariate with default status scale 0 - 1def plotUnivariateBar(x, figsize=(10,5)): plt.figure(figsize=figsize) sns.barplot(x=x, y='loan_status', data=loan) plt.title("Loan Defaults wrt "+str(x)+" feature - countplot") plt.xlabel(x, fontsize=16) plt.ylabel("defaulter ratio", fontsize=16) plt.show()
a. Categorical Features
# check for defaulters wrt term in the data using countplotplotUnivariateBar("term", figsize=(8,5))
From above plot for ‘term’ we can infer that the defaulters rate is increasing wrt term, hence the chances of loan getting deaulted is less for 36m than 60m.
is term benificial -> Yes
# check for defaulters wrt grade in the data using countplotplotUnivariateRatioBar("grade")
From above plot for ‘grade’ we can infer that the defaulters rate is increasing wrt grade, hence the chances of loan getting deaulted increases with the grade from A moving towards G.
is grade benificial -> Yes
# check for defaulters wrt sub_grade in the data using countplotplotUnivariateBar("sub_grade", figsize=(16,5))
From above plot for ‘sub_grade’ we can infer that the defaulters rate is increasing wrt sub_grade, hence the chances of loan getting deaulted increases with the sub_grade from A1 moving towards G5.
is sub_grade benificial -> Yes
# check for defaulters wrt home_ownership in the data plotUnivariateRatioBar("home_ownership")
From above plot for ‘home_ownership’ we can infer that the defaulters rate is constant here (it is quite more for OTHERS but we dont know what is in there, so we’ll not consider it for analysis), hence defaulter does not depends on home_ownership
is home_ownership benificial -> No
# check for defaulters wrt verification_status in the dataplotUnivariateRatioBar("verification_status")
From above plot for ‘verification_status’ we can infer that the defaulters rate is increasing and is less for Not Verified users than Verified ones, but not useful for analysis.
is verification_status benificial -> No
# check for defaulters wrt purpose in the data using countplotplotUnivariateBar("purpose", figsize=(16,6))
From above plot for ‘purpose’ we can infer that the defaulters rate is nearly constant for all purpose type except ‘small business’, hence rate will depend on purpose of the loan
is purpose benificial -> Yes
# check for defaulters wrt open_acc in the data using countplotplotUnivariateRatioBar("open_acc", figsize=(16,6))
From above plot for ‘open_acc’ we can infer that the defaulters rate is nearly constant for feature open_acc, hence rate will not depend on open_acc feature
is open_acc benificial -> No
# check for defaulters wrt pub_rec in the data using countplotplotUnivariateRatioBar("pub_rec")
From above plot for ‘pub_rec’ we can infer that the defaulters rate is nearly increasing as it is less for 0 and more for pub_rec with value 1, but as other values are very less as compared to 0 we’ll not consider this
is pub_rec benificial -> No
b. Continuous Features
# check for defaulters wrt emp_length in the data using countplotplotUnivariateBar("emp_length", figsize=(14,6))
From above plot for ‘emp_length’ we can infer that the defaulters rate is constant here, hence defaulter does not depends on emp_length
is emp_length benificial -> No
# check for defaulters wrt month in the data using countplotplotUnivariateBar("month", figsize=(14,6))
From above plot for ‘month’ we can infer that the defaulters rate is nearly constant here, not useful
is month benificial -> No
# check for defaulters wrt year in the data using countplotplotUnivariateBar("year")
From above plot for ‘year’ we can infer that the defaulters rate is nearly constant here, not useful
is year benificial -> No
# check for defaulters wrt earliest_cr_line in the dataplotUnivariateBar("earliest_cr_line", figsize=(16,10))
From above plot for ‘earliest_cr_line’ we can infer that the defaulters rate is nearly constant for all purpose type except year around 65, hence rate does not depends on earliest_cr_line of the person
is earliest_cr_line benificial -> No
# check for defaulters wrt inq_last_6mths in the dataplotUnivariateBar("inq_last_6mths")
From above plot for ‘inq_last_6mths’ we can infer that the defaulters rate is not consistently increasing with inq_last_6mths type, hence not useful
is inq_last_6mths benificial -> No
# check for defaulters wrt revol_util in the data using countplotplotUnivariateRatioBar("revol_util", figsize=(16,6))
From above plot for ‘revol_util’ we can infer that the defaulters rate is fluctuating where some have complete 100% ratio for defaulter and is increasing as the magnitude increases, hence rate will depend on revol_util feature
is revol_util benificial -> Yes
# check for defaulters wrt total_acc in the data using countplotplotUnivariateRatioBar("total_acc", figsize=(14,6))
From above plot for ‘total_acc’ we can infer that the defaulters rate is nearly constant for all total_acc values, hence rate will not depend on total_acc feature
is total_acc benificial -> No
# check for defaulters wrt loan_amnt_range in the data using countplotplotUnivariateBar("loan_amnt_range")
From above plot for ‘loan_amnt_range’ we can infer that the defaulters rate is increasing loan_amnt_range values, hence rate will depend on loan_amnt_range feature
is loan_amnt_range benificial -> Yes
# check for defaulters wrt int_rate_range in the dataplotUnivariateBar("int_rate_range")
From above plot for ‘int_rate_range’ we can infer that the defaulters rate is decreasing with int_rate_range values, hence rate will depend on int_rate_range feature
is int_rate_range benificial -> Yes
# check for defaulters wrt annual_inc_range in the dataplotUnivariateBar("annual_inc_range")
From above plot for ‘annual_inc_range’ we can infer that the defaulters rate is decreasing as with annual_inc_range values, hence rate will depend on annual_inc_range feature
is annual_inc_range benificial -> Yes
# check for defaulters wrt dti_range in the data using countplotplotUnivariateBar("dti_range", figsize=(16,5))
From above plot for ‘dti_range’ we can infer that the defaulters rate is increasing as with dti_range values, hence rate will depend on dti_range feature
is dti_range benificial -> Yes
# check for defaulters wrt installment range in the dataplotUnivariateBar("installment", figsize=(8,5))
From above plot for ‘installment’ we can infer that the defaulters rate is increasing as with installment values, hence rate will depend on dti_range feature
is installment benificial -> Yes
Therefore, following are the important feature we deduced from above Univariate analysis:
term, grade, purpose, pub_rec, revol_util, funded_amnt_inv, int_rate, annual_inc, dti, installment
# function to plot scatter plot for two featuresdef plotScatter(x, y): plt.figure(figsize=(16,6)) sns.scatterplot(x=x, y=y, hue="loan_status", data=loan) plt.title("Scatter plot between "+x+" and "+y) plt.xlabel(x, fontsize=16) plt.ylabel(y, fontsize=16) plt.show() def plotBivariateBar(x, hue, figsize=(16,6)): plt.figure(figsize=figsize) sns.barplot(x=x, y='loan_status', hue=hue, data=loan) plt.title("Loan Default ratio wrt "+x+" feature for hue "+hue+" in the data using countplot") plt.xlabel(x, fontsize=16) plt.ylabel("defaulter ratio", fontsize=16) plt.show()
Plotting for two different features with respect to loan default ratio on y-axis with Bar Plots and Scatter Plots.
# check for defaulters wrt annual_inc and purpose in the data using countplotplotBivariateBar("annual_inc_range", "purpose")
From above plot, we can infer it doesn’t shows any correlation
related - N
# check for defaulters wrt term and purpose in the data plotBivariateBar("term", "purpose")
As we can see straight lines on the plot, default ratio increases for every purpose wrt term
related - Y
# check for defaulters wrt grade and purpose in the data plotBivariateBar("grade", "purpose")
As we can see straight lines on the plot, default ratio increases for every purpose wrt grade
related - Y
# check for defaulters wrt loan_amnt_range and purpose in the dataplotBivariateBar("loan_amnt_range", "purpose")
As we can see straight lines on the plot, default ratio increases for every purpose wrt loan_amnt_range
related - Y
# check for defaulters wrt loan_amnt_range and term in the dataplotBivariateBar("loan_amnt_range", "term")
As we can see straight lines on the plot, default ratio increases for every term wrt loan_amnt_range
related - Y
# check for defaulters wrt annual_inc_range and purpose in the dataplotBivariateBar("annual_inc_range", "purpose")
As we can see straight lines on the plot, default ratio increases for every purpose wrt annual_inc_range
related - Y
# check for defaulters wrt annual_inc_range and purpose in the dataplotBivariateBar("installment", "purpose")
As we can see straight lines on the plot, default ratio increases for every purpose wrt installment except for small_business
related - Y
# check for defaulters wrt loan_amnt_range in the dataplotScatter("int_rate", "annual_inc")
As we can see straight lines on the plot, there is no relation between above mentioned features
related - N
# plot scatter for funded_amnt_inv with dtiplotScatter("funded_amnt_inv", "dti")
As we can see straight lines on the plot, there is no relation between above mentioned features
related - N
# plot scatter for funded_amnt_inv with annual_incplotScatter("annual_inc", "funded_amnt_inv")
As we can see slope pattern on the plot, there is positive relation between above mentioned features
related - Y
# plot scatter for loan_amnt with int_rateplotScatter("loan_amnt", "int_rate")
As we can see straight line patterns on the plot, there is no relation between above mentioned features
related - N
# plot scatter for int_rate with annual_incplotScatter("int_rate", "annual_inc")
As we can see negative correlation pattern with reduced density on the plot, there is some relation between above mentioned features
related - Y
# plot scatter for earliest_cr_line with int_rateplotScatter("earliest_cr_line", "int_rate")
As we can see positive correlation pattern with increasing density on the plot, there is co-relation between above mentioned features
related - Y
# plot scatter for annual_inc with emp_lengthplotScatter("annual_inc", "emp_length")
As we can see straight line patterns on the plot, there is no relation between above mentioned features
related - N
# plot scatter for earliest_cr_line with dtiplotScatter("earliest_cr_line", "dti")
Plotting for two different features with respect to loan default ratio on y-axis with Box Plots and Violin Plots.
# function to plot boxplot for comparing two featuresdef plotBox(x, y, hue="loan_status"): plt.figure(figsize=(16,6)) sns.boxplot(x=x, y=y, data=loan, hue=hue, order=sorted(loan[x].unique())) plt.title("Box plot between "+x+" and "+y+" for each "+hue) plt.xlabel(x, fontsize=16) plt.ylabel(y, fontsize=16) plt.show() plt.figure(figsize=(16,8)) sns.violinplot(x=x, y=y, data=loan, hue=hue, order=sorted(loan[x].unique())) plt.title("Violin plot between "+x+" and "+y+" for each "+hue) plt.xlabel(x, fontsize=16) plt.ylabel(y, fontsize=16) plt.show()# plot box for term vs int_rate for each loan_statusplotBox("term", "int_rate")
int_rate increases with term on loan and the chances of default also increases
# plot box for loan_status vs int_rate for each purposeplotBox("loan_status", "int_rate", hue="purpose")
int_rate is quite high where the loan is defaulted for every purpose value
# plot box for purpose vs revo_util for each statusplotBox("purpose", "revol_util")
revol_util is more for every purpose value where the loan is defaulted and quite high for credit_card
# plot box for grade vs int_rate for each loan_statusplotBox("grade", "int_rate", "loan_status")
int_rate is increasing with every grade and also the defaulters for every grade are having their median near the non-defaulter 75% quantile of int_rate
# plot box for issue_d vs int_rate for each loan_statusplotBox("month", "int_rate", "loan_status")
int_rate for defaulter is increasing with every month where the defaulters for every month are having their median near the non-defaulter’s 75% quantile of int_rate, but is almost constant for each month, not useful
Therefore, following are the important feature we deduced from above Bivariate analysis:
term, grade, purpose, pub_rec, revol_util, funded_amnt_inv, int_rate, annual_inc, installment
# plot heat map to see correlation between featurescontinuous_f = ["funded_amnt_inv", "annual_inc", "term", "int_rate", "loan_status", "revol_util", "pub_rec", "earliest_cr_line"]loan_corr = loan[continuous_f].corr()sns.heatmap(loan_corr,vmin=-1.0,vmax=1.0,annot=True, cmap="YlGnBu")plt.title("Correlation Heatmap")plt.show()
Hence, important related feature from above Multivariate analysis are:
term, grade, purpose, revol_util, int_rate, installment, annual_inc, funded_amnt_inv
After analysing all the related features available in the dataset, we have come to an end, deducing the main driving features for the Lending Club Loan Default analysis:
The best driving features for the Loan default analysis are: term, grade, purpose, revol_util, int_rate, installment, annual_inc, funded_amnt_inv
|
[
{
"code": null,
"e": 394,
"s": 172,
"text": "Lending Club is the largest online loan marketplace, facilitating personal loans, business loans, and financing of medical procedures. Borrowers can easily access lower interest rate loans through a fast online interface."
},
{
"code": null,
"e": 739,
"s": 394,
"text": "Like most other lending companies, lending loans to ‘risky’ applicants is the largest source of financial loss (called credit loss). The credit loss is the amount of money lost by the lender when the borrower refuses to pay or runs away with the money owed. In other words, borrowers who default cause the largest amount of loss to the lenders."
},
{
"code": null,
"e": 1073,
"s": 739,
"text": "Therefore, using Data Science, Exploratory Data Analysis and public data from Lending Club, we will be exploring and crunching out the driving factors that exists behind the loan default, i.e. the variables which are strong indicators of default. Further, the company can utilise this knowledge for its portfolio and risk assessment."
},
{
"code": null,
"e": 1545,
"s": 1073,
"text": "The dataset contains complete loan data for all loans issued through the 2007–2011, including the current loan status (Current, Charged-off, Fully Paid) and latest payment information. Additional features include credit scores, number of finance inquiries, and collections among others. The file is a matrix of about 39 thousand observations and 111 variables. A Data Dictionary is provided in a separate file in the dataset. The dataset can be downloaded here on Kaggle."
},
{
"code": null,
"e": 1588,
"s": 1545,
"text": "What set of loan data are we working with?"
},
{
"code": null,
"e": 1623,
"s": 1588,
"text": "What types of features do we have?"
},
{
"code": null,
"e": 1659,
"s": 1623,
"text": "Do we need to treat missing values?"
},
{
"code": null,
"e": 1700,
"s": 1659,
"text": "What is the distribution of Loan Status?"
},
{
"code": null,
"e": 1762,
"s": 1700,
"text": "What is the distribution of Loan Default with other features?"
},
{
"code": null,
"e": 1835,
"s": 1762,
"text": "What all plots we can draw for inferring the relation with Loan Default?"
},
{
"code": null,
"e": 1907,
"s": 1835,
"text": "Majorly, what are the driving features that describes the Loan Default?"
},
{
"code": null,
"e": 2049,
"s": 1907,
"text": "Loan Characteristics such as loan amount, term, purpose which shows the information about the loan that will help us in finding loan default."
},
{
"code": null,
"e": 2206,
"s": 2049,
"text": "Demographic Variables such as age, employment status, relationship status which shows the information about the borrower profile which is not useful for us."
},
{
"code": null,
"e": 2458,
"s": 2206,
"text": "Behavioural Variables such as next payment date, EMI, delinquency which shows the information which is updated after providing the loan which in our case is not useful as we need to decide whether we should approve the loan or not by default analysis."
},
{
"code": null,
"e": 2530,
"s": 2458,
"text": "Here is a quick overview of things we are going to see in this article:"
},
{
"code": null,
"e": 2571,
"s": 2530,
"text": "Dataset Overview (Distribution of Loans)"
},
{
"code": null,
"e": 2639,
"s": 2571,
"text": "Data Cleaning (Missing Values, Standardize Data, Outlier Treatment)"
},
{
"code": null,
"e": 2668,
"s": 2639,
"text": "Metrics Derivation (Binning)"
},
{
"code": null,
"e": 2722,
"s": 2668,
"text": "Univariate Analysis (Categorical/Continuous Features)"
},
{
"code": null,
"e": 2782,
"s": 2722,
"text": "Bivariate Analysis (Box Plots, Scatter Plots, Violin Plots)"
},
{
"code": null,
"e": 2826,
"s": 2782,
"text": "Multivariate Analysis (Correlation Heatmap)"
},
{
"code": null,
"e": 3432,
"s": 2826,
"text": "# import required librariesimport numpy as npprint('numpy version:',np.__version__)import pandas as pdprint('pandas version:',pd.__version__)import matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinesns.set(style=\"whitegrid\")plt.style.use('ggplot')plt.rcParams['figure.figsize'] = (12, 8)pd.options.mode.chained_assignment = Nonepd.options.display.float_format = '{:.2f}'.formatpd.set_option('display.max_columns', 200)pd.set_option('display.width', 400)# file path variablecase_data = \"/kaggle/input/lending-club-loan-dataset-2007-2011/loan.csv\"loan = pd.read_csv(case_data, low_memory=False)"
},
{
"code": null,
"e": 3472,
"s": 3432,
"text": "Data set has 111 columns and 39717 rows"
},
{
"code": null,
"e": 4437,
"s": 3472,
"text": "# plotting pie chart for different types of loan_statuschargedOffLoans = loan.loc[(loan[\"loan_status\"] == \"Charged Off\")]currentLoans = loan.loc[(loan[\"loan_status\"] == \"Current\")]fullyPaidLoans = loan.loc[(loan[\"loan_status\"]== \"Fully Paid\")]data = [{\"Charged Off\": chargedOffLoans[\"funded_amnt_inv\"].sum(), \"Fully Paid\":fullyPaidLoans[\"funded_amnt_inv\"].sum(), \"Current\":currentLoans[\"funded_amnt_inv\"].sum()}]investment_sum = pd.DataFrame(data) chargedOffTotalSum = float(investment_sum[\"Charged Off\"])fullyPaidTotalSum = float(investment_sum[\"Fully Paid\"])currentTotalSum = float(investment_sum[\"Current\"])loan_status = [chargedOffTotalSum,fullyPaidTotalSum,currentTotalSum]loan_status_labels = 'Charged Off','Fully Paid','Current'plt.pie(loan_status,labels=loan_status_labels,autopct='%1.1f%%')plt.title('Loan Status Aggregate Information')plt.axis('equal')plt.legend(loan_status,title=\"Loan Amount\",loc=\"center left\",bbox_to_anchor=(1, 0, 0.5, 1))plt.show()"
},
{
"code": null,
"e": 4854,
"s": 4437,
"text": "# plotting pie chart for different types of purposeloans_purpose = loan.groupby(['purpose'])['funded_amnt_inv'].sum().reset_index()plt.figure(figsize=(14, 10))plt.pie(loans_purpose[\"funded_amnt_inv\"],labels=loans_purpose[\"purpose\"],autopct='%1.1f%%')plt.title('Loan purpose Aggregate Information')plt.axis('equal')plt.legend(loan_status,title=\"Loan purpose\",loc=\"center left\",bbox_to_anchor=(1, 0, 0.5, 1))plt.show()"
},
{
"code": null,
"e": 5082,
"s": 4854,
"text": "# in dataset, we can see around half of the columns are null# completely, hence remove all columns having no valuesloan = loan.dropna(axis=1, how=\"all\")print(\"Looking into remaining columns info:\")print(loan.info(max_cols=200))"
},
{
"code": null,
"e": 5118,
"s": 5082,
"text": "We are left with following columns:"
},
{
"code": null,
"e": 8629,
"s": 5118,
"text": "Looking into remaining columns info:<class 'pandas.core.frame.DataFrame'>RangeIndex: 39717 entries, 0 to 39716Data columns (total 57 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 39717 non-null int64 1 member_id 39717 non-null int64 2 loan_amnt 39717 non-null int64 3 funded_amnt 39717 non-null int64 4 funded_amnt_inv 39717 non-null float64 5 term 39717 non-null object 6 int_rate 39717 non-null object 7 installment 39717 non-null float64 8 grade 39717 non-null object 9 sub_grade 39717 non-null object 10 emp_title 37258 non-null object 11 emp_length 38642 non-null object 12 home_ownership 39717 non-null object 13 annual_inc 39717 non-null float64 14 verification_status 39717 non-null object 15 issue_d 39717 non-null object 16 loan_status 39717 non-null object 17 pymnt_plan 39717 non-null object 18 url 39717 non-null object 19 desc 26777 non-null object 20 purpose 39717 non-null object 21 title 39706 non-null object 22 zip_code 39717 non-null object 23 addr_state 39717 non-null object 24 dti 39717 non-null float64 25 delinq_2yrs 39717 non-null int64 26 earliest_cr_line 39717 non-null object 27 inq_last_6mths 39717 non-null int64 28 mths_since_last_delinq 14035 non-null float64 29 mths_since_last_record 2786 non-null float64 30 open_acc 39717 non-null int64 31 pub_rec 39717 non-null int64 32 revol_bal 39717 non-null int64 33 revol_util 39667 non-null object 34 total_acc 39717 non-null int64 35 initial_list_status 39717 non-null object 36 out_prncp 39717 non-null float64 37 out_prncp_inv 39717 non-null float64 38 total_pymnt 39717 non-null float64 39 total_pymnt_inv 39717 non-null float64 40 total_rec_prncp 39717 non-null float64 41 total_rec_int 39717 non-null float64 42 total_rec_late_fee 39717 non-null float64 43 recoveries 39717 non-null float64 44 collection_recovery_fee 39717 non-null float64 45 last_pymnt_d 39646 non-null object 46 last_pymnt_amnt 39717 non-null float64 47 next_pymnt_d 1140 non-null object 48 last_credit_pull_d 39715 non-null object 49 collections_12_mths_ex_med 39661 non-null float64 50 policy_code 39717 non-null int64 51 application_type 39717 non-null object 52 acc_now_delinq 39717 non-null int64 53 chargeoff_within_12_mths 39661 non-null float64 54 delinq_amnt 39717 non-null int64 55 pub_rec_bankruptcies 39020 non-null float64 56 tax_liens 39678 non-null float64dtypes: float64(20), int64(13), object(24)memory usage: 17.3+ MB"
},
{
"code": null,
"e": 8764,
"s": 8629,
"text": "Now, we will remove all the Demographic and Customer Behavioural features which is of no use for default analysis for credit approval."
},
{
"code": null,
"e": 11022,
"s": 8764,
"text": "# remove non-required columns# id - not required# member_id - not required# acc_now_delinq - empty# funded_amnt - not useful, funded_amnt_inv is useful which is funded to person# emp_title - brand names not useful# pymnt_plan - fixed value as n for all# url - not useful# desc - can be applied some NLP but not for EDA# title - too many distinct values not useful# zip_code - complete zip is not available# delinq_2yrs - post approval feature# mths_since_last_delinq - only half values are there, not much information# mths_since_last_record - only 10% values are there# revol_bal - post/behavioural feature# initial_list_status - fixed value as f for all# out_prncp - post approval feature# out_prncp_inv - not useful as its for investors# total_pymnt - post approval feature# total_pymnt_inv - not useful as it is for investors# total_rec_prncp - post approval feature# total_rec_int - post approval feature# total_rec_late_fee - post approval feature# recoveries - post approval feature# collection_recovery_fee - post approval feature# last_pymnt_d - post approval feature# last_credit_pull_d - irrelevant for approval# last_pymnt_amnt - post feature# next_pymnt_d - post feature# collections_12_mths_ex_med - only 1 value # policy_code - only 1 value# acc_now_delinq - single valued# chargeoff_within_12_mths - post feature# delinq_amnt - single valued# tax_liens - single valued# application_type - single# pub_rec_bankruptcies - single valued for more than 99%# addr_state - may not depend on location as its in financial domaincolsToDrop = [\"id\", \"member_id\", \"funded_amnt\", \"emp_title\", \"pymnt_plan\", \"url\", \"desc\", \"title\", \"zip_code\", \"delinq_2yrs\", \"mths_since_last_delinq\", \"mths_since_last_record\", \"revol_bal\", \"initial_list_status\", \"out_prncp\", \"out_prncp_inv\", \"total_pymnt\", \"total_pymnt_inv\", \"total_rec_prncp\", \"total_rec_int\", \"total_rec_late_fee\", \"recoveries\", \"collection_recovery_fee\", \"last_pymnt_d\", \"last_pymnt_amnt\", \"next_pymnt_d\", \"last_credit_pull_d\", \"collections_12_mths_ex_med\", \"policy_code\", \"acc_now_delinq\", \"chargeoff_within_12_mths\", \"delinq_amnt\", \"tax_liens\", \"application_type\", \"pub_rec_bankruptcies\", \"addr_state\"]loan.drop(colsToDrop, axis=1, inplace=True)print(\"Features we are left with\",list(loan.columns))"
},
{
"code": null,
"e": 11330,
"s": 11022,
"text": "We are left with [‘loan_amnt’, ‘funded_amnt_inv’, ‘term’, ‘int_rate’, ‘installment’, ‘grade’, ‘sub_grade’, ‘emp_length’, ‘home_ownership’, ‘annual_inc’, ‘verification_status’, ‘issue_d’, ‘loan_status’, ‘purpose’, ‘dti’, ‘earliest_cr_line’, ‘inq_last_6mths’, ‘open_acc’, ‘pub_rec’, ‘revol_util’, ‘total_acc’]"
},
{
"code": null,
"e": 11385,
"s": 11330,
"text": "Now, dealing with missing values by removing/imputing:"
},
{
"code": null,
"e": 11748,
"s": 11385,
"text": "# in 12 unique values we have 10+ years the most for emp_length, # but it is highly dependent variable so we will not impute# but remove the rows with null values which is around 2.5%loan.dropna(axis=0, subset=[\"emp_length\"], inplace=True)# remove NA rows for revol_util as its dependent and is around 0.1%loan.dropna(axis=0, subset=[\"revol_util\"], inplace=True)"
},
{
"code": null,
"e": 11827,
"s": 11748,
"text": "Now, we standardize some feature columns to make data compatible for analysis:"
},
{
"code": null,
"e": 12190,
"s": 11827,
"text": "# update int_rate, revol_util without % sign and as numeric typeloan[\"int_rate\"] = pd.to_numeric(loan[\"int_rate\"].apply(lambda x:x.split('%')[0]))loan[\"revol_util\"] = pd.to_numeric(loan[\"revol_util\"].apply(lambda x:x.split('%')[0]))# remove text data from term feature and store as numericalloan[\"term\"] = pd.to_numeric(loan[\"term\"].apply(lambda x:x.split()[0]))"
},
{
"code": null,
"e": 12341,
"s": 12190,
"text": "Removing records with loan status as “Current”, as the loan is currently running and we can’t infer any information regarding default from such loans."
},
{
"code": null,
"e": 13255,
"s": 12341,
"text": "# remove the rows with loan_status as \"Current\"loan = loan[loan[\"loan_status\"].apply(lambda x:False if x == \"Current\" else True)]# update loan_status as Fully Paid to 0 and Charged Off to 1loan[\"loan_status\"] = loan[\"loan_status\"].apply(lambda x: 0 if x == \"Fully Paid\" else 1)# update emp_length feature with continuous values as int# where (< 1 year) is assumed as 0 and 10+ years is assumed as 10 and rest are stored as their magnitudeloan[\"emp_length\"] = pd.to_numeric(loan[\"emp_length\"].apply(lambda x:0 if \"<\" in x else (x.split('+')[0] if \"+\" in x else x.split()[0])))# look through the purpose value countsloan_purpose_values = loan[\"purpose\"].value_counts()*100/loan.shape[0]# remove rows with less than 1% of value counts in paricular purpose loan_purpose_delete = loan_purpose_values[loan_purpose_values<1].index.valuesloan = loan[[False if p in loan_purpose_delete else True for p in loan[\"purpose\"]]]"
},
{
"code": null,
"e": 13352,
"s": 13255,
"text": "Looking upon the quantile values of each features, we will treat outliers for the some features."
},
{
"code": null,
"e": 14340,
"s": 13352,
"text": "# for annual_inc, the highest value is 6000000 where 75% quantile value is 83000, and is 100 times the mean# we need to remomve outliers from annual_inc i.e. 99 to 100%annual_inc_q = loan[\"annual_inc\"].quantile(0.99)loan = loan[loan[\"annual_inc\"] < annual_inc_q]# for open_acc, the highest value is 44 where 75% quantile value is 12, and is 5 times the mean# we need to remomve outliers from open_acc i.e. 99.9 to 100%open_acc_q = loan[\"open_acc\"].quantile(0.999)loan = loan[loan[\"open_acc\"] < open_acc_q]# for total_acc, the highest value is 90 where 75% quantile value is 29, and is 4 times the mean# we need to remomve outliers from total_acc i.e. 98 to 100%total_acc_q = loan[\"total_acc\"].quantile(0.98)loan = loan[loan[\"total_acc\"] < total_acc_q]# for pub_rec, the highest value is 4 where 75% quantile value is 0, and is 4 times the mean# we need to remomve outliers from pub_rec i.e. 99.5 to 100%pub_rec_q = loan[\"pub_rec\"].quantile(0.995)loan = loan[loan[\"pub_rec\"] <= pub_rec_q]"
},
{
"code": null,
"e": 14418,
"s": 14340,
"text": "Now this is how our data looks after cleaning and standardizing the features:"
},
{
"code": null,
"e": 14564,
"s": 14418,
"text": "Issue date is not in the standard format also we can split the date into two columns with month and the year which will make it easy for analysis"
},
{
"code": null,
"e": 14757,
"s": 14564,
"text": "Year in the datetime requires year between 00 to 99 and in some cases year is single digit number i.e. 9 writing a function which will convert such dates to avoid exception in date conversion."
},
{
"code": null,
"e": 15346,
"s": 14757,
"text": "def standerdisedate(date): year = date.split(\"-\")[0] if(len(year) == 1): date = \"0\"+date return datefrom datetime import datetimeloan['issue_d'] = loan['issue_d'].apply(lambda x:standerdisedate(x))loan['issue_d'] = loan['issue_d'].apply(lambda x: datetime.strptime(x, '%b-%y'))# extracting month and year from issue_dateloan['month'] = loan['issue_d'].apply(lambda x: x.month)loan['year'] = loan['issue_d'].apply(lambda x: x.year)# get year from issue_d and replace the sameloan[\"earliest_cr_line\"] = pd.to_numeric(loan[\"earliest_cr_line\"].apply(lambda x:x.split('-')[1]))"
},
{
"code": null,
"e": 15375,
"s": 15346,
"text": "Binning Continuous features:"
},
{
"code": null,
"e": 16564,
"s": 15375,
"text": "# create bins for loan_amnt rangebins = [0, 5000, 10000, 15000, 20000, 25000, 36000]bucket_l = ['0-5000', '5000-10000', '10000-15000', '15000-20000', '20000-25000','25000+']loan['loan_amnt_range'] = pd.cut(loan['loan_amnt'], bins, labels=bucket_l)# create bins for int_rate rangebins = [0, 7.5, 10, 12.5, 15, 100]bucket_l = ['0-7.5', '7.5-10', '10-12.5', '12.5-15', '15+']loan['int_rate_range'] = pd.cut(loan['int_rate'], bins, labels=bucket_l)# create bins for annual_inc rangebins = [0, 25000, 50000, 75000, 100000, 1000000]bucket_l = ['0-25000', '25000-50000', '50000-75000', '75000-100000', '100000+']loan['annual_inc_range'] = pd.cut(loan['annual_inc'], bins, labels=bucket_l)# create bins for installment rangedef installment(n): if n <= 200: return 'low' elif n > 200 and n <=500: return 'medium' elif n > 500 and n <=800: return 'high' else: return 'very high'loan['installment'] = loan['installment'].apply(lambda x: installment(x))# create bins for dti rangebins = [-1, 5.00, 10.00, 15.00, 20.00, 25.00, 50.00]bucket_l = ['0-5%', '5-10%', '10-15%', '15-20%', '20-25%', '25%+']loan['dti_range'] = pd.cut(loan['dti'], bins, labels=bucket_l)"
},
{
"code": null,
"e": 16596,
"s": 16564,
"text": "The following bins are created:"
},
{
"code": null,
"e": 16732,
"s": 16596,
"text": "# check for amount of defaults in the data using countplotplt.figure(figsize=(14,5))sns.countplot(y=\"loan_status\", data=loan)plt.show()"
},
{
"code": null,
"e": 16831,
"s": 16732,
"text": "From above plot we can see that around 16% i.e. 5062 people are defaulters in total 35152 records."
},
{
"code": null,
"e": 17983,
"s": 16831,
"text": "# function for plotting the count plot features wrt default ratiodef plotUnivariateRatioBar(feature, data=loan, figsize=(10,5), rsorted=True): plt.figure(figsize=figsize) if rsorted: feature_dimension = sorted(data[feature].unique()) else: feature_dimension = data[feature].unique() feature_values = [] for fd in feature_dimension: feature_filter = data[data[feature]==fd] feature_count = len(feature_filter[feature_filter[\"loan_status\"]==1]) feature_values.append(feature_count*100/feature_filter[\"loan_status\"].count()) plt.bar(feature_dimension, feature_values, color='orange', edgecolor='white') plt.title(\"Loan Defaults wrt \"+str(feature)+\" feature - countplot\") plt.xlabel(feature, fontsize=16) plt.ylabel(\"defaulter %\", fontsize=16) plt.show()# function to plot univariate with default status scale 0 - 1def plotUnivariateBar(x, figsize=(10,5)): plt.figure(figsize=figsize) sns.barplot(x=x, y='loan_status', data=loan) plt.title(\"Loan Defaults wrt \"+str(x)+\" feature - countplot\") plt.xlabel(x, fontsize=16) plt.ylabel(\"defaulter ratio\", fontsize=16) plt.show()"
},
{
"code": null,
"e": 18007,
"s": 17983,
"text": "a. Categorical Features"
},
{
"code": null,
"e": 18107,
"s": 18007,
"text": "# check for defaulters wrt term in the data using countplotplotUnivariateBar(\"term\", figsize=(8,5))"
},
{
"code": null,
"e": 18265,
"s": 18107,
"text": "From above plot for ‘term’ we can infer that the defaulters rate is increasing wrt term, hence the chances of loan getting deaulted is less for 36m than 60m."
},
{
"code": null,
"e": 18291,
"s": 18265,
"text": "is term benificial -> Yes"
},
{
"code": null,
"e": 18383,
"s": 18291,
"text": "# check for defaulters wrt grade in the data using countplotplotUnivariateRatioBar(\"grade\")"
},
{
"code": null,
"e": 18567,
"s": 18383,
"text": "From above plot for ‘grade’ we can infer that the defaulters rate is increasing wrt grade, hence the chances of loan getting deaulted increases with the grade from A moving towards G."
},
{
"code": null,
"e": 18594,
"s": 18567,
"text": "is grade benificial -> Yes"
},
{
"code": null,
"e": 18705,
"s": 18594,
"text": "# check for defaulters wrt sub_grade in the data using countplotplotUnivariateBar(\"sub_grade\", figsize=(16,5))"
},
{
"code": null,
"e": 18903,
"s": 18705,
"text": "From above plot for ‘sub_grade’ we can infer that the defaulters rate is increasing wrt sub_grade, hence the chances of loan getting deaulted increases with the sub_grade from A1 moving towards G5."
},
{
"code": null,
"e": 18934,
"s": 18903,
"text": "is sub_grade benificial -> Yes"
},
{
"code": null,
"e": 19029,
"s": 18934,
"text": "# check for defaulters wrt home_ownership in the data plotUnivariateRatioBar(\"home_ownership\")"
},
{
"code": null,
"e": 19276,
"s": 19029,
"text": "From above plot for ‘home_ownership’ we can infer that the defaulters rate is constant here (it is quite more for OTHERS but we dont know what is in there, so we’ll not consider it for analysis), hence defaulter does not depends on home_ownership"
},
{
"code": null,
"e": 19311,
"s": 19276,
"text": "is home_ownership benificial -> No"
},
{
"code": null,
"e": 19415,
"s": 19311,
"text": "# check for defaulters wrt verification_status in the dataplotUnivariateRatioBar(\"verification_status\")"
},
{
"code": null,
"e": 19593,
"s": 19415,
"text": "From above plot for ‘verification_status’ we can infer that the defaulters rate is increasing and is less for Not Verified users than Verified ones, but not useful for analysis."
},
{
"code": null,
"e": 19633,
"s": 19593,
"text": "is verification_status benificial -> No"
},
{
"code": null,
"e": 19740,
"s": 19633,
"text": "# check for defaulters wrt purpose in the data using countplotplotUnivariateBar(\"purpose\", figsize=(16,6))"
},
{
"code": null,
"e": 19919,
"s": 19740,
"text": "From above plot for ‘purpose’ we can infer that the defaulters rate is nearly constant for all purpose type except ‘small business’, hence rate will depend on purpose of the loan"
},
{
"code": null,
"e": 19948,
"s": 19919,
"text": "is purpose benificial -> Yes"
},
{
"code": null,
"e": 20062,
"s": 19948,
"text": "# check for defaulters wrt open_acc in the data using countplotplotUnivariateRatioBar(\"open_acc\", figsize=(16,6))"
},
{
"code": null,
"e": 20219,
"s": 20062,
"text": "From above plot for ‘open_acc’ we can infer that the defaulters rate is nearly constant for feature open_acc, hence rate will not depend on open_acc feature"
},
{
"code": null,
"e": 20248,
"s": 20219,
"text": "is open_acc benificial -> No"
},
{
"code": null,
"e": 20344,
"s": 20248,
"text": "# check for defaulters wrt pub_rec in the data using countplotplotUnivariateRatioBar(\"pub_rec\")"
},
{
"code": null,
"e": 20563,
"s": 20344,
"text": "From above plot for ‘pub_rec’ we can infer that the defaulters rate is nearly increasing as it is less for 0 and more for pub_rec with value 1, but as other values are very less as compared to 0 we’ll not consider this"
},
{
"code": null,
"e": 20591,
"s": 20563,
"text": "is pub_rec benificial -> No"
},
{
"code": null,
"e": 20614,
"s": 20591,
"text": "b. Continuous Features"
},
{
"code": null,
"e": 20727,
"s": 20614,
"text": "# check for defaulters wrt emp_length in the data using countplotplotUnivariateBar(\"emp_length\", figsize=(14,6))"
},
{
"code": null,
"e": 20863,
"s": 20727,
"text": "From above plot for ‘emp_length’ we can infer that the defaulters rate is constant here, hence defaulter does not depends on emp_length"
},
{
"code": null,
"e": 20894,
"s": 20863,
"text": "is emp_length benificial -> No"
},
{
"code": null,
"e": 20997,
"s": 20894,
"text": "# check for defaulters wrt month in the data using countplotplotUnivariateBar(\"month\", figsize=(14,6))"
},
{
"code": null,
"e": 21099,
"s": 20997,
"text": "From above plot for ‘month’ we can infer that the defaulters rate is nearly constant here, not useful"
},
{
"code": null,
"e": 21125,
"s": 21099,
"text": "is month benificial -> No"
},
{
"code": null,
"e": 21210,
"s": 21125,
"text": "# check for defaulters wrt year in the data using countplotplotUnivariateBar(\"year\")"
},
{
"code": null,
"e": 21311,
"s": 21210,
"text": "From above plot for ‘year’ we can infer that the defaulters rate is nearly constant here, not useful"
},
{
"code": null,
"e": 21336,
"s": 21311,
"text": "is year benificial -> No"
},
{
"code": null,
"e": 21446,
"s": 21336,
"text": "# check for defaulters wrt earliest_cr_line in the dataplotUnivariateBar(\"earliest_cr_line\", figsize=(16,10))"
},
{
"code": null,
"e": 21648,
"s": 21446,
"text": "From above plot for ‘earliest_cr_line’ we can infer that the defaulters rate is nearly constant for all purpose type except year around 65, hence rate does not depends on earliest_cr_line of the person"
},
{
"code": null,
"e": 21685,
"s": 21648,
"text": "is earliest_cr_line benificial -> No"
},
{
"code": null,
"e": 21774,
"s": 21685,
"text": "# check for defaulters wrt inq_last_6mths in the dataplotUnivariateBar(\"inq_last_6mths\")"
},
{
"code": null,
"e": 21923,
"s": 21774,
"text": "From above plot for ‘inq_last_6mths’ we can infer that the defaulters rate is not consistently increasing with inq_last_6mths type, hence not useful"
},
{
"code": null,
"e": 21958,
"s": 21923,
"text": "is inq_last_6mths benificial -> No"
},
{
"code": null,
"e": 22076,
"s": 21958,
"text": "# check for defaulters wrt revol_util in the data using countplotplotUnivariateRatioBar(\"revol_util\", figsize=(16,6))"
},
{
"code": null,
"e": 22303,
"s": 22076,
"text": "From above plot for ‘revol_util’ we can infer that the defaulters rate is fluctuating where some have complete 100% ratio for defaulter and is increasing as the magnitude increases, hence rate will depend on revol_util feature"
},
{
"code": null,
"e": 22335,
"s": 22303,
"text": "is revol_util benificial -> Yes"
},
{
"code": null,
"e": 22451,
"s": 22335,
"text": "# check for defaulters wrt total_acc in the data using countplotplotUnivariateRatioBar(\"total_acc\", figsize=(14,6))"
},
{
"code": null,
"e": 22614,
"s": 22451,
"text": "From above plot for ‘total_acc’ we can infer that the defaulters rate is nearly constant for all total_acc values, hence rate will not depend on total_acc feature"
},
{
"code": null,
"e": 22644,
"s": 22614,
"text": "is total_acc benificial -> No"
},
{
"code": null,
"e": 22751,
"s": 22644,
"text": "# check for defaulters wrt loan_amnt_range in the data using countplotplotUnivariateBar(\"loan_amnt_range\")"
},
{
"code": null,
"e": 22915,
"s": 22751,
"text": "From above plot for ‘loan_amnt_range’ we can infer that the defaulters rate is increasing loan_amnt_range values, hence rate will depend on loan_amnt_range feature"
},
{
"code": null,
"e": 22952,
"s": 22915,
"text": "is loan_amnt_range benificial -> Yes"
},
{
"code": null,
"e": 23041,
"s": 22952,
"text": "# check for defaulters wrt int_rate_range in the dataplotUnivariateBar(\"int_rate_range\")"
},
{
"code": null,
"e": 23207,
"s": 23041,
"text": "From above plot for ‘int_rate_range’ we can infer that the defaulters rate is decreasing with int_rate_range values, hence rate will depend on int_rate_range feature"
},
{
"code": null,
"e": 23243,
"s": 23207,
"text": "is int_rate_range benificial -> Yes"
},
{
"code": null,
"e": 23336,
"s": 23243,
"text": "# check for defaulters wrt annual_inc_range in the dataplotUnivariateBar(\"annual_inc_range\")"
},
{
"code": null,
"e": 23511,
"s": 23336,
"text": "From above plot for ‘annual_inc_range’ we can infer that the defaulters rate is decreasing as with annual_inc_range values, hence rate will depend on annual_inc_range feature"
},
{
"code": null,
"e": 23549,
"s": 23511,
"text": "is annual_inc_range benificial -> Yes"
},
{
"code": null,
"e": 23660,
"s": 23549,
"text": "# check for defaulters wrt dti_range in the data using countplotplotUnivariateBar(\"dti_range\", figsize=(16,5))"
},
{
"code": null,
"e": 23814,
"s": 23660,
"text": "From above plot for ‘dti_range’ we can infer that the defaulters rate is increasing as with dti_range values, hence rate will depend on dti_range feature"
},
{
"code": null,
"e": 23845,
"s": 23814,
"text": "is dti_range benificial -> Yes"
},
{
"code": null,
"e": 23949,
"s": 23845,
"text": "# check for defaulters wrt installment range in the dataplotUnivariateBar(\"installment\", figsize=(8,5))"
},
{
"code": null,
"e": 24107,
"s": 23949,
"text": "From above plot for ‘installment’ we can infer that the defaulters rate is increasing as with installment values, hence rate will depend on dti_range feature"
},
{
"code": null,
"e": 24140,
"s": 24107,
"text": "is installment benificial -> Yes"
},
{
"code": null,
"e": 24230,
"s": 24140,
"text": "Therefore, following are the important feature we deduced from above Univariate analysis:"
},
{
"code": null,
"e": 24329,
"s": 24230,
"text": "term, grade, purpose, pub_rec, revol_util, funded_amnt_inv, int_rate, annual_inc, dti, installment"
},
{
"code": null,
"e": 24937,
"s": 24329,
"text": "# function to plot scatter plot for two featuresdef plotScatter(x, y): plt.figure(figsize=(16,6)) sns.scatterplot(x=x, y=y, hue=\"loan_status\", data=loan) plt.title(\"Scatter plot between \"+x+\" and \"+y) plt.xlabel(x, fontsize=16) plt.ylabel(y, fontsize=16) plt.show() def plotBivariateBar(x, hue, figsize=(16,6)): plt.figure(figsize=figsize) sns.barplot(x=x, y='loan_status', hue=hue, data=loan) plt.title(\"Loan Default ratio wrt \"+x+\" feature for hue \"+hue+\" in the data using countplot\") plt.xlabel(x, fontsize=16) plt.ylabel(\"defaulter ratio\", fontsize=16) plt.show()"
},
{
"code": null,
"e": 25052,
"s": 24937,
"text": "Plotting for two different features with respect to loan default ratio on y-axis with Bar Plots and Scatter Plots."
},
{
"code": null,
"e": 25177,
"s": 25052,
"text": "# check for defaulters wrt annual_inc and purpose in the data using countplotplotBivariateBar(\"annual_inc_range\", \"purpose\")"
},
{
"code": null,
"e": 25240,
"s": 25177,
"text": "From above plot, we can infer it doesn’t shows any correlation"
},
{
"code": null,
"e": 25252,
"s": 25240,
"text": "related - N"
},
{
"code": null,
"e": 25344,
"s": 25252,
"text": "# check for defaulters wrt term and purpose in the data plotBivariateBar(\"term\", \"purpose\")"
},
{
"code": null,
"e": 25437,
"s": 25344,
"text": "As we can see straight lines on the plot, default ratio increases for every purpose wrt term"
},
{
"code": null,
"e": 25449,
"s": 25437,
"text": "related - Y"
},
{
"code": null,
"e": 25543,
"s": 25449,
"text": "# check for defaulters wrt grade and purpose in the data plotBivariateBar(\"grade\", \"purpose\")"
},
{
"code": null,
"e": 25637,
"s": 25543,
"text": "As we can see straight lines on the plot, default ratio increases for every purpose wrt grade"
},
{
"code": null,
"e": 25649,
"s": 25637,
"text": "related - Y"
},
{
"code": null,
"e": 25762,
"s": 25649,
"text": "# check for defaulters wrt loan_amnt_range and purpose in the dataplotBivariateBar(\"loan_amnt_range\", \"purpose\")"
},
{
"code": null,
"e": 25866,
"s": 25762,
"text": "As we can see straight lines on the plot, default ratio increases for every purpose wrt loan_amnt_range"
},
{
"code": null,
"e": 25878,
"s": 25866,
"text": "related - Y"
},
{
"code": null,
"e": 25985,
"s": 25878,
"text": "# check for defaulters wrt loan_amnt_range and term in the dataplotBivariateBar(\"loan_amnt_range\", \"term\")"
},
{
"code": null,
"e": 26086,
"s": 25985,
"text": "As we can see straight lines on the plot, default ratio increases for every term wrt loan_amnt_range"
},
{
"code": null,
"e": 26098,
"s": 26086,
"text": "related - Y"
},
{
"code": null,
"e": 26213,
"s": 26098,
"text": "# check for defaulters wrt annual_inc_range and purpose in the dataplotBivariateBar(\"annual_inc_range\", \"purpose\")"
},
{
"code": null,
"e": 26318,
"s": 26213,
"text": "As we can see straight lines on the plot, default ratio increases for every purpose wrt annual_inc_range"
},
{
"code": null,
"e": 26330,
"s": 26318,
"text": "related - Y"
},
{
"code": null,
"e": 26440,
"s": 26330,
"text": "# check for defaulters wrt annual_inc_range and purpose in the dataplotBivariateBar(\"installment\", \"purpose\")"
},
{
"code": null,
"e": 26566,
"s": 26440,
"text": "As we can see straight lines on the plot, default ratio increases for every purpose wrt installment except for small_business"
},
{
"code": null,
"e": 26578,
"s": 26566,
"text": "related - Y"
},
{
"code": null,
"e": 26670,
"s": 26578,
"text": "# check for defaulters wrt loan_amnt_range in the dataplotScatter(\"int_rate\", \"annual_inc\")"
},
{
"code": null,
"e": 26766,
"s": 26670,
"text": "As we can see straight lines on the plot, there is no relation between above mentioned features"
},
{
"code": null,
"e": 26778,
"s": 26766,
"text": "related - N"
},
{
"code": null,
"e": 26859,
"s": 26778,
"text": "# plot scatter for funded_amnt_inv with dtiplotScatter(\"funded_amnt_inv\", \"dti\")"
},
{
"code": null,
"e": 26955,
"s": 26859,
"text": "As we can see straight lines on the plot, there is no relation between above mentioned features"
},
{
"code": null,
"e": 26967,
"s": 26955,
"text": "related - N"
},
{
"code": null,
"e": 27062,
"s": 26967,
"text": "# plot scatter for funded_amnt_inv with annual_incplotScatter(\"annual_inc\", \"funded_amnt_inv\")"
},
{
"code": null,
"e": 27163,
"s": 27062,
"text": "As we can see slope pattern on the plot, there is positive relation between above mentioned features"
},
{
"code": null,
"e": 27175,
"s": 27163,
"text": "related - Y"
},
{
"code": null,
"e": 27254,
"s": 27175,
"text": "# plot scatter for loan_amnt with int_rateplotScatter(\"loan_amnt\", \"int_rate\")"
},
{
"code": null,
"e": 27358,
"s": 27254,
"text": "As we can see straight line patterns on the plot, there is no relation between above mentioned features"
},
{
"code": null,
"e": 27370,
"s": 27358,
"text": "related - N"
},
{
"code": null,
"e": 27451,
"s": 27370,
"text": "# plot scatter for int_rate with annual_incplotScatter(\"int_rate\", \"annual_inc\")"
},
{
"code": null,
"e": 27584,
"s": 27451,
"text": "As we can see negative correlation pattern with reduced density on the plot, there is some relation between above mentioned features"
},
{
"code": null,
"e": 27596,
"s": 27584,
"text": "related - Y"
},
{
"code": null,
"e": 27689,
"s": 27596,
"text": "# plot scatter for earliest_cr_line with int_rateplotScatter(\"earliest_cr_line\", \"int_rate\")"
},
{
"code": null,
"e": 27823,
"s": 27689,
"text": "As we can see positive correlation pattern with increasing density on the plot, there is co-relation between above mentioned features"
},
{
"code": null,
"e": 27835,
"s": 27823,
"text": "related - Y"
},
{
"code": null,
"e": 27920,
"s": 27835,
"text": "# plot scatter for annual_inc with emp_lengthplotScatter(\"annual_inc\", \"emp_length\")"
},
{
"code": null,
"e": 28024,
"s": 27920,
"text": "As we can see straight line patterns on the plot, there is no relation between above mentioned features"
},
{
"code": null,
"e": 28036,
"s": 28024,
"text": "related - N"
},
{
"code": null,
"e": 28119,
"s": 28036,
"text": "# plot scatter for earliest_cr_line with dtiplotScatter(\"earliest_cr_line\", \"dti\")"
},
{
"code": null,
"e": 28233,
"s": 28119,
"text": "Plotting for two different features with respect to loan default ratio on y-axis with Box Plots and Violin Plots."
},
{
"code": null,
"e": 28897,
"s": 28233,
"text": "# function to plot boxplot for comparing two featuresdef plotBox(x, y, hue=\"loan_status\"): plt.figure(figsize=(16,6)) sns.boxplot(x=x, y=y, data=loan, hue=hue, order=sorted(loan[x].unique())) plt.title(\"Box plot between \"+x+\" and \"+y+\" for each \"+hue) plt.xlabel(x, fontsize=16) plt.ylabel(y, fontsize=16) plt.show() plt.figure(figsize=(16,8)) sns.violinplot(x=x, y=y, data=loan, hue=hue, order=sorted(loan[x].unique())) plt.title(\"Violin plot between \"+x+\" and \"+y+\" for each \"+hue) plt.xlabel(x, fontsize=16) plt.ylabel(y, fontsize=16) plt.show()# plot box for term vs int_rate for each loan_statusplotBox(\"term\", \"int_rate\")"
},
{
"code": null,
"e": 28976,
"s": 28897,
"text": "int_rate increases with term on loan and the chances of default also increases"
},
{
"code": null,
"e": 29081,
"s": 28976,
"text": "# plot box for loan_status vs int_rate for each purposeplotBox(\"loan_status\", \"int_rate\", hue=\"purpose\")"
},
{
"code": null,
"e": 29156,
"s": 29081,
"text": "int_rate is quite high where the loan is defaulted for every purpose value"
},
{
"code": null,
"e": 29240,
"s": 29156,
"text": "# plot box for purpose vs revo_util for each statusplotBox(\"purpose\", \"revol_util\")"
},
{
"code": null,
"e": 29342,
"s": 29240,
"text": "revol_util is more for every purpose value where the loan is defaulted and quite high for credit_card"
},
{
"code": null,
"e": 29439,
"s": 29342,
"text": "# plot box for grade vs int_rate for each loan_statusplotBox(\"grade\", \"int_rate\", \"loan_status\")"
},
{
"code": null,
"e": 29591,
"s": 29439,
"text": "int_rate is increasing with every grade and also the defaulters for every grade are having their median near the non-defaulter 75% quantile of int_rate"
},
{
"code": null,
"e": 29690,
"s": 29591,
"text": "# plot box for issue_d vs int_rate for each loan_statusplotBox(\"month\", \"int_rate\", \"loan_status\")"
},
{
"code": null,
"e": 29906,
"s": 29690,
"text": "int_rate for defaulter is increasing with every month where the defaulters for every month are having their median near the non-defaulter’s 75% quantile of int_rate, but is almost constant for each month, not useful"
},
{
"code": null,
"e": 29995,
"s": 29906,
"text": "Therefore, following are the important feature we deduced from above Bivariate analysis:"
},
{
"code": null,
"e": 30089,
"s": 29995,
"text": "term, grade, purpose, pub_rec, revol_util, funded_amnt_inv, int_rate, annual_inc, installment"
},
{
"code": null,
"e": 30415,
"s": 30089,
"text": "# plot heat map to see correlation between featurescontinuous_f = [\"funded_amnt_inv\", \"annual_inc\", \"term\", \"int_rate\", \"loan_status\", \"revol_util\", \"pub_rec\", \"earliest_cr_line\"]loan_corr = loan[continuous_f].corr()sns.heatmap(loan_corr,vmin=-1.0,vmax=1.0,annot=True, cmap=\"YlGnBu\")plt.title(\"Correlation Heatmap\")plt.show()"
},
{
"code": null,
"e": 30486,
"s": 30415,
"text": "Hence, important related feature from above Multivariate analysis are:"
},
{
"code": null,
"e": 30571,
"s": 30486,
"text": "term, grade, purpose, revol_util, int_rate, installment, annual_inc, funded_amnt_inv"
},
{
"code": null,
"e": 30741,
"s": 30571,
"text": "After analysing all the related features available in the dataset, we have come to an end, deducing the main driving features for the Lending Club Loan Default analysis:"
}
] |
How to ignore the multiple properties of a JSON object in Java?
|
The @JsonIgnoreProperties Jackson annotation can be used to specify a list of properties or fields of a class to ignore. The @JsonIgnoreProperties
annotation can be placed above the class declaration instead of above the individual properties or fields to ignore.
@Target(value={ANNOTATION_TYPE,TYPE,METHOD,CONSTRUCTOR,FIELD})
@Retention(value=RUNTIME)
public @interface JsonIgnoreProperties
import java.io.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
public class JsonIgnorePropertiesTest {
public static void main(String[] args) throws IOException {
Customer customer = new Customer("120", "Ravi", "Hyderabad");
System.out.println(customer);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(customer);
System.out.println("JSON: " + jsonString);
System.out.println("---------");
jsonString = "{\"id\":\"130\",\"name\":\"Rahul\", \"address\":\"Mumbai\"}";
System.out.println("JSON: " + jsonString);
customer = mapper.readValue(jsonString, Customer.class);
System.out.println(customer);
}
}
// Customer class
@JsonIgnoreProperties({"id", "address"})
class Customer {
private String id;
private String name;
private String address;
public Customer() {
}
public Customer(String id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
}
}
Customer [id=120, name=Ravi, address=Hyderabad]
JSON: {"name":"Ravi"}
---------
JSON: {"id":"130","name":"Rahul", "address":"Mumbai"}
Customer [id=null, name=Rahul, address=null]
|
[
{
"code": null,
"e": 1326,
"s": 1062,
"text": "The @JsonIgnoreProperties Jackson annotation can be used to specify a list of properties or fields of a class to ignore. The @JsonIgnoreProperties\nannotation can be placed above the class declaration instead of above the individual properties or fields to ignore."
},
{
"code": null,
"e": 1454,
"s": 1326,
"text": "@Target(value={ANNOTATION_TYPE,TYPE,METHOD,CONSTRUCTOR,FIELD})\n@Retention(value=RUNTIME)\npublic @interface JsonIgnoreProperties"
},
{
"code": null,
"e": 2813,
"s": 1454,
"text": "import java.io.*;\nimport com.fasterxml.jackson.annotation.*;\nimport com.fasterxml.jackson.databind.*;\npublic class JsonIgnorePropertiesTest {\n public static void main(String[] args) throws IOException {\n Customer customer = new Customer(\"120\", \"Ravi\", \"Hyderabad\");\n System.out.println(customer);\n ObjectMapper mapper = new ObjectMapper();\n String jsonString = mapper.writeValueAsString(customer);\n System.out.println(\"JSON: \" + jsonString);\n System.out.println(\"---------\");\n jsonString = \"{\\\"id\\\":\\\"130\\\",\\\"name\\\":\\\"Rahul\\\", \\\"address\\\":\\\"Mumbai\\\"}\";\n System.out.println(\"JSON: \" + jsonString);\n customer = mapper.readValue(jsonString, Customer.class);\n System.out.println(customer);\n }\n}\n// Customer class\n@JsonIgnoreProperties({\"id\", \"address\"}) \nclass Customer {\n private String id;\n private String name;\n private String address;\n public Customer() {\n }\n public Customer(String id, String name, String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n public String getId() {\n return id;\n }\n public String getName() {\n return name;\n }\n public String getAddress() {\n return address;\n }\n @Override\n public String toString() {\n return \"Customer [id=\" + id + \", name=\" + name + \", address=\" + address + \"]\";\n }\n}"
},
{
"code": null,
"e": 2992,
"s": 2813,
"text": "Customer [id=120, name=Ravi, address=Hyderabad]\nJSON: {\"name\":\"Ravi\"}\n---------\nJSON: {\"id\":\"130\",\"name\":\"Rahul\", \"address\":\"Mumbai\"}\nCustomer [id=null, name=Rahul, address=null]"
}
] |
Min and max values of an array in MongoDB?
|
To get the min and max values, use minandmax. Let us create a collection with documents −
> db.demo286.insertOne({"details":[{Value1:70,Value2:50},{Value1:30,Value2:36}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4ac743f49383b52759cbbc")
}
Display all documents from a collection with the help of find() method −
> db.demo286.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e4ac743f49383b52759cbbc"),
"details" : [
{
"Value1" : 70,
"Value2" : 50
},
{
"Value1" : 30,
"Value2" : 36
}
]
}
Here is the query to get min and max values of an array −
> db.demo286.aggregate([ { "$project": { "name": 1, "MinValue1": { "$min": "$details.Value1" }, "MaxValue2": { "$max": "$details.Value2" } }} ])
This will produce the following output −
{ "_id" : ObjectId("5e4ac743f49383b52759cbbc"), "MinValue1" : 30, "MaxValue2" : 50 }
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "To get the min and max values, use minandmax. Let us create a collection with documents −"
},
{
"code": null,
"e": 1320,
"s": 1152,
"text": "> db.demo286.insertOne({\"details\":[{Value1:70,Value2:50},{Value1:30,Value2:36}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e4ac743f49383b52759cbbc\")\n}"
},
{
"code": null,
"e": 1393,
"s": 1320,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1423,
"s": 1393,
"text": "> db.demo286.find().pretty();"
},
{
"code": null,
"e": 1464,
"s": 1423,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1666,
"s": 1464,
"text": "{\n \"_id\" : ObjectId(\"5e4ac743f49383b52759cbbc\"),\n \"details\" : [\n {\n \"Value1\" : 70,\n \"Value2\" : 50\n },\n {\n \"Value1\" : 30,\n \"Value2\" : 36\n }\n ]\n}"
},
{
"code": null,
"e": 1724,
"s": 1666,
"text": "Here is the query to get min and max values of an array −"
},
{
"code": null,
"e": 1875,
"s": 1724,
"text": "> db.demo286.aggregate([ { \"$project\": { \"name\": 1, \"MinValue1\": { \"$min\": \"$details.Value1\" }, \"MaxValue2\": { \"$max\": \"$details.Value2\" } }} ])"
},
{
"code": null,
"e": 1916,
"s": 1875,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2001,
"s": 1916,
"text": "{ \"_id\" : ObjectId(\"5e4ac743f49383b52759cbbc\"), \"MinValue1\" : 30, \"MaxValue2\" : 50 }"
}
] |
Stars Charts in Python. A Tutorial to Create Star Charts using... | by Cody Glickman, PhD | Towards Data Science
|
Diamonds are a data scientist’s best friend. More specifically, the diamond dataset found on Kaggle. In this article, I will walk through a simple workflow to create a Star Chart (aka Spider Chart or Radar Charts). This tutorial was adapted from the wonderful workflow of Alex at Python Charts. All of the code in this article and the needed dataset are available on GitHub.
To begin you will need a few libraries. I am running Python 3. I created this workflow using a Jupyter notebook, pandas, matplotlib, and numpy. These packages can be installed via pip or conda if they are not already on your system.
pip install jupyterlabpip install pandaspip install matplotlib pip install numpy
The dataset can be downloaded from Kaggle and should be around 3.2 MB. I have included a copy of the dataset on the Github. I have the dataset in the data folder. Load the dataset with pandas, drop the extra index column, and we are off!
df = pd.read_csv("data/diamonds.csv")df.drop("Unnamed: 0", axis=1, inplace=True)
The 4 C’s of diamonds are Cut, Color, Clarity, and Carat. Cut, Color, and Clarity are defined as categorical variables used in the diamond industry. Carat is a numeric representing the weight of a stone.
To create the Star chart, we need to represent the diamond industry terms as numerics. To do this we need to gather information about the levels that are in our dataset. Cut is composed five levels with Ideal being the highest [4] and Fair being the lowest level [0]. In the seven levels of Color, D is the highest [6] and J is the lowest level [0]. Finally, Clarity is composed of eight levels with IF, meaning internally flawless as the highest level [7] and I1, inclusions level 1, as the lowest level [0].
In our dataset, we cut 3 outliers in carat size that skew the downstream column scaling.
## Cut diamonds that skew carat rangeindicies_to_remove = [27415, 27630, 27130]df = df.drop(indicies_to_remove)
Next, we create new columns in our dataframe to house the rankings created by mapping a dictionary against our C’s column. An example of the mapping is below.
cut={'Ideal':4,'Premium':3,'Very Good':2,'Good': 1,'Fair':0}df['Cut'] = df['cut'].map(cut) #Note: 'Cut' is a different column
Finally, we need to scale the columns that we will use in our Star Chart to represent the data fairly.
## Convert all rankings and contiguous data to scale between 0-100factors = ['Cut', 'Color', "Clarity", "carat", "price"]new_max = 100new_min = 0new_range = new_max - new_min## Create Scaled Columnsfor factor in factors: max_val = df[factor].max() min_val = df[factor].min() val_range = max_val - min_val df[factor + '_Adj'] = df[factor].apply(lambda x: (((x - min_val) * new_range) / val_range) + new_min)
We then subset the scaled columns for downstream plotting. Notice how we are creating a new dataframe (df2) with only the columns we intend to use in the Star Chart.
## Subset scaled columns df2 = df[['Cut_Adj', "Color_Adj", "Clarity_Adj", "carat_Adj", "price_Adj"]]df2.columns = ['Cut', "Color", "Clarity", "Carat", "Price"]
To create the Star Chart, we must specify which columns to use and create the circular plot object using numpy.
labels = ['Cut', "Color", "Clarity", "Carat", "Price"]points = len(labels)angles = np.linspace(0, 2 * np.pi, points, endpoint=False).tolist()angles += angles[:1]
We then create a helper function to plot a diamond solely by the index number.
def add_to_star(diamond, color, label=None): values = df2.loc[diamond].tolist() values += values[:1] if label != None: ax.plot(angles, values, color=color, linewidth=1, label=label) else: ax.plot(angles, values, color=color, linewidth=1, label=diamond) ax.fill(angles, values, color=color, alpha=0.25)
Now the magic begins! We can begin populating our Star Chart with any diamonds we want. How about the most expensive and the two least expensive:
## Create plot object fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))## Plot a new diamond with the add_to_star functionadd_to_star(27749, '#1aaf6c', "Most Expensive Diamond")add_to_star(0, '#429bf4', "Least Expensive A")add_to_star(1, '#d42cea', "Least Expensive B")
This amount is enough to create a Star Chart, however, there are no x labels, no orientation, and no custom flair. Let’s change that!
## Fix axis to star from topax.set_theta_offset(np.pi / 2)ax.set_theta_direction(-1)## Edit x axis labelsfor label, angle in zip(ax.get_xticklabels(), angles): if angle in (0, np.pi): label.set_horizontalalignment('center') elif 0 < angle < np.pi: label.set_horizontalalignment('left') else: label.set_horizontalalignment('right')## Customize your graphic# Change the location of the gridlines or remove themax.set_rgrids([20, 40, 60 ,80])#ax.set_rgrids([]) # This removes grid lines# Change the color of the ticksax.tick_params(colors='#222222')# Make the y-axis labels larger, smaller, or remove by setting fontsizeax.tick_params(axis='y', labelsize=0)# Make the x-axis labels larger or smaller.ax.tick_params(axis='x', labelsize=13)# Change the color of the circular gridlines.ax.grid(color='#AAAAAA')# Change the color of the outer circleax.spines['polar'].set_color('#222222')# Change the circle background colorax.set_facecolor('#FAFAFA')# Add title and legendax.set_title('Comparing Diamonds Across Dimensions', y=1.08)ax.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))# Draw axis lines for each angle and label.ax.set_thetagrids(np.degrees(angles), labels)
So what is the output?
What is the diamond with the highest rating across the 4 C’s with the lowest price? To find out we must get the total value across the 4 C’s and divide by the raw (unscaled) price. This section operates over the original dataframe with all the raw columns. To find the total, we sum the four scaled columns.
df['Total'] = df['Cut_Adj'] + df['Color_Adj'] + df['Clarity_Adj'] + df['carat_Adj']## Divide Value total by Pricedf['4C_by_Price'] = df['Total']/df['price']df = df.sort_values(by="4C_by_Price", ascending=False)
The diamond with the most bling for our buck is #31597 and the diamond with the least bling for our buck is #26320. How do these diamonds compare on a Star Chart? Let’s explore below:
Thank you for exploring a few diamond characteristics in a Star Chart format using matplotlib. If you have any questions post them below or to the location of the full code, the GitHub repository. My name is Cody Glickman and I can be found on LinkedIn. Be sure to check out some other articles about fun data science projects!
|
[
{
"code": null,
"e": 547,
"s": 172,
"text": "Diamonds are a data scientist’s best friend. More specifically, the diamond dataset found on Kaggle. In this article, I will walk through a simple workflow to create a Star Chart (aka Spider Chart or Radar Charts). This tutorial was adapted from the wonderful workflow of Alex at Python Charts. All of the code in this article and the needed dataset are available on GitHub."
},
{
"code": null,
"e": 780,
"s": 547,
"text": "To begin you will need a few libraries. I am running Python 3. I created this workflow using a Jupyter notebook, pandas, matplotlib, and numpy. These packages can be installed via pip or conda if they are not already on your system."
},
{
"code": null,
"e": 861,
"s": 780,
"text": "pip install jupyterlabpip install pandaspip install matplotlib pip install numpy"
},
{
"code": null,
"e": 1099,
"s": 861,
"text": "The dataset can be downloaded from Kaggle and should be around 3.2 MB. I have included a copy of the dataset on the Github. I have the dataset in the data folder. Load the dataset with pandas, drop the extra index column, and we are off!"
},
{
"code": null,
"e": 1180,
"s": 1099,
"text": "df = pd.read_csv(\"data/diamonds.csv\")df.drop(\"Unnamed: 0\", axis=1, inplace=True)"
},
{
"code": null,
"e": 1384,
"s": 1180,
"text": "The 4 C’s of diamonds are Cut, Color, Clarity, and Carat. Cut, Color, and Clarity are defined as categorical variables used in the diamond industry. Carat is a numeric representing the weight of a stone."
},
{
"code": null,
"e": 1894,
"s": 1384,
"text": "To create the Star chart, we need to represent the diamond industry terms as numerics. To do this we need to gather information about the levels that are in our dataset. Cut is composed five levels with Ideal being the highest [4] and Fair being the lowest level [0]. In the seven levels of Color, D is the highest [6] and J is the lowest level [0]. Finally, Clarity is composed of eight levels with IF, meaning internally flawless as the highest level [7] and I1, inclusions level 1, as the lowest level [0]."
},
{
"code": null,
"e": 1983,
"s": 1894,
"text": "In our dataset, we cut 3 outliers in carat size that skew the downstream column scaling."
},
{
"code": null,
"e": 2095,
"s": 1983,
"text": "## Cut diamonds that skew carat rangeindicies_to_remove = [27415, 27630, 27130]df = df.drop(indicies_to_remove)"
},
{
"code": null,
"e": 2254,
"s": 2095,
"text": "Next, we create new columns in our dataframe to house the rankings created by mapping a dictionary against our C’s column. An example of the mapping is below."
},
{
"code": null,
"e": 2380,
"s": 2254,
"text": "cut={'Ideal':4,'Premium':3,'Very Good':2,'Good': 1,'Fair':0}df['Cut'] = df['cut'].map(cut) #Note: 'Cut' is a different column"
},
{
"code": null,
"e": 2483,
"s": 2380,
"text": "Finally, we need to scale the columns that we will use in our Star Chart to represent the data fairly."
},
{
"code": null,
"e": 2902,
"s": 2483,
"text": "## Convert all rankings and contiguous data to scale between 0-100factors = ['Cut', 'Color', \"Clarity\", \"carat\", \"price\"]new_max = 100new_min = 0new_range = new_max - new_min## Create Scaled Columnsfor factor in factors: max_val = df[factor].max() min_val = df[factor].min() val_range = max_val - min_val df[factor + '_Adj'] = df[factor].apply(lambda x: (((x - min_val) * new_range) / val_range) + new_min)"
},
{
"code": null,
"e": 3068,
"s": 2902,
"text": "We then subset the scaled columns for downstream plotting. Notice how we are creating a new dataframe (df2) with only the columns we intend to use in the Star Chart."
},
{
"code": null,
"e": 3228,
"s": 3068,
"text": "## Subset scaled columns df2 = df[['Cut_Adj', \"Color_Adj\", \"Clarity_Adj\", \"carat_Adj\", \"price_Adj\"]]df2.columns = ['Cut', \"Color\", \"Clarity\", \"Carat\", \"Price\"]"
},
{
"code": null,
"e": 3340,
"s": 3228,
"text": "To create the Star Chart, we must specify which columns to use and create the circular plot object using numpy."
},
{
"code": null,
"e": 3502,
"s": 3340,
"text": "labels = ['Cut', \"Color\", \"Clarity\", \"Carat\", \"Price\"]points = len(labels)angles = np.linspace(0, 2 * np.pi, points, endpoint=False).tolist()angles += angles[:1]"
},
{
"code": null,
"e": 3581,
"s": 3502,
"text": "We then create a helper function to plot a diamond solely by the index number."
},
{
"code": null,
"e": 3912,
"s": 3581,
"text": "def add_to_star(diamond, color, label=None): values = df2.loc[diamond].tolist() values += values[:1] if label != None: ax.plot(angles, values, color=color, linewidth=1, label=label) else: ax.plot(angles, values, color=color, linewidth=1, label=diamond) ax.fill(angles, values, color=color, alpha=0.25)"
},
{
"code": null,
"e": 4058,
"s": 3912,
"text": "Now the magic begins! We can begin populating our Star Chart with any diamonds we want. How about the most expensive and the two least expensive:"
},
{
"code": null,
"e": 4348,
"s": 4058,
"text": "## Create plot object fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))## Plot a new diamond with the add_to_star functionadd_to_star(27749, '#1aaf6c', \"Most Expensive Diamond\")add_to_star(0, '#429bf4', \"Least Expensive A\")add_to_star(1, '#d42cea', \"Least Expensive B\")"
},
{
"code": null,
"e": 4482,
"s": 4348,
"text": "This amount is enough to create a Star Chart, however, there are no x labels, no orientation, and no custom flair. Let’s change that!"
},
{
"code": null,
"e": 5682,
"s": 4482,
"text": "## Fix axis to star from topax.set_theta_offset(np.pi / 2)ax.set_theta_direction(-1)## Edit x axis labelsfor label, angle in zip(ax.get_xticklabels(), angles): if angle in (0, np.pi): label.set_horizontalalignment('center') elif 0 < angle < np.pi: label.set_horizontalalignment('left') else: label.set_horizontalalignment('right')## Customize your graphic# Change the location of the gridlines or remove themax.set_rgrids([20, 40, 60 ,80])#ax.set_rgrids([]) # This removes grid lines# Change the color of the ticksax.tick_params(colors='#222222')# Make the y-axis labels larger, smaller, or remove by setting fontsizeax.tick_params(axis='y', labelsize=0)# Make the x-axis labels larger or smaller.ax.tick_params(axis='x', labelsize=13)# Change the color of the circular gridlines.ax.grid(color='#AAAAAA')# Change the color of the outer circleax.spines['polar'].set_color('#222222')# Change the circle background colorax.set_facecolor('#FAFAFA')# Add title and legendax.set_title('Comparing Diamonds Across Dimensions', y=1.08)ax.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))# Draw axis lines for each angle and label.ax.set_thetagrids(np.degrees(angles), labels)"
},
{
"code": null,
"e": 5705,
"s": 5682,
"text": "So what is the output?"
},
{
"code": null,
"e": 6013,
"s": 5705,
"text": "What is the diamond with the highest rating across the 4 C’s with the lowest price? To find out we must get the total value across the 4 C’s and divide by the raw (unscaled) price. This section operates over the original dataframe with all the raw columns. To find the total, we sum the four scaled columns."
},
{
"code": null,
"e": 6224,
"s": 6013,
"text": "df['Total'] = df['Cut_Adj'] + df['Color_Adj'] + df['Clarity_Adj'] + df['carat_Adj']## Divide Value total by Pricedf['4C_by_Price'] = df['Total']/df['price']df = df.sort_values(by=\"4C_by_Price\", ascending=False)"
},
{
"code": null,
"e": 6408,
"s": 6224,
"text": "The diamond with the most bling for our buck is #31597 and the diamond with the least bling for our buck is #26320. How do these diamonds compare on a Star Chart? Let’s explore below:"
}
] |
Java Program to Illustrate Use of Binary Literals - GeeksforGeeks
|
09 Nov, 2020
A binary literal is a number that is represented in 0s and 1s (binary digits). Java allows you to express integral types (byte, short, int, and long) in a binary number system. To specify a binary literal, add the prefix 0b or 0B to the integral value. So, we can express binary digits in a program by assigning them to variables, and the output of those variables after executing the program will be decimal digits.
Implementing Binary literals in Java:
We can explore the ways in which we can implement and use binary literals in Java programming language. The first and following Java program is an example to implement different types of binary literals. As mentioned above Java allows us to express byte, short, int, and long types of binary literals.
Java
// Java Program to Illustrate Use of Binary Literalspublic class GFG { public static void main(String[] args) { // Byte type Binary Literal byte a1 = 0b011; // The b can be lower or upper case byte a2 = 0B101; System.out.println("Binary Literal in Byte----->"); System.out.println("a1 = " + a1 + ", " + "a2 = " + a2); // Short type Binary Literal short b1 = 0b101; // The b can be lower or upper case short b2 = 0B111; System.out.println("Binary Literal in Short----->"); System.out.println("b1 = " + b1 + ", " + "b2 = " + b2); // Int type Binary literal int c1 = 0b011; // The b can be lower or upper case int c2 = 0B111; System.out.println( "Binary Literal in Integer----->"); System.out.println("c1 = " + c1 + ", " + "c2 = " + c2); // Long type Binary literal long d1 = 0b0000011111100011; // The b can be lower or upper case long d2 = 0B0000011111100001; System.out.println("Binary Literal in Long----->"); System.out.println("d1 = " + d1 + ", " + "d2 = " + d2); }}
Binary Literal in Byte----->
a1 = 3, a2 = 5
Binary Literal in Short----->
b1 = 5, b2 = 7
Binary Literal in Integer----->
c1 = 3, c2 = 7
Binary Literal in Long----->
d1 = 2019, d2 = 2017
In Java, operators can be used on binary literals to perform operations. The following Java program is an example to implement different mathematical and comparison operations on binary literals. The results of these operations on binary literals are decimal digits.
Java
// Java Program to Illustrate Use of Binary Literalspublic class GFG { public static void main(String[] args) { byte n1 = 3; // Decimal number byte n2 = 0b011; // Binary of 5 byte n3 = -0b111; // Negative binary number byte n4 = 0b1101; System.out.println("n1 = " + n1); System.out.println("n2 = " + n2); System.out.println("n3 = " + n3); System.out.println("n4 = " + n4); // Checking if the decimal and binary digits are // equal System.out.println("is n1 and n2 equal: " + (n1 == n2)); // Adding 1 to a binary digit System.out.println("n2 + 1 = " + (n2 + 1)); // Adding 1 to a negative binary digit System.out.println("n3 + 1 = " + (n3 + 1)); // Multiplying 2 with a binary digit System.out.println("n4 x 2 = " + (n4 * 2)); }}
n1 = 3
n2 = 3
n3 = -7
n4 = 13
is n1 and n2 equal: true
n2 + 1 = 4
n3 + 1 = -6
n4 x 2 = 26
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n09 Nov, 2020"
},
{
"code": null,
"e": 23974,
"s": 23557,
"text": "A binary literal is a number that is represented in 0s and 1s (binary digits). Java allows you to express integral types (byte, short, int, and long) in a binary number system. To specify a binary literal, add the prefix 0b or 0B to the integral value. So, we can express binary digits in a program by assigning them to variables, and the output of those variables after executing the program will be decimal digits."
},
{
"code": null,
"e": 24012,
"s": 23974,
"text": "Implementing Binary literals in Java:"
},
{
"code": null,
"e": 24314,
"s": 24012,
"text": "We can explore the ways in which we can implement and use binary literals in Java programming language. The first and following Java program is an example to implement different types of binary literals. As mentioned above Java allows us to express byte, short, int, and long types of binary literals."
},
{
"code": null,
"e": 24319,
"s": 24314,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Use of Binary Literalspublic class GFG { public static void main(String[] args) { // Byte type Binary Literal byte a1 = 0b011; // The b can be lower or upper case byte a2 = 0B101; System.out.println(\"Binary Literal in Byte----->\"); System.out.println(\"a1 = \" + a1 + \", \" + \"a2 = \" + a2); // Short type Binary Literal short b1 = 0b101; // The b can be lower or upper case short b2 = 0B111; System.out.println(\"Binary Literal in Short----->\"); System.out.println(\"b1 = \" + b1 + \", \" + \"b2 = \" + b2); // Int type Binary literal int c1 = 0b011; // The b can be lower or upper case int c2 = 0B111; System.out.println( \"Binary Literal in Integer----->\"); System.out.println(\"c1 = \" + c1 + \", \" + \"c2 = \" + c2); // Long type Binary literal long d1 = 0b0000011111100011; // The b can be lower or upper case long d2 = 0B0000011111100001; System.out.println(\"Binary Literal in Long----->\"); System.out.println(\"d1 = \" + d1 + \", \" + \"d2 = \" + d2); }}",
"e": 25597,
"s": 24319,
"text": null
},
{
"code": null,
"e": 25784,
"s": 25597,
"text": "Binary Literal in Byte----->\na1 = 3, a2 = 5\nBinary Literal in Short----->\nb1 = 5, b2 = 7\nBinary Literal in Integer----->\nc1 = 3, c2 = 7\nBinary Literal in Long----->\nd1 = 2019, d2 = 2017\n"
},
{
"code": null,
"e": 26051,
"s": 25784,
"text": "In Java, operators can be used on binary literals to perform operations. The following Java program is an example to implement different mathematical and comparison operations on binary literals. The results of these operations on binary literals are decimal digits."
},
{
"code": null,
"e": 26056,
"s": 26051,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Use of Binary Literalspublic class GFG { public static void main(String[] args) { byte n1 = 3; // Decimal number byte n2 = 0b011; // Binary of 5 byte n3 = -0b111; // Negative binary number byte n4 = 0b1101; System.out.println(\"n1 = \" + n1); System.out.println(\"n2 = \" + n2); System.out.println(\"n3 = \" + n3); System.out.println(\"n4 = \" + n4); // Checking if the decimal and binary digits are // equal System.out.println(\"is n1 and n2 equal: \" + (n1 == n2)); // Adding 1 to a binary digit System.out.println(\"n2 + 1 = \" + (n2 + 1)); // Adding 1 to a negative binary digit System.out.println(\"n3 + 1 = \" + (n3 + 1)); // Multiplying 2 with a binary digit System.out.println(\"n4 x 2 = \" + (n4 * 2)); }}",
"e": 26947,
"s": 26056,
"text": null
},
{
"code": null,
"e": 27038,
"s": 26947,
"text": "n1 = 3\nn2 = 3\nn3 = -7\nn4 = 13\nis n1 and n2 equal: true\nn2 + 1 = 4\nn3 + 1 = -6\nn4 x 2 = 26\n"
},
{
"code": null,
"e": 27043,
"s": 27038,
"text": "Java"
},
{
"code": null,
"e": 27057,
"s": 27043,
"text": "Java Programs"
},
{
"code": null,
"e": 27062,
"s": 27057,
"text": "Java"
},
{
"code": null,
"e": 27160,
"s": 27062,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27169,
"s": 27160,
"text": "Comments"
},
{
"code": null,
"e": 27182,
"s": 27169,
"text": "Old Comments"
},
{
"code": null,
"e": 27212,
"s": 27182,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27227,
"s": 27212,
"text": "Stream In Java"
},
{
"code": null,
"e": 27248,
"s": 27227,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27294,
"s": 27248,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27313,
"s": 27294,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27357,
"s": 27313,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 27383,
"s": 27357,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27417,
"s": 27383,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 27464,
"s": 27417,
"text": "Implementing a Linked List in Java using Class"
}
] |
How to find the number of distinct values in an R vector?
|
When we have repeated elements in an R vector and the vector size is large then we might want to know the distinct values in that vector. This will help us to understand the unique values we have in our vector, so that we can create the appropriate chart and perform the appropriate analysis using that vector. This can be done by using length function with unique.
Live Demo
> x1<-sample(1:5,50,replace=TRUE)
> x1
[1] 2 5 5 3 2 4 3 3 1 4 5 4 5 3 3 1 1 2 5 1 3 2 4 1 3 1 5 4 2 5 5 3 2 4 1 1 1 3
[39] 3 5 2 5 4 2 2 2 4 1 1 1
> length(unique(x1))
[1] 5
Live Demo
> x2<-rpois(100,5)
> x2
[1] 2 2 9 5 4 3 2 6 5 11 5 2 3 5 0 5 3 9 6 3 5 6 5 9 6
[26] 4 2 3 7 4 5 6 6 3 7 9 5 5 3 0 8 3 1 9 4 3 4 5 4 5
[51] 7 2 5 6 6 6 5 10 4 7 6 5 8 5 1 6 6 3 6 5 4 6 7 6 4
[76] 3 4 8 7 6 9 11 5 1 4 4 2 2 4 4 3 6 4 9 6 4 3 2 12 4
> length(unique(x2))
[1] 13
> x3<-rpois(100,2)
> length(unique(x3))
[1] 6
> x3
[1] 3 4 2 3 1 1 2 0 1 2 3 4 1 3 0 2 1 2 4 1 1 2 3 2 3 2 2 2 1 0 1 1 3 3 1 2 2
[38] 2 1 2 0 4 0 2 3 2 2 2 3 1 5 2 4 4 3 2 2 0 2 2 4 3 3 2 0 3 2 2 0 1 2 3 0 2
[75] 4 3 1 3 1 2 2 0 3 2 3 0 3 1 1 3 0 0 1 2 2 1 1 1 2 3
> length(unique(x3))
[1] 6
Live Demo
> x4<-rnorm(50,mean=2,sd=10)
> x4
[1] -9.6766233 1.9169099 3.2885540 0.5412437 0.3608904 19.6355200
[7] 9.6258651 13.1143108 -7.2320695 3.6434184 13.5482519 1.4347858
[13] -19.2936065 5.4484576 -17.0495545 -6.1117015 15.2400432 8.1563685
[19] 12.9166896 5.0660486 0.8984124 -7.2431277 17.9291375 2.4501060
[25] -5.1512840 10.6522310 12.7444096 20.9565477 -4.0299730 -1.9086782
[31] -2.1622203 -1.7565742 -1.6663095 -0.9567745 16.4182041 -4.9753829
[37] -1.8816751 8.5253645 13.2477245 -5.7211080 -3.0808622 7.2362059
[43] 12.1775423 -0.5116459 -12.2999345 19.0912103 16.3506957 -5.1037115
[49] 1.3493243 -15.5946874
> length(unique(x4))
[1] 50
Live Demo
> x5<-runif(50,2,5)
> x5
[1] 4.146702 3.055000 4.839670 4.229320 2.152358 4.941094 2.653467 2.108588
[9] 2.782112 4.161247 2.743683 2.704747 2.063036 2.793862 4.075405 2.104008
[17] 2.188358 3.193118 3.470085 3.893146 4.170213 2.230297 3.264338 4.921180
[25] 4.441417 2.671303 3.469227 2.034021 2.775807 3.363796 4.222930 4.971980
[33] 2.996615 4.834374 4.885560 4.697832 3.478148 4.354806 4.409357 4.033303
[41] 3.743833 2.992004 2.003944 2.197406 2.257856 2.039329 3.007237 2.357793
[49] 3.780786 2.111938
> length(unique(x5))
[1] 50
Live Demo
> x6<-rpois(100,10)
> x6
[1] 2 12 7 25 12 5 6 13 15 4 11 10 10 7 12 9 8 14 9 9 12 12 7 10 13
[26] 9 8 6 7 17 17 9 16 12 6 7 8 10 9 7 11 7 11 15 4 13 15 5 13 8
[51] 8 12 13 12 8 11 9 15 7 13 7 10 9 8 14 10 14 6 10 6 6 8 15 7 9
[76] 10 12 11 11 10 14 9 7 12 10 14 7 6 9 9 11 11 10 12 12 12 13 14 9 8
> length(unique(x6))
[1] 16
Live Demo
> x7<-rep(LETTERS[1:10],5)
> x7
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "A" "B" "C" "D" "E" "F" "G" "H" "I"
[20] "J" "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "A" "B" "C" "D" "E" "F" "G" "H"
[39] "I" "J" "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"
> length(unique(x7))
[1] 10
Live Demo
> x8<-sample(LETTERS[1:26],50,replace=TRUE)
> x8
[1] "U" "P" "G" "Y" "J" "S" "Z" "C" "Y" "M" "P" "S" "N" "S" "J" "B" "P" "K" "S"
[20] "X" "C" "G" "V" "W" "X" "L" "H" "W" "M" "T" "U" "R" "J" "B" "I" "S" "L" "J"
[39] "X" "L" "Y" "W" "F" "H" "W" "M" "K" "M" "B" "H"
> length(unique(x8))
[1] 21
Live Demo
> x9<-sample(letters[1:26],50,replace=TRUE)
> x9
[1] "l" "s" "v" "w" "t" "c" "d" "u" "u" "l" "x" "m" "g" "v" "x" "z" "v" "w" "c"
[20] "e" "t" "t" "v" "o" "w" "f" "j" "m" "y" "w" "l" "q" "r" "t" "g" "n" "j" "p"
[39] "a" "x" "i" "c" "k" "h" "z" "d" "q" "e" "w" "j"
> length(unique(x9))
[1] 25
Live Demo
> x10<-rbinom(50,10,0.5)
> x10
[1] 2 4 4 7 6 5 5 4 1 8 6 4 6 7 5 6 4 6 8 5 5 6 5 2 3 3 3 5 3 5 4 5 7 5 8 5 7 6
[39] 7 4 5 2 3 5 4 6 1 7 4 5
> length(unique(x10))
[1] 8
|
[
{
"code": null,
"e": 1428,
"s": 1062,
"text": "When we have repeated elements in an R vector and the vector size is large then we might want to know the distinct values in that vector. This will help us to understand the unique values we have in our vector, so that we can create the appropriate chart and perform the appropriate analysis using that vector. This can be done by using length function with unique."
},
{
"code": null,
"e": 1439,
"s": 1428,
"text": " Live Demo"
},
{
"code": null,
"e": 1478,
"s": 1439,
"text": "> x1<-sample(1:5,50,replace=TRUE)\n> x1"
},
{
"code": null,
"e": 1587,
"s": 1478,
"text": "[1] 2 5 5 3 2 4 3 3 1 4 5 4 5 3 3 1 1 2 5 1 3 2 4 1 3 1 5 4 2 5 5 3 2 4 1 1 1 3\n[39] 3 5 2 5 4 2 2 2 4 1 1 1"
},
{
"code": null,
"e": 1608,
"s": 1587,
"text": "> length(unique(x1))"
},
{
"code": null,
"e": 1614,
"s": 1608,
"text": "[1] 5"
},
{
"code": null,
"e": 1625,
"s": 1614,
"text": " Live Demo"
},
{
"code": null,
"e": 1649,
"s": 1625,
"text": "> x2<-rpois(100,5)\n> x2"
},
{
"code": null,
"e": 1872,
"s": 1649,
"text": "[1] 2 2 9 5 4 3 2 6 5 11 5 2 3 5 0 5 3 9 6 3 5 6 5 9 6\n[26] 4 2 3 7 4 5 6 6 3 7 9 5 5 3 0 8 3 1 9 4 3 4 5 4 5\n[51] 7 2 5 6 6 6 5 10 4 7 6 5 8 5 1 6 6 3 6 5 4 6 7 6 4\n[76] 3 4 8 7 6 9 11 5 1 4 4 2 2 4 4 3 6 4 9 6 4 3 2 12 4"
},
{
"code": null,
"e": 1893,
"s": 1872,
"text": "> length(unique(x2))"
},
{
"code": null,
"e": 1900,
"s": 1893,
"text": "[1] 13"
},
{
"code": null,
"e": 1951,
"s": 1900,
"text": "> x3<-rpois(100,2)\n> length(unique(x3))\n[1] 6\n> x3"
},
{
"code": null,
"e": 2165,
"s": 1951,
"text": "[1] 3 4 2 3 1 1 2 0 1 2 3 4 1 3 0 2 1 2 4 1 1 2 3 2 3 2 2 2 1 0 1 1 3 3 1 2 2\n[38] 2 1 2 0 4 0 2 3 2 2 2 3 1 5 2 4 4 3 2 2 0 2 2 4 3 3 2 0 3 2 2 0 1 2 3 0 2\n[75] 4 3 1 3 1 2 2 0 3 2 3 0 3 1 1 3 0 0 1 2 2 1 1 1 2 3"
},
{
"code": null,
"e": 2186,
"s": 2165,
"text": "> length(unique(x3))"
},
{
"code": null,
"e": 2192,
"s": 2186,
"text": "[1] 6"
},
{
"code": null,
"e": 2203,
"s": 2192,
"text": " Live Demo"
},
{
"code": null,
"e": 2237,
"s": 2203,
"text": "> x4<-rnorm(50,mean=2,sd=10)\n> x4"
},
{
"code": null,
"e": 2819,
"s": 2237,
"text": "[1] -9.6766233 1.9169099 3.2885540 0.5412437 0.3608904 19.6355200\n[7] 9.6258651 13.1143108 -7.2320695 3.6434184 13.5482519 1.4347858\n[13] -19.2936065 5.4484576 -17.0495545 -6.1117015 15.2400432 8.1563685\n[19] 12.9166896 5.0660486 0.8984124 -7.2431277 17.9291375 2.4501060\n[25] -5.1512840 10.6522310 12.7444096 20.9565477 -4.0299730 -1.9086782\n[31] -2.1622203 -1.7565742 -1.6663095 -0.9567745 16.4182041 -4.9753829\n[37] -1.8816751 8.5253645 13.2477245 -5.7211080 -3.0808622 7.2362059\n[43] 12.1775423 -0.5116459 -12.2999345 19.0912103 16.3506957 -5.1037115\n[49] 1.3493243 -15.5946874"
},
{
"code": null,
"e": 2840,
"s": 2819,
"text": "> length(unique(x4))"
},
{
"code": null,
"e": 2847,
"s": 2840,
"text": "[1] 50"
},
{
"code": null,
"e": 2858,
"s": 2847,
"text": " Live Demo"
},
{
"code": null,
"e": 2883,
"s": 2858,
"text": "> x5<-runif(50,2,5)\n> x5"
},
{
"code": null,
"e": 3366,
"s": 2883,
"text": "[1] 4.146702 3.055000 4.839670 4.229320 2.152358 4.941094 2.653467 2.108588\n[9] 2.782112 4.161247 2.743683 2.704747 2.063036 2.793862 4.075405 2.104008\n[17] 2.188358 3.193118 3.470085 3.893146 4.170213 2.230297 3.264338 4.921180\n[25] 4.441417 2.671303 3.469227 2.034021 2.775807 3.363796 4.222930 4.971980\n[33] 2.996615 4.834374 4.885560 4.697832 3.478148 4.354806 4.409357 4.033303\n[41] 3.743833 2.992004 2.003944 2.197406 2.257856 2.039329 3.007237 2.357793\n[49] 3.780786 2.111938"
},
{
"code": null,
"e": 3387,
"s": 3366,
"text": "> length(unique(x5))"
},
{
"code": null,
"e": 3394,
"s": 3387,
"text": "[1] 50"
},
{
"code": null,
"e": 3405,
"s": 3394,
"text": " Live Demo"
},
{
"code": null,
"e": 3430,
"s": 3405,
"text": "> x6<-rpois(100,10)\n> x6"
},
{
"code": null,
"e": 3703,
"s": 3430,
"text": "[1] 2 12 7 25 12 5 6 13 15 4 11 10 10 7 12 9 8 14 9 9 12 12 7 10 13\n[26] 9 8 6 7 17 17 9 16 12 6 7 8 10 9 7 11 7 11 15 4 13 15 5 13 8\n[51] 8 12 13 12 8 11 9 15 7 13 7 10 9 8 14 10 14 6 10 6 6 8 15 7 9\n[76] 10 12 11 11 10 14 9 7 12 10 14 7 6 9 9 11 11 10 12 12 12 13 14 9 8"
},
{
"code": null,
"e": 3724,
"s": 3703,
"text": "> length(unique(x6))"
},
{
"code": null,
"e": 3731,
"s": 3724,
"text": "[1] 16"
},
{
"code": null,
"e": 3742,
"s": 3731,
"text": " Live Demo"
},
{
"code": null,
"e": 3774,
"s": 3742,
"text": "> x7<-rep(LETTERS[1:10],5)\n> x7"
},
{
"code": null,
"e": 3988,
"s": 3774,
"text": "[1] \"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\" \"J\" \"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\"\n[20] \"J\" \"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\" \"J\" \"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\"\n[39] \"I\" \"J\" \"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\" \"J\""
},
{
"code": null,
"e": 4009,
"s": 3988,
"text": "> length(unique(x7))"
},
{
"code": null,
"e": 4016,
"s": 4009,
"text": "[1] 10"
},
{
"code": null,
"e": 4027,
"s": 4016,
"text": " Live Demo"
},
{
"code": null,
"e": 4076,
"s": 4027,
"text": "> x8<-sample(LETTERS[1:26],50,replace=TRUE)\n> x8"
},
{
"code": null,
"e": 4290,
"s": 4076,
"text": "[1] \"U\" \"P\" \"G\" \"Y\" \"J\" \"S\" \"Z\" \"C\" \"Y\" \"M\" \"P\" \"S\" \"N\" \"S\" \"J\" \"B\" \"P\" \"K\" \"S\"\n[20] \"X\" \"C\" \"G\" \"V\" \"W\" \"X\" \"L\" \"H\" \"W\" \"M\" \"T\" \"U\" \"R\" \"J\" \"B\" \"I\" \"S\" \"L\" \"J\"\n[39] \"X\" \"L\" \"Y\" \"W\" \"F\" \"H\" \"W\" \"M\" \"K\" \"M\" \"B\" \"H\""
},
{
"code": null,
"e": 4311,
"s": 4290,
"text": "> length(unique(x8))"
},
{
"code": null,
"e": 4318,
"s": 4311,
"text": "[1] 21"
},
{
"code": null,
"e": 4329,
"s": 4318,
"text": " Live Demo"
},
{
"code": null,
"e": 4378,
"s": 4329,
"text": "> x9<-sample(letters[1:26],50,replace=TRUE)\n> x9"
},
{
"code": null,
"e": 4592,
"s": 4378,
"text": "[1] \"l\" \"s\" \"v\" \"w\" \"t\" \"c\" \"d\" \"u\" \"u\" \"l\" \"x\" \"m\" \"g\" \"v\" \"x\" \"z\" \"v\" \"w\" \"c\"\n[20] \"e\" \"t\" \"t\" \"v\" \"o\" \"w\" \"f\" \"j\" \"m\" \"y\" \"w\" \"l\" \"q\" \"r\" \"t\" \"g\" \"n\" \"j\" \"p\"\n[39] \"a\" \"x\" \"i\" \"c\" \"k\" \"h\" \"z\" \"d\" \"q\" \"e\" \"w\" \"j\""
},
{
"code": null,
"e": 4613,
"s": 4592,
"text": "> length(unique(x9))"
},
{
"code": null,
"e": 4620,
"s": 4613,
"text": "[1] 25"
},
{
"code": null,
"e": 4631,
"s": 4620,
"text": " Live Demo"
},
{
"code": null,
"e": 4662,
"s": 4631,
"text": "> x10<-rbinom(50,10,0.5)\n> x10"
},
{
"code": null,
"e": 4771,
"s": 4662,
"text": "[1] 2 4 4 7 6 5 5 4 1 8 6 4 6 7 5 6 4 6 8 5 5 6 5 2 3 3 3 5 3 5 4 5 7 5 8 5 7 6\n[39] 7 4 5 2 3 5 4 6 1 7 4 5"
},
{
"code": null,
"e": 4793,
"s": 4771,
"text": "> length(unique(x10))"
},
{
"code": null,
"e": 4799,
"s": 4793,
"text": "[1] 8"
}
] |
Python | Binning method for data smoothing - GeeksforGeeks
|
13 Apr, 2022
Prerequisite: ML | Binning or Discretization Binning method is used to smoothing data or to handle noisy data. In this method, the data is first sorted and then the sorted values are distributed into a number of buckets or bins. As binning methods consult the neighbourhood of values, they perform local smoothing. There are three approaches to performing smoothing –
Smoothing by bin means : In smoothing by bin means, each value in a bin is replaced by the mean value of the bin. Smoothing by bin median : In this method each bin value is replaced by its bin median value. Smoothing by bin boundary : In smoothing by bin boundaries, the minimum and maximum values in a given bin are identified as the bin boundaries. Each bin value is then replaced by the closest boundary value.
Approach:
Sort the array of a given data set.Divides the range into N intervals, each containing the approximately same number of samples(Equal-depth partitioning).Store mean/ median/ boundaries in each row.
Sort the array of a given data set.
Divides the range into N intervals, each containing the approximately same number of samples(Equal-depth partitioning).
Store mean/ median/ boundaries in each row.
Examples:
Sorted data for price (in dollars): 4, 8, 9, 15, 21, 21, 24, 25, 26, 28, 29, 34
Partition using equal frequency approach:
- Bin 1 : 4, 8, 9, 15
- Bin 2 : 21, 21, 24, 25
- Bin 3 : 26, 28, 29, 34
Smoothing by bin means:
- Bin 1: 9, 9, 9, 9
- Bin 2: 23, 23, 23, 23
- Bin 3: 29, 29, 29, 29
Smoothing by bin boundaries:
- Bin 1: 4, 4, 4, 15
- Bin 2: 21, 21, 25, 25
- Bin 3: 26, 26, 26, 34
Smoothing by bin median:
- Bin 1: 9 9, 9, 9
- Bin 2: 23, 23, 23, 23
- Bin 3: 29, 29, 29, 29
Below is the Python implementation for the above algorithm –
Python3
import numpy as npimport mathfrom sklearn.datasets import load_irisfrom sklearn import datasets, linear_model, metrics # load iris data setdataset = load_iris()a = dataset.datab = np.zeros(150) # take 1st column among 4 column of data setfor i in range (150): b[i]=a[i,1] b=np.sort(b) #sort the array # create binsbin1=np.zeros((30,5))bin2=np.zeros((30,5))bin3=np.zeros((30,5)) # Bin meanfor i in range (0,150,5): k=int(i/5) mean=(b[i] + b[i+1] + b[i+2] + b[i+3] + b[i+4])/5 for j in range(5): bin1[k,j]=meanprint("Bin Mean: \n",bin1) # Bin boundariesfor i in range (0,150,5): k=int(i/5) for j in range (5): if (b[i+j]-b[i]) < (b[i+4]-b[i+j]): bin2[k,j]=b[i] else: bin2[k,j]=b[i+4] print("Bin Boundaries: \n",bin2) # Bin medianfor i in range (0,150,5): k=int(i/5) for j in range (5): bin3[k,j]=b[i+2]print("Bin Median: \n",bin3)
user282
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Linear Regression
Python | Decision tree implementation
Search Algorithms in AI
Difference between Informed and Uninformed Search in AI
Decision Tree Introduction with example
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 23859,
"s": 23831,
"text": "\n13 Apr, 2022"
},
{
"code": null,
"e": 24227,
"s": 23859,
"text": "Prerequisite: ML | Binning or Discretization Binning method is used to smoothing data or to handle noisy data. In this method, the data is first sorted and then the sorted values are distributed into a number of buckets or bins. As binning methods consult the neighbourhood of values, they perform local smoothing. There are three approaches to performing smoothing –"
},
{
"code": null,
"e": 24641,
"s": 24227,
"text": "Smoothing by bin means : In smoothing by bin means, each value in a bin is replaced by the mean value of the bin. Smoothing by bin median : In this method each bin value is replaced by its bin median value. Smoothing by bin boundary : In smoothing by bin boundaries, the minimum and maximum values in a given bin are identified as the bin boundaries. Each bin value is then replaced by the closest boundary value."
},
{
"code": null,
"e": 24651,
"s": 24641,
"text": "Approach:"
},
{
"code": null,
"e": 24849,
"s": 24651,
"text": "Sort the array of a given data set.Divides the range into N intervals, each containing the approximately same number of samples(Equal-depth partitioning).Store mean/ median/ boundaries in each row."
},
{
"code": null,
"e": 24885,
"s": 24849,
"text": "Sort the array of a given data set."
},
{
"code": null,
"e": 25005,
"s": 24885,
"text": "Divides the range into N intervals, each containing the approximately same number of samples(Equal-depth partitioning)."
},
{
"code": null,
"e": 25049,
"s": 25005,
"text": "Store mean/ median/ boundaries in each row."
},
{
"code": null,
"e": 25059,
"s": 25049,
"text": "Examples:"
},
{
"code": null,
"e": 25611,
"s": 25059,
"text": "Sorted data for price (in dollars): 4, 8, 9, 15, 21, 21, 24, 25, 26, 28, 29, 34\n\nPartition using equal frequency approach:\n - Bin 1 : 4, 8, 9, 15\n - Bin 2 : 21, 21, 24, 25\n - Bin 3 : 26, 28, 29, 34\n\nSmoothing by bin means:\n - Bin 1: 9, 9, 9, 9\n - Bin 2: 23, 23, 23, 23\n - Bin 3: 29, 29, 29, 29\n\nSmoothing by bin boundaries:\n - Bin 1: 4, 4, 4, 15\n - Bin 2: 21, 21, 25, 25\n - Bin 3: 26, 26, 26, 34\n\nSmoothing by bin median:\n - Bin 1: 9 9, 9, 9\n - Bin 2: 23, 23, 23, 23\n - Bin 3: 29, 29, 29, 29"
},
{
"code": null,
"e": 25675,
"s": 25611,
"text": " Below is the Python implementation for the above algorithm – "
},
{
"code": null,
"e": 25683,
"s": 25675,
"text": "Python3"
},
{
"code": "import numpy as npimport mathfrom sklearn.datasets import load_irisfrom sklearn import datasets, linear_model, metrics # load iris data setdataset = load_iris()a = dataset.datab = np.zeros(150) # take 1st column among 4 column of data setfor i in range (150): b[i]=a[i,1] b=np.sort(b) #sort the array # create binsbin1=np.zeros((30,5))bin2=np.zeros((30,5))bin3=np.zeros((30,5)) # Bin meanfor i in range (0,150,5): k=int(i/5) mean=(b[i] + b[i+1] + b[i+2] + b[i+3] + b[i+4])/5 for j in range(5): bin1[k,j]=meanprint(\"Bin Mean: \\n\",bin1) # Bin boundariesfor i in range (0,150,5): k=int(i/5) for j in range (5): if (b[i+j]-b[i]) < (b[i+4]-b[i+j]): bin2[k,j]=b[i] else: bin2[k,j]=b[i+4] print(\"Bin Boundaries: \\n\",bin2) # Bin medianfor i in range (0,150,5): k=int(i/5) for j in range (5): bin3[k,j]=b[i+2]print(\"Bin Median: \\n\",bin3)",
"e": 26592,
"s": 25683,
"text": null
},
{
"code": null,
"e": 26600,
"s": 26592,
"text": "user282"
},
{
"code": null,
"e": 26617,
"s": 26600,
"text": "Machine Learning"
},
{
"code": null,
"e": 26624,
"s": 26617,
"text": "Python"
},
{
"code": null,
"e": 26641,
"s": 26624,
"text": "Machine Learning"
},
{
"code": null,
"e": 26739,
"s": 26641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26748,
"s": 26739,
"text": "Comments"
},
{
"code": null,
"e": 26761,
"s": 26748,
"text": "Old Comments"
},
{
"code": null,
"e": 26784,
"s": 26761,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 26822,
"s": 26784,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 26846,
"s": 26822,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 26902,
"s": 26846,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 26942,
"s": 26902,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 26970,
"s": 26942,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27020,
"s": 26970,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 27042,
"s": 27020,
"text": "Python map() function"
}
] |
Train GPT-2 in your own language. A step-by-step guide to train your own... | by Arshabhi Kayal | Towards Data Science
|
We all know modern day Natural Language Processing (NLP) has progressed by leaps and bounds in the past couple of years following the development of attention networks and transformers. It paved the way for a plethora of new algorithms achieving State-Of-The-Art (SOTA) for the different tasks of NLP.
OpenAI has been one of the leaders in providing their own language model (now released GPT-3) which is trained on a huge corpus of internet data. Since, GPT-3 is a recent phenomenon and in English at the moment, and is only accessible through API given by OpenAI, we shift our focus on the earlier version of it i.e. GPT-2. To know about the internal nuts and bolts of GPT-2, I’d suggest you to go through this link. For more depths into Attention and Transformers, here are some excellent links:
The illustrated Transformer by Jay Alammar
The Annotated Transformer by Harvard NLP
GPT-2 was also released for English, which makes it difficult for someone trying to generate text in a different language.
So why not train your own GPT-2 model on your favourite language for text generation? That is exactly what we are going to do. So, without further ado, let us jump in.
For the demo, I have considered a non-Latin alphabet script (Bengali here), because why not!! I have used Huggingface’s implementation for the model.
Gathering good quality data is one of the most important stages as all Data Scientists would agree. So, we are going to assume that you already have a folder containing .txt files having all the data cleaned and stored. For ease, you can use the Wikipedia article data, which is available and can be downloaded with the following code.
python wikipedia_download.py --lang bn
This will create a folder containing all Wikipedia files looking like:
Note: due to resource constraint, and since it is for demo purpose, I have trained the model in a small subset of books by Satyajit Ray, especially his detective Feluda series.
Now, the second step will be to tokenize the data. For that, we use the following class.
We use BPE (Byte Pair Encoding), which is a sub word encoding, this generally takes care of not treating different forms of word as different. (e.g. greatest will be treated as two tokens: ‘great’ and ‘est’ which is advantageous since it retains the similarity between great and greatest, while ‘greatest’ has another token ‘est’ added which makes it different). Also, it is not as low level as character-level encoding, which doesn’t retain any value of a particular word.
Another small but subtle point is NFKC (Normalization Form Compatibility Composition) in line 13 of code. It is one of the standard Unicode compatibility form. It would not matter much if the language is English, but since we are using Bengali, which contains a different form of character, we are using this specific one. More on it can be found in this link
So what we do here is tokenize our data and save it in a folder. Two files will be created (merges.txt and vocab.json) in a specified directory. To run the file, use the following code:
from tokenise import BPE_tokenfrom pathlib import Pathimport os# the folder 'text' contains all the filespaths = [str(x) for x in Path("./text/").glob("**/*.txt")]tokenizer = BPE_token()# train the tokenizer modeltokenizer.bpe_train(paths)# saving the tokenized data in our specified folder save_path = 'tokenized_data'tokenizer.save_tokenizer(save_path)
Before the real magic begins, we need to make sure the artilleries are ready. Let us start with some initializations.
import tensorflow as tffrom transformers import GPT2Config, TFGPT2LMHeadModel, GPT2Tokenizer# loading tokenizer from the saved model pathtokenizer = GPT2Tokenizer.from_pretrained(save_path)tokenizer.add_special_tokens({ "eos_token": "</s>", "bos_token": "<s>", "unk_token": "<unk>", "pad_token": "<pad>", "mask_token": "<mask>"})# creating the configurations from which the model can be madeconfig = GPT2Config( vocab_size=tokenizer.vocab_size, bos_token_id=tokenizer.bos_token_id, eos_token_id=tokenizer.eos_token_id)# creating the modelmodel = TFGPT2LMHeadModel(config)
We also create a single string from all our documents and tokenize it.
single_string = ''for filename in paths: with open(filename, "r", encoding='utf-8') as f: x = f.read() single_string += x + tokenizer.eos_tokenstring_tokenized = tokenizer.encode(single_string)
After we have encoded the whole string, we now move on to make a TensorFlow dataset, slicing the data into equal intervals, so that our model can learn. Here we use a block size of 100 (length of token in each example) and a batch size of 16. This is kept low else we can run it with ease on a RTX 2060 GPU.
examples = []block_size = 100BATCH_SIZE = 12BUFFER_SIZE = 1000for i in range(0, len(string_tokenized) - block_size + 1, block_size): examples.append(string_tokenized[i:i + block_size])inputs, labels = [], []for ex in examples: inputs.append(ex[:-1]) labels.append(ex[1:])dataset = tf.data.Dataset.from_tensor_slices((inputs, labels))dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)
Now comes the part we’ve been waiting for, making the model and training. So we define our optimizer, loss functions and the metrics, and start training.
# defining our optimizeroptimizer = tf.keras.optimizers.Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0)# definining our loss functionloss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)# defining our metric which we want to observemetric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')# compiling the modelmodel.compile(optimizer=optimizer, loss=[loss, *[None] * model.config.n_layer], metrics=[metric])
Now, let’s train the model
num_epoch = 10history = model.fit(dataset, epochs=num_epoch)
To predict, we just need to simply encode the input text and pass it to the model
text = "লালমোহনবাবু "# encoding the input textinput_ids = tokenizer.encode(text, return_tensors='tf')# getting out outputbeam_output = model.generate( input_ids, max_length = 50, num_beams = 5, temperature = 0.7, no_repeat_ngram_size=2, num_return_sequences=5)
Now, if you are a Bengali, then you can point it out that the output although the sentence is syntactically correct, it doesn’t look cohesive. True, but for this demo, I have kept this demo a minimal as possible.
Well, after long training time, what good will it do if we close our session and all our trained model is just lost and we again need to train it from scratch. So, let’s save the model and the tokenizer so that we can retrain from where we left off
from transformers import WEIGHTS_NAME, CONFIG_NAMEimport osoutput_dir = './model_bn_custom/'# creating directory if it is not presentif not os.path.exists(output_dir): os.mkdir(output_dir)model_to_save = model.module if hasattr(model, 'module') else modeloutput_model_file = os.path.join(output_dir, WEIGHTS_NAME)output_config_file = os.path.join(output_dir, CONFIG_NAME)# save model and model configsmodel.save_pretrained(output_dir)model_to_save.config.to_json_file(output_config_file)# save tokenizertokenizer.save_pretrained(output_dir)
We have already done all the hard work, so to load the saved model and tokenizer, we only need to execute two lines of code and we’re all set.
tokenizer = GPT2Tokenizer.from_pretrained(output_dir)model = TFGPT2LMHeadModel.from_pretrained(output_dir)
Voila! Now you can train your own model in your own language. And create content which can race with some of the best literary works in any language.
This blog gives a framework of how can one train GPT-2 model in any language. This is not at par with some of the pre-trained model available, but to reach that state, we need a lot of training data and computational power.
|
[
{
"code": null,
"e": 474,
"s": 172,
"text": "We all know modern day Natural Language Processing (NLP) has progressed by leaps and bounds in the past couple of years following the development of attention networks and transformers. It paved the way for a plethora of new algorithms achieving State-Of-The-Art (SOTA) for the different tasks of NLP."
},
{
"code": null,
"e": 971,
"s": 474,
"text": "OpenAI has been one of the leaders in providing their own language model (now released GPT-3) which is trained on a huge corpus of internet data. Since, GPT-3 is a recent phenomenon and in English at the moment, and is only accessible through API given by OpenAI, we shift our focus on the earlier version of it i.e. GPT-2. To know about the internal nuts and bolts of GPT-2, I’d suggest you to go through this link. For more depths into Attention and Transformers, here are some excellent links:"
},
{
"code": null,
"e": 1014,
"s": 971,
"text": "The illustrated Transformer by Jay Alammar"
},
{
"code": null,
"e": 1055,
"s": 1014,
"text": "The Annotated Transformer by Harvard NLP"
},
{
"code": null,
"e": 1178,
"s": 1055,
"text": "GPT-2 was also released for English, which makes it difficult for someone trying to generate text in a different language."
},
{
"code": null,
"e": 1346,
"s": 1178,
"text": "So why not train your own GPT-2 model on your favourite language for text generation? That is exactly what we are going to do. So, without further ado, let us jump in."
},
{
"code": null,
"e": 1496,
"s": 1346,
"text": "For the demo, I have considered a non-Latin alphabet script (Bengali here), because why not!! I have used Huggingface’s implementation for the model."
},
{
"code": null,
"e": 1832,
"s": 1496,
"text": "Gathering good quality data is one of the most important stages as all Data Scientists would agree. So, we are going to assume that you already have a folder containing .txt files having all the data cleaned and stored. For ease, you can use the Wikipedia article data, which is available and can be downloaded with the following code."
},
{
"code": null,
"e": 1871,
"s": 1832,
"text": "python wikipedia_download.py --lang bn"
},
{
"code": null,
"e": 1942,
"s": 1871,
"text": "This will create a folder containing all Wikipedia files looking like:"
},
{
"code": null,
"e": 2119,
"s": 1942,
"text": "Note: due to resource constraint, and since it is for demo purpose, I have trained the model in a small subset of books by Satyajit Ray, especially his detective Feluda series."
},
{
"code": null,
"e": 2208,
"s": 2119,
"text": "Now, the second step will be to tokenize the data. For that, we use the following class."
},
{
"code": null,
"e": 2682,
"s": 2208,
"text": "We use BPE (Byte Pair Encoding), which is a sub word encoding, this generally takes care of not treating different forms of word as different. (e.g. greatest will be treated as two tokens: ‘great’ and ‘est’ which is advantageous since it retains the similarity between great and greatest, while ‘greatest’ has another token ‘est’ added which makes it different). Also, it is not as low level as character-level encoding, which doesn’t retain any value of a particular word."
},
{
"code": null,
"e": 3042,
"s": 2682,
"text": "Another small but subtle point is NFKC (Normalization Form Compatibility Composition) in line 13 of code. It is one of the standard Unicode compatibility form. It would not matter much if the language is English, but since we are using Bengali, which contains a different form of character, we are using this specific one. More on it can be found in this link"
},
{
"code": null,
"e": 3228,
"s": 3042,
"text": "So what we do here is tokenize our data and save it in a folder. Two files will be created (merges.txt and vocab.json) in a specified directory. To run the file, use the following code:"
},
{
"code": null,
"e": 3583,
"s": 3228,
"text": "from tokenise import BPE_tokenfrom pathlib import Pathimport os# the folder 'text' contains all the filespaths = [str(x) for x in Path(\"./text/\").glob(\"**/*.txt\")]tokenizer = BPE_token()# train the tokenizer modeltokenizer.bpe_train(paths)# saving the tokenized data in our specified folder save_path = 'tokenized_data'tokenizer.save_tokenizer(save_path)"
},
{
"code": null,
"e": 3701,
"s": 3583,
"text": "Before the real magic begins, we need to make sure the artilleries are ready. Let us start with some initializations."
},
{
"code": null,
"e": 4281,
"s": 3701,
"text": "import tensorflow as tffrom transformers import GPT2Config, TFGPT2LMHeadModel, GPT2Tokenizer# loading tokenizer from the saved model pathtokenizer = GPT2Tokenizer.from_pretrained(save_path)tokenizer.add_special_tokens({ \"eos_token\": \"</s>\", \"bos_token\": \"<s>\", \"unk_token\": \"<unk>\", \"pad_token\": \"<pad>\", \"mask_token\": \"<mask>\"})# creating the configurations from which the model can be madeconfig = GPT2Config( vocab_size=tokenizer.vocab_size, bos_token_id=tokenizer.bos_token_id, eos_token_id=tokenizer.eos_token_id)# creating the modelmodel = TFGPT2LMHeadModel(config)"
},
{
"code": null,
"e": 4352,
"s": 4281,
"text": "We also create a single string from all our documents and tokenize it."
},
{
"code": null,
"e": 4550,
"s": 4352,
"text": "single_string = ''for filename in paths: with open(filename, \"r\", encoding='utf-8') as f: x = f.read() single_string += x + tokenizer.eos_tokenstring_tokenized = tokenizer.encode(single_string)"
},
{
"code": null,
"e": 4858,
"s": 4550,
"text": "After we have encoded the whole string, we now move on to make a TensorFlow dataset, slicing the data into equal intervals, so that our model can learn. Here we use a block size of 100 (length of token in each example) and a batch size of 16. This is kept low else we can run it with ease on a RTX 2060 GPU."
},
{
"code": null,
"e": 5272,
"s": 4858,
"text": "examples = []block_size = 100BATCH_SIZE = 12BUFFER_SIZE = 1000for i in range(0, len(string_tokenized) - block_size + 1, block_size): examples.append(string_tokenized[i:i + block_size])inputs, labels = [], []for ex in examples: inputs.append(ex[:-1]) labels.append(ex[1:])dataset = tf.data.Dataset.from_tensor_slices((inputs, labels))dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)"
},
{
"code": null,
"e": 5426,
"s": 5272,
"text": "Now comes the part we’ve been waiting for, making the model and training. So we define our optimizer, loss functions and the metrics, and start training."
},
{
"code": null,
"e": 5863,
"s": 5426,
"text": "# defining our optimizeroptimizer = tf.keras.optimizers.Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0)# definining our loss functionloss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)# defining our metric which we want to observemetric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')# compiling the modelmodel.compile(optimizer=optimizer, loss=[loss, *[None] * model.config.n_layer], metrics=[metric])"
},
{
"code": null,
"e": 5890,
"s": 5863,
"text": "Now, let’s train the model"
},
{
"code": null,
"e": 5951,
"s": 5890,
"text": "num_epoch = 10history = model.fit(dataset, epochs=num_epoch)"
},
{
"code": null,
"e": 6033,
"s": 5951,
"text": "To predict, we just need to simply encode the input text and pass it to the model"
},
{
"code": null,
"e": 6301,
"s": 6033,
"text": "text = \"লালমোহনবাবু \"# encoding the input textinput_ids = tokenizer.encode(text, return_tensors='tf')# getting out outputbeam_output = model.generate( input_ids, max_length = 50, num_beams = 5, temperature = 0.7, no_repeat_ngram_size=2, num_return_sequences=5)"
},
{
"code": null,
"e": 6514,
"s": 6301,
"text": "Now, if you are a Bengali, then you can point it out that the output although the sentence is syntactically correct, it doesn’t look cohesive. True, but for this demo, I have kept this demo a minimal as possible."
},
{
"code": null,
"e": 6763,
"s": 6514,
"text": "Well, after long training time, what good will it do if we close our session and all our trained model is just lost and we again need to train it from scratch. So, let’s save the model and the tokenizer so that we can retrain from where we left off"
},
{
"code": null,
"e": 7305,
"s": 6763,
"text": "from transformers import WEIGHTS_NAME, CONFIG_NAMEimport osoutput_dir = './model_bn_custom/'# creating directory if it is not presentif not os.path.exists(output_dir): os.mkdir(output_dir)model_to_save = model.module if hasattr(model, 'module') else modeloutput_model_file = os.path.join(output_dir, WEIGHTS_NAME)output_config_file = os.path.join(output_dir, CONFIG_NAME)# save model and model configsmodel.save_pretrained(output_dir)model_to_save.config.to_json_file(output_config_file)# save tokenizertokenizer.save_pretrained(output_dir)"
},
{
"code": null,
"e": 7448,
"s": 7305,
"text": "We have already done all the hard work, so to load the saved model and tokenizer, we only need to execute two lines of code and we’re all set."
},
{
"code": null,
"e": 7555,
"s": 7448,
"text": "tokenizer = GPT2Tokenizer.from_pretrained(output_dir)model = TFGPT2LMHeadModel.from_pretrained(output_dir)"
},
{
"code": null,
"e": 7705,
"s": 7555,
"text": "Voila! Now you can train your own model in your own language. And create content which can race with some of the best literary works in any language."
}
] |
String compareToIgnoreCase() Method
|
This method compares two strings lexicographically, ignoring case differences.
Here is the syntax of this method −
int compareToIgnoreCase(String str)
Here is the detail of parameters −
str − the String to be compared.
str − the String to be compared.
This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations.
This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations.
public class Test {
public static void main(String args[]) {
String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";
int result = str1.compareToIgnoreCase( str2 );
System.out.println(result);
result = str2.compareToIgnoreCase( str3 );
System.out.println(result);
result = str3.compareToIgnoreCase( str1 );
System.out.println(result);
}
}
This will produce the following result −
0
10
-10
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": 2456,
"s": 2377,
"text": "This method compares two strings lexicographically, ignoring case differences."
},
{
"code": null,
"e": 2492,
"s": 2456,
"text": "Here is the syntax of this method −"
},
{
"code": null,
"e": 2529,
"s": 2492,
"text": "int compareToIgnoreCase(String str)\n"
},
{
"code": null,
"e": 2564,
"s": 2529,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2597,
"s": 2564,
"text": "str − the String to be compared."
},
{
"code": null,
"e": 2630,
"s": 2597,
"text": "str − the String to be compared."
},
{
"code": null,
"e": 2805,
"s": 2630,
"text": "This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations."
},
{
"code": null,
"e": 2980,
"s": 2805,
"text": "This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations."
},
{
"code": null,
"e": 3448,
"s": 2980,
"text": "public class Test {\n\n public static void main(String args[]) {\n String str1 = \"Strings are immutable\";\n String str2 = \"Strings are immutable\";\n String str3 = \"Integers are not immutable\";\n\n int result = str1.compareToIgnoreCase( str2 );\n System.out.println(result);\n\n result = str2.compareToIgnoreCase( str3 );\n System.out.println(result);\n\n result = str3.compareToIgnoreCase( str1 );\n System.out.println(result);\n }\n}"
},
{
"code": null,
"e": 3489,
"s": 3448,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3499,
"s": 3489,
"text": "0\n10\n-10\n"
},
{
"code": null,
"e": 3532,
"s": 3499,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3548,
"s": 3532,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3581,
"s": 3548,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3597,
"s": 3581,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3632,
"s": 3597,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3646,
"s": 3632,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3680,
"s": 3646,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3694,
"s": 3680,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3731,
"s": 3694,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3746,
"s": 3731,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3779,
"s": 3746,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3798,
"s": 3779,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3805,
"s": 3798,
"text": " Print"
},
{
"code": null,
"e": 3816,
"s": 3805,
"text": " Add Notes"
}
] |
NLP Based Information Retrieval System | by Nikhil Sharma | Towards Data Science
|
In this post, we will understand how to build a recommendation system with text data. Here text data is comprised of scholarly articles about COVID-19, SARS-COV-2, and related coronaviruses. The dataset is known as CORD-19, prepared by the White House and a coalition of leading research groups. This freely available dataset is provided to the global research community to apply recent advances in natural language processing and other AI techniques to generate new insights in support of the ongoing fight against this infectious disease. There is a growing urgency for these approaches because of the rapid acceleration in new coronavirus literature, making it difficult for the medical research community to keep up.
For this post, we will need Python 3.6, spacy, Tensorflow, NLTK, Dask, and we will install them step by step whenever required.
The dataset used here is from Kaggle competition. The dataset contains doc_id, source, title, abstract, and text body. doc_id is document id, the source is the place from where the paper is extracted like biorxiv, abstract is a summary of the paper, and text body is body or content of the research paper.
Our task is to retrieve information based on the following questions.
What is known about transmission, incubation, and environmental stability?
What do we know about natural history, transmission, and diagnostics for the virus? What have we learned about infection prevention and control?
Specifically, we want to know what the literature reports about:
Range of incubation periods for the disease in humans (and how this varies across age and health status) and how long individuals are contagious, even after recovery.
Prevalence of asymptomatic shedding and transmission (e.g., particularly children).
Seasonality of transmission.
Physical science of the coronavirus (e.g., charge distribution, adhesion to hydrophilic/phobic surfaces, environmental survival to inform decontamination efforts for affected areas and provide information about viral shedding).
Persistence and stability on a multitude of substrates and sources (e.g., nasal discharge, sputum, urine, fecal matter, blood).
Persistence of virus on surfaces of different materials (e,g., copper, stainless steel, plastic).
Natural history of the virus and shedding of it from an infected person
Implementation of diagnostics and products to improve clinical processes
Disease models, including animal models for infection, disease and transmission
Tools and studies to monitor phenotypic change and potential adaptation of the virus
Immune response and immunity
Effectiveness of movement control strategies to prevent secondary transmission in health care and community settings
Effectiveness of personal protective equipment (PPE) and its usefulness to reduce risk of transmission in health care and community settings
Role of the environment in transmission
Exploratory Data Analysis (EDA) is the process by which the data analyst becomes acquainted with their data in order to drive intuition. This process typically makes use of descriptive statistics and visualizations. Visually representing the content of a text document is one of the most important tasks in the field of text mining as a Data Scientist or NLP specialist. However, there are some gaps between visualizing unstructured (text) data and structured data.
It is a good practice to understand the data first and try to gather as many insights from it. EDA is all about making sense of data in hand, before getting them dirty with it.
Let’s install some required packages and import them. we will be using the scispacy for analysis. scispaCy is a Python package containing spaCy models for processing biomedical, scientific or clinical text.
import them as usual!!
When you call nlp on a text, spaCy first tokenizes the text to produce a Doc object. The Doc is then processed in several different steps – this is also referred to as the processing pipeline. The pipeline used by the default models consists of a tagger, a parser and an entity recognizer. Each pipeline component returns the processed Doc, which is then passed on to the next component.
tokenizer: Segment text into tokens.
tagger: Assign part-of-speech tags.
parser: Assign dependency labels.
ner: Detect and label named entities.
The processing pipeline always depends on the statistical model and its capabilities. For example, a pipeline can only include an entity recognizer component if the model includes data to make predictions of entity labels.
NOTE: you can create own pipeline components for further processing
now, create a function for cleaning data, this will remove all the stop words, punctuations, extra spaces, URLs, email, and currency. sometimes verbs, adverbs, pronouns are not required and can be removed. this function will return the base form of word which is known as lemmatization.
Text contains lots of abbreviations and full form, this code is used to extract all abbreviations and respective full forms within the text and put them in a dictionary where keys are abbreviations and values are full forms.
Now, we need to create a function to replace all abbreviations with their respective full forms.
similarily, we will create functions for removing email ids, weblink, paper references, extra spaces, unwanted characters, etc.
here, we’re going to use Dask for processing, Dask is a flexible library for parallel computing in python, provides multi-core execution on larger-than-memory datasets.
“Dask provides advanced parallelism for analytics, enabling performance at scale for the tools you love” — https://dask.pydata.org/en/latest/
now, call above function to preprocess text
The model is trained and optimized for greater-than-word length text, such as sentences, phrases or short paragraphs. It is trained on a variety of data sources and a variety of tasks with the aim of dynamically accommodating a wide variety of natural language understanding tasks. The input is variable length English text and the output is a 128-dimensional vector. The universal-sentence-encoder model has trained with a deep averaging network (DAN) encoder.
let's install required packages for USE
load model from its URL
now, split text body of research papers by new line into list separate paragraphs, so that we can create embeddings for each paragraph. for example, if a text has 100 paragraphs, then we will get a list of these 100 elements.
Convert the different list of paragraphs for each row of text into a single list
now create embeddings
this will return a tensor object of shape nx128, where n is the number of paragraphs or sentences, as number of sentences are 1052935, therefore the shape of tensor will be 1052935x128
TensorShape([1052935, 128])
Cosine similarity is a measure of similarity that can be used to compare documents or, say, give a ranking of documents with respect to a given vector of query words.
Mathematically, it measures the cosine of the angle between two vectors projected in a multi-dimensional space. In this context, the two vectors I am talking about are arrays containing the embeddings of two documents.
Let x and y be two vectors for comparison. Using the cosine measure as a similarity function, we have
where ||x|| is the Euclidean norm of vector x=(x1,x2,...,xn), defined as x1^2+x2^2+⋯+xn^2. Conceptually, it is the length of the vector. Similarly, ||y|| is the Euclidean norm of vector y. The measure computes the cosine of the angle between vectors x and y. A cosine value of 0 means that the two vectors are at 90 degrees to each other (orthogonal) and have no match. The closer the cosine value to 1, the smaller the angle, and the greater the match between vectors.
The cosine similarity is advantageous because even if the two similar documents are far apart by the Euclidean distance because of the size, they could still have a smaller angle between them. Smaller the angle, higher the similarity.
Please refer to a link to check more about cosine similarity.
This function extracts information from corpus, based upon query. it calculates cosine similarity of query with all paragraphs or sentences, standardize it to fix its range b/w 0 to 1, and return sentences based upon threshold.
4.8.1 Incubation period
output:
['statements of incubation period and sources of original incubation period data for', ' the incubation period of yellow fever is around 3-6 days. the incubation period of dengue fever is around 8-10 days.', ' the incubation period of lassa fever ranges from 3 to 21 days. symptoms of new world haemorrhagic fever typically develop over 7-14 days.', ]
Output:
' determination of the dynamics of disease transmission in geographically widespread areas global spread of foot-and-mouth disease; spread of newcastle disease virus in asia distinction between pathovars and nonpathovars pathogenic and nonpathogenic escherichia coli in petting zoos addressing hospital and institutional infectious disease problems',' respiratory viruses detected in outbreaks in institutions reflect those known to be major causes of acute respiratory disease in the community; prevalence varies based on geographic location, season, and detection methods . free access to such institutions by members of the community , in conjunction with communal close quarters of residents, creates an ideal environment for propagation of viral respiratory outbreaks .', ' incidence of infection within a community social economic status of the community season per capita water use time of day age distribution within the community chronic infections table 2 concentration of enteric viruses in feces.']
4.8.3 Role of environment in Transmission
Output:
[' disease control efforts can also make it challenging to determine effects of climate change on disease. for instance, if climate change causes range shifts of parasites from tropical to temperate countries, this might result in an overall reduction, rather than increase, in human diseases because temperate countries often have superior health infrastructures . regardless of the outcome of climate change on diseases, integrating control efforts into projections should improve predictions of future disease risk for humans and wildlife. furthermore, given that control measures could obscure increases in transmission, incorporating control measures into models could reveal underlying increases in disease risk that might otherwise be missed.', ' environmental variables can affect responses of mice in experimental situations. changes in respiratory epithelial physiology and function from elevated levels of ammonia, effects of temperature and humidity on metabolism, effects of light on eye lesions and retinal function, and effects of noise on neurophysiology are examples of complications that can vary with the form of insult and the strain of mouse employed. ', ' effects of meteorological factors on transmission. climate change can influence the occurrence and spread of infectious diseases through its effect on transmission. for example, climate change can cause air pollution and shortages of food and clean water , leading to changes of high-incidence areas and outbreak patterns, thereby affecting the occurrence and spread of infectious disease.', ' future studies that focused on other components of air pollution and environmental factors are necessary to more fully understand the possible impact on infectious disease transmission . studies are in need to establish the relationships between particle attachment and survival of influenza virus, and also methods should be developed to quantify airborne influenza virus and measure the concentration of influenza virus in ambient air especially for extremely low virus concentrations . we set the number of cases to zero on hot days due to there being no significant effect of pm 2.5 on influenza incidence on hot days .']
Output:
[' seasonal patterns were observed for hmpv, rhinovirus, enterovirus and influenza viruses with peak prevalence in late winter and spring . in addition, a seasonal pattern was detected for tuberculosis . no distinct seasonal patterns were observed for other microbes.', 'not disperse low pathogenic avian influenza virus during autumn migration .', 'the severity of seasonal influenza epidemics is unpredictable and influenced by the predominant circulating virus strains and level of immunity in the population . during peak community influenza activity, hospitals and emergency rooms may be overwhelmed by patients presenting with influenza-like illness and more severe disease , . illness attack rates may be higher among most age groups during pandemics than observed for seasonal influenza due to limited immunity among exposed populations . the re-emergence of highly pathogenic avian influenza a virus among poultry with sporadic transmission to exposed persons and the resulting high mortality has stimulated global influenza pandemic preparedness .',' the two gastrointestinal viruses in the study both also presented with winter seasonality, often with norovirus preceding rotavirus epidemics . norovirus and influenza a virus epidemics usually overlapped, but the norovirus epidemics had broader peaks, and numbers tended to start increasing earlier than influenza a virus diagnoses levels and decreased after the disappearance of influenza a virus. also, rotavirus outbreaks usually occurred before influenza a outbreaks started.','influenza viruses circulate in temperate climates from early autumn to late spring, and in tropical climates throughout the year with unpredictable peaks, usually occurring during the wet season and cooler months. routine surveillance for influenza and influenzalike illness can provide estimates of the relative severity of influenza seasons, and can also provide clinical specimens from which influenza viruses can be detected. this allows comparison of circulating influenza strains with vaccine strains in the current influenza season, and may provide potential vaccine strains for future seasons.]
(e.g., charge distribution, adhesion to hydrophilic/phobic surfaces, environmental survival to inform decontamination efforts for affected areas and provide information about viral shedding).
output:
[' antiadhesive surfaces target microbial adhesion usually by the interaction of antagonist physicochemical properties. easy-clean surfaces that are hydrophobic repel bacteria better than glass-coated controls , while hydrophilic surfaces favour water sheeting and subsequent cleaning. similarly, polyethylene glycol coated surfaces promote a hydrophilic interaction against bacteria, preventing attachment . the use of diamond-like carbon films has already been tried for medical implanted devices such as joint prostheses and stents in order to repel microbial adhesion . despite being non-toxic and appealing, the lack of biocidal properties may turn discouraging a more generalized implementation of such easy-clean technologies.', ' in vitro testing compared the adhesion of representative proteins, prokaryotes, and eukaryotes on nanostructured and flat si3n4 surfaces with lysine-coated glass slides as positive controls. flat si3n4 is moderately hydrophilic and known to vigorously promote cell adhesion and proliferation due to increased adsorption of proteins when compared to more hydrophilic surfaces 33,34. hence, we further increased the hydrophilicity of the si3n4 surface by varying the aspect-ratios of the nanostructures from 0.15 to 0.90 and systematically controlled surface hydrophilicity . once strong hydrophilicity is achieved , a nanostructure-mediated aqueous barrier forms on the surface and limits protein adsorption and cell adhesion to provide an anti-adhesion property 6,35,36.', ' for htcc nanofibers to become an adsorptive membrane material, the fibers must not dissolve in water. crosslinking of polymer structures is a common method to impart membrane stability in water soluble polymers. 21 pva fibers were crosslinked with maleic anhydride to create a filtration membrane. 22 htcc blended with polyvinyl alcohol was photo-crosslinked to impart antimicrobial resistance to the fibers. 10 glutaraldehyde vapor was used to crosslink htcc-pva fibers to create an antimicrobial surface. 7 here, we demonstrate that htcc nanofibers can be crosslinked while retaining their nonwoven structure and their ability to bind to negatively-charged viruses. we have explored the crosslinking conditions that give the greatest water stability. these conditions allowed for high virus removal. our model viruses include the non-enveloped porcine parvovirus , one of the smallest known mammalian viruses and the enveloped virus, sindbis virus. this nanofiber material has the potential to become an inexpensive defense against water-borne diseases.',
output:
[" therefore, china's advancements in research and development, technical and scientific capacity transferring can support african next generation of proactive scientists to develop more sensitive simplified diagnostic tools and reduce the costs of laboratory diagnosis and medical equipment. furthermore, research and development is needed in examining the biological mechanisms of stressors or risk factors exposure and health effects, assessing evidence-based mitigation or adaptation interventions and benefits . innovative solutions and breakthroughs in human-animal-environment fields would not only enable africa to meet its own growing needs, but also support integrating health systems, including strengthening the capacities of laboratory diagnostics and medical care, as well as establishing the china-africa platforms that could generate evidence-based low-cost, available and easy-to-use health packages and solutions for the reduction of public health burden.", ' 1. access to data and samples to enable and accelerate research, which would involve rapid sharing of epidemiological surveillance and clinical data to inform outbreak control strategies; incentives and platforms for open sharing and access to genomic sequencing data; access to specimen samples . 2. appropriate conduct of research, including improved ethical standards for research and development ; previous agreement about experimental protocols, such as trial design, to speed clinical trials when outbreaks strike; 80 access to clinical trial data, such as publication of negative and positive results; clear pathways for approval by stringent regulatory authorities and in countries of use; and building on and investing in research capacities in epidemicaff ected countries. 3. equitable access to the benefi ts of research, including priority, aff ordable access to newly developed health technologies for aff ected populations, including health workers; and ethical guidelines for rationing products with limited availability. an overarching framework is needed to bring coherence and fi ll gaps in the fragmented system of international rules shaping outbreak-related research (including the international health regulations, pandemic',' clinical laboratories are highly regulated, and general laboratory and testing requirements apply to all molecular diagnostic assays reported for patient care90. quality control is paramount, and methods must be developed to ensure analytic accuracy throughout the assay workflow. important quality control steps can include initial sample quality checks, library parameters , sequence data generation , recovery of internal controls and performance of external controls. validation data generated during assay development and implementation should be recorded and made available to laboratory inspectors or submitted to regulatory agencies, such as the fda in the usa or the european medicines agency in europe, for approval.', ' future applications of advanced molecular diagnostics in clinical laboratories will enhance significantly capabilities to diagnose bacterial, parasitic, and viral agents in the early course of disease through enhanced assay sensitivities and specificities and improved turnaround times, theoretically leading to more timely and directed therapeutic intervention. until such time, clinicians must continue to rely on clinical judgment and the diverse battery of traditional culture techniques, direct examination , and immunoassays that are available. cost considerations and the ever-increasing array of infectious agents responsible for infectious gastroenteritis will continue to drive the development of practice guidelines to assist practitioners with reasoned and reasonable approaches to management of diarrheal illnesses. ']
output:
[' this paper reviews animal models currently in use for the study of influenza pathogenesis and immune responses to influenza virus infections and to assess vaccine and antiviral drug efficacy. models that will be reviewed will include: models of benign influenza, typical severe seasonal influenza and pneumonia, influenza-associated sepsis, models using h5n1 viruses, models in which acute respiratory distress syndrome is induced, models of influenzaassociated neurologic disease, models for virus transmission studies, immunocompromised models, and models of host resistance.', ' pregnancy poses an increased risk of severe maternal illness due to a number of acute and chronic viral infections; the common rhinovirus, influenza virus, sars coronavirus and varicella zoster, hepatitis e/b, hiv and cytomegalovirus . viral infections can also lead to pre-term birth and other pregnancy complications . however, few murine models are available to study pathogenesis of viral infections.', ' coronaviruses can cause a variety of diseases in animals and humans . of economical importance are coronaviruses such as porcine transmissible gastroenteritis virus, bovine coronavirus, feline infectious peritonitis virus, and avian infectious bronchitis virus. mhv, a natural mouse pathogen, has been extensively studied in the context of host immune responses and pathogenesis . there are many different and well-characterized strains of mhv which, depending on organ tropism, virulence and host strain, can cause a wide array of diseases ranging from hepatitis, respiratory symptoms and gastroenteritis to cns infection, demyelination, and acute meningitis [2, 17, . therefore, by using appropriate combinations of virus and mouse strains, mhv infections provide suitable models for a number of diseases that are of medical importance, such as encephalitis, immune-mediated demyelination , hepatitis and acute respiratory infections .', ' although in most host-virus interaction studies typically protein-coding genes have been the center of attention, there are few examples of virus and host lncrna interactions in human and mouse models . for instance, hepatitis b virus infection altered lncrna profiles in patients, with about 4% of human lncrnas showing more than 2-fold changes in hbv infected liver tissue . winterling et al. identified a virus inducible lncrna, which is induced by vesicular stomatitis virus and several strains of influenza a virus .']
similarily, we can retrieve information for other queries, you just need to type query and call “recommend_text” function.
Refrences:
[1] Jiawei Han, Jian Pei, Micheline Kamber, Data Mining: Concepts and Techniques provides the concepts and techniques (2012), Elsevier Inc
[2] Daniel Cer, Yinfei Yang, Sheng-yi Kong, Nan Hua, Nicole Limtiaco, Rhomni St. John, Noah Constant, Mario Guajardo-Cespedes, Steve Yuan, Chris Tar, Yun-Hsuan Sung, Brian Strope, Ray Kurzweil, Universal Sentence Encoder (2018), arXiv.org
|
[
{
"code": null,
"e": 893,
"s": 172,
"text": "In this post, we will understand how to build a recommendation system with text data. Here text data is comprised of scholarly articles about COVID-19, SARS-COV-2, and related coronaviruses. The dataset is known as CORD-19, prepared by the White House and a coalition of leading research groups. This freely available dataset is provided to the global research community to apply recent advances in natural language processing and other AI techniques to generate new insights in support of the ongoing fight against this infectious disease. There is a growing urgency for these approaches because of the rapid acceleration in new coronavirus literature, making it difficult for the medical research community to keep up."
},
{
"code": null,
"e": 1021,
"s": 893,
"text": "For this post, we will need Python 3.6, spacy, Tensorflow, NLTK, Dask, and we will install them step by step whenever required."
},
{
"code": null,
"e": 1327,
"s": 1021,
"text": "The dataset used here is from Kaggle competition. The dataset contains doc_id, source, title, abstract, and text body. doc_id is document id, the source is the place from where the paper is extracted like biorxiv, abstract is a summary of the paper, and text body is body or content of the research paper."
},
{
"code": null,
"e": 1397,
"s": 1327,
"text": "Our task is to retrieve information based on the following questions."
},
{
"code": null,
"e": 1472,
"s": 1397,
"text": "What is known about transmission, incubation, and environmental stability?"
},
{
"code": null,
"e": 1617,
"s": 1472,
"text": "What do we know about natural history, transmission, and diagnostics for the virus? What have we learned about infection prevention and control?"
},
{
"code": null,
"e": 1682,
"s": 1617,
"text": "Specifically, we want to know what the literature reports about:"
},
{
"code": null,
"e": 1849,
"s": 1682,
"text": "Range of incubation periods for the disease in humans (and how this varies across age and health status) and how long individuals are contagious, even after recovery."
},
{
"code": null,
"e": 1933,
"s": 1849,
"text": "Prevalence of asymptomatic shedding and transmission (e.g., particularly children)."
},
{
"code": null,
"e": 1962,
"s": 1933,
"text": "Seasonality of transmission."
},
{
"code": null,
"e": 2190,
"s": 1962,
"text": "Physical science of the coronavirus (e.g., charge distribution, adhesion to hydrophilic/phobic surfaces, environmental survival to inform decontamination efforts for affected areas and provide information about viral shedding)."
},
{
"code": null,
"e": 2318,
"s": 2190,
"text": "Persistence and stability on a multitude of substrates and sources (e.g., nasal discharge, sputum, urine, fecal matter, blood)."
},
{
"code": null,
"e": 2416,
"s": 2318,
"text": "Persistence of virus on surfaces of different materials (e,g., copper, stainless steel, plastic)."
},
{
"code": null,
"e": 2488,
"s": 2416,
"text": "Natural history of the virus and shedding of it from an infected person"
},
{
"code": null,
"e": 2561,
"s": 2488,
"text": "Implementation of diagnostics and products to improve clinical processes"
},
{
"code": null,
"e": 2641,
"s": 2561,
"text": "Disease models, including animal models for infection, disease and transmission"
},
{
"code": null,
"e": 2726,
"s": 2641,
"text": "Tools and studies to monitor phenotypic change and potential adaptation of the virus"
},
{
"code": null,
"e": 2755,
"s": 2726,
"text": "Immune response and immunity"
},
{
"code": null,
"e": 2872,
"s": 2755,
"text": "Effectiveness of movement control strategies to prevent secondary transmission in health care and community settings"
},
{
"code": null,
"e": 3013,
"s": 2872,
"text": "Effectiveness of personal protective equipment (PPE) and its usefulness to reduce risk of transmission in health care and community settings"
},
{
"code": null,
"e": 3053,
"s": 3013,
"text": "Role of the environment in transmission"
},
{
"code": null,
"e": 3519,
"s": 3053,
"text": "Exploratory Data Analysis (EDA) is the process by which the data analyst becomes acquainted with their data in order to drive intuition. This process typically makes use of descriptive statistics and visualizations. Visually representing the content of a text document is one of the most important tasks in the field of text mining as a Data Scientist or NLP specialist. However, there are some gaps between visualizing unstructured (text) data and structured data."
},
{
"code": null,
"e": 3696,
"s": 3519,
"text": "It is a good practice to understand the data first and try to gather as many insights from it. EDA is all about making sense of data in hand, before getting them dirty with it."
},
{
"code": null,
"e": 3903,
"s": 3696,
"text": "Let’s install some required packages and import them. we will be using the scispacy for analysis. scispaCy is a Python package containing spaCy models for processing biomedical, scientific or clinical text."
},
{
"code": null,
"e": 3926,
"s": 3903,
"text": "import them as usual!!"
},
{
"code": null,
"e": 4314,
"s": 3926,
"text": "When you call nlp on a text, spaCy first tokenizes the text to produce a Doc object. The Doc is then processed in several different steps – this is also referred to as the processing pipeline. The pipeline used by the default models consists of a tagger, a parser and an entity recognizer. Each pipeline component returns the processed Doc, which is then passed on to the next component."
},
{
"code": null,
"e": 4351,
"s": 4314,
"text": "tokenizer: Segment text into tokens."
},
{
"code": null,
"e": 4387,
"s": 4351,
"text": "tagger: Assign part-of-speech tags."
},
{
"code": null,
"e": 4421,
"s": 4387,
"text": "parser: Assign dependency labels."
},
{
"code": null,
"e": 4459,
"s": 4421,
"text": "ner: Detect and label named entities."
},
{
"code": null,
"e": 4682,
"s": 4459,
"text": "The processing pipeline always depends on the statistical model and its capabilities. For example, a pipeline can only include an entity recognizer component if the model includes data to make predictions of entity labels."
},
{
"code": null,
"e": 4750,
"s": 4682,
"text": "NOTE: you can create own pipeline components for further processing"
},
{
"code": null,
"e": 5037,
"s": 4750,
"text": "now, create a function for cleaning data, this will remove all the stop words, punctuations, extra spaces, URLs, email, and currency. sometimes verbs, adverbs, pronouns are not required and can be removed. this function will return the base form of word which is known as lemmatization."
},
{
"code": null,
"e": 5262,
"s": 5037,
"text": "Text contains lots of abbreviations and full form, this code is used to extract all abbreviations and respective full forms within the text and put them in a dictionary where keys are abbreviations and values are full forms."
},
{
"code": null,
"e": 5359,
"s": 5262,
"text": "Now, we need to create a function to replace all abbreviations with their respective full forms."
},
{
"code": null,
"e": 5487,
"s": 5359,
"text": "similarily, we will create functions for removing email ids, weblink, paper references, extra spaces, unwanted characters, etc."
},
{
"code": null,
"e": 5656,
"s": 5487,
"text": "here, we’re going to use Dask for processing, Dask is a flexible library for parallel computing in python, provides multi-core execution on larger-than-memory datasets."
},
{
"code": null,
"e": 5798,
"s": 5656,
"text": "“Dask provides advanced parallelism for analytics, enabling performance at scale for the tools you love” — https://dask.pydata.org/en/latest/"
},
{
"code": null,
"e": 5842,
"s": 5798,
"text": "now, call above function to preprocess text"
},
{
"code": null,
"e": 6304,
"s": 5842,
"text": "The model is trained and optimized for greater-than-word length text, such as sentences, phrases or short paragraphs. It is trained on a variety of data sources and a variety of tasks with the aim of dynamically accommodating a wide variety of natural language understanding tasks. The input is variable length English text and the output is a 128-dimensional vector. The universal-sentence-encoder model has trained with a deep averaging network (DAN) encoder."
},
{
"code": null,
"e": 6344,
"s": 6304,
"text": "let's install required packages for USE"
},
{
"code": null,
"e": 6368,
"s": 6344,
"text": "load model from its URL"
},
{
"code": null,
"e": 6594,
"s": 6368,
"text": "now, split text body of research papers by new line into list separate paragraphs, so that we can create embeddings for each paragraph. for example, if a text has 100 paragraphs, then we will get a list of these 100 elements."
},
{
"code": null,
"e": 6675,
"s": 6594,
"text": "Convert the different list of paragraphs for each row of text into a single list"
},
{
"code": null,
"e": 6697,
"s": 6675,
"text": "now create embeddings"
},
{
"code": null,
"e": 6882,
"s": 6697,
"text": "this will return a tensor object of shape nx128, where n is the number of paragraphs or sentences, as number of sentences are 1052935, therefore the shape of tensor will be 1052935x128"
},
{
"code": null,
"e": 6910,
"s": 6882,
"text": "TensorShape([1052935, 128])"
},
{
"code": null,
"e": 7077,
"s": 6910,
"text": "Cosine similarity is a measure of similarity that can be used to compare documents or, say, give a ranking of documents with respect to a given vector of query words."
},
{
"code": null,
"e": 7296,
"s": 7077,
"text": "Mathematically, it measures the cosine of the angle between two vectors projected in a multi-dimensional space. In this context, the two vectors I am talking about are arrays containing the embeddings of two documents."
},
{
"code": null,
"e": 7398,
"s": 7296,
"text": "Let x and y be two vectors for comparison. Using the cosine measure as a similarity function, we have"
},
{
"code": null,
"e": 7868,
"s": 7398,
"text": "where ||x|| is the Euclidean norm of vector x=(x1,x2,...,xn), defined as x1^2+x2^2+⋯+xn^2. Conceptually, it is the length of the vector. Similarly, ||y|| is the Euclidean norm of vector y. The measure computes the cosine of the angle between vectors x and y. A cosine value of 0 means that the two vectors are at 90 degrees to each other (orthogonal) and have no match. The closer the cosine value to 1, the smaller the angle, and the greater the match between vectors."
},
{
"code": null,
"e": 8103,
"s": 7868,
"text": "The cosine similarity is advantageous because even if the two similar documents are far apart by the Euclidean distance because of the size, they could still have a smaller angle between them. Smaller the angle, higher the similarity."
},
{
"code": null,
"e": 8165,
"s": 8103,
"text": "Please refer to a link to check more about cosine similarity."
},
{
"code": null,
"e": 8393,
"s": 8165,
"text": "This function extracts information from corpus, based upon query. it calculates cosine similarity of query with all paragraphs or sentences, standardize it to fix its range b/w 0 to 1, and return sentences based upon threshold."
},
{
"code": null,
"e": 8417,
"s": 8393,
"text": "4.8.1 Incubation period"
},
{
"code": null,
"e": 8425,
"s": 8417,
"text": "output:"
},
{
"code": null,
"e": 8777,
"s": 8425,
"text": "['statements of incubation period and sources of original incubation period data for', ' the incubation period of yellow fever is around 3-6 days. the incubation period of dengue fever is around 8-10 days.', ' the incubation period of lassa fever ranges from 3 to 21 days. symptoms of new world haemorrhagic fever typically develop over 7-14 days.', ]"
},
{
"code": null,
"e": 8785,
"s": 8777,
"text": "Output:"
},
{
"code": null,
"e": 9797,
"s": 8785,
"text": " ' determination of the dynamics of disease transmission in geographically widespread areas global spread of foot-and-mouth disease; spread of newcastle disease virus in asia distinction between pathovars and nonpathovars pathogenic and nonpathogenic escherichia coli in petting zoos addressing hospital and institutional infectious disease problems',' respiratory viruses detected in outbreaks in institutions reflect those known to be major causes of acute respiratory disease in the community; prevalence varies based on geographic location, season, and detection methods . free access to such institutions by members of the community , in conjunction with communal close quarters of residents, creates an ideal environment for propagation of viral respiratory outbreaks .', ' incidence of infection within a community social economic status of the community season per capita water use time of day age distribution within the community chronic infections table 2 concentration of enteric viruses in feces.']"
},
{
"code": null,
"e": 9839,
"s": 9797,
"text": "4.8.3 Role of environment in Transmission"
},
{
"code": null,
"e": 9847,
"s": 9839,
"text": "Output:"
},
{
"code": null,
"e": 12045,
"s": 9847,
"text": "[' disease control efforts can also make it challenging to determine effects of climate change on disease. for instance, if climate change causes range shifts of parasites from tropical to temperate countries, this might result in an overall reduction, rather than increase, in human diseases because temperate countries often have superior health infrastructures . regardless of the outcome of climate change on diseases, integrating control efforts into projections should improve predictions of future disease risk for humans and wildlife. furthermore, given that control measures could obscure increases in transmission, incorporating control measures into models could reveal underlying increases in disease risk that might otherwise be missed.', ' environmental variables can affect responses of mice in experimental situations. changes in respiratory epithelial physiology and function from elevated levels of ammonia, effects of temperature and humidity on metabolism, effects of light on eye lesions and retinal function, and effects of noise on neurophysiology are examples of complications that can vary with the form of insult and the strain of mouse employed. ', ' effects of meteorological factors on transmission. climate change can influence the occurrence and spread of infectious diseases through its effect on transmission. for example, climate change can cause air pollution and shortages of food and clean water , leading to changes of high-incidence areas and outbreak patterns, thereby affecting the occurrence and spread of infectious disease.', ' future studies that focused on other components of air pollution and environmental factors are necessary to more fully understand the possible impact on infectious disease transmission . studies are in need to establish the relationships between particle attachment and survival of influenza virus, and also methods should be developed to quantify airborne influenza virus and measure the concentration of influenza virus in ambient air especially for extremely low virus concentrations . we set the number of cases to zero on hot days due to there being no significant effect of pm 2.5 on influenza incidence on hot days .']"
},
{
"code": null,
"e": 12053,
"s": 12045,
"text": "Output:"
},
{
"code": null,
"e": 14200,
"s": 12053,
"text": "[' seasonal patterns were observed for hmpv, rhinovirus, enterovirus and influenza viruses with peak prevalence in late winter and spring . in addition, a seasonal pattern was detected for tuberculosis . no distinct seasonal patterns were observed for other microbes.', 'not disperse low pathogenic avian influenza virus during autumn migration .', 'the severity of seasonal influenza epidemics is unpredictable and influenced by the predominant circulating virus strains and level of immunity in the population . during peak community influenza activity, hospitals and emergency rooms may be overwhelmed by patients presenting with influenza-like illness and more severe disease , . illness attack rates may be higher among most age groups during pandemics than observed for seasonal influenza due to limited immunity among exposed populations . the re-emergence of highly pathogenic avian influenza a virus among poultry with sporadic transmission to exposed persons and the resulting high mortality has stimulated global influenza pandemic preparedness .',' the two gastrointestinal viruses in the study both also presented with winter seasonality, often with norovirus preceding rotavirus epidemics . norovirus and influenza a virus epidemics usually overlapped, but the norovirus epidemics had broader peaks, and numbers tended to start increasing earlier than influenza a virus diagnoses levels and decreased after the disappearance of influenza a virus. also, rotavirus outbreaks usually occurred before influenza a outbreaks started.','influenza viruses circulate in temperate climates from early autumn to late spring, and in tropical climates throughout the year with unpredictable peaks, usually occurring during the wet season and cooler months. routine surveillance for influenza and influenzalike illness can provide estimates of the relative severity of influenza seasons, and can also provide clinical specimens from which influenza viruses can be detected. this allows comparison of circulating influenza strains with vaccine strains in the current influenza season, and may provide potential vaccine strains for future seasons.]"
},
{
"code": null,
"e": 14392,
"s": 14200,
"text": "(e.g., charge distribution, adhesion to hydrophilic/phobic surfaces, environmental survival to inform decontamination efforts for affected areas and provide information about viral shedding)."
},
{
"code": null,
"e": 14400,
"s": 14392,
"text": "output:"
},
{
"code": null,
"e": 16971,
"s": 14400,
"text": "[' antiadhesive surfaces target microbial adhesion usually by the interaction of antagonist physicochemical properties. easy-clean surfaces that are hydrophobic repel bacteria better than glass-coated controls , while hydrophilic surfaces favour water sheeting and subsequent cleaning. similarly, polyethylene glycol coated surfaces promote a hydrophilic interaction against bacteria, preventing attachment . the use of diamond-like carbon films has already been tried for medical implanted devices such as joint prostheses and stents in order to repel microbial adhesion . despite being non-toxic and appealing, the lack of biocidal properties may turn discouraging a more generalized implementation of such easy-clean technologies.', ' in vitro testing compared the adhesion of representative proteins, prokaryotes, and eukaryotes on nanostructured and flat si3n4 surfaces with lysine-coated glass slides as positive controls. flat si3n4 is moderately hydrophilic and known to vigorously promote cell adhesion and proliferation due to increased adsorption of proteins when compared to more hydrophilic surfaces 33,34. hence, we further increased the hydrophilicity of the si3n4 surface by varying the aspect-ratios of the nanostructures from 0.15 to 0.90 and systematically controlled surface hydrophilicity . once strong hydrophilicity is achieved , a nanostructure-mediated aqueous barrier forms on the surface and limits protein adsorption and cell adhesion to provide an anti-adhesion property 6,35,36.', ' for htcc nanofibers to become an adsorptive membrane material, the fibers must not dissolve in water. crosslinking of polymer structures is a common method to impart membrane stability in water soluble polymers. 21 pva fibers were crosslinked with maleic anhydride to create a filtration membrane. 22 htcc blended with polyvinyl alcohol was photo-crosslinked to impart antimicrobial resistance to the fibers. 10 glutaraldehyde vapor was used to crosslink htcc-pva fibers to create an antimicrobial surface. 7 here, we demonstrate that htcc nanofibers can be crosslinked while retaining their nonwoven structure and their ability to bind to negatively-charged viruses. we have explored the crosslinking conditions that give the greatest water stability. these conditions allowed for high virus removal. our model viruses include the non-enveloped porcine parvovirus , one of the smallest known mammalian viruses and the enveloped virus, sindbis virus. this nanofiber material has the potential to become an inexpensive defense against water-borne diseases.',"
},
{
"code": null,
"e": 16979,
"s": 16971,
"text": "output:"
},
{
"code": null,
"e": 20769,
"s": 16979,
"text": "[\" therefore, china's advancements in research and development, technical and scientific capacity transferring can support african next generation of proactive scientists to develop more sensitive simplified diagnostic tools and reduce the costs of laboratory diagnosis and medical equipment. furthermore, research and development is needed in examining the biological mechanisms of stressors or risk factors exposure and health effects, assessing evidence-based mitigation or adaptation interventions and benefits . innovative solutions and breakthroughs in human-animal-environment fields would not only enable africa to meet its own growing needs, but also support integrating health systems, including strengthening the capacities of laboratory diagnostics and medical care, as well as establishing the china-africa platforms that could generate evidence-based low-cost, available and easy-to-use health packages and solutions for the reduction of public health burden.\", ' 1. access to data and samples to enable and accelerate research, which would involve rapid sharing of epidemiological surveillance and clinical data to inform outbreak control strategies; incentives and platforms for open sharing and access to genomic sequencing data; access to specimen samples . 2. appropriate conduct of research, including improved ethical standards for research and development ; previous agreement about experimental protocols, such as trial design, to speed clinical trials when outbreaks strike; 80 access to clinical trial data, such as publication of negative and positive results; clear pathways for approval by stringent regulatory authorities and in countries of use; and building on and investing in research capacities in epidemicaff ected countries. 3. equitable access to the benefi ts of research, including priority, aff ordable access to newly developed health technologies for aff ected populations, including health workers; and ethical guidelines for rationing products with limited availability. an overarching framework is needed to bring coherence and fi ll gaps in the fragmented system of international rules shaping outbreak-related research (including the international health regulations, pandemic',' clinical laboratories are highly regulated, and general laboratory and testing requirements apply to all molecular diagnostic assays reported for patient care90. quality control is paramount, and methods must be developed to ensure analytic accuracy throughout the assay workflow. important quality control steps can include initial sample quality checks, library parameters , sequence data generation , recovery of internal controls and performance of external controls. validation data generated during assay development and implementation should be recorded and made available to laboratory inspectors or submitted to regulatory agencies, such as the fda in the usa or the european medicines agency in europe, for approval.', ' future applications of advanced molecular diagnostics in clinical laboratories will enhance significantly capabilities to diagnose bacterial, parasitic, and viral agents in the early course of disease through enhanced assay sensitivities and specificities and improved turnaround times, theoretically leading to more timely and directed therapeutic intervention. until such time, clinicians must continue to rely on clinical judgment and the diverse battery of traditional culture techniques, direct examination , and immunoassays that are available. cost considerations and the ever-increasing array of infectious agents responsible for infectious gastroenteritis will continue to drive the development of practice guidelines to assist practitioners with reasoned and reasonable approaches to management of diarrheal illnesses. ']"
},
{
"code": null,
"e": 20777,
"s": 20769,
"text": "output:"
},
{
"code": null,
"e": 23237,
"s": 20777,
"text": "[' this paper reviews animal models currently in use for the study of influenza pathogenesis and immune responses to influenza virus infections and to assess vaccine and antiviral drug efficacy. models that will be reviewed will include: models of benign influenza, typical severe seasonal influenza and pneumonia, influenza-associated sepsis, models using h5n1 viruses, models in which acute respiratory distress syndrome is induced, models of influenzaassociated neurologic disease, models for virus transmission studies, immunocompromised models, and models of host resistance.', ' pregnancy poses an increased risk of severe maternal illness due to a number of acute and chronic viral infections; the common rhinovirus, influenza virus, sars coronavirus and varicella zoster, hepatitis e/b, hiv and cytomegalovirus . viral infections can also lead to pre-term birth and other pregnancy complications . however, few murine models are available to study pathogenesis of viral infections.', ' coronaviruses can cause a variety of diseases in animals and humans . of economical importance are coronaviruses such as porcine transmissible gastroenteritis virus, bovine coronavirus, feline infectious peritonitis virus, and avian infectious bronchitis virus. mhv, a natural mouse pathogen, has been extensively studied in the context of host immune responses and pathogenesis . there are many different and well-characterized strains of mhv which, depending on organ tropism, virulence and host strain, can cause a wide array of diseases ranging from hepatitis, respiratory symptoms and gastroenteritis to cns infection, demyelination, and acute meningitis [2, 17, . therefore, by using appropriate combinations of virus and mouse strains, mhv infections provide suitable models for a number of diseases that are of medical importance, such as encephalitis, immune-mediated demyelination , hepatitis and acute respiratory infections .', ' although in most host-virus interaction studies typically protein-coding genes have been the center of attention, there are few examples of virus and host lncrna interactions in human and mouse models . for instance, hepatitis b virus infection altered lncrna profiles in patients, with about 4% of human lncrnas showing more than 2-fold changes in hbv infected liver tissue . winterling et al. identified a virus inducible lncrna, which is induced by vesicular stomatitis virus and several strains of influenza a virus .']"
},
{
"code": null,
"e": 23360,
"s": 23237,
"text": "similarily, we can retrieve information for other queries, you just need to type query and call “recommend_text” function."
},
{
"code": null,
"e": 23371,
"s": 23360,
"text": "Refrences:"
},
{
"code": null,
"e": 23510,
"s": 23371,
"text": "[1] Jiawei Han, Jian Pei, Micheline Kamber, Data Mining: Concepts and Techniques provides the concepts and techniques (2012), Elsevier Inc"
}
] |
Maximum difference of zeros and ones in binary string | Practice | GeeksforGeeks
|
Given a binary string S consisting of 0s and 1s. The task is to find the maximum difference of the number of 0s and the number of 1s (number of 0s – number of 1s) in the substrings of a string.
Note: In the case of all 1s, the answer will be -1.
Example 1:
Input : S = "11000010001"
Output : 6
Explanatio: From index 2 to index 9,
there are 7 0s and 1 1s, so number
of 0s - number of 1s is 6.
Example 2:
Input: S = "111111"
Output: -1
Explanation: S contains 1s only
Your task:
You do not need to read any input or print anything. The task is to complete the function maxSubstring(), which takes a string as input and returns an integer.
Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(|S|)
Constraints:
1 ≤ |S| ≤ 105
S contains 0s and 1s only
+1
sanketbhagat2 days ago
SIMPLE JAVA SOLUTION
class Solution {
int zero=0,one=0,ans=-1;
int maxSubstring(String s) {
// code here
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='0') zero++;
else one++;
if(zero>one) ans = Math.max(ans,zero-one);
else zero = one = 0;
}
return ans;
}
}
0
milindprajapatmst191 week ago
class Solution {
public:
int maxSubstring(string& str) {
int one = 0, zero = 0, result = -1;
for (char& ch : str) {
one += (ch == '1');
zero += (ch == '0');
result = max(result, zero - one);
if (zero - one < 0)
one = zero = 0;
}
return result;
}
};
0
jainmuskan5652 weeks ago
int maxSubstring(string S){ // create vector for the amount the binary string adds 0/1 vector<int> arr(S.size(),0); for(int i=0;i<S.size();i++){ if(S[i]=='1'){ arr[i]=-1; } else{ arr[i]=1; } } // kadanes maxSum int sum=0,maxSum=INT_MIN; for(int i=0;i<arr.size();i++){ sum+= arr[i]; maxSum=max(maxSum,sum); if(sum<0){ sum=0; } } return maxSum;}
+1
dattatraygujar773 weeks ago
//O(1) SPACE
int maxSubstring(String S) {
int i=0,max=-1,count=0,count1=0;
while(i<S.length())
{
if(S.charAt(i)=='0')
{
count++;
max=Math.max(max,count-count1);
}
if(count>0 && S.charAt(i)=='1')
{
count1++;
max=Math.max(max,count-count1+1);
if(count-count1 < 0)
{
count1=0;
count=0;
}
}
i++;
}
return max;
}
0
sandeepkmrnayak4 weeks ago
This Problem is same as Maximum Subarray Sum
int maxSubstring(string S)
{
// Your code goes here
int ans = 0;
int temp = 0;
for(int i=0;i<S.size();i++)
{
if(S[i]=='0')
{
temp++;
}
else
{
temp--;
}
ans = max(ans,temp);
if(temp<0)
{
temp = 0;
}
}
return ans==0?-1:ans;
}
+1
madhukartemba1 month ago
JAVA SOLUTION O(1) SPACE COMPLEXITY:
THIS PROBLEM CAN BE SOLVED BY MODIFYING KADANE'S ALGORITHM:
class Solution {
int maxSubstring(String S) {
int n = S.length();
int i = 0;
while(i<n && S.charAt(i)=='1')
{
i++;
}
if(i==n) return -1;
int max_diff = 0, diff = 0;
while(i<n)
{
if(S.charAt(i++)=='0')
{
diff++;
}
else
{
max_diff = Math.max(diff, max_diff);
diff--;
}
if(diff<0) diff=0;
max_diff = Math.max(diff, max_diff);
}
return max_diff;
}
}
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(N) and space complexity as O(1) is as follows :-
Execution Time :- 0.0 / 1.6 sec
int maxSubstring(string S){ int max_so_far = 0; int curr_max = 0; for(int i = 0; i < S.length(); i++){ int x = S[i] == '0' ? 1 : -1; curr_max += x; max_so_far = max(max_so_far,curr_max); if(curr_max < 0) curr_max = 0; } return (max_so_far == 0 ? -1 : max_so_far);}
0
anuragncp2 months ago
Cakewalk C++ solution
‘’'int maxSubstring(string S){ // Your code goes here int n = S.length() ; int dp[n+1] ; dp[0] = 0 ; int m = -1 ; for(int i=1;i<=n;i++) { if(S[i-1]=='1') dp[i] = max(dp[i-1]-1,-1) ; else dp[i] = 1+max(0,dp[i-1]) ; m = max(m,dp[i]) ; } return m ; } ‘’'
0
rakeshkumarverma20223 months ago
c++ solution time(O(n)), space(O(1))
int maxSubstring(string S){ int dif=0,ans=0; for(int i=0;i<S.length();i++){ if(S[i]=='1') dif=--dif<0?0:dif; else ans=max(ans,++dif); } return ans==0?-1:ans; }
0
himanshukug19cs3 months ago
java solution
int maxSubstring(String S) { // code here int ans=0; int[] dp = new int[S.length()]; int sum=0; if(S.charAt(0)=='1') dp[0]=0; else{ dp[0]=1; ans=1; } for(int i=1;i<S.length();i++){ if(S.charAt(i)=='1'){ if(dp[i-1]==0) dp[i]=0; else dp[i]=Math.max(dp[i-1]-1,-1); } else dp[i]=dp[i-1]+1; ans=Math.max(dp[i],ans); } if(ans==0) return -1; else return ans; }
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": 432,
"s": 238,
"text": "Given a binary string S consisting of 0s and 1s. The task is to find the maximum difference of the number of 0s and the number of 1s (number of 0s – number of 1s) in the substrings of a string."
},
{
"code": null,
"e": 485,
"s": 432,
"text": "Note: In the case of all 1s, the answer will be -1. "
},
{
"code": null,
"e": 496,
"s": 485,
"text": "Example 1:"
},
{
"code": null,
"e": 637,
"s": 496,
"text": "Input : S = \"11000010001\" \nOutput : 6 \nExplanatio: From index 2 to index 9, \nthere are 7 0s and 1 1s, so number \nof 0s - number of 1s is 6. "
},
{
"code": null,
"e": 648,
"s": 637,
"text": "Example 2:"
},
{
"code": null,
"e": 712,
"s": 648,
"text": "Input: S = \"111111\"\nOutput: -1\nExplanation: S contains 1s only "
},
{
"code": null,
"e": 884,
"s": 712,
"text": "Your task:\nYou do not need to read any input or print anything. The task is to complete the function maxSubstring(), which takes a string as input and returns an integer. "
},
{
"code": null,
"e": 950,
"s": 884,
"text": "Expected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(|S|)"
},
{
"code": null,
"e": 1003,
"s": 950,
"text": "Constraints:\n1 ≤ |S| ≤ 105\nS contains 0s and 1s only"
},
{
"code": null,
"e": 1006,
"s": 1003,
"text": "+1"
},
{
"code": null,
"e": 1029,
"s": 1006,
"text": "sanketbhagat2 days ago"
},
{
"code": null,
"e": 1050,
"s": 1029,
"text": "SIMPLE JAVA SOLUTION"
},
{
"code": null,
"e": 1380,
"s": 1050,
"text": "class Solution {\n int zero=0,one=0,ans=-1;\n int maxSubstring(String s) {\n // code here\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)=='0') zero++;\n else one++;\n if(zero>one) ans = Math.max(ans,zero-one);\n else zero = one = 0;\n }\n return ans;\n }\n}"
},
{
"code": null,
"e": 1382,
"s": 1380,
"text": "0"
},
{
"code": null,
"e": 1412,
"s": 1382,
"text": "milindprajapatmst191 week ago"
},
{
"code": null,
"e": 1733,
"s": 1412,
"text": "class Solution {\npublic:\t\n\tint maxSubstring(string& str) {\n\t int one = 0, zero = 0, result = -1;\n\t for (char& ch : str) {\n\t one += (ch == '1');\n\t zero += (ch == '0');\n\t result = max(result, zero - one);\n\t if (zero - one < 0)\n\t one = zero = 0;\n\t }\n\t return result;\n\t}\n};"
},
{
"code": null,
"e": 1735,
"s": 1733,
"text": "0"
},
{
"code": null,
"e": 1760,
"s": 1735,
"text": "jainmuskan5652 weeks ago"
},
{
"code": null,
"e": 2221,
"s": 1760,
"text": " int maxSubstring(string S){ // create vector for the amount the binary string adds 0/1 vector<int> arr(S.size(),0); for(int i=0;i<S.size();i++){ if(S[i]=='1'){ arr[i]=-1; } else{ arr[i]=1; } } // kadanes maxSum int sum=0,maxSum=INT_MIN; for(int i=0;i<arr.size();i++){ sum+= arr[i]; maxSum=max(maxSum,sum); if(sum<0){ sum=0; } } return maxSum;}"
},
{
"code": null,
"e": 2224,
"s": 2221,
"text": "+1"
},
{
"code": null,
"e": 2252,
"s": 2224,
"text": "dattatraygujar773 weeks ago"
},
{
"code": null,
"e": 2817,
"s": 2252,
"text": " //O(1) SPACE\n int maxSubstring(String S) {\n int i=0,max=-1,count=0,count1=0;\n while(i<S.length())\n {\n if(S.charAt(i)=='0')\n {\n count++;\n max=Math.max(max,count-count1); \n }\n if(count>0 && S.charAt(i)=='1')\n {\n count1++;\n max=Math.max(max,count-count1+1);\n if(count-count1 < 0)\n {\n count1=0;\n count=0;\n }\n }\n \n i++;\n }\n return max;\n }"
},
{
"code": null,
"e": 2819,
"s": 2817,
"text": "0"
},
{
"code": null,
"e": 2846,
"s": 2819,
"text": "sandeepkmrnayak4 weeks ago"
},
{
"code": null,
"e": 2891,
"s": 2846,
"text": "This Problem is same as Maximum Subarray Sum"
},
{
"code": null,
"e": 3281,
"s": 2891,
"text": "int maxSubstring(string S)\n\t{\n\t // Your code goes here\n\t int ans = 0;\n\t int temp = 0;\n\t for(int i=0;i<S.size();i++)\n\t {\n\t if(S[i]=='0')\n\t {\n\t temp++;\n\t }\n\t else\n\t {\n\t temp--;\n\t }\n\t ans = max(ans,temp);\n\t if(temp<0)\n\t {\n\t temp = 0;\n\t }\n\t }\n\t return ans==0?-1:ans;\n\t}"
},
{
"code": null,
"e": 3284,
"s": 3281,
"text": "+1"
},
{
"code": null,
"e": 3309,
"s": 3284,
"text": "madhukartemba1 month ago"
},
{
"code": null,
"e": 3346,
"s": 3309,
"text": "JAVA SOLUTION O(1) SPACE COMPLEXITY:"
},
{
"code": null,
"e": 3406,
"s": 3346,
"text": "THIS PROBLEM CAN BE SOLVED BY MODIFYING KADANE'S ALGORITHM:"
},
{
"code": null,
"e": 4059,
"s": 3408,
"text": "class Solution {\n int maxSubstring(String S) {\n int n = S.length();\n int i = 0;\n while(i<n && S.charAt(i)=='1')\n {\n i++;\n }\n \n if(i==n) return -1;\n \n int max_diff = 0, diff = 0;\n while(i<n)\n {\n if(S.charAt(i++)=='0')\n {\n diff++;\n }\n else\n {\n max_diff = Math.max(diff, max_diff);\n diff--;\n }\n \n if(diff<0) diff=0;\n \n max_diff = Math.max(diff, max_diff);\n }\n \n return max_diff;\n }\n}"
},
{
"code": null,
"e": 4062,
"s": 4059,
"text": "+1"
},
{
"code": null,
"e": 4090,
"s": 4062,
"text": "aloksinghbais022 months ago"
},
{
"code": null,
"e": 4181,
"s": 4090,
"text": "C++ solution having time complexity as O(N) and space complexity as O(1) is as follows :- "
},
{
"code": null,
"e": 4215,
"s": 4183,
"text": "Execution Time :- 0.0 / 1.6 sec"
},
{
"code": null,
"e": 4525,
"s": 4217,
"text": "int maxSubstring(string S){ int max_so_far = 0; int curr_max = 0; for(int i = 0; i < S.length(); i++){ int x = S[i] == '0' ? 1 : -1; curr_max += x; max_so_far = max(max_so_far,curr_max); if(curr_max < 0) curr_max = 0; } return (max_so_far == 0 ? -1 : max_so_far);}"
},
{
"code": null,
"e": 4527,
"s": 4525,
"text": "0"
},
{
"code": null,
"e": 4549,
"s": 4527,
"text": "anuragncp2 months ago"
},
{
"code": null,
"e": 4572,
"s": 4549,
"text": "Cakewalk C++ solution "
},
{
"code": null,
"e": 4871,
"s": 4572,
"text": "‘’'int maxSubstring(string S){ // Your code goes here int n = S.length() ; int dp[n+1] ; dp[0] = 0 ; int m = -1 ; for(int i=1;i<=n;i++) { if(S[i-1]=='1') dp[i] = max(dp[i-1]-1,-1) ; else dp[i] = 1+max(0,dp[i-1]) ; m = max(m,dp[i]) ; } return m ; } ‘’'"
},
{
"code": null,
"e": 4873,
"s": 4871,
"text": "0"
},
{
"code": null,
"e": 4906,
"s": 4873,
"text": "rakeshkumarverma20223 months ago"
},
{
"code": null,
"e": 4943,
"s": 4906,
"text": "c++ solution time(O(n)), space(O(1))"
},
{
"code": null,
"e": 5146,
"s": 4943,
"text": " int maxSubstring(string S){ int dif=0,ans=0; for(int i=0;i<S.length();i++){ if(S[i]=='1') dif=--dif<0?0:dif; else ans=max(ans,++dif); } return ans==0?-1:ans; }"
},
{
"code": null,
"e": 5148,
"s": 5146,
"text": "0"
},
{
"code": null,
"e": 5176,
"s": 5148,
"text": "himanshukug19cs3 months ago"
},
{
"code": null,
"e": 5190,
"s": 5176,
"text": "java solution"
},
{
"code": null,
"e": 5657,
"s": 5192,
"text": " int maxSubstring(String S) { // code here int ans=0; int[] dp = new int[S.length()]; int sum=0; if(S.charAt(0)=='1') dp[0]=0; else{ dp[0]=1; ans=1; } for(int i=1;i<S.length();i++){ if(S.charAt(i)=='1'){ if(dp[i-1]==0) dp[i]=0; else dp[i]=Math.max(dp[i-1]-1,-1); } else dp[i]=dp[i-1]+1; ans=Math.max(dp[i],ans); } if(ans==0) return -1; else return ans; }"
},
{
"code": null,
"e": 5803,
"s": 5657,
"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": 5839,
"s": 5803,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5849,
"s": 5839,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5859,
"s": 5849,
"text": "\nContest\n"
},
{
"code": null,
"e": 5922,
"s": 5859,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6070,
"s": 5922,
"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": 6278,
"s": 6070,
"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": 6384,
"s": 6278,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Collections.sort() in Java with Examples - GeeksforGeeks
|
07 Dec, 2018
java.util.Collections.sort() method is present in java.util.Collections class. It is used to sort the elements present in the specified list of Collection in ascending order.It works similar to java.util.Arrays.sort() method but it is better then as it can sort the elements of Array as well as linked list, queue and many more present in it.
public static void sort(List myList)
myList : A List type object we want to sort.
This method doesn't return anything
Example:
Let us suppose that our list contains
{"Geeks For Geeks", "Friends", "Dear", "Is", "Superb"}
After using Collection.sort(), we obtain a sorted list as
{"Dear", "Friends", "Geeks For Geeks", "Is", "Superb"}
Sorting an ArrayList in ascending order
// Java program to demonstrate working of Collections.sort()import java.util.*; public class Collectionsorting{ public static void main(String[] args) { // Create a list of strings ArrayList<String> al = new ArrayList<String>(); al.add("Geeks For Geeks"); al.add("Friends"); al.add("Dear"); al.add("Is"); al.add("Superb"); /* Collections.sort method is sorting the elements of ArrayList in ascending order. */ Collections.sort(al); // Let us print the sorted list System.out.println("List after the use of" + " Collection.sort() :\n" + al); }}
Output:
List after the use of Collection.sort() :
[Dear, Friends, Geeks For Geeks, Is, Superb]
Sorting an ArrayList in descending order
// Java program to demonstrate working of Collections.sort()// to descending order.import java.util.*; public class Collectionsorting{ public static void main(String[] args) { // Create a list of strings ArrayList<String> al = new ArrayList<String>(); al.add("Geeks For Geeks"); al.add("Friends"); al.add("Dear"); al.add("Is"); al.add("Superb"); /* Collections.sort method is sorting the elements of ArrayList in ascending order. */ Collections.sort(al, Collections.reverseOrder()); // Let us print the sorted list System.out.println("List after the use of" + " Collection.sort() :\n" + al); }}
Output:
List after the use of Collection.sort() :
[Superb, Is, Geeks For Geeks, Friends, Dear]
Sorting an ArrayList according to user defined criteria.We can use Comparator Interface for this purpose.
// Java program to demonstrate working of Comparator// interface and Collections.sort() to sort according// to user defined criteria.import java.util.*;import java.lang.*;import java.io.*; // A class to represent a student.class Student{ int rollno; String name, address; // Constructor public Student(int rollno, String name, String address) { this.rollno = rollno; this.name = name; this.address = address; } // Used to print student details in main() public String toString() { return this.rollno + " " + this.name + " " + this.address; }} class Sortbyroll implements Comparator<Student>{ // Used for sorting in ascending order of // roll number public int compare(Student a, Student b) { return a.rollno - b.rollno; }} // Driver classclass Main{ public static void main (String[] args) { ArrayList<Student> ar = new ArrayList<Student>(); ar.add(new Student(111, "bbbb", "london")); ar.add(new Student(131, "aaaa", "nyc")); ar.add(new Student(121, "cccc", "jaipur")); System.out.println("Unsorted"); for (int i=0; i<ar.size(); i++) System.out.println(ar.get(i)); Collections.sort(ar, new Sortbyroll()); System.out.println("\nSorted by rollno"); for (int i=0; i<ar.size(); i++) System.out.println(ar.get(i)); }}
Output :
Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur
Sorted by rollno
111 bbbb london
121 cccc jaipur
131 aaaa nyc
Arrays.sort() vs Collections.sort()Arrays.sort works for arrays which can be of primitive data type also. Collections.sort() works for objects Collections like ArrayList, LinkedList, etc.
We can use Collections.sort() to sort an array after creating a ArrayList of given array items.
// Using Collections.sort() to sort an arrayimport java.util.*;public class Collectionsort{ public static void main(String[] args) { // create an array of string objs String domains[] = {"Practice", "Geeks", "Code", "Quiz"}; // Here we are making a list named as Collist List colList = new ArrayList(Arrays.asList(domains)); // Collection.sort() method is used here // to sort the list elements. Collections.sort(colList); // Let us print the sorted list System.out.println("List after the use of" + " Collection.sort() :\n" + colList); }}
Output:
List after the use of Collection.sort() :
[Code, Geeks, Practice, Quiz]
This article is contributed by Mohit Gupta. Article is wished to be useful to the esteemed Geeks.If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks..
Java - util package
Java-Collections
Java-Collections-Class
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
Set in Java
Overriding in Java
Functional Interfaces in Java
Queue Interface In Java
Stream In Java
How to add an element to an Array in Java?
|
[
{
"code": null,
"e": 23873,
"s": 23845,
"text": "\n07 Dec, 2018"
},
{
"code": null,
"e": 24216,
"s": 23873,
"text": "java.util.Collections.sort() method is present in java.util.Collections class. It is used to sort the elements present in the specified list of Collection in ascending order.It works similar to java.util.Arrays.sort() method but it is better then as it can sort the elements of Array as well as linked list, queue and many more present in it."
},
{
"code": null,
"e": 24337,
"s": 24216,
"text": "public static void sort(List myList)\n\nmyList : A List type object we want to sort.\n\nThis method doesn't return anything\n"
},
{
"code": null,
"e": 24346,
"s": 24337,
"text": "Example:"
},
{
"code": null,
"e": 24555,
"s": 24346,
"text": "\nLet us suppose that our list contains\n{\"Geeks For Geeks\", \"Friends\", \"Dear\", \"Is\", \"Superb\"}\n\nAfter using Collection.sort(), we obtain a sorted list as\n{\"Dear\", \"Friends\", \"Geeks For Geeks\", \"Is\", \"Superb\"}\n"
},
{
"code": null,
"e": 24595,
"s": 24555,
"text": "Sorting an ArrayList in ascending order"
},
{
"code": "// Java program to demonstrate working of Collections.sort()import java.util.*; public class Collectionsorting{ public static void main(String[] args) { // Create a list of strings ArrayList<String> al = new ArrayList<String>(); al.add(\"Geeks For Geeks\"); al.add(\"Friends\"); al.add(\"Dear\"); al.add(\"Is\"); al.add(\"Superb\"); /* Collections.sort method is sorting the elements of ArrayList in ascending order. */ Collections.sort(al); // Let us print the sorted list System.out.println(\"List after the use of\" + \" Collection.sort() :\\n\" + al); }}",
"e": 25263,
"s": 24595,
"text": null
},
{
"code": null,
"e": 25271,
"s": 25263,
"text": "Output:"
},
{
"code": null,
"e": 25359,
"s": 25271,
"text": "List after the use of Collection.sort() :\n[Dear, Friends, Geeks For Geeks, Is, Superb]\n"
},
{
"code": null,
"e": 25401,
"s": 25359,
"text": " Sorting an ArrayList in descending order"
},
{
"code": "// Java program to demonstrate working of Collections.sort()// to descending order.import java.util.*; public class Collectionsorting{ public static void main(String[] args) { // Create a list of strings ArrayList<String> al = new ArrayList<String>(); al.add(\"Geeks For Geeks\"); al.add(\"Friends\"); al.add(\"Dear\"); al.add(\"Is\"); al.add(\"Superb\"); /* Collections.sort method is sorting the elements of ArrayList in ascending order. */ Collections.sort(al, Collections.reverseOrder()); // Let us print the sorted list System.out.println(\"List after the use of\" + \" Collection.sort() :\\n\" + al); }}",
"e": 26120,
"s": 25401,
"text": null
},
{
"code": null,
"e": 26128,
"s": 26120,
"text": "Output:"
},
{
"code": null,
"e": 26216,
"s": 26128,
"text": "List after the use of Collection.sort() :\n[Superb, Is, Geeks For Geeks, Friends, Dear]\n"
},
{
"code": null,
"e": 26323,
"s": 26216,
"text": " Sorting an ArrayList according to user defined criteria.We can use Comparator Interface for this purpose."
},
{
"code": "// Java program to demonstrate working of Comparator// interface and Collections.sort() to sort according// to user defined criteria.import java.util.*;import java.lang.*;import java.io.*; // A class to represent a student.class Student{ int rollno; String name, address; // Constructor public Student(int rollno, String name, String address) { this.rollno = rollno; this.name = name; this.address = address; } // Used to print student details in main() public String toString() { return this.rollno + \" \" + this.name + \" \" + this.address; }} class Sortbyroll implements Comparator<Student>{ // Used for sorting in ascending order of // roll number public int compare(Student a, Student b) { return a.rollno - b.rollno; }} // Driver classclass Main{ public static void main (String[] args) { ArrayList<Student> ar = new ArrayList<Student>(); ar.add(new Student(111, \"bbbb\", \"london\")); ar.add(new Student(131, \"aaaa\", \"nyc\")); ar.add(new Student(121, \"cccc\", \"jaipur\")); System.out.println(\"Unsorted\"); for (int i=0; i<ar.size(); i++) System.out.println(ar.get(i)); Collections.sort(ar, new Sortbyroll()); System.out.println(\"\\nSorted by rollno\"); for (int i=0; i<ar.size(); i++) System.out.println(ar.get(i)); }}",
"e": 27780,
"s": 26323,
"text": null
},
{
"code": null,
"e": 27789,
"s": 27780,
"text": "Output :"
},
{
"code": null,
"e": 27907,
"s": 27789,
"text": "Unsorted\n111 bbbb london\n131 aaaa nyc\n121 cccc jaipur\n\nSorted by rollno\n111 bbbb london\n121 cccc jaipur\n131 aaaa nyc\n"
},
{
"code": null,
"e": 28095,
"s": 27907,
"text": "Arrays.sort() vs Collections.sort()Arrays.sort works for arrays which can be of primitive data type also. Collections.sort() works for objects Collections like ArrayList, LinkedList, etc."
},
{
"code": null,
"e": 28191,
"s": 28095,
"text": "We can use Collections.sort() to sort an array after creating a ArrayList of given array items."
},
{
"code": "// Using Collections.sort() to sort an arrayimport java.util.*;public class Collectionsort{ public static void main(String[] args) { // create an array of string objs String domains[] = {\"Practice\", \"Geeks\", \"Code\", \"Quiz\"}; // Here we are making a list named as Collist List colList = new ArrayList(Arrays.asList(domains)); // Collection.sort() method is used here // to sort the list elements. Collections.sort(colList); // Let us print the sorted list System.out.println(\"List after the use of\" + \" Collection.sort() :\\n\" + colList); }}",
"e": 28901,
"s": 28191,
"text": null
},
{
"code": null,
"e": 28909,
"s": 28901,
"text": "Output:"
},
{
"code": null,
"e": 28983,
"s": 28909,
"text": "List after the use of Collection.sort() :\n[Code, Geeks, Practice, Quiz]\n"
},
{
"code": null,
"e": 29336,
"s": 28983,
"text": "This article is contributed by Mohit Gupta. Article is wished to be useful to the esteemed Geeks.If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.."
},
{
"code": null,
"e": 29356,
"s": 29336,
"text": "Java - util package"
},
{
"code": null,
"e": 29373,
"s": 29356,
"text": "Java-Collections"
},
{
"code": null,
"e": 29396,
"s": 29373,
"text": "Java-Collections-Class"
},
{
"code": null,
"e": 29411,
"s": 29396,
"text": "Java-Functions"
},
{
"code": null,
"e": 29416,
"s": 29411,
"text": "Java"
},
{
"code": null,
"e": 29421,
"s": 29416,
"text": "Java"
},
{
"code": null,
"e": 29438,
"s": 29421,
"text": "Java-Collections"
},
{
"code": null,
"e": 29536,
"s": 29438,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29545,
"s": 29536,
"text": "Comments"
},
{
"code": null,
"e": 29558,
"s": 29545,
"text": "Old Comments"
},
{
"code": null,
"e": 29577,
"s": 29558,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29601,
"s": 29577,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29620,
"s": 29601,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 29640,
"s": 29620,
"text": "Collections in Java"
},
{
"code": null,
"e": 29652,
"s": 29640,
"text": "Set in Java"
},
{
"code": null,
"e": 29671,
"s": 29652,
"text": "Overriding in Java"
},
{
"code": null,
"e": 29701,
"s": 29671,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29725,
"s": 29701,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 29740,
"s": 29725,
"text": "Stream In Java"
}
] |
GeeksforGeeks | A computer science portal for geeks
|
Events at GeeksforGeeks
Courses at GeeksforGeeks
Write an Article
Java Tutorial
Python Tutorial
Data Structures Tutorial
Coding Practice
Events at GeeksforGeeks
Courses at GeeksforGeeks
Write an Article
Java Tutorial
Python Tutorial
Data Structures Tutorial
Coding Practice
Get Hired With GeeksforGeeks and Win Exciting Rewards!
October 30, 2021
October 30, 2021
Master the Coding Interview – Contest Series Based On Real Interviews
October 5, 2021
October 5, 2021
Recently Asked Interview Questions in Product Based Companies
May 11, 2021
May 11, 2021
Bridge the Gap Between Engineering and Your Dream Job – Complete Interview Preparation
May 1, 2021
May 1, 2021
100 Days of Code – A Complete Guide For Beginners and Experienced
May 1, 2021
May 1, 2021
Guest Blogs
Must Do Coding Questions
Company-wise
Practice for cracking any coding
interview
Placements
Complete Interview Preparation With
Doubt Assistance
GATE Computer Science Notes
Machine Learning
Django Tutorial
Computer Science Projects
Amazon SDE Test Series
Company Interview Corner
The C++ Standard Template Library
(STL)
Software Design Patterns
SQL Tutorial
Advanced Data Structures
|
[
{
"code": null,
"e": 21968,
"s": 21938,
"text": "\n\n\nEvents at GeeksforGeeks\n\n\n"
},
{
"code": null,
"e": 21999,
"s": 21968,
"text": "\n\n\nCourses at GeeksforGeeks\n\n\n"
},
{
"code": null,
"e": 22022,
"s": 21999,
"text": "\n\n\nWrite an Article\n\n\n"
},
{
"code": null,
"e": 22042,
"s": 22022,
"text": "\n\n\nJava Tutorial\n\n\n"
},
{
"code": null,
"e": 22064,
"s": 22042,
"text": "\n\n\nPython Tutorial\n\n\n"
},
{
"code": null,
"e": 22095,
"s": 22064,
"text": "\n\n\nData Structures Tutorial\n\n\n"
},
{
"code": null,
"e": 22117,
"s": 22095,
"text": "\n\n\nCoding Practice\n\n\n"
},
{
"code": null,
"e": 22147,
"s": 22117,
"text": "\n\n\nEvents at GeeksforGeeks\n\n\n"
},
{
"code": null,
"e": 22178,
"s": 22147,
"text": "\n\n\nCourses at GeeksforGeeks\n\n\n"
},
{
"code": null,
"e": 22201,
"s": 22178,
"text": "\n\n\nWrite an Article\n\n\n"
},
{
"code": null,
"e": 22221,
"s": 22201,
"text": "\n\n\nJava Tutorial\n\n\n"
},
{
"code": null,
"e": 22243,
"s": 22221,
"text": "\n\n\nPython Tutorial\n\n\n"
},
{
"code": null,
"e": 22274,
"s": 22243,
"text": "\n\n\nData Structures Tutorial\n\n\n"
},
{
"code": null,
"e": 22296,
"s": 22274,
"text": "\n\n\nCoding Practice\n\n\n"
},
{
"code": null,
"e": 22391,
"s": 22296,
"text": "\nGet Hired With GeeksforGeeks and Win Exciting Rewards!\n \nOctober 30, 2021\n"
},
{
"code": null,
"e": 22408,
"s": 22391,
"text": "October 30, 2021"
},
{
"code": null,
"e": 22517,
"s": 22408,
"text": "\nMaster the Coding Interview – Contest Series Based On Real Interviews\n \nOctober 5, 2021\n"
},
{
"code": null,
"e": 22533,
"s": 22517,
"text": "October 5, 2021"
},
{
"code": null,
"e": 22631,
"s": 22533,
"text": "\nRecently Asked Interview Questions in Product Based Companies\n \nMay 11, 2021\n"
},
{
"code": null,
"e": 22644,
"s": 22631,
"text": "May 11, 2021"
},
{
"code": null,
"e": 22766,
"s": 22644,
"text": "\nBridge the Gap Between Engineering and Your Dream Job – Complete Interview Preparation\n \nMay 1, 2021\n"
},
{
"code": null,
"e": 22778,
"s": 22766,
"text": "May 1, 2021"
},
{
"code": null,
"e": 22879,
"s": 22778,
"text": "\n100 Days of Code – A Complete Guide For Beginners and Experienced\n \nMay 1, 2021\n"
},
{
"code": null,
"e": 22891,
"s": 22879,
"text": "May 1, 2021"
},
{
"code": null,
"e": 22908,
"s": 22891,
"text": "\n\n\nGuest Blogs\n\n"
},
{
"code": null,
"e": 22995,
"s": 22908,
"text": "\n\n\nMust Do Coding Questions\n Company-wise\n\n"
},
{
"code": null,
"e": 23087,
"s": 22995,
"text": "\n\n\nPractice for cracking any coding\n interview\n\n"
},
{
"code": null,
"e": 23103,
"s": 23087,
"text": "\n\n\nPlacements\n\n"
},
{
"code": null,
"e": 23205,
"s": 23103,
"text": "\n\n\nComplete Interview Preparation With\n Doubt Assistance\n\n"
},
{
"code": null,
"e": 23238,
"s": 23205,
"text": "\n\n\nGATE Computer Science Notes\n\n"
},
{
"code": null,
"e": 23260,
"s": 23238,
"text": "\n\n\nMachine Learning\n\n"
},
{
"code": null,
"e": 23281,
"s": 23260,
"text": "\n\n\nDjango Tutorial\n\n"
},
{
"code": null,
"e": 23312,
"s": 23281,
"text": "\n\n\nComputer Science Projects\n\n"
},
{
"code": null,
"e": 23340,
"s": 23312,
"text": "\n\n\nAmazon SDE Test Series\n\n"
},
{
"code": null,
"e": 23370,
"s": 23340,
"text": "\n\n\nCompany Interview Corner\n\n"
},
{
"code": null,
"e": 23459,
"s": 23370,
"text": "\n\n\nThe C++ Standard Template Library\n (STL)\n\n"
},
{
"code": null,
"e": 23489,
"s": 23459,
"text": "\n\n\nSoftware Design Patterns\n\n"
},
{
"code": null,
"e": 23507,
"s": 23489,
"text": "\n\n\nSQL Tutorial\n\n"
}
] |
C# - Break Statement
|
The break statement in C# has following two usage −
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement.
It can be used to terminate a case in the switch statement.
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.
The syntax for a break statement in C# is as follows −
break;
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
/* while loop execution */
while (a < 20) {
Console.WriteLine("value of a: {0}", a);
a++;
if (a > 15) {
/* terminate the loop using break statement */
break;
}
}
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2322,
"s": 2270,
"text": "The break statement in C# has following two usage −"
},
{
"code": null,
"e": 2482,
"s": 2322,
"text": "When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop."
},
{
"code": null,
"e": 2642,
"s": 2482,
"text": "When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop."
},
{
"code": null,
"e": 2702,
"s": 2642,
"text": "It can be used to terminate a case in the switch statement."
},
{
"code": null,
"e": 2762,
"s": 2702,
"text": "It can be used to terminate a case in the switch statement."
},
{
"code": null,
"e": 2955,
"s": 2762,
"text": "If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block."
},
{
"code": null,
"e": 3010,
"s": 2955,
"text": "The syntax for a break statement in C# is as follows −"
},
{
"code": null,
"e": 3018,
"s": 3010,
"text": "break;\n"
},
{
"code": null,
"e": 3507,
"s": 3018,
"text": "using System;\n\nnamespace Loops {\n class Program {\n static void Main(string[] args) {\n /* local variable definition */\n int a = 10;\n \n /* while loop execution */\n while (a < 20) {\n Console.WriteLine(\"value of a: {0}\", a);\n a++;\n \n if (a > 15) {\n /* terminate the loop using break statement */\n break;\n }\n }\n Console.ReadLine();\n }\n }\n} "
},
{
"code": null,
"e": 3588,
"s": 3507,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3679,
"s": 3588,
"text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\n"
},
{
"code": null,
"e": 3716,
"s": 3679,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 3729,
"s": 3716,
"text": " Raja Biswas"
},
{
"code": null,
"e": 3763,
"s": 3729,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3781,
"s": 3763,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 3814,
"s": 3781,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3828,
"s": 3814,
"text": " Peter Jepson"
},
{
"code": null,
"e": 3865,
"s": 3828,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 3880,
"s": 3865,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 3915,
"s": 3880,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 3930,
"s": 3915,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3965,
"s": 3930,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3977,
"s": 3965,
"text": " Eric Frick"
},
{
"code": null,
"e": 3984,
"s": 3977,
"text": " Print"
},
{
"code": null,
"e": 3995,
"s": 3984,
"text": " Add Notes"
}
] |
Find specific records from a column with comma separated values in MySQL
|
For this, you can use FIND_IN_SET(). Let us first create a table −
mysql> create table DemoTable
-> (
-> ListOfValue varchar(20)
-> );
Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('78,89,65');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('88,96,97');
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values('95,96,99,100');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('78,45,67,98');
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+--------------+
| ListOfValue |
+--------------+
| 78,89,65 |
| 88,96,97 |
| 95,96,99,100 |
| 78,45,67,98 |
+--------------+
4 rows in set (0.00 sec)
Following is the query to find specific records from a column with comma-separated values −
mysql> select * from DemoTable
-> where find_in_set('89',ListOfValue)
-> or
-> find_in_set('99',ListOfValue);
This will produce the following output −
+--------------+
| ListOfValue |
+--------------+
| 78,89,65 |
| 95,96,99,100 |
+--------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1129,
"s": 1062,
"text": "For this, you can use FIND_IN_SET(). Let us first create a table −"
},
{
"code": null,
"e": 1243,
"s": 1129,
"text": "mysql> create table DemoTable\n -> (\n -> ListOfValue varchar(20)\n -> );\nQuery OK, 0 rows affected (0.52 sec)"
},
{
"code": null,
"e": 1299,
"s": 1243,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1646,
"s": 1299,
"text": "mysql> insert into DemoTable values('78,89,65');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values('88,96,97');\nQuery OK, 1 row affected (0.30 sec)\nmysql> insert into DemoTable values('95,96,99,100');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values('78,45,67,98');\nQuery OK, 1 row affected (0.10 sec)"
},
{
"code": null,
"e": 1706,
"s": 1646,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1738,
"s": 1706,
"text": "mysql> select * from DemoTable;"
},
{
"code": null,
"e": 1779,
"s": 1738,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1940,
"s": 1779,
"text": "+--------------+\n| ListOfValue |\n+--------------+\n| 78,89,65 |\n| 88,96,97 |\n| 95,96,99,100 |\n| 78,45,67,98 |\n+--------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2032,
"s": 1940,
"text": "Following is the query to find specific records from a column with comma-separated values −"
},
{
"code": null,
"e": 2151,
"s": 2032,
"text": "mysql> select * from DemoTable\n -> where find_in_set('89',ListOfValue)\n -> or\n -> find_in_set('99',ListOfValue);"
},
{
"code": null,
"e": 2192,
"s": 2151,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2319,
"s": 2192,
"text": "+--------------+\n| ListOfValue |\n+--------------+\n| 78,89,65 |\n| 95,96,99,100 |\n+--------------+\n2 rows in set (0.00 sec)"
}
] |
Check whether the Average Character of the String is present or not - GeeksforGeeks
|
05 Apr, 2019
Given a string of alphanumeric characters, the task is to check whether the average character of the string is present or not. Average character refers to the character corresponding to the ASCII value which is the floor of the average value of the ASCII values of all characters in the string.
Examples:
Input: abcdef
Output: d
Yes
Explanation:
string = "abcdef"
ASCII values of a = 97, b=98,
c=99, d=100, e=101, f=101
Sum of these values is 597
Average is 99.5 ~ 100
Character of ASCII value 100 = d
Hence d is present in the string.
Input: MNFGH
Output: J
No
Approach: The approach to solve this problem is very simple. It can be solved in the following steps:
Find the sum of ASCII values of all the characters from the given string.
Find the average of the ASCII value as average = (sum / numberOfCharacters)
Get the character of this average ASCII value. Print this character
Check if this character is present in the string or not. Print Yes or No accordingly.
Below is the implementation of the above approach:
Implementation:
C++
Java
Python3
C#
// CPP program to check if the average character// is present in the string or not #include <bits/stdc++.h>#include <math.h>using namespace std; // Checks if the character is presentbool check_char(char* st, char ch){ // Get the length of string int l = strlen(st); // Iterate from i=0 to // the length of the string // to check if the character // is present in the string for (int i = 0; i < l; i++) { if (st[i] == ch) return true; } return false;} // Finds the average character of the stringchar find_avg(char* st){ int i, sm = 0; int l = strlen(st); char ch; for (i = 0; i < l; i++) { ch = st[i]; // Calculate the sum of ASCII // values of each character sm = sm + (int)(ch); } // Calculate average of ascii values int avg = (int)(floor(sm / l)); // Convert the ASCII value to character // and return it return ((char)(avg));} // Driver codeint main(){ char st[] = "ag23sdfa"; // Get the average character char ch = find_avg(st); cout << ch << endl; // Check if the average character // is present in string or not if (check_char(st, ch) == true) cout << "Yes"; else cout << "No"; return 0;}
// Java program to check if the average character// is present in the string or not import java.math.*; class GFG { // Checks if the character is present static boolean check_char(String st, char ch) { // Get the length of string int l = st.length(); // Iterate from i=0 to // the length of the string // to check if the character // is present in the string for (int i = 0; i < l; i++) { if (st.charAt(i) == ch) return true; } return false; } // Finds the average character of the string static char find_avg(String st) { int i, sm = 0; int l = st.length(); char ch; for (i = 0; i < l; i++) { ch = st.charAt(i); // Calculate the sum of ASCII // values of each character sm = sm + (int)(ch); } // Calculate the average of ASCII values int avg = (int)(Math.floor(sm / l)); // Convert the ASCII value to character // and return it return ((char)(avg)); } // Driver code public static void main(String[] args) { String st = "ag23sdfa"; // Get the average character char ch = find_avg(st); System.out.println(ch); // Check if the average character // is present in string or not if (check_char(st, ch) == true) System.out.println("Yes"); else System.out.println("No"); }}
# Python 3 program to check if the average # character is present in the string or notfrom math import floor # Checks if the character is presentdef check_char(st, ch): # Get the length of string l = len(st) # Iterate from i=0 to # the length of the string # to check if the character # is present in the string for i in range(l): if (st[i] == ch): return True return False # Finds the average character# of the stringdef find_avg(st): sm = 0 l = len(st) for i in range(l): ch = st[i] # Calculate the sum of ASCII # values of each character sm = sm + ord(ch) # Calculate average of ascii values avg = int(floor(sm / l)) # Convert the ASCII value to character # and return it return (chr(avg)) # Driver codeif __name__ == '__main__': st = "ag23sdfa" # Get the average character ch = find_avg(st) print(ch) # Check if the average character # is present in string or not if (check_char(st, ch) == True): print("Yes") else: print("No") # This code is contributed by# Surendra_Gangwar
// C# program to check if the average character// is present in the string or notusing System; class GFG { // Checks if the character is present static bool check_char(string st, char ch) { // Get the length of string int l = st.Length; // Iterate from i=0 to // the length of the string // to check if the character // is present in the string for (int i = 0; i < l; i++) { if (st[i] == ch) return true; } return false; } // Finds the average character of the string static char find_avg(string st) { int i, sm = 0; int l = st.Length; char ch; for (i = 0; i < l; i++) { ch = st[i]; // Calculate the sum of ASCII // values of each character sm = sm + (int)(ch); } // Calculate the average of ASCII values int avg = (int)(Math.Floor((double)(sm / l))); // Convert the ASCII value to character // and return it return ((char)(avg)); } // Driver code public static void Main() { string st = "ag23sdfa"; // Get the average character char ch = find_avg(st); Console.WriteLine(ch); // Check if the average character // is present in string or not if (check_char(st, ch) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Akanksha Rai
Y
No
SURENDRA_GANGWAR
Akanksha_Rai
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Exceptions in Java
Ternary Operator in Python
Inline Functions in C++
Destructors in C++
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
|
[
{
"code": null,
"e": 24150,
"s": 24122,
"text": "\n05 Apr, 2019"
},
{
"code": null,
"e": 24445,
"s": 24150,
"text": "Given a string of alphanumeric characters, the task is to check whether the average character of the string is present or not. Average character refers to the character corresponding to the ASCII value which is the floor of the average value of the ASCII values of all characters in the string."
},
{
"code": null,
"e": 24455,
"s": 24445,
"text": "Examples:"
},
{
"code": null,
"e": 24745,
"s": 24455,
"text": "Input: abcdef\nOutput: d \nYes\nExplanation:\n string = \"abcdef\"\n ASCII values of a = 97, b=98, \n c=99, d=100, e=101, f=101\n Sum of these values is 597\n Average is 99.5 ~ 100 \n Character of ASCII value 100 = d\n Hence d is present in the string.\n\nInput: MNFGH\nOutput: J\nNo\n"
},
{
"code": null,
"e": 24847,
"s": 24745,
"text": "Approach: The approach to solve this problem is very simple. It can be solved in the following steps:"
},
{
"code": null,
"e": 24921,
"s": 24847,
"text": "Find the sum of ASCII values of all the characters from the given string."
},
{
"code": null,
"e": 24997,
"s": 24921,
"text": "Find the average of the ASCII value as average = (sum / numberOfCharacters)"
},
{
"code": null,
"e": 25065,
"s": 24997,
"text": "Get the character of this average ASCII value. Print this character"
},
{
"code": null,
"e": 25151,
"s": 25065,
"text": "Check if this character is present in the string or not. Print Yes or No accordingly."
},
{
"code": null,
"e": 25202,
"s": 25151,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25218,
"s": 25202,
"text": "Implementation:"
},
{
"code": null,
"e": 25222,
"s": 25218,
"text": "C++"
},
{
"code": null,
"e": 25227,
"s": 25222,
"text": "Java"
},
{
"code": null,
"e": 25235,
"s": 25227,
"text": "Python3"
},
{
"code": null,
"e": 25238,
"s": 25235,
"text": "C#"
},
{
"code": "// CPP program to check if the average character// is present in the string or not #include <bits/stdc++.h>#include <math.h>using namespace std; // Checks if the character is presentbool check_char(char* st, char ch){ // Get the length of string int l = strlen(st); // Iterate from i=0 to // the length of the string // to check if the character // is present in the string for (int i = 0; i < l; i++) { if (st[i] == ch) return true; } return false;} // Finds the average character of the stringchar find_avg(char* st){ int i, sm = 0; int l = strlen(st); char ch; for (i = 0; i < l; i++) { ch = st[i]; // Calculate the sum of ASCII // values of each character sm = sm + (int)(ch); } // Calculate average of ascii values int avg = (int)(floor(sm / l)); // Convert the ASCII value to character // and return it return ((char)(avg));} // Driver codeint main(){ char st[] = \"ag23sdfa\"; // Get the average character char ch = find_avg(st); cout << ch << endl; // Check if the average character // is present in string or not if (check_char(st, ch) == true) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 26499,
"s": 25238,
"text": null
},
{
"code": "// Java program to check if the average character// is present in the string or not import java.math.*; class GFG { // Checks if the character is present static boolean check_char(String st, char ch) { // Get the length of string int l = st.length(); // Iterate from i=0 to // the length of the string // to check if the character // is present in the string for (int i = 0; i < l; i++) { if (st.charAt(i) == ch) return true; } return false; } // Finds the average character of the string static char find_avg(String st) { int i, sm = 0; int l = st.length(); char ch; for (i = 0; i < l; i++) { ch = st.charAt(i); // Calculate the sum of ASCII // values of each character sm = sm + (int)(ch); } // Calculate the average of ASCII values int avg = (int)(Math.floor(sm / l)); // Convert the ASCII value to character // and return it return ((char)(avg)); } // Driver code public static void main(String[] args) { String st = \"ag23sdfa\"; // Get the average character char ch = find_avg(st); System.out.println(ch); // Check if the average character // is present in string or not if (check_char(st, ch) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}",
"e": 28022,
"s": 26499,
"text": null
},
{
"code": "# Python 3 program to check if the average # character is present in the string or notfrom math import floor # Checks if the character is presentdef check_char(st, ch): # Get the length of string l = len(st) # Iterate from i=0 to # the length of the string # to check if the character # is present in the string for i in range(l): if (st[i] == ch): return True return False # Finds the average character# of the stringdef find_avg(st): sm = 0 l = len(st) for i in range(l): ch = st[i] # Calculate the sum of ASCII # values of each character sm = sm + ord(ch) # Calculate average of ascii values avg = int(floor(sm / l)) # Convert the ASCII value to character # and return it return (chr(avg)) # Driver codeif __name__ == '__main__': st = \"ag23sdfa\" # Get the average character ch = find_avg(st) print(ch) # Check if the average character # is present in string or not if (check_char(st, ch) == True): print(\"Yes\") else: print(\"No\") # This code is contributed by# Surendra_Gangwar",
"e": 29164,
"s": 28022,
"text": null
},
{
"code": "// C# program to check if the average character// is present in the string or notusing System; class GFG { // Checks if the character is present static bool check_char(string st, char ch) { // Get the length of string int l = st.Length; // Iterate from i=0 to // the length of the string // to check if the character // is present in the string for (int i = 0; i < l; i++) { if (st[i] == ch) return true; } return false; } // Finds the average character of the string static char find_avg(string st) { int i, sm = 0; int l = st.Length; char ch; for (i = 0; i < l; i++) { ch = st[i]; // Calculate the sum of ASCII // values of each character sm = sm + (int)(ch); } // Calculate the average of ASCII values int avg = (int)(Math.Floor((double)(sm / l))); // Convert the ASCII value to character // and return it return ((char)(avg)); } // Driver code public static void Main() { string st = \"ag23sdfa\"; // Get the average character char ch = find_avg(st); Console.WriteLine(ch); // Check if the average character // is present in string or not if (check_char(st, ch) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Akanksha Rai",
"e": 30710,
"s": 29164,
"text": null
},
{
"code": null,
"e": 30716,
"s": 30710,
"text": "Y\nNo\n"
},
{
"code": null,
"e": 30733,
"s": 30716,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 30746,
"s": 30733,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30765,
"s": 30746,
"text": "School Programming"
},
{
"code": null,
"e": 30773,
"s": 30765,
"text": "Strings"
},
{
"code": null,
"e": 30781,
"s": 30773,
"text": "Strings"
},
{
"code": null,
"e": 30879,
"s": 30781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30888,
"s": 30879,
"text": "Comments"
},
{
"code": null,
"e": 30901,
"s": 30888,
"text": "Old Comments"
},
{
"code": null,
"e": 30922,
"s": 30901,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30941,
"s": 30922,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30968,
"s": 30941,
"text": "Ternary Operator in Python"
},
{
"code": null,
"e": 30992,
"s": 30968,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 31011,
"s": 30992,
"text": "Destructors in C++"
},
{
"code": null,
"e": 31057,
"s": 31011,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 31091,
"s": 31057,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 31151,
"s": 31091,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31226,
"s": 31151,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
What is the character wrapper class and its methods in Java?
|
The Character class of the java.lang package wraps a value of the primitive datatype char. It offers a number of useful class (i.e., static) methods for manipulating characters. You can create a Character object with the Character constructor.
Character ch = new Character('a');
Following are the notable methods of the Character class.
isLetter()
Determines whether the specified char value is a letter.
isDigit()
Determines whether the specified char value is a digit.
isWhitespace()
Determines whether the specified char value is white space.
isUpperCase()
Determines whether the specified char value is uppercase.
isLowerCase()
Determines whether the specified char value is lowercase.
toUpperCase()
Returns the uppercase form of the specified char value.
toLowerCase()
Returns the lowercase form of the specified char value.
toString()
Returns a String object representing the specified character value that is, a one-character string.
Live Demo
public class CharacterClassExample {
public static void main(String[] args) {
char ch1, ch2;
ch1 = '9';
ch2 = 'V';
boolean b1, b2;
b1 = Character.isDigit(ch1);
b2 = Character.isDigit(ch2);
String str1 = ch1 + " is a digit is " + b1;
String str2 = ch2 + " is a digit is " + b2;
System.out.println( str1 );
System.out.println( str2 );
}
}
9 is a digit is true
V is a digit is false
|
[
{
"code": null,
"e": 1306,
"s": 1062,
"text": "The Character class of the java.lang package wraps a value of the primitive datatype char. It offers a number of useful class (i.e., static) methods for manipulating characters. You can create a Character object with the Character constructor."
},
{
"code": null,
"e": 1342,
"s": 1306,
"text": "Character ch = new Character('a');\n"
},
{
"code": null,
"e": 1400,
"s": 1342,
"text": "Following are the notable methods of the Character class."
},
{
"code": null,
"e": 1411,
"s": 1400,
"text": "isLetter()"
},
{
"code": null,
"e": 1468,
"s": 1411,
"text": "Determines whether the specified char value is a letter."
},
{
"code": null,
"e": 1478,
"s": 1468,
"text": "isDigit()"
},
{
"code": null,
"e": 1534,
"s": 1478,
"text": "Determines whether the specified char value is a digit."
},
{
"code": null,
"e": 1549,
"s": 1534,
"text": "isWhitespace()"
},
{
"code": null,
"e": 1609,
"s": 1549,
"text": "Determines whether the specified char value is white space."
},
{
"code": null,
"e": 1623,
"s": 1609,
"text": "isUpperCase()"
},
{
"code": null,
"e": 1681,
"s": 1623,
"text": "Determines whether the specified char value is uppercase."
},
{
"code": null,
"e": 1695,
"s": 1681,
"text": "isLowerCase()"
},
{
"code": null,
"e": 1753,
"s": 1695,
"text": "Determines whether the specified char value is lowercase."
},
{
"code": null,
"e": 1767,
"s": 1753,
"text": "toUpperCase()"
},
{
"code": null,
"e": 1823,
"s": 1767,
"text": "Returns the uppercase form of the specified char value."
},
{
"code": null,
"e": 1837,
"s": 1823,
"text": "toLowerCase()"
},
{
"code": null,
"e": 1893,
"s": 1837,
"text": "Returns the lowercase form of the specified char value."
},
{
"code": null,
"e": 1904,
"s": 1893,
"text": "toString()"
},
{
"code": null,
"e": 2004,
"s": 1904,
"text": "Returns a String object representing the specified character value that is, a one-character string."
},
{
"code": null,
"e": 2015,
"s": 2004,
"text": " Live Demo"
},
{
"code": null,
"e": 2432,
"s": 2015,
"text": "public class CharacterClassExample {\n public static void main(String[] args) {\n char ch1, ch2;\n ch1 = '9';\n ch2 = 'V';\n \n boolean b1, b2;\n b1 = Character.isDigit(ch1);\n b2 = Character.isDigit(ch2);\n \n String str1 = ch1 + \" is a digit is \" + b1;\n String str2 = ch2 + \" is a digit is \" + b2;\n System.out.println( str1 );\n System.out.println( str2 );\n }\n}"
},
{
"code": null,
"e": 2476,
"s": 2432,
"text": "9 is a digit is true\nV is a digit is false\n"
}
] |
Check for Balanced Tree | Practice | GeeksforGeeks
|
Given a binary tree, find if it is height balanced or not.
A tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes of tree.
A height balanced tree
1
/ \
10 39
/
5
An unbalanced tree
1
/
10
/
5
Example 1:
Input:
1
/
2
\
3
Output: 0
Explanation: The max difference in height
of left subtree and right subtree is 2,
which is greater than 1. Hence unbalanced
Example 2:
Input:
10
/ \
20 30
/ \
40 60
Output: 1
Explanation: The max difference in height
of left subtree and right subtree is 1.
Hence balanced.
Your Task:
You don't need to take input. Just complete the function isBalanced() that takes root node as parameter and returns true, if the tree is balanced else returns false.
Constraints:
1 <= Number of nodes <= 105
0 <= Data of a node <= 106
Expected time complexity: O(N)
Expected auxiliary space: O(h) , where h = height of tree
+1
mayurkamble8473 hours ago
int height(Node *root)
{
int lh= root==NULL?0:height(root->left);
int rh= root==NULL?0:height(root->right);
return lh>rh?lh+1:rh+1;
}
int balanceFactor(Node *root)
{
return abs(height(root->left)-height(root->right));
}
class Solution{
public:
//Function to check whether a binary tree is balanced or not.
bool isBalanced(Node *root)
{
// Your Code here
if(root==NULL)
return 0;
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node *p=q.front();
q.pop();
if(balanceFactor(p)>1)
return 0;
if(p->left!=NULL)
q.push(p->left);
if(p->right!=NULL)
q.push(p->right);
}
return 1;
}
};
0
ayush94602461251 day ago
SIMPLE C++ SOLUTION::
class Solution{ public: //Function to check whether a binary tree is balanced or not. int height(Node* root){ if(root==NULL) return 0; int leftHeight=height(root->left); if(leftHeight==-1) return -1; int rightHeight=height(root->right); if(rightHeight==-1) return -1; if(abs(leftHeight-rightHeight)>1) return -1; return max(leftHeight,rightHeight)+1; } bool isBalanced(Node *root) { // Your Code here return height(root)!=-1; }};
0
randeepsarma102 days ago
int d =0;
int funct(Node*root){
if(root==NULL)return 0;
int lh=funct(root->left);
int rh=funct(root->right);
d=max(d,abs(lh-rh));
return max(lh,rh)+1;
}
bool isBalanced(Node *root)
{
// Your Code here
funct(root);
if(d>1)return false;
return true;
}
0
rajeshsurana2 days ago
Java Solution from GeeksforGeeks article
class Height { int height; }
boolean isBalanced(Node root, Height h) {
if (root == null) {
h.height = 0;
return true;
}
Height lh = new Height(), rh = new Height();
boolean lb = isBalanced(root.left, lh);
boolean rb = isBalanced(root.right, rh);
h.height = Math.max(lh.height, rh.height) + 1;
return Math.abs(lh.height-rh.height)<2 && lb && rb;
}
boolean isBalanced(Node root)
{
return isBalanced(root, new Height());
}
0
swatibovi4 days ago
Anyone getting TLE for the recursive solution?
----------------------------------------------------------------------------JAVA CODE
boolean isBalanced(Node root) { if(findHeight(root) == -1) return false; else return true; } int findHeight(Node node){ if(node == null) return 0; if(findHeight(node.left) == -1 || findHeight(node.right) == -1) return -1; if(Math.abs(findHeight(node.left) - findHeight(node.right)) > 1) return -1; return 1 + Math.max(findHeight(node.left), findHeight(node.right)); }
+1
ialtafshaikh1 week ago
Python Solution using max height of Binary Tree | TC O(n)
-----------------------------------------------------------------
class Solution: def isBalanced(self,root): return self.maxHeight(root) != -1 def maxHeight(self, root): if(root is None): return 0 lh = self.maxHeight(root.left) if(lh == -1): return -1 rh = self.maxHeight(root.right) if(rh == -1): return -1 # balanced tree condition # abs()=> it will remove the negative sign of the number. if(abs(lh-rh) > 1): return -1 return 1 + max(lh, rh)
0
satviksingh351 week ago
class Solution{ public: int check(Node* node, int height, bool &ans){ if(node==NULL) return height; int lh = check(node->left, height+1, ans); int rh = check(node->right, height+1, ans); if(abs(lh-rh)>1) ans = false; return max(lh, rh); } bool isBalanced(Node *node) { int height=0; bool ans = true; check(node, height, ans); return ans; }};
0
itachinamikaze2211 week ago
int helper(Node root) { if(root==null) return 0; int l=helper(root.left); int r=helper(root.right); if(l==-1||r==-1) { return -1; } if(Math.abs(l-r)>1) { return -1; } else { return 1+Math.max(l,r); } } //Function to check whether a binary tree is balanced or not. boolean isBalanced(Node root) { int res= helper(root); if(res==-1) return false; else return true; }}
+1
tirtha19025681 week ago
class Tree
{
boolean isBalanced(Node root)
{
if(root == null) return true;
int lh = height(root.left);
int rh = height(root.right);
int diff = Math.abs(lh-rh);
if(diff>1) return false;
return isBalanced(root.left) && isBalanced(root.right);
}
int height(Node root){
if(root == null) return 0;
return Math.max(height(root.left),height(root.right))+1;
}
}
0
anshulgupta966262 weeks ago
int check(Node *root){
if(root == NULL){
return 0;
}
else{
int left = check(root->left);
int right = check(root->right);
if(right == -1 || left == -1){
return -1;
}
if(abs(left-right) > 1){
return -1;
}
return 1 + max(left, right);
}
}
bool isBalanced(Node *root)
{
// Your Code here
int n = check(root);
if(n == -1){
return false;
}
return true;
}
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": 426,
"s": 238,
"text": "Given a binary tree, find if it is height balanced or not. \nA tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes of tree. "
},
{
"code": null,
"e": 492,
"s": 426,
"text": "A height balanced tree\n 1\n / \\\n 10 39\n /\n5"
},
{
"code": null,
"e": 547,
"s": 492,
"text": "An unbalanced tree\n 1\n / \n 10 \n /\n5"
},
{
"code": null,
"e": 558,
"s": 547,
"text": "Example 1:"
},
{
"code": null,
"e": 733,
"s": 558,
"text": "Input:\n 1\n /\n 2\n \\\n 3 \nOutput: 0\nExplanation: The max difference in height\nof left subtree and right subtree is 2,\nwhich is greater than 1. Hence unbalanced\n"
},
{
"code": null,
"e": 744,
"s": 733,
"text": "Example 2:"
},
{
"code": null,
"e": 912,
"s": 744,
"text": "Input:\n 10\n / \\\n 20 30 \n / \\\n 40 60\nOutput: 1\nExplanation: The max difference in height\nof left subtree and right subtree is 1.\nHence balanced. \n"
},
{
"code": null,
"e": 1089,
"s": 912,
"text": "Your Task:\nYou don't need to take input. Just complete the function isBalanced() that takes root node as parameter and returns true, if the tree is balanced else returns false."
},
{
"code": null,
"e": 1157,
"s": 1089,
"text": "Constraints:\n1 <= Number of nodes <= 105\n0 <= Data of a node <= 106"
},
{
"code": null,
"e": 1246,
"s": 1157,
"text": "Expected time complexity: O(N)\nExpected auxiliary space: O(h) , where h = height of tree"
},
{
"code": null,
"e": 1249,
"s": 1246,
"text": "+1"
},
{
"code": null,
"e": 1275,
"s": 1249,
"text": "mayurkamble8473 hours ago"
},
{
"code": null,
"e": 2143,
"s": 1275,
"text": " int height(Node *root)\n {\n int lh= root==NULL?0:height(root->left);\n int rh= root==NULL?0:height(root->right);\n \n return lh>rh?lh+1:rh+1;\n\n }\n int balanceFactor(Node *root)\n {\n return abs(height(root->left)-height(root->right));\n }\n\nclass Solution{\n public:\n //Function to check whether a binary tree is balanced or not.\n bool isBalanced(Node *root)\n {\n // Your Code here\n if(root==NULL)\n return 0;\n \n queue<Node*> q;\n q.push(root);\n \n while(!q.empty())\n {\n Node *p=q.front();\n q.pop();\n if(balanceFactor(p)>1)\n return 0;\n \n if(p->left!=NULL)\n q.push(p->left);\n \n if(p->right!=NULL)\n q.push(p->right);\n \n }\n \n return 1;\n }\n};"
},
{
"code": null,
"e": 2145,
"s": 2143,
"text": "0"
},
{
"code": null,
"e": 2170,
"s": 2145,
"text": "ayush94602461251 day ago"
},
{
"code": null,
"e": 2192,
"s": 2170,
"text": "SIMPLE C++ SOLUTION::"
},
{
"code": null,
"e": 2728,
"s": 2194,
"text": "class Solution{ public: //Function to check whether a binary tree is balanced or not. int height(Node* root){ if(root==NULL) return 0; int leftHeight=height(root->left); if(leftHeight==-1) return -1; int rightHeight=height(root->right); if(rightHeight==-1) return -1; if(abs(leftHeight-rightHeight)>1) return -1; return max(leftHeight,rightHeight)+1; } bool isBalanced(Node *root) { // Your Code here return height(root)!=-1; }};"
},
{
"code": null,
"e": 2730,
"s": 2728,
"text": "0"
},
{
"code": null,
"e": 2755,
"s": 2730,
"text": "randeepsarma102 days ago"
},
{
"code": null,
"e": 3125,
"s": 2755,
"text": "int d =0;\n int funct(Node*root){\n if(root==NULL)return 0;\n \n int lh=funct(root->left);\n int rh=funct(root->right);\n d=max(d,abs(lh-rh));\n return max(lh,rh)+1;\n }\n bool isBalanced(Node *root)\n {\n // Your Code here\n funct(root);\n \n if(d>1)return false;\n return true;\n \n }"
},
{
"code": null,
"e": 3127,
"s": 3125,
"text": "0"
},
{
"code": null,
"e": 3150,
"s": 3127,
"text": "rajeshsurana2 days ago"
},
{
"code": null,
"e": 3192,
"s": 3150,
"text": "Java Solution from GeeksforGeeks article "
},
{
"code": null,
"e": 3725,
"s": 3192,
"text": " class Height { int height; }\n boolean isBalanced(Node root, Height h) {\n if (root == null) {\n h.height = 0;\n return true;\n }\n Height lh = new Height(), rh = new Height();\n boolean lb = isBalanced(root.left, lh);\n boolean rb = isBalanced(root.right, rh);\n h.height = Math.max(lh.height, rh.height) + 1;\n return Math.abs(lh.height-rh.height)<2 && lb && rb; \n }\n boolean isBalanced(Node root)\n {\n return isBalanced(root, new Height());\n }"
},
{
"code": null,
"e": 3727,
"s": 3725,
"text": "0"
},
{
"code": null,
"e": 3747,
"s": 3727,
"text": "swatibovi4 days ago"
},
{
"code": null,
"e": 3795,
"s": 3747,
"text": "Anyone getting TLE for the recursive solution? "
},
{
"code": null,
"e": 3881,
"s": 3795,
"text": "----------------------------------------------------------------------------JAVA CODE"
},
{
"code": null,
"e": 4355,
"s": 3881,
"text": "boolean isBalanced(Node root) { if(findHeight(root) == -1) return false; else return true; } int findHeight(Node node){ if(node == null) return 0; if(findHeight(node.left) == -1 || findHeight(node.right) == -1) return -1; if(Math.abs(findHeight(node.left) - findHeight(node.right)) > 1) return -1; return 1 + Math.max(findHeight(node.left), findHeight(node.right)); } "
},
{
"code": null,
"e": 4358,
"s": 4355,
"text": "+1"
},
{
"code": null,
"e": 4381,
"s": 4358,
"text": "ialtafshaikh1 week ago"
},
{
"code": null,
"e": 4439,
"s": 4381,
"text": "Python Solution using max height of Binary Tree | TC O(n)"
},
{
"code": null,
"e": 4505,
"s": 4439,
"text": "-----------------------------------------------------------------"
},
{
"code": null,
"e": 5012,
"s": 4505,
"text": "class Solution: def isBalanced(self,root): return self.maxHeight(root) != -1 def maxHeight(self, root): if(root is None): return 0 lh = self.maxHeight(root.left) if(lh == -1): return -1 rh = self.maxHeight(root.right) if(rh == -1): return -1 # balanced tree condition # abs()=> it will remove the negative sign of the number. if(abs(lh-rh) > 1): return -1 return 1 + max(lh, rh)"
},
{
"code": null,
"e": 5014,
"s": 5012,
"text": "0"
},
{
"code": null,
"e": 5038,
"s": 5014,
"text": "satviksingh351 week ago"
},
{
"code": null,
"e": 5446,
"s": 5038,
"text": "class Solution{ public: int check(Node* node, int height, bool &ans){ if(node==NULL) return height; int lh = check(node->left, height+1, ans); int rh = check(node->right, height+1, ans); if(abs(lh-rh)>1) ans = false; return max(lh, rh); } bool isBalanced(Node *node) { int height=0; bool ans = true; check(node, height, ans); return ans; }};"
},
{
"code": null,
"e": 5448,
"s": 5446,
"text": "0"
},
{
"code": null,
"e": 5476,
"s": 5448,
"text": "itachinamikaze2211 week ago"
},
{
"code": null,
"e": 5994,
"s": 5476,
"text": " int helper(Node root) { if(root==null) return 0; int l=helper(root.left); int r=helper(root.right); if(l==-1||r==-1) { return -1; } if(Math.abs(l-r)>1) { return -1; } else { return 1+Math.max(l,r); } } //Function to check whether a binary tree is balanced or not. boolean isBalanced(Node root) { int res= helper(root); if(res==-1) return false; else return true; }}"
},
{
"code": null,
"e": 5997,
"s": 5994,
"text": "+1"
},
{
"code": null,
"e": 6021,
"s": 5997,
"text": "tirtha19025681 week ago"
},
{
"code": null,
"e": 6440,
"s": 6021,
"text": "class Tree\n{\n boolean isBalanced(Node root)\n {\n if(root == null) return true;\n int lh = height(root.left);\n int rh = height(root.right);\n int diff = Math.abs(lh-rh);\n if(diff>1) return false;\n return isBalanced(root.left) && isBalanced(root.right);\n }\n \n int height(Node root){\n if(root == null) return 0;\n \n return Math.max(height(root.left),height(root.right))+1;\n }\n}"
},
{
"code": null,
"e": 6442,
"s": 6440,
"text": "0"
},
{
"code": null,
"e": 6470,
"s": 6442,
"text": "anshulgupta966262 weeks ago"
},
{
"code": null,
"e": 7053,
"s": 6470,
"text": "int check(Node *root){\n if(root == NULL){\n return 0;\n }\n else{\n int left = check(root->left);\n int right = check(root->right);\n if(right == -1 || left == -1){\n return -1;\n }\n if(abs(left-right) > 1){\n return -1;\n }\n return 1 + max(left, right);\n }\n }\n bool isBalanced(Node *root)\n {\n // Your Code here\n int n = check(root);\n if(n == -1){\n return false;\n }\n return true;\n }\n "
},
{
"code": null,
"e": 7199,
"s": 7053,
"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": 7235,
"s": 7199,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7245,
"s": 7235,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7255,
"s": 7245,
"text": "\nContest\n"
},
{
"code": null,
"e": 7318,
"s": 7255,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7466,
"s": 7318,
"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": 7674,
"s": 7466,
"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": 7780,
"s": 7674,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Setup Web Server Over Docker Container in Linux - GeeksforGeeks
|
04 May, 2020
Before setting up a server we must know the real meaning or definition of a server. So, the Server is a program that provides the client with any kind of services. For example, a web server provides our websites, a database server provides us data. This means every server has work to do and for every different work we want them to do, we have to choose different servers.For knowing more about servers and their working click here. To check more about dockers – click here.
Linux Operating system Like Ubuntu, Redhat, Kali Linux.Internet connectivityDocker installed on system
Linux Operating system Like Ubuntu, Redhat, Kali Linux.
Internet connectivity
Docker installed on system
Let’s now understand the installation and configuration.
Install the Server Program
Configuration of Server
Start the server
Start docker services.
systemctl start docker
Open the docker container, you can use centos 7 images to launch.If you don’t have centos images you can download it from the www.hub.docker.com
docker run -it --network host centos:7
We are going to use HTTPD server.It could be installed using YUM command and DNF if you are using RHEL 8.
yum install httpd
webserver installation
Actually the server is already been configured and now its the time to update or make a website over this server.Server website can be accessed using the IP address of the host.Setup website
cd /var/www/html/
In this directory you could save your website and it would be available over the network.
systemctl start httpd
If this doesn’t start the server, try this
/usr/sbin/httpd
To access the content of the webserver you must know the ip address, which could be known using “ifconfig” command.And then do the further steps.
curl http://IP of host/page_name.html
Visit Webpage
linux
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
ZIP command in Linux with examples
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
'crontab' in Linux with Examples
Tail command in Linux with examples
UDP Server-Client implementation in C
diff command in Linux with examples
|
[
{
"code": null,
"e": 25831,
"s": 25803,
"text": "\n04 May, 2020"
},
{
"code": null,
"e": 26307,
"s": 25831,
"text": "Before setting up a server we must know the real meaning or definition of a server. So, the Server is a program that provides the client with any kind of services. For example, a web server provides our websites, a database server provides us data. This means every server has work to do and for every different work we want them to do, we have to choose different servers.For knowing more about servers and their working click here. To check more about dockers – click here."
},
{
"code": null,
"e": 26410,
"s": 26307,
"text": "Linux Operating system Like Ubuntu, Redhat, Kali Linux.Internet connectivityDocker installed on system"
},
{
"code": null,
"e": 26466,
"s": 26410,
"text": "Linux Operating system Like Ubuntu, Redhat, Kali Linux."
},
{
"code": null,
"e": 26488,
"s": 26466,
"text": "Internet connectivity"
},
{
"code": null,
"e": 26515,
"s": 26488,
"text": "Docker installed on system"
},
{
"code": null,
"e": 26572,
"s": 26515,
"text": "Let’s now understand the installation and configuration."
},
{
"code": null,
"e": 26599,
"s": 26572,
"text": "Install the Server Program"
},
{
"code": null,
"e": 26623,
"s": 26599,
"text": "Configuration of Server"
},
{
"code": null,
"e": 26640,
"s": 26623,
"text": "Start the server"
},
{
"code": null,
"e": 26663,
"s": 26640,
"text": "Start docker services."
},
{
"code": null,
"e": 26686,
"s": 26663,
"text": "systemctl start docker"
},
{
"code": null,
"e": 26831,
"s": 26686,
"text": "Open the docker container, you can use centos 7 images to launch.If you don’t have centos images you can download it from the www.hub.docker.com"
},
{
"code": null,
"e": 26870,
"s": 26831,
"text": "docker run -it --network host centos:7"
},
{
"code": null,
"e": 26976,
"s": 26870,
"text": "We are going to use HTTPD server.It could be installed using YUM command and DNF if you are using RHEL 8."
},
{
"code": null,
"e": 26994,
"s": 26976,
"text": "yum install httpd"
},
{
"code": null,
"e": 27017,
"s": 26994,
"text": "webserver installation"
},
{
"code": null,
"e": 27208,
"s": 27017,
"text": "Actually the server is already been configured and now its the time to update or make a website over this server.Server website can be accessed using the IP address of the host.Setup website"
},
{
"code": null,
"e": 27226,
"s": 27208,
"text": "cd /var/www/html/"
},
{
"code": null,
"e": 27316,
"s": 27226,
"text": "In this directory you could save your website and it would be available over the network."
},
{
"code": null,
"e": 27338,
"s": 27316,
"text": "systemctl start httpd"
},
{
"code": null,
"e": 27381,
"s": 27338,
"text": "If this doesn’t start the server, try this"
},
{
"code": null,
"e": 27397,
"s": 27381,
"text": "/usr/sbin/httpd"
},
{
"code": null,
"e": 27543,
"s": 27397,
"text": "To access the content of the webserver you must know the ip address, which could be known using “ifconfig” command.And then do the further steps."
},
{
"code": null,
"e": 27582,
"s": 27543,
"text": " curl http://IP of host/page_name.html"
},
{
"code": null,
"e": 27596,
"s": 27582,
"text": "Visit Webpage"
},
{
"code": null,
"e": 27602,
"s": 27596,
"text": "linux"
},
{
"code": null,
"e": 27613,
"s": 27602,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27711,
"s": 27613,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27749,
"s": 27711,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27784,
"s": 27749,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 27825,
"s": 27784,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 27860,
"s": 27825,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 27896,
"s": 27860,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 27934,
"s": 27896,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 27967,
"s": 27934,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 28003,
"s": 27967,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 28041,
"s": 28003,
"text": "UDP Server-Client implementation in C"
}
] |
A Protocol Using Selective Repeat
|
Selective repeat protocol, also called Selective Repeat ARQ (Automatic Repeat reQuest), is a data link layer protocol that uses sliding window method for reliable delivery of data frames. Here, only the erroneous or lost frames are retransmitted, while the good frames are received and buffered.
It uses two windows of equal size: a sending window that stores the frames to be sent and a receiving window that stores the frames receive by the receiver. The size is half the maximum sequence number of the frame. For example, if the sequence number is from 0 – 15, the window size will be 8.
Selective Repeat protocol provides for sending multiple frames depending upon the availability of frames in the sending window, even if it does not receive acknowledgement for any frame in the interim. The maximum number of frames that can be sent depends upon the size of the sending window.
The receiver records the sequence number of the earliest incorrect or un-received frame. It then fills the receiving window with the subsequent frames that it has received. It sends the sequence number of the missing frame along with every acknowledgement frame.
The sender continues to send frames that are in its sending window. Once, it has sent all the frames in the window, it retransmits the frame whose sequence number is given by the acknowledgements. It then continues sending the other frames.
begin
frame s; //s denotes frame to be sent
frame t; //t is temporary frame
S_window = power(2,m-1); //Assign maximum window size
SeqFirst = 0; // Sequence number of first frame in window
SeqN = 0; // Sequence number of Nth frame window
while (true) //check repeatedly
do
Wait_For_Event(); //wait for availability of packet
if ( Event(Request_For_Transfer)) then
//check if window is full
if (SeqN–SeqFirst >= S_window) then
doNothing();
end if;
Get_Data_From_Network_Layer();
s = Make_Frame();
s.seq = SeqN;
Store_Copy_Frame(s);
Send_Frame(s);
Start_Timer(s);
SeqN = SeqN + 1;
end if;
if ( Event(Frame_Arrival) then
r = Receive_Acknowledgement();
//Resend frame whose sequence number is with ACK
if ( r.type = NAK) then
if ( NAK_No > SeqFirst && NAK_No < SeqN ) then
Retransmit( s.seq(NAK_No));
Start_Timer(s);
end if
//Remove frames from sending window with positive ACK
else if ( r.type = ACK ) then
Remove_Frame(s.seq(SeqFirst));
Stop_Timer(s);
SeqFirst = SeqFirst + 1;
end if
end if
// Resend frame if acknowledgement haven’t been received
if ( Event(Time_Out)) then
Start_Timer(s);
Retransmit_Frame(s);
end if
end
Begin
frame f;
RSeqNo = 0; // Initialise sequence number of expected frame
NAKsent = false;
ACK = false;
For each slot in receive_window
Mark(slot)=false;
while (true) //check repeatedly
do
Wait_For_Event(); //wait for arrival of frame
if ( Event(Frame_Arrival) then
Receive_Frame_From_Physical_Layer();
if ( Corrupted ( f.SeqNo ) AND NAKsent = false) then
SendNAK(f.SeqNo);
NAKsent = true;
end if
if ( f.SeqNo != RSeqNo AND NAKsent = false ) then
SendNAK(f.SeqNo);
NAKsent = true;
if ( f.SeqNo is in receive_window ) then
if ( Mark(RSeqNo) = false ) then
Store_frame(f.SeqNo);
Mark(RSeqNo) = true;
end if
end if
else
while ( Mark(RSeqNo))
Extract_Data(RSeqNo);
Deliver_Data_To_Network_Layer();
RSeqNo = RSeqNo + 1;
Send_ACK(RSeqNo);
end while
end if
end if
end while
end
|
[
{
"code": null,
"e": 1358,
"s": 1062,
"text": "Selective repeat protocol, also called Selective Repeat ARQ (Automatic Repeat reQuest), is a data link layer protocol that uses sliding window method for reliable delivery of data frames. Here, only the erroneous or lost frames are retransmitted, while the good frames are received and buffered."
},
{
"code": null,
"e": 1653,
"s": 1358,
"text": "It uses two windows of equal size: a sending window that stores the frames to be sent and a receiving window that stores the frames receive by the receiver. The size is half the maximum sequence number of the frame. For example, if the sequence number is from 0 – 15, the window size will be 8."
},
{
"code": null,
"e": 1946,
"s": 1653,
"text": "Selective Repeat protocol provides for sending multiple frames depending upon the availability of frames in the sending window, even if it does not receive acknowledgement for any frame in the interim. The maximum number of frames that can be sent depends upon the size of the sending window."
},
{
"code": null,
"e": 2209,
"s": 1946,
"text": "The receiver records the sequence number of the earliest incorrect or un-received frame. It then fills the receiving window with the subsequent frames that it has received. It sends the sequence number of the missing frame along with every acknowledgement frame."
},
{
"code": null,
"e": 2450,
"s": 2209,
"text": "The sender continues to send frames that are in its sending window. Once, it has sent all the frames in the window, it retransmits the frame whose sequence number is given by the acknowledgements. It then continues sending the other frames."
},
{
"code": null,
"e": 4029,
"s": 2450,
"text": "begin\n frame s; //s denotes frame to be sent\n frame t; //t is temporary frame\n S_window = power(2,m-1); //Assign maximum window size\n SeqFirst = 0; // Sequence number of first frame in window\n SeqN = 0; // Sequence number of Nth frame window\n while (true) //check repeatedly\n do\n Wait_For_Event(); //wait for availability of packet\n if ( Event(Request_For_Transfer)) then\n //check if window is full\n if (SeqN–SeqFirst >= S_window) then\n doNothing();\n end if;\n Get_Data_From_Network_Layer();\n s = Make_Frame();\n s.seq = SeqN;\n Store_Copy_Frame(s);\n Send_Frame(s);\n Start_Timer(s);\n SeqN = SeqN + 1;\n end if;\n if ( Event(Frame_Arrival) then\n r = Receive_Acknowledgement();\n //Resend frame whose sequence number is with ACK\n if ( r.type = NAK) then\n if ( NAK_No > SeqFirst && NAK_No < SeqN ) then\n Retransmit( s.seq(NAK_No));\n Start_Timer(s);\n end if\n //Remove frames from sending window with positive ACK\n else if ( r.type = ACK ) then\n Remove_Frame(s.seq(SeqFirst));\n Stop_Timer(s);\n SeqFirst = SeqFirst + 1;\n end if\n end if\n // Resend frame if acknowledgement haven’t been received\n if ( Event(Time_Out)) then\n Start_Timer(s);\n Retransmit_Frame(s);\n end if\nend"
},
{
"code": null,
"e": 5203,
"s": 4029,
"text": "Begin\n frame f;\n RSeqNo = 0; // Initialise sequence number of expected frame\n NAKsent = false;\n ACK = false;\n For each slot in receive_window\n Mark(slot)=false;\n while (true) //check repeatedly\n do\n Wait_For_Event(); //wait for arrival of frame\n if ( Event(Frame_Arrival) then\n Receive_Frame_From_Physical_Layer();\n if ( Corrupted ( f.SeqNo ) AND NAKsent = false) then\n SendNAK(f.SeqNo);\n NAKsent = true;\n end if\n if ( f.SeqNo != RSeqNo AND NAKsent = false ) then\n SendNAK(f.SeqNo);\n NAKsent = true;\n if ( f.SeqNo is in receive_window ) then\n if ( Mark(RSeqNo) = false ) then\n Store_frame(f.SeqNo);\n Mark(RSeqNo) = true;\n end if\n end if\n else\n while ( Mark(RSeqNo))\n Extract_Data(RSeqNo);\n Deliver_Data_To_Network_Layer();\n RSeqNo = RSeqNo + 1;\n Send_ACK(RSeqNo);\n end while\n end if\n end if\n end while\nend"
}
] |
How to print "GeeksforGeeks" with empty main() in C, C++ and Java? - GeeksforGeeks
|
25 Jul, 2017
Write a program that prints “GeeksforGeeks” with empty main() function. You are not allowed to write anything in main().
C language
One way of doing this is to apply GCC constructor attribute to a function so that it executes before main() (See this for details).#include <stdio.h> /* Apply the constructor attribute to myStartupFun() so that it is executed before main() */void myStartupFun(void) __attribute__((constructor)); /* implementation of myStartupFun */void myStartupFun(void){ printf("GeeksforGeeks");} int main(){}Output:GeeksforGeeksIn linux, just override the default definition of _start() function so that it would work as a custom startup code. See this article to understand more.#include <stdio.h>#include <stdlib.h> int main(void){} // _start() functionvoid _start(void){ printf("GeeeksforGeeks"); // Call main() function int var = main(); exit(var);}Now compile this by following commandgcc -nostartfiles -o file file.cOutput:GeeksforGeeks
One way of doing this is to apply GCC constructor attribute to a function so that it executes before main() (See this for details).#include <stdio.h> /* Apply the constructor attribute to myStartupFun() so that it is executed before main() */void myStartupFun(void) __attribute__((constructor)); /* implementation of myStartupFun */void myStartupFun(void){ printf("GeeksforGeeks");} int main(){}Output:GeeksforGeeks
#include <stdio.h> /* Apply the constructor attribute to myStartupFun() so that it is executed before main() */void myStartupFun(void) __attribute__((constructor)); /* implementation of myStartupFun */void myStartupFun(void){ printf("GeeksforGeeks");} int main(){}
Output:
GeeksforGeeks
In linux, just override the default definition of _start() function so that it would work as a custom startup code. See this article to understand more.#include <stdio.h>#include <stdlib.h> int main(void){} // _start() functionvoid _start(void){ printf("GeeeksforGeeks"); // Call main() function int var = main(); exit(var);}Now compile this by following commandgcc -nostartfiles -o file file.cOutput:GeeksforGeeks
#include <stdio.h>#include <stdlib.h> int main(void){} // _start() functionvoid _start(void){ printf("GeeeksforGeeks"); // Call main() function int var = main(); exit(var);}
Now compile this by following command
gcc -nostartfiles -o file file.c
Output:
GeeksforGeeks
C++ language
The idea is to create a class, have a cout statement in constructor and create a global object of the class. When the object is created, constructor is called and “GeeksforGeeks” is printed.#include <iostream> class MyClass {public: MyClass() { std::cout << "GeeksforGeeks"; }} m; int main(){}Output:GeeksforGeeksThe idea is to create struct and use the same logic which is discussed in above. The reason is that struct and class in C++ are exactly the same data structure except struct default to public visibility while class defaults to private visibility#include <iostream> struct Mystruct { Mystruct() { std::cout << "GeeksforGeeks"; }} obj; int main() {}Output:GeeksforGeeksBy using global variable, idea is to initialise printf() function to global variable, but it will work only in C++ language as in C language we can’t initialise variable or expression like this to global variable.#include <cstdio> int var = printf("GeeksforGeeks"); int main(){}Output:GeeksforGeeks
The idea is to create a class, have a cout statement in constructor and create a global object of the class. When the object is created, constructor is called and “GeeksforGeeks” is printed.#include <iostream> class MyClass {public: MyClass() { std::cout << "GeeksforGeeks"; }} m; int main(){}Output:GeeksforGeeks
#include <iostream> class MyClass {public: MyClass() { std::cout << "GeeksforGeeks"; }} m; int main(){}
Output:
GeeksforGeeks
The idea is to create struct and use the same logic which is discussed in above. The reason is that struct and class in C++ are exactly the same data structure except struct default to public visibility while class defaults to private visibility#include <iostream> struct Mystruct { Mystruct() { std::cout << "GeeksforGeeks"; }} obj; int main() {}Output:GeeksforGeeks
#include <iostream> struct Mystruct { Mystruct() { std::cout << "GeeksforGeeks"; }} obj; int main() {}
Output:
GeeksforGeeks
By using global variable, idea is to initialise printf() function to global variable, but it will work only in C++ language as in C language we can’t initialise variable or expression like this to global variable.#include <cstdio> int var = printf("GeeksforGeeks"); int main(){}Output:GeeksforGeeks
#include <cstdio> int var = printf("GeeksforGeeks"); int main(){}
Output:
GeeksforGeeks
Java language
The idea is to use static block for printing, actually any static blocks declared outside the main() method in java is executed before the main method.
class Myjava { static { System.out.println("GeeksforGeeks"); } public static void main(String args[]) { }}
Output:
GeeksforGeeks
This article is contributed by Viki and improved by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
|
[
{
"code": null,
"e": 26975,
"s": 26947,
"text": "\n25 Jul, 2017"
},
{
"code": null,
"e": 27096,
"s": 26975,
"text": "Write a program that prints “GeeksforGeeks” with empty main() function. You are not allowed to write anything in main()."
},
{
"code": null,
"e": 27107,
"s": 27096,
"text": "C language"
},
{
"code": null,
"e": 27962,
"s": 27107,
"text": "One way of doing this is to apply GCC constructor attribute to a function so that it executes before main() (See this for details).#include <stdio.h> /* Apply the constructor attribute to myStartupFun() so that it is executed before main() */void myStartupFun(void) __attribute__((constructor)); /* implementation of myStartupFun */void myStartupFun(void){ printf(\"GeeksforGeeks\");} int main(){}Output:GeeksforGeeksIn linux, just override the default definition of _start() function so that it would work as a custom startup code. See this article to understand more.#include <stdio.h>#include <stdlib.h> int main(void){} // _start() functionvoid _start(void){ printf(\"GeeeksforGeeks\"); // Call main() function int var = main(); exit(var);}Now compile this by following commandgcc -nostartfiles -o file file.cOutput:GeeksforGeeks"
},
{
"code": null,
"e": 28387,
"s": 27962,
"text": "One way of doing this is to apply GCC constructor attribute to a function so that it executes before main() (See this for details).#include <stdio.h> /* Apply the constructor attribute to myStartupFun() so that it is executed before main() */void myStartupFun(void) __attribute__((constructor)); /* implementation of myStartupFun */void myStartupFun(void){ printf(\"GeeksforGeeks\");} int main(){}Output:GeeksforGeeks"
},
{
"code": "#include <stdio.h> /* Apply the constructor attribute to myStartupFun() so that it is executed before main() */void myStartupFun(void) __attribute__((constructor)); /* implementation of myStartupFun */void myStartupFun(void){ printf(\"GeeksforGeeks\");} int main(){}",
"e": 28661,
"s": 28387,
"text": null
},
{
"code": null,
"e": 28669,
"s": 28661,
"text": "Output:"
},
{
"code": null,
"e": 28683,
"s": 28669,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 29114,
"s": 28683,
"text": "In linux, just override the default definition of _start() function so that it would work as a custom startup code. See this article to understand more.#include <stdio.h>#include <stdlib.h> int main(void){} // _start() functionvoid _start(void){ printf(\"GeeeksforGeeks\"); // Call main() function int var = main(); exit(var);}Now compile this by following commandgcc -nostartfiles -o file file.cOutput:GeeksforGeeks"
},
{
"code": "#include <stdio.h>#include <stdlib.h> int main(void){} // _start() functionvoid _start(void){ printf(\"GeeeksforGeeks\"); // Call main() function int var = main(); exit(var);}",
"e": 29304,
"s": 29114,
"text": null
},
{
"code": null,
"e": 29342,
"s": 29304,
"text": "Now compile this by following command"
},
{
"code": null,
"e": 29375,
"s": 29342,
"text": "gcc -nostartfiles -o file file.c"
},
{
"code": null,
"e": 29383,
"s": 29375,
"text": "Output:"
},
{
"code": null,
"e": 29397,
"s": 29383,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 29410,
"s": 29397,
"text": "C++ language"
},
{
"code": null,
"e": 30429,
"s": 29410,
"text": "The idea is to create a class, have a cout statement in constructor and create a global object of the class. When the object is created, constructor is called and “GeeksforGeeks” is printed.#include <iostream> class MyClass {public: MyClass() { std::cout << \"GeeksforGeeks\"; }} m; int main(){}Output:GeeksforGeeksThe idea is to create struct and use the same logic which is discussed in above. The reason is that struct and class in C++ are exactly the same data structure except struct default to public visibility while class defaults to private visibility#include <iostream> struct Mystruct { Mystruct() { std::cout << \"GeeksforGeeks\"; }} obj; int main() {}Output:GeeksforGeeksBy using global variable, idea is to initialise printf() function to global variable, but it will work only in C++ language as in C language we can’t initialise variable or expression like this to global variable.#include <cstdio> int var = printf(\"GeeksforGeeks\"); int main(){}Output:GeeksforGeeks"
},
{
"code": null,
"e": 30761,
"s": 30429,
"text": "The idea is to create a class, have a cout statement in constructor and create a global object of the class. When the object is created, constructor is called and “GeeksforGeeks” is printed.#include <iostream> class MyClass {public: MyClass() { std::cout << \"GeeksforGeeks\"; }} m; int main(){}Output:GeeksforGeeks"
},
{
"code": "#include <iostream> class MyClass {public: MyClass() { std::cout << \"GeeksforGeeks\"; }} m; int main(){}",
"e": 30883,
"s": 30761,
"text": null
},
{
"code": null,
"e": 30891,
"s": 30883,
"text": "Output:"
},
{
"code": null,
"e": 30905,
"s": 30891,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 31293,
"s": 30905,
"text": "The idea is to create struct and use the same logic which is discussed in above. The reason is that struct and class in C++ are exactly the same data structure except struct default to public visibility while class defaults to private visibility#include <iostream> struct Mystruct { Mystruct() { std::cout << \"GeeksforGeeks\"; }} obj; int main() {}Output:GeeksforGeeks"
},
{
"code": "#include <iostream> struct Mystruct { Mystruct() { std::cout << \"GeeksforGeeks\"; }} obj; int main() {}",
"e": 31416,
"s": 31293,
"text": null
},
{
"code": null,
"e": 31424,
"s": 31416,
"text": "Output:"
},
{
"code": null,
"e": 31438,
"s": 31424,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 31739,
"s": 31438,
"text": "By using global variable, idea is to initialise printf() function to global variable, but it will work only in C++ language as in C language we can’t initialise variable or expression like this to global variable.#include <cstdio> int var = printf(\"GeeksforGeeks\"); int main(){}Output:GeeksforGeeks"
},
{
"code": "#include <cstdio> int var = printf(\"GeeksforGeeks\"); int main(){}",
"e": 31807,
"s": 31739,
"text": null
},
{
"code": null,
"e": 31815,
"s": 31807,
"text": "Output:"
},
{
"code": null,
"e": 31829,
"s": 31815,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 31843,
"s": 31829,
"text": "Java language"
},
{
"code": null,
"e": 31995,
"s": 31843,
"text": "The idea is to use static block for printing, actually any static blocks declared outside the main() method in java is executed before the main method."
},
{
"code": "class Myjava { static { System.out.println(\"GeeksforGeeks\"); } public static void main(String args[]) { }}",
"e": 32127,
"s": 31995,
"text": null
},
{
"code": null,
"e": 32135,
"s": 32127,
"text": "Output:"
},
{
"code": null,
"e": 32149,
"s": 32135,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 32472,
"s": 32149,
"text": "This article is contributed by Viki and improved by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 32483,
"s": 32472,
"text": "C Language"
},
{
"code": null,
"e": 32487,
"s": 32483,
"text": "C++"
},
{
"code": null,
"e": 32491,
"s": 32487,
"text": "CPP"
},
{
"code": null,
"e": 32589,
"s": 32491,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32624,
"s": 32589,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 32670,
"s": 32624,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 32692,
"s": 32670,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 32732,
"s": 32692,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 32760,
"s": 32732,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 32778,
"s": 32760,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 32797,
"s": 32778,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 32843,
"s": 32797,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 32886,
"s": 32843,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
How to convert a decimal number to roman using JavaScript?
|
To convert a decimal number to roman, try to run the following JavaScript code −
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
// roman numeral
var romanNum = new Array();
romanNum = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
// decimal number
var dNum = new Array();
dNum = [1000,900,500,400,100,90,50,40,10,9,5,4,1];
function decimalRoman(value) {
if (value <= 0 || value >= 4000)
return value;
var romanNumeral = "";
for (var i = 0; i<romanNum.length; i++) {
while (value >= dNum[i]) {
value -= dNum[i];
romanNumeral += romanNum[i];
}
}
return romanNumeral;
}
document.write(decimalRoman(39));
document.write("<br>"+decimalRoman(145));
document.write("<br>"+decimalRoman(520));
</script>
</body>
</html>
XXXIX
CXLV
DXX
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "To convert a decimal number to roman, try to run the following JavaScript code −"
},
{
"code": null,
"e": 1153,
"s": 1143,
"text": "Live Demo"
},
{
"code": null,
"e": 2051,
"s": 1153,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n // roman numeral\n var romanNum = new Array();\n romanNum = [\"M\",\"CM\",\"D\",\"CD\",\"C\",\"XC\",\"L\",\"XL\",\"X\",\"IX\",\"V\",\"IV\",\"I\"];\n // decimal number\n var dNum = new Array();\n dNum = [1000,900,500,400,100,90,50,40,10,9,5,4,1];\n function decimalRoman(value) {\n if (value <= 0 || value >= 4000)\n return value;\n var romanNumeral = \"\";\n for (var i = 0; i<romanNum.length; i++) {\n while (value >= dNum[i]) {\n value -= dNum[i];\n romanNumeral += romanNum[i];\n }\n }\n return romanNumeral;\n }\n document.write(decimalRoman(39));\n document.write(\"<br>\"+decimalRoman(145));\n document.write(\"<br>\"+decimalRoman(520));\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 2066,
"s": 2051,
"text": "XXXIX\nCXLV\nDXX"
}
] |
Distributed Component Object Model (DCOM) - GeeksforGeeks
|
22 Jul, 2020
In the last two decades, a massive range of modifications took place in an object-oriented and distributed component-oriented paradigm. To fulfill this demand, Microsoft developed Distributed Component Object Model. DCOM can be defined as COM with inclusion of a long wire and this is an extension to Component Object Model (COM). DCOM- Distributed Component Object Model– helps remote object via running on a protocol known as the.
Object Remote Procedure Call (ORPC). 10 million people use of Windows every day in networked environments DCOM emerge as extensively used primary purpose of DCOM is to support development of components that can be dynamically activated and that can engage with every other. DCOM object model is based on implementations of interfaces.
(DCOM) both object and component paradigm consists of a number of issues.
1. Interoperability
2. Versioning
3. Language independence
4. Size and complexity of system
Dynamic Data Exchange :Dynamic Data Exchange or DDE, used to be designed for Microsoft Windows to enable applications to exchange information of any specific type. As DDE protocol is actually a little complicated and this complexity used to be interpreted by using many software program vendors, Dynamic Data Exchange Management Library (DDEML) was created. This library simplified interfacing with DDE protocol as well as furnished a frequent interface for all developers.
DCOM Architecture :DCOM structure is designed for promoting software interoperability.
The architecture supports a “software bus” on which reusable software program components can be used and built-in with one any other seamlessly.
In order to furnish support for this reusable software component, complete object model is based totally on an object-based programming model.
Object model used to be selected due to fact of its incapability to provide inheritance.
This means that architecture is successful in keeping off fragile base class syndrome which exists in different models.
The fragile base class syndrome seems when one class inherits members and behavior of any other class.
Class which offers behavior and member functions is recognized as base class while other class is recognized as derived class.
If the member and functionality of base class modifications then behavior and member functions of derived class additionally change.
Changes like this end result in having to alter base class which in turn requires compilation of all dependent classes.
DCOM architecture shown in fig 1.0 possesses a special infrastructure as it helps continual storage.
Working of DCOM :For working of DCOM, COM object desires to be configured effectively on both computer systems and you hardly had to uninstall and reinstall objects numerous times to get them to work effectively on a particular task. Windows Registry consists of DCOM configuration information in three identifiers i.e. CLSID, PROGID, and APPID.
CLSID –Class Identifier or CLSID is a Global Unique Identifier or GUID to create a unique identity for an entity. Windows stores this CLSID for every setup class in a program for performing a particular task. When you want to run a class, you need right CLSID, so Windows is aware of place to go and locate program.PROGID –Programmatic Identifier or PROGID is a non-obligatory or you can say an optional identifier a programmer can use as an alternative for any complex and strict CLSID. PROGIDs are generally less complicated to read and can be easily understood. There are no restrictions on how many PROGIDs can have an identical name, which motives problems on occasion.APPID –Application Identifier or APPID is a type of unique identifier for every available app also called App IDs hel ps in securing and authenticating your apps. It identifies all of classes that are part of identical executable andpermissions required to get entry to it. DCOM can’t work if APPID isn’t correct i.e. for DCOM to work perfectly you need to have a correct APPID. You will likely get permissions errors making an attempt to create remote object, in my experience.
CLSID –Class Identifier or CLSID is a Global Unique Identifier or GUID to create a unique identity for an entity. Windows stores this CLSID for every setup class in a program for performing a particular task. When you want to run a class, you need right CLSID, so Windows is aware of place to go and locate program.
PROGID –Programmatic Identifier or PROGID is a non-obligatory or you can say an optional identifier a programmer can use as an alternative for any complex and strict CLSID. PROGIDs are generally less complicated to read and can be easily understood. There are no restrictions on how many PROGIDs can have an identical name, which motives problems on occasion.
APPID –Application Identifier or APPID is a type of unique identifier for every available app also called App IDs hel ps in securing and authenticating your apps. It identifies all of classes that are part of identical executable andpermissions required to get entry to it. DCOM can’t work if APPID isn’t correct i.e. for DCOM to work perfectly you need to have a correct APPID. You will likely get permissions errors making an attempt to create remote object, in my experience.
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
RSA Algorithm in Cryptography
Differences between TCP and UDP
TCP Server-Client implementation in C
Data encryption standard (DES) | Set 1
Differences between IPv4 and IPv6
Socket Programming in Python
Types of Network Topology
TCP 3-Way Handshake Process
Implementation of Diffie-Hellman Algorithm
Types of Transmission Media
|
[
{
"code": null,
"e": 25893,
"s": 25865,
"text": "\n22 Jul, 2020"
},
{
"code": null,
"e": 26326,
"s": 25893,
"text": "In the last two decades, a massive range of modifications took place in an object-oriented and distributed component-oriented paradigm. To fulfill this demand, Microsoft developed Distributed Component Object Model. DCOM can be defined as COM with inclusion of a long wire and this is an extension to Component Object Model (COM). DCOM- Distributed Component Object Model– helps remote object via running on a protocol known as the."
},
{
"code": null,
"e": 26661,
"s": 26326,
"text": "Object Remote Procedure Call (ORPC). 10 million people use of Windows every day in networked environments DCOM emerge as extensively used primary purpose of DCOM is to support development of components that can be dynamically activated and that can engage with every other. DCOM object model is based on implementations of interfaces."
},
{
"code": null,
"e": 26735,
"s": 26661,
"text": "(DCOM) both object and component paradigm consists of a number of issues."
},
{
"code": null,
"e": 26828,
"s": 26735,
"text": "1. Interoperability\n2. Versioning\n3. Language independence\n4. Size and complexity of system "
},
{
"code": null,
"e": 27302,
"s": 26828,
"text": "Dynamic Data Exchange :Dynamic Data Exchange or DDE, used to be designed for Microsoft Windows to enable applications to exchange information of any specific type. As DDE protocol is actually a little complicated and this complexity used to be interpreted by using many software program vendors, Dynamic Data Exchange Management Library (DDEML) was created. This library simplified interfacing with DDE protocol as well as furnished a frequent interface for all developers."
},
{
"code": null,
"e": 27389,
"s": 27302,
"text": "DCOM Architecture :DCOM structure is designed for promoting software interoperability."
},
{
"code": null,
"e": 27534,
"s": 27389,
"text": "The architecture supports a “software bus” on which reusable software program components can be used and built-in with one any other seamlessly."
},
{
"code": null,
"e": 27677,
"s": 27534,
"text": "In order to furnish support for this reusable software component, complete object model is based totally on an object-based programming model."
},
{
"code": null,
"e": 27766,
"s": 27677,
"text": "Object model used to be selected due to fact of its incapability to provide inheritance."
},
{
"code": null,
"e": 27886,
"s": 27766,
"text": "This means that architecture is successful in keeping off fragile base class syndrome which exists in different models."
},
{
"code": null,
"e": 27989,
"s": 27886,
"text": "The fragile base class syndrome seems when one class inherits members and behavior of any other class."
},
{
"code": null,
"e": 28116,
"s": 27989,
"text": "Class which offers behavior and member functions is recognized as base class while other class is recognized as derived class."
},
{
"code": null,
"e": 28249,
"s": 28116,
"text": "If the member and functionality of base class modifications then behavior and member functions of derived class additionally change."
},
{
"code": null,
"e": 28369,
"s": 28249,
"text": "Changes like this end result in having to alter base class which in turn requires compilation of all dependent classes."
},
{
"code": null,
"e": 28470,
"s": 28369,
"text": "DCOM architecture shown in fig 1.0 possesses a special infrastructure as it helps continual storage."
},
{
"code": null,
"e": 28816,
"s": 28470,
"text": "Working of DCOM :For working of DCOM, COM object desires to be configured effectively on both computer systems and you hardly had to uninstall and reinstall objects numerous times to get them to work effectively on a particular task. Windows Registry consists of DCOM configuration information in three identifiers i.e. CLSID, PROGID, and APPID."
},
{
"code": null,
"e": 29969,
"s": 28816,
"text": "CLSID –Class Identifier or CLSID is a Global Unique Identifier or GUID to create a unique identity for an entity. Windows stores this CLSID for every setup class in a program for performing a particular task. When you want to run a class, you need right CLSID, so Windows is aware of place to go and locate program.PROGID –Programmatic Identifier or PROGID is a non-obligatory or you can say an optional identifier a programmer can use as an alternative for any complex and strict CLSID. PROGIDs are generally less complicated to read and can be easily understood. There are no restrictions on how many PROGIDs can have an identical name, which motives problems on occasion.APPID –Application Identifier or APPID is a type of unique identifier for every available app also called App IDs hel ps in securing and authenticating your apps. It identifies all of classes that are part of identical executable andpermissions required to get entry to it. DCOM can’t work if APPID isn’t correct i.e. for DCOM to work perfectly you need to have a correct APPID. You will likely get permissions errors making an attempt to create remote object, in my experience."
},
{
"code": null,
"e": 30285,
"s": 29969,
"text": "CLSID –Class Identifier or CLSID is a Global Unique Identifier or GUID to create a unique identity for an entity. Windows stores this CLSID for every setup class in a program for performing a particular task. When you want to run a class, you need right CLSID, so Windows is aware of place to go and locate program."
},
{
"code": null,
"e": 30645,
"s": 30285,
"text": "PROGID –Programmatic Identifier or PROGID is a non-obligatory or you can say an optional identifier a programmer can use as an alternative for any complex and strict CLSID. PROGIDs are generally less complicated to read and can be easily understood. There are no restrictions on how many PROGIDs can have an identical name, which motives problems on occasion."
},
{
"code": null,
"e": 31124,
"s": 30645,
"text": "APPID –Application Identifier or APPID is a type of unique identifier for every available app also called App IDs hel ps in securing and authenticating your apps. It identifies all of classes that are part of identical executable andpermissions required to get entry to it. DCOM can’t work if APPID isn’t correct i.e. for DCOM to work perfectly you need to have a correct APPID. You will likely get permissions errors making an attempt to create remote object, in my experience."
},
{
"code": null,
"e": 31142,
"s": 31124,
"text": "Computer Networks"
},
{
"code": null,
"e": 31160,
"s": 31142,
"text": "Computer Networks"
},
{
"code": null,
"e": 31258,
"s": 31160,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31288,
"s": 31258,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 31320,
"s": 31288,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 31358,
"s": 31320,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 31397,
"s": 31358,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 31431,
"s": 31397,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 31460,
"s": 31431,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 31486,
"s": 31460,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 31514,
"s": 31486,
"text": "TCP 3-Way Handshake Process"
},
{
"code": null,
"e": 31557,
"s": 31514,
"text": "Implementation of Diffie-Hellman Algorithm"
}
] |
Android - Date Picker
|
Android Date Picker allows you to select the date consisting of day, month and year in your custom user interface. For this functionality android provides DatePicker and DatePickerDialog components.
In this tutorial, we are going to demonstrate the use of Date Picker through DatePickerDialog. DatePickerDialog is a simple dialog containing DatePicker.
In order to show DatePickerDialog , you have to pass the DatePickerDialog id to showDialog(id_of_dialog) method. Its syntax is given below −
showDialog(999);
On calling this showDialog method, another method called onCreateDialog gets automatically called. So we have to override that method too. Its syntax is given below −
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year, month, day);
}
return null;
}
In the last step, you have to register the DatePickerDialog listener and override its onDateSet method. This onDateSet method contains the updated day, month and year. Its syntax is given below −
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// arg1 = year
// arg2 = month
// arg3 = day
}
};
Apart form date attributes, DatePicker object is also passed into this function. You can use the following methods of the DatePicker to perform further operation.
getDayOfMonth()
This method gets the selected day of month
getMonth()
This method gets the selected month
getYear()
This method gets the selected year
setMaxDate(long maxDate)
This method sets the maximal date supported by this DatePicker in milliseconds since January 1, 1970 00:00:00 in getDefault() time zone
setMinDate(long minDate)
This method sets the minimal date supported by this NumberPicker in milliseconds since January 1, 1970 00:00:00 in getDefault() time zone
setSpinnersShown(boolean shown)
This method sets whether the spinners are shown
updateDate(int year, int month, int dayOfMonth)
This method updates the current date
getCalendarView()
This method returns calendar view
getFirstDayOfWeek()
This Method returns first day of the week
Here is an example demonstrating the use of DatePickerDialog class. It creates a basic Date Picker application that allows you to set the Date using DatePicker Widget
To experiment with this example , you can run this on an actual device or in an emulator.
Following is the content of the modified main activity file src/com.example.datepicker/MainActivity.java.
package com.example.datepicker;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateView = (TextView) findViewById(R.id.textView3);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
}
@SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(999);
Toast.makeText(getApplicationContext(), "ca",
Toast.LENGTH_SHORT)
.show();
}
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this,
myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new
DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0,
int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int month, int day) {
dateView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
}
Following is the modified content of the xml 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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:onClick="setDate"
android:text="@string/date_button_set" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:text="@string/date_label_set"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginTop="66dp"
android:layout_toLeftOf="@+id/button1"
android:text="@string/date_view_set"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/button1"
android:layout_below="@+id/textView2"
android:layout_marginTop="72dp"
android:text="@string/date_selected"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Following is the content of the res/values/string.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DatePicker</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="date_label_set">Press the button to set the date</string>
<string name="date_button_set">Set Date</string>
<string name="date_view_set">The Date is: </string>
<string name="date_selected"></string>
</resources>
Let's try to run our DatePicker application we just modified. I assume you had created your AVD while doing environment set-up. To run the app from Eclipse, open one of your project's activity files and click Run icon from the tool bar. Eclipse installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window −
Now you can see that the date has already been set at the bottom label. Now we will change the date through DatePickerDialog by pressing the Set Date button. On pressing the button following screen would appear.
Now set the required date, and after setting the date, press the Done button. This dialog will disappear and your newly setted date will start showing at the screen. This is shown below.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3806,
"s": 3607,
"text": "Android Date Picker allows you to select the date consisting of day, month and year in your custom user interface. For this functionality android provides DatePicker and DatePickerDialog components."
},
{
"code": null,
"e": 3960,
"s": 3806,
"text": "In this tutorial, we are going to demonstrate the use of Date Picker through DatePickerDialog. DatePickerDialog is a simple dialog containing DatePicker."
},
{
"code": null,
"e": 4101,
"s": 3960,
"text": "In order to show DatePickerDialog , you have to pass the DatePickerDialog id to showDialog(id_of_dialog) method. Its syntax is given below −"
},
{
"code": null,
"e": 4118,
"s": 4101,
"text": "showDialog(999);"
},
{
"code": null,
"e": 4285,
"s": 4118,
"text": "On calling this showDialog method, another method called onCreateDialog gets automatically called. So we have to override that method too. Its syntax is given below −"
},
{
"code": null,
"e": 4493,
"s": 4285,
"text": "@Override\nprotected Dialog onCreateDialog(int id) {\n // TODO Auto-generated method stub\n if (id == 999) {\n return new DatePickerDialog(this, myDateListener, year, month, day);\n }\n return null;\n}"
},
{
"code": null,
"e": 4689,
"s": 4493,
"text": "In the last step, you have to register the DatePickerDialog listener and override its onDateSet method. This onDateSet method contains the updated day, month and year. Its syntax is given below −"
},
{
"code": null,
"e": 4952,
"s": 4689,
"text": "private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {\n @Override\n public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {\n // arg1 = year\n // arg2 = month\n // arg3 = day\t\t\n }\n};"
},
{
"code": null,
"e": 5115,
"s": 4952,
"text": "Apart form date attributes, DatePicker object is also passed into this function. You can use the following methods of the DatePicker to perform further operation."
},
{
"code": null,
"e": 5131,
"s": 5115,
"text": "getDayOfMonth()"
},
{
"code": null,
"e": 5174,
"s": 5131,
"text": "This method gets the selected day of month"
},
{
"code": null,
"e": 5185,
"s": 5174,
"text": "getMonth()"
},
{
"code": null,
"e": 5221,
"s": 5185,
"text": "This method gets the selected month"
},
{
"code": null,
"e": 5231,
"s": 5221,
"text": "getYear()"
},
{
"code": null,
"e": 5266,
"s": 5231,
"text": "This method gets the selected year"
},
{
"code": null,
"e": 5291,
"s": 5266,
"text": "setMaxDate(long maxDate)"
},
{
"code": null,
"e": 5427,
"s": 5291,
"text": "This method sets the maximal date supported by this DatePicker in milliseconds since January 1, 1970 00:00:00 in getDefault() time zone"
},
{
"code": null,
"e": 5452,
"s": 5427,
"text": "setMinDate(long minDate)"
},
{
"code": null,
"e": 5590,
"s": 5452,
"text": "This method sets the minimal date supported by this NumberPicker in milliseconds since January 1, 1970 00:00:00 in getDefault() time zone"
},
{
"code": null,
"e": 5622,
"s": 5590,
"text": "setSpinnersShown(boolean shown)"
},
{
"code": null,
"e": 5670,
"s": 5622,
"text": "This method sets whether the spinners are shown"
},
{
"code": null,
"e": 5718,
"s": 5670,
"text": "updateDate(int year, int month, int dayOfMonth)"
},
{
"code": null,
"e": 5755,
"s": 5718,
"text": "This method updates the current date"
},
{
"code": null,
"e": 5773,
"s": 5755,
"text": "getCalendarView()"
},
{
"code": null,
"e": 5807,
"s": 5773,
"text": "This method returns calendar view"
},
{
"code": null,
"e": 5827,
"s": 5807,
"text": "getFirstDayOfWeek()"
},
{
"code": null,
"e": 5869,
"s": 5827,
"text": "This Method returns first day of the week"
},
{
"code": null,
"e": 6036,
"s": 5869,
"text": "Here is an example demonstrating the use of DatePickerDialog class. It creates a basic Date Picker application that allows you to set the Date using DatePicker Widget"
},
{
"code": null,
"e": 6126,
"s": 6036,
"text": "To experiment with this example , you can run this on an actual device or in an emulator."
},
{
"code": null,
"e": 6232,
"s": 6126,
"text": "Following is the content of the modified main activity file src/com.example.datepicker/MainActivity.java."
},
{
"code": null,
"e": 8192,
"s": 6232,
"text": "package com.example.datepicker;\n\nimport java.util.Calendar;\n\nimport android.app.Activity;\nimport android.app.DatePickerDialog;\nimport android.app.Dialog;\n\nimport android.os.Bundle;\n\nimport android.view.Menu;\nimport android.view.View;\n\nimport android.widget.DatePicker;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class MainActivity extends Activity {\n private DatePicker datePicker;\n private Calendar calendar;\n private TextView dateView;\n private int year, month, day;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n dateView = (TextView) findViewById(R.id.textView3);\n calendar = Calendar.getInstance();\n year = calendar.get(Calendar.YEAR);\n \n month = calendar.get(Calendar.MONTH);\n day = calendar.get(Calendar.DAY_OF_MONTH);\n showDate(year, month+1, day);\n }\n\n @SuppressWarnings(\"deprecation\")\n public void setDate(View view) {\n showDialog(999);\n Toast.makeText(getApplicationContext(), \"ca\", \n Toast.LENGTH_SHORT)\n .show();\n }\n\n @Override\n protected Dialog onCreateDialog(int id) {\n // TODO Auto-generated method stub\n if (id == 999) {\n return new DatePickerDialog(this, \n myDateListener, year, month, day);\n }\n return null;\n }\n\n private DatePickerDialog.OnDateSetListener myDateListener = new \n DatePickerDialog.OnDateSetListener() {\n @Override\n public void onDateSet(DatePicker arg0, \n int arg1, int arg2, int arg3) {\n // TODO Auto-generated method stub\n // arg1 = year\n // arg2 = month\n // arg3 = day\n showDate(arg1, arg2+1, arg3);\n }\n };\n\n private void showDate(int year, int month, int day) {\n dateView.setText(new StringBuilder().append(day).append(\"/\")\n .append(month).append(\"/\").append(year));\n }\n}"
},
{
"code": null,
"e": 8267,
"s": 8192,
"text": "Following is the modified content of the xml res/layout/activity_main.xml."
},
{
"code": null,
"e": 10253,
"s": 8267,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout \n 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 android:paddingBottom=\"@dimen/activity_vertical_margin\"\n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\" >\n\n <Button\n android:id=\"@+id/button1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:onClick=\"setDate\"\n android:text=\"@string/date_button_set\" />\n\n <TextView\n android:id=\"@+id/textView1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"24dp\"\n android:text=\"@string/date_label_set\"\n android:textAppearance=\"?android:attr/textAppearanceMedium\" />\n\n <TextView\n android:id=\"@+id/textView2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/button1\"\n android:layout_marginTop=\"66dp\"\n android:layout_toLeftOf=\"@+id/button1\"\n android:text=\"@string/date_view_set\"\n android:textAppearance=\"?android:attr/textAppearanceMedium\" />\n\n <TextView\n android:id=\"@+id/textView3\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignRight=\"@+id/button1\"\n android:layout_below=\"@+id/textView2\"\n android:layout_marginTop=\"72dp\"\n android:text=\"@string/date_selected\"\n android:textAppearance=\"?android:attr/textAppearanceMedium\" />\n\n</RelativeLayout>"
},
{
"code": null,
"e": 10308,
"s": 10253,
"text": "Following is the content of the res/values/string.xml."
},
{
"code": null,
"e": 10747,
"s": 10308,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">DatePicker</string>\n <string name=\"action_settings\">Settings</string>\n <string name=\"hello_world\">Hello world!</string>\n <string name=\"date_label_set\">Press the button to set the date</string>\n <string name=\"date_button_set\">Set Date</string>\n <string name=\"date_view_set\">The Date is: </string>\n <string name=\"date_selected\"></string>\n</resources>"
},
{
"code": null,
"e": 11140,
"s": 10747,
"text": "Let's try to run our DatePicker application we just modified. I assume you had created your AVD while doing environment set-up. To run the app from Eclipse, open one of your project's activity files and click Run icon from the tool bar. Eclipse installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window −"
},
{
"code": null,
"e": 11352,
"s": 11140,
"text": "Now you can see that the date has already been set at the bottom label. Now we will change the date through DatePickerDialog by pressing the Set Date button. On pressing the button following screen would appear."
},
{
"code": null,
"e": 11539,
"s": 11352,
"text": "Now set the required date, and after setting the date, press the Done button. This dialog will disappear and your newly setted date will start showing at the screen. This is shown below."
},
{
"code": null,
"e": 11574,
"s": 11539,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 11586,
"s": 11574,
"text": " Aditya Dua"
},
{
"code": null,
"e": 11621,
"s": 11586,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 11635,
"s": 11621,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 11667,
"s": 11635,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11684,
"s": 11667,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11719,
"s": 11684,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11736,
"s": 11719,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11771,
"s": 11736,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11788,
"s": 11771,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11821,
"s": 11788,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11838,
"s": 11821,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11845,
"s": 11838,
"text": " Print"
},
{
"code": null,
"e": 11856,
"s": 11845,
"text": " Add Notes"
}
] |
Minimum jumps required to reach all array elements using largest element - GeeksforGeeks
|
14 Jan, 2022
Given an array arr[] of N distinct integer, the task is to find the minimum number of jumps required from the largest element to reach all array elements such that a jump is possible from the ith element to the jth element if the value of arr[i] is greater than arr[j] and value of arr[j] is greater than all other elements between the ith and jth element.
Examples:
Input: arr[] = {1, 3, 6, 5}Output: [2, 1, 0, 1]Explanation:Below are the jumps required to reach each platform:
For the 1st platform, the jump from the 3rd platform to the 2nd platform, then jump to the 1st platform is required. Hence, a total of 2 jumps are required.
For the 2nd platform, the jump from the 3rd platform directly to the 2nd platform is required. Hence, a total of 1 jump are required.
For the 3rd platform, we are already on the 3rd platform. Hence, a total of 0 jumps are required.
For the 4th platform, the jump from the 3rd platform directly to the 4th platform is required. Hence, a total of 1 jump are required.
Input: arr[] = {3, 5}Output: [1, 0]
Approach: The given problem can be solved using Dynamic Programming which is based on the observation that the minimum jump possible from the largest element to the ith element is one greater than the minimum of minimum jumps required for the next greater element in the left or right. So, the idea is to precompute the results of larger elements and use them to find answers to smaller elements. Follow the steps below to solve the given problem:
For each array element arr[i] store the two indices L and R representing the index of the next greater element to the left and right in the map respectively.
Sort the array arr[] in descending order.
Initialize a vector, say ans[] that stores the minimum jumps for all array elements.
Traverse the array arr[] and perform the following steps:If the current array element is the largest element then 0 jumps are required for the current element.Find the distance of the next greater element to the left and right of the current element using the value stored in the maps. Store the distances in the variables, L and R respectively.Update the value of minimum jumps, say M as per the following criteria:If L is at least 0 and R is less than N, then the value of M is min(ans[L], ans[R]) + 1.If L is less than 0 and R is less than N, then the value of M is ans[R] + 1.If L is at least 0 and R is at least N, then the value of M is ans[L] + 1.Update the value of minimum jumps for the current index as the value of M.
If the current array element is the largest element then 0 jumps are required for the current element.
Find the distance of the next greater element to the left and right of the current element using the value stored in the maps. Store the distances in the variables, L and R respectively.
Update the value of minimum jumps, say M as per the following criteria:If L is at least 0 and R is less than N, then the value of M is min(ans[L], ans[R]) + 1.If L is less than 0 and R is less than N, then the value of M is ans[R] + 1.If L is at least 0 and R is at least N, then the value of M is ans[L] + 1.
If L is at least 0 and R is less than N, then the value of M is min(ans[L], ans[R]) + 1.
If L is less than 0 and R is less than N, then the value of M is ans[R] + 1.
If L is at least 0 and R is at least N, then the value of M is ans[L] + 1.
Update the value of minimum jumps for the current index as the value of M.
After completing the above steps, print the array ans[] as the resultant jumps of indices.
Below is the implementation of the above approach:
C++
Python3
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define ar array // Function to find next greater element// to left and right of current elementar<int, 2> expand(int idx, vector<int>& A){ // Starting l and r from previous // and the next element of the // current element int l = idx - 1; int r = idx + 1; // FInd the next greater element // to the left while (l >= 0) { if ((int)(A[idx]) > A[l]) { --l; } else { break; } } if (l < 0 || l == idx) { l = -2; } // Find the next greater element // to the right while (r < (int)(A.size())) { if ((int)A[idx] > A[r]) { ++r; } else { break; } } if (r >= (int)(A.size()) || r == idx) { r = -2; } // Return l and r in the form of // array of size 2 return { l, r };} // Function to find the minimum jumps// required to reach to all elements from// the largest elementvector<int> minJumps(int N, vector<int>& A){ vector<int> ans(N, 0); // Stores the mapping from index // to the element in array A[] map<int, ar<int, 2> > mp; map<int, int> iToA; map<int, int> AToi; // Stores largest array element int big = A[0]; // Find the two indices l, r such // that A[l] > A[i] < A[r] and // l<i<r using expand function for (int i = 0; i < N; ++i) { big = max({ big, A[i] }); mp[i] = expand(i, A); iToA[i] = A[i]; AToi[A[i]] = i; } // sorting A in descending order sort(A.begin(), A.end(), greater<int>()); for (int i = 0; i < A.size(); ++i) { // Stores the resultant minimum // jumps required int m; // Check if the current element // is largest or not if (A[i] == big) { int cur = AToi[A[i]]; ans[cur] = 0; continue; } // Find the answer to the // current element int cur = AToi[A[i]]; int l = mp[cur][0]; int r = mp[cur][1]; if (l >= 0 && r < N) { m = min(ans[l], ans[r]) + 1; } else if (l < 0 && r < N) { m = ans[r] + 1; } else if (l >= 0 && r >= N) { m = ans[l] + 1; } // Update the resultant minimum // jumps for the current element ans[cur] = m; } // Return the result return ans;} // Driver Codeint main(){ vector<int> arr = { 5, 1, 3, 4, 7 }; int N = arr.size(); vector<int> out = minJumps(N, arr); // Print the result for (auto& it : out) cout << it << ' '; return 0;}
# Python program for the above approach # Function to find next greater element# to left and right of current elementdef expand(idx, A): # Starting l and r from previous # and the next element of the # current element l = idx - 1 r = idx + 1 # FInd the next greater element # to the left while (l >= 0): if (A[idx] > A[l]): l -= 1 else: break if (l < 0 or l == idx): l = -2 # Find the next greater element # to the right while (r < len(A)): if (A[idx] > A[r]): r += 1 else: break if (r >= len(A) or r == idx): r = -2 # Return l and r in the form of # array of size 2 return [l, r] # Function to find the minimum jumps# required to reach to all elements from# the largest elementdef minJumps(N, A): ans = [0 for i in range(N)] # Stores the mapping from index # to the element in array A[] mp = {} iToA = {} AToi = {} # Stores largest array element big = A[0] # Find the two indices l, r such # that A[l] > A[i] < A[r] and # l<i<r using expand function for i in range(N): big = max(big, A[i]) mp[i] = expand(i, A) iToA[i] = A[i] AToi[A[i]] = i # sorting A in descending order A = sorted(A, reverse=True) for i in range(len(A)): # Stores the resultant minimum # jumps required m = None # Check if the current element # is largest or not if (A[i] == big): cur = AToi[A[i]] ans[cur] = 0 continue # Find the answer to the # current element cur = AToi[A[i]] l = mp[cur][0] r = mp[cur][1] if (l >= 0 and r < N): m = min(ans[l], ans[r]) + 1 elif (l < 0 and r < N): m = ans[r] + 1 elif (l >= 0 and r >= N): m = ans[l] + 1 # Update the resultant minimum # jumps for the current element ans[cur] = m # Return the result return ans # Driver Codearr = [5, 1, 3, 4, 7]N = len(arr) out = minJumps(N, arr) # Print the resultfor it in out: print(it, end=" ") # This code is contributed by saurabh_jaiswal.
<script>// Javascript program for the above approach // Function to find next greater element// to left and right of current elementfunction expand(idx, A){ // Starting l and r from previous // and the next element of the // current element let l = idx - 1; let r = idx + 1; // FInd the next greater element // to the left while (l >= 0) { if (A[idx] > A[l]) { --l; } else { break; } } if (l < 0 || l == idx) { l = -2; } // Find the next greater element // to the right while (r < A.length) { if (A[idx] > A[r]) { ++r; } else { break; } } if (r >= A.length || r == idx) { r = -2; } // Return l and r in the form of // array of size 2 return [l, r];} // Function to find the minimum jumps// required to reach to all elements from// the largest elementfunction minJumps(N, A) { let ans = new Array(N).fill(0); // Stores the mapping from index // to the element in array A[] let mp = new Map(); let iToA = new Map(); let AToi = new Map(); // Stores largest array element let big = A[0]; // Find the two indices l, r such // that A[l] > A[i] < A[r] and // l<i<r using expand function for (let i = 0; i < N; ++i) { big = Math.max(big, A[i]); mp.set(i, expand(i, A)); iToA.set(i, A[i]); AToi.set(A[i], i); } // sorting A in descending order A.sort((a, b) => - a + b); for (let i = 0; i < A.length; ++i) { // Stores the resultant minimum // jumps required let m; // Check if the current element // is largest or not if (A[i] == big) { let cur = AToi.get(A[i]); ans[cur] = 0; continue; } // Find the answer to the // current element let cur = AToi.get(A[i]); let l = mp.get(cur)[0]; let r = mp.get(cur)[1]; if (l >= 0 && r < N) { m = Math.min(ans[l], ans[r]) + 1; } else if (l < 0 && r < N) { m = ans[r] + 1; } else if (l >= 0 && r >= N) { m = ans[l] + 1; } // Update the resultant minimum // jumps for the current element ans[cur] = m; } // Return the result return ans;} // Driver Code let arr = [5, 1, 3, 4, 7];let N = arr.length; let out = minJumps(N, arr); // Print the resultfor (it of out) document.write(it + " "); // This code is contributed by gfgking.</script>
1 2 2 1 0
Time Complexity: O(N2)Auxiliary Space: O(N)
gfgking
duttaaniruddha31
_saurabh_jaiswal
khushboogoyal499
Arrays
Dynamic Programming
Greedy
Mathematical
Arrays
Dynamic Programming
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Linear Search
Maximum and minimum of an array using minimum number of comparisons
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Bellman–Ford Algorithm | DP-23
Longest Common Subsequence | DP-4
Floyd Warshall Algorithm | DP-16
|
[
{
"code": null,
"e": 25178,
"s": 25150,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 25535,
"s": 25178,
"text": "Given an array arr[] of N distinct integer, the task is to find the minimum number of jumps required from the largest element to reach all array elements such that a jump is possible from the ith element to the jth element if the value of arr[i] is greater than arr[j] and value of arr[j] is greater than all other elements between the ith and jth element."
},
{
"code": null,
"e": 25545,
"s": 25535,
"text": "Examples:"
},
{
"code": null,
"e": 25657,
"s": 25545,
"text": "Input: arr[] = {1, 3, 6, 5}Output: [2, 1, 0, 1]Explanation:Below are the jumps required to reach each platform:"
},
{
"code": null,
"e": 25814,
"s": 25657,
"text": "For the 1st platform, the jump from the 3rd platform to the 2nd platform, then jump to the 1st platform is required. Hence, a total of 2 jumps are required."
},
{
"code": null,
"e": 25948,
"s": 25814,
"text": "For the 2nd platform, the jump from the 3rd platform directly to the 2nd platform is required. Hence, a total of 1 jump are required."
},
{
"code": null,
"e": 26046,
"s": 25948,
"text": "For the 3rd platform, we are already on the 3rd platform. Hence, a total of 0 jumps are required."
},
{
"code": null,
"e": 26180,
"s": 26046,
"text": "For the 4th platform, the jump from the 3rd platform directly to the 4th platform is required. Hence, a total of 1 jump are required."
},
{
"code": null,
"e": 26216,
"s": 26180,
"text": "Input: arr[] = {3, 5}Output: [1, 0]"
},
{
"code": null,
"e": 26664,
"s": 26216,
"text": "Approach: The given problem can be solved using Dynamic Programming which is based on the observation that the minimum jump possible from the largest element to the ith element is one greater than the minimum of minimum jumps required for the next greater element in the left or right. So, the idea is to precompute the results of larger elements and use them to find answers to smaller elements. Follow the steps below to solve the given problem:"
},
{
"code": null,
"e": 26822,
"s": 26664,
"text": "For each array element arr[i] store the two indices L and R representing the index of the next greater element to the left and right in the map respectively."
},
{
"code": null,
"e": 26864,
"s": 26822,
"text": "Sort the array arr[] in descending order."
},
{
"code": null,
"e": 26949,
"s": 26864,
"text": "Initialize a vector, say ans[] that stores the minimum jumps for all array elements."
},
{
"code": null,
"e": 27678,
"s": 26949,
"text": "Traverse the array arr[] and perform the following steps:If the current array element is the largest element then 0 jumps are required for the current element.Find the distance of the next greater element to the left and right of the current element using the value stored in the maps. Store the distances in the variables, L and R respectively.Update the value of minimum jumps, say M as per the following criteria:If L is at least 0 and R is less than N, then the value of M is min(ans[L], ans[R]) + 1.If L is less than 0 and R is less than N, then the value of M is ans[R] + 1.If L is at least 0 and R is at least N, then the value of M is ans[L] + 1.Update the value of minimum jumps for the current index as the value of M."
},
{
"code": null,
"e": 27781,
"s": 27678,
"text": "If the current array element is the largest element then 0 jumps are required for the current element."
},
{
"code": null,
"e": 27968,
"s": 27781,
"text": "Find the distance of the next greater element to the left and right of the current element using the value stored in the maps. Store the distances in the variables, L and R respectively."
},
{
"code": null,
"e": 28278,
"s": 27968,
"text": "Update the value of minimum jumps, say M as per the following criteria:If L is at least 0 and R is less than N, then the value of M is min(ans[L], ans[R]) + 1.If L is less than 0 and R is less than N, then the value of M is ans[R] + 1.If L is at least 0 and R is at least N, then the value of M is ans[L] + 1."
},
{
"code": null,
"e": 28367,
"s": 28278,
"text": "If L is at least 0 and R is less than N, then the value of M is min(ans[L], ans[R]) + 1."
},
{
"code": null,
"e": 28444,
"s": 28367,
"text": "If L is less than 0 and R is less than N, then the value of M is ans[R] + 1."
},
{
"code": null,
"e": 28519,
"s": 28444,
"text": "If L is at least 0 and R is at least N, then the value of M is ans[L] + 1."
},
{
"code": null,
"e": 28594,
"s": 28519,
"text": "Update the value of minimum jumps for the current index as the value of M."
},
{
"code": null,
"e": 28685,
"s": 28594,
"text": "After completing the above steps, print the array ans[] as the resultant jumps of indices."
},
{
"code": null,
"e": 28736,
"s": 28685,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28740,
"s": 28736,
"text": "C++"
},
{
"code": null,
"e": 28748,
"s": 28740,
"text": "Python3"
},
{
"code": null,
"e": 28759,
"s": 28748,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define ar array // Function to find next greater element// to left and right of current elementar<int, 2> expand(int idx, vector<int>& A){ // Starting l and r from previous // and the next element of the // current element int l = idx - 1; int r = idx + 1; // FInd the next greater element // to the left while (l >= 0) { if ((int)(A[idx]) > A[l]) { --l; } else { break; } } if (l < 0 || l == idx) { l = -2; } // Find the next greater element // to the right while (r < (int)(A.size())) { if ((int)A[idx] > A[r]) { ++r; } else { break; } } if (r >= (int)(A.size()) || r == idx) { r = -2; } // Return l and r in the form of // array of size 2 return { l, r };} // Function to find the minimum jumps// required to reach to all elements from// the largest elementvector<int> minJumps(int N, vector<int>& A){ vector<int> ans(N, 0); // Stores the mapping from index // to the element in array A[] map<int, ar<int, 2> > mp; map<int, int> iToA; map<int, int> AToi; // Stores largest array element int big = A[0]; // Find the two indices l, r such // that A[l] > A[i] < A[r] and // l<i<r using expand function for (int i = 0; i < N; ++i) { big = max({ big, A[i] }); mp[i] = expand(i, A); iToA[i] = A[i]; AToi[A[i]] = i; } // sorting A in descending order sort(A.begin(), A.end(), greater<int>()); for (int i = 0; i < A.size(); ++i) { // Stores the resultant minimum // jumps required int m; // Check if the current element // is largest or not if (A[i] == big) { int cur = AToi[A[i]]; ans[cur] = 0; continue; } // Find the answer to the // current element int cur = AToi[A[i]]; int l = mp[cur][0]; int r = mp[cur][1]; if (l >= 0 && r < N) { m = min(ans[l], ans[r]) + 1; } else if (l < 0 && r < N) { m = ans[r] + 1; } else if (l >= 0 && r >= N) { m = ans[l] + 1; } // Update the resultant minimum // jumps for the current element ans[cur] = m; } // Return the result return ans;} // Driver Codeint main(){ vector<int> arr = { 5, 1, 3, 4, 7 }; int N = arr.size(); vector<int> out = minJumps(N, arr); // Print the result for (auto& it : out) cout << it << ' '; return 0;}",
"e": 31422,
"s": 28759,
"text": null
},
{
"code": "# Python program for the above approach # Function to find next greater element# to left and right of current elementdef expand(idx, A): # Starting l and r from previous # and the next element of the # current element l = idx - 1 r = idx + 1 # FInd the next greater element # to the left while (l >= 0): if (A[idx] > A[l]): l -= 1 else: break if (l < 0 or l == idx): l = -2 # Find the next greater element # to the right while (r < len(A)): if (A[idx] > A[r]): r += 1 else: break if (r >= len(A) or r == idx): r = -2 # Return l and r in the form of # array of size 2 return [l, r] # Function to find the minimum jumps# required to reach to all elements from# the largest elementdef minJumps(N, A): ans = [0 for i in range(N)] # Stores the mapping from index # to the element in array A[] mp = {} iToA = {} AToi = {} # Stores largest array element big = A[0] # Find the two indices l, r such # that A[l] > A[i] < A[r] and # l<i<r using expand function for i in range(N): big = max(big, A[i]) mp[i] = expand(i, A) iToA[i] = A[i] AToi[A[i]] = i # sorting A in descending order A = sorted(A, reverse=True) for i in range(len(A)): # Stores the resultant minimum # jumps required m = None # Check if the current element # is largest or not if (A[i] == big): cur = AToi[A[i]] ans[cur] = 0 continue # Find the answer to the # current element cur = AToi[A[i]] l = mp[cur][0] r = mp[cur][1] if (l >= 0 and r < N): m = min(ans[l], ans[r]) + 1 elif (l < 0 and r < N): m = ans[r] + 1 elif (l >= 0 and r >= N): m = ans[l] + 1 # Update the resultant minimum # jumps for the current element ans[cur] = m # Return the result return ans # Driver Codearr = [5, 1, 3, 4, 7]N = len(arr) out = minJumps(N, arr) # Print the resultfor it in out: print(it, end=\" \") # This code is contributed by saurabh_jaiswal.",
"e": 33630,
"s": 31422,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to find next greater element// to left and right of current elementfunction expand(idx, A){ // Starting l and r from previous // and the next element of the // current element let l = idx - 1; let r = idx + 1; // FInd the next greater element // to the left while (l >= 0) { if (A[idx] > A[l]) { --l; } else { break; } } if (l < 0 || l == idx) { l = -2; } // Find the next greater element // to the right while (r < A.length) { if (A[idx] > A[r]) { ++r; } else { break; } } if (r >= A.length || r == idx) { r = -2; } // Return l and r in the form of // array of size 2 return [l, r];} // Function to find the minimum jumps// required to reach to all elements from// the largest elementfunction minJumps(N, A) { let ans = new Array(N).fill(0); // Stores the mapping from index // to the element in array A[] let mp = new Map(); let iToA = new Map(); let AToi = new Map(); // Stores largest array element let big = A[0]; // Find the two indices l, r such // that A[l] > A[i] < A[r] and // l<i<r using expand function for (let i = 0; i < N; ++i) { big = Math.max(big, A[i]); mp.set(i, expand(i, A)); iToA.set(i, A[i]); AToi.set(A[i], i); } // sorting A in descending order A.sort((a, b) => - a + b); for (let i = 0; i < A.length; ++i) { // Stores the resultant minimum // jumps required let m; // Check if the current element // is largest or not if (A[i] == big) { let cur = AToi.get(A[i]); ans[cur] = 0; continue; } // Find the answer to the // current element let cur = AToi.get(A[i]); let l = mp.get(cur)[0]; let r = mp.get(cur)[1]; if (l >= 0 && r < N) { m = Math.min(ans[l], ans[r]) + 1; } else if (l < 0 && r < N) { m = ans[r] + 1; } else if (l >= 0 && r >= N) { m = ans[l] + 1; } // Update the resultant minimum // jumps for the current element ans[cur] = m; } // Return the result return ans;} // Driver Code let arr = [5, 1, 3, 4, 7];let N = arr.length; let out = minJumps(N, arr); // Print the resultfor (it of out) document.write(it + \" \"); // This code is contributed by gfgking.</script>",
"e": 35894,
"s": 33630,
"text": null
},
{
"code": null,
"e": 35907,
"s": 35897,
"text": "1 2 2 1 0"
},
{
"code": null,
"e": 35955,
"s": 35911,
"text": "Time Complexity: O(N2)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 35965,
"s": 35957,
"text": "gfgking"
},
{
"code": null,
"e": 35982,
"s": 35965,
"text": "duttaaniruddha31"
},
{
"code": null,
"e": 35999,
"s": 35982,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 36016,
"s": 35999,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 36023,
"s": 36016,
"text": "Arrays"
},
{
"code": null,
"e": 36043,
"s": 36023,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 36050,
"s": 36043,
"text": "Greedy"
},
{
"code": null,
"e": 36063,
"s": 36050,
"text": "Mathematical"
},
{
"code": null,
"e": 36070,
"s": 36063,
"text": "Arrays"
},
{
"code": null,
"e": 36090,
"s": 36070,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 36097,
"s": 36090,
"text": "Greedy"
},
{
"code": null,
"e": 36110,
"s": 36097,
"text": "Mathematical"
},
{
"code": null,
"e": 36208,
"s": 36110,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36217,
"s": 36208,
"text": "Comments"
},
{
"code": null,
"e": 36230,
"s": 36217,
"text": "Old Comments"
},
{
"code": null,
"e": 36278,
"s": 36230,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 36322,
"s": 36278,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36345,
"s": 36322,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36359,
"s": 36345,
"text": "Linear Search"
},
{
"code": null,
"e": 36427,
"s": 36359,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36456,
"s": 36427,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 36486,
"s": 36456,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 36517,
"s": 36486,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 36551,
"s": 36517,
"text": "Longest Common Subsequence | DP-4"
}
] |
Plotting at full resolution with matplotlib.pyplot, imshow() and savefig()
|
To plot at full resolution with matplotlib.pyplot, imshow() and savefig(), we can keep the dpi value from 600 to 1200.
Set the figure size and adjust the padding between and around the subplots.
Set random values in a given shape.
Display the data as an image, i.e., on a 2D regular raster
Save the figure with 1200 dpi.
To display the figure, use show() method.
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.rand(5, 5)
plt.imshow(data, cmap="plasma")
plt.savefig("myimage.eps", dpi=1200)
plt.show()
|
[
{
"code": null,
"e": 1181,
"s": 1062,
"text": "To plot at full resolution with matplotlib.pyplot, imshow() and savefig(), we can keep the dpi value from 600 to 1200."
},
{
"code": null,
"e": 1257,
"s": 1181,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1293,
"s": 1257,
"text": "Set random values in a given shape."
},
{
"code": null,
"e": 1352,
"s": 1293,
"text": "Display the data as an image, i.e., on a 2D regular raster"
},
{
"code": null,
"e": 1383,
"s": 1352,
"text": "Save the figure with 1200 dpi."
},
{
"code": null,
"e": 1425,
"s": 1383,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1680,
"s": 1425,
"text": "from matplotlib import pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndata = np.random.rand(5, 5)\n\nplt.imshow(data, cmap=\"plasma\")\nplt.savefig(\"myimage.eps\", dpi=1200)\n\nplt.show()"
}
] |
Introducing End-to-End Interpolation of Time Series Data in Apache PySpark | by Jessica Walkenhorst | Towards Data Science
|
Anyone working with data knows that real-world data is often patchy and cleaning it takes up a considerable amount of your time (80/20 rule anyone?). Having recently moved from Pandas to Pyspark, I was used to the conveniences that Pandas offers and that Pyspark sometimes lacks due to its distributed nature. One of the features I have been particularly missing is a straight-forward way of interpolating (or in-filling) time series data. While the problem of in-filling missing values has been covered a few times (e.g. [here]), I was not able to find a source, which detailed the end-to-end process of generating the underlying time-grid and then subsequently filling in the missing values. This post tries to close this gap. Starting from a time-series with missing entries, I will show how we can leverage PySpark to first generate the missing time-stamps and then fill in the missing values using three different interpolation methods (forward filling, backward filling and interpolation). This is demonstrated using the example of sensor read data collected in a set of houses. The full code for this post can be found [here in my github].
To demonstrate the procedure, first, we generate some test data. The data set contains data for two houses and uses a sin() and a cos() function to generate some sensor read data for a set of dates. To generate the missing values, we randomly drop half of the entries.
The following graph shows the data with the missing values clearly visible.
To parallelize the data set, we convert the Pandas data frame into a Spark data frame. Note, that we need to divide the datetime by 109 since the unit of time is different for pandas datetime and spark. We also add the column ‘readtime_existent’ to keep track of which values are missing.
import pyspark.sql.functions as funcfrom pyspark.sql.functions import coldf = spark.createDataFrame(df0)df = df.withColumn("readtime", col('readtime')/1e9)\ .withColumn("readtime_existent", col("readtime"))
Now our dataframe looks like this:
The first step is to resample the readtime data. If we were working with Pandas, this would be straight forward, we could just use the resample() method. However, Spark works on distributed datasets and therefore does not provide an equivalent method. Obtaining the same functionality in PySpark requires a three-step process. In the first step, we group the data by ‘house’ and generate an array containing an equally spaced time grid for each house. In the second step, we create one row for each element of the arrays by using the spark SQL function explode(). In the third step, the resulting structure is used as a basis to which the existing read value information is joined using an outer left join. The following code shows how this can be done.
Note, that here we are using a spark user-defined function (if you want to learn more about how to create UDFs, you can take a look here. Starting from Spark 2.3, Spark provides a pandas udf, which leverages the performance of Apache Arrow to distribute calculations. If you use Spark 2.3, I would recommend looking into this instead of using the (badly performant) in-build udfs.
An extract of the resulting table looks like this:
As one can see, a null in the readtime_existent column indicates a missing read value.
When using a forward-fill, we infill the missing data with the latest known value. In contrast, when using a backwards-fill, we infill the data with the next known value. This can be achieved using an SQL window function in combination with last() and first(). To make sure that we don’t infill the missing values with another missing value, use the ignorenulls=True argument. We also need to make sure that we set the correct window ranges. For the forward-fill, we restrict the window to values between minus infinity and now (we only look into the past, not into the future), for the backward-fill we restrict the window to values between now and infinity (we only look into the future, we don’t look into the past). The code below shows how to implement this.
Note, that if we want to use interpolation instead of forward or backward fill, we need to know the time difference between the previous, existing and the next, existing read value. Therefore, we need to keep the readtime_existent column.
from pyspark.sql import Windowimport syswindow_ff = Window.partitionBy('house')\ .orderBy('readtime')\ .rowsBetween(-sys.maxsize, 0) window_bf = Window.partitionBy('house')\ .orderBy('readtime')\ .rowsBetween(0, sys.maxsize) # create series containing the filled valuesread_last = func.last(df_all_dates['readvalue'], ignorenulls=True)\ .over(window_ff)readtime_last = func.last(df_all_dates['readtime_existent'], ignorenulls=True)\ .over(window_ff)read_next = func.first(df_all_dates['readvalue'], ignorenulls=True)\ .over(window_bf)readtime_next = func.first(df_all_dates['readtime_existent'], ignorenulls=True)\ .over(window_bf)# add columns to the dataframedf_filled = df_all_dates.withColumn('readvalue_ff', read_last)\ .withColumn('readtime_ff', readtime_last)\ .withColumn('readvalue_bf', read_next)\ .withColumn('readtime_bf', readtime_next)
In the final step, we use the forward filled and backwards filled data to interpolate the read datetimes and the read values using a simple spline. This can again be done using a user-defined function.
This leaves us with a single dataframe containing all of the interpolation methods. This is how its structure looks like:
Finally, we can visualize the results to observe the differences between the interpolation techniques. The opaque dots show the interpolated values.
We can clearly see how in the top figure, the gaps have been filled with the last known value, in the middle figure, the gaps have been filled with the next value to come and in the bottom figure, the difference has been interpolated.
In this post, we have seen how we can use PySpark to perform end-to-end interpolation of time series data. We have demonstrated, how we can use resample time series data and how we can use the Window function in combination with the first() and last() function to fill-in the generated missing values. We have then seen, how we can use a user-defined function to perform a simple spline-interpolation.
I hope this post helps to plug the gap of literature about end-to-end time series interpolation in PySpark.
Originally published at https://walkenho.github.io.
|
[
{
"code": null,
"e": 1319,
"s": 172,
"text": "Anyone working with data knows that real-world data is often patchy and cleaning it takes up a considerable amount of your time (80/20 rule anyone?). Having recently moved from Pandas to Pyspark, I was used to the conveniences that Pandas offers and that Pyspark sometimes lacks due to its distributed nature. One of the features I have been particularly missing is a straight-forward way of interpolating (or in-filling) time series data. While the problem of in-filling missing values has been covered a few times (e.g. [here]), I was not able to find a source, which detailed the end-to-end process of generating the underlying time-grid and then subsequently filling in the missing values. This post tries to close this gap. Starting from a time-series with missing entries, I will show how we can leverage PySpark to first generate the missing time-stamps and then fill in the missing values using three different interpolation methods (forward filling, backward filling and interpolation). This is demonstrated using the example of sensor read data collected in a set of houses. The full code for this post can be found [here in my github]."
},
{
"code": null,
"e": 1588,
"s": 1319,
"text": "To demonstrate the procedure, first, we generate some test data. The data set contains data for two houses and uses a sin() and a cos() function to generate some sensor read data for a set of dates. To generate the missing values, we randomly drop half of the entries."
},
{
"code": null,
"e": 1664,
"s": 1588,
"text": "The following graph shows the data with the missing values clearly visible."
},
{
"code": null,
"e": 1953,
"s": 1664,
"text": "To parallelize the data set, we convert the Pandas data frame into a Spark data frame. Note, that we need to divide the datetime by 109 since the unit of time is different for pandas datetime and spark. We also add the column ‘readtime_existent’ to keep track of which values are missing."
},
{
"code": null,
"e": 2166,
"s": 1953,
"text": "import pyspark.sql.functions as funcfrom pyspark.sql.functions import coldf = spark.createDataFrame(df0)df = df.withColumn(\"readtime\", col('readtime')/1e9)\\ .withColumn(\"readtime_existent\", col(\"readtime\"))"
},
{
"code": null,
"e": 2201,
"s": 2166,
"text": "Now our dataframe looks like this:"
},
{
"code": null,
"e": 2955,
"s": 2201,
"text": "The first step is to resample the readtime data. If we were working with Pandas, this would be straight forward, we could just use the resample() method. However, Spark works on distributed datasets and therefore does not provide an equivalent method. Obtaining the same functionality in PySpark requires a three-step process. In the first step, we group the data by ‘house’ and generate an array containing an equally spaced time grid for each house. In the second step, we create one row for each element of the arrays by using the spark SQL function explode(). In the third step, the resulting structure is used as a basis to which the existing read value information is joined using an outer left join. The following code shows how this can be done."
},
{
"code": null,
"e": 3336,
"s": 2955,
"text": "Note, that here we are using a spark user-defined function (if you want to learn more about how to create UDFs, you can take a look here. Starting from Spark 2.3, Spark provides a pandas udf, which leverages the performance of Apache Arrow to distribute calculations. If you use Spark 2.3, I would recommend looking into this instead of using the (badly performant) in-build udfs."
},
{
"code": null,
"e": 3387,
"s": 3336,
"text": "An extract of the resulting table looks like this:"
},
{
"code": null,
"e": 3474,
"s": 3387,
"text": "As one can see, a null in the readtime_existent column indicates a missing read value."
},
{
"code": null,
"e": 4238,
"s": 3474,
"text": "When using a forward-fill, we infill the missing data with the latest known value. In contrast, when using a backwards-fill, we infill the data with the next known value. This can be achieved using an SQL window function in combination with last() and first(). To make sure that we don’t infill the missing values with another missing value, use the ignorenulls=True argument. We also need to make sure that we set the correct window ranges. For the forward-fill, we restrict the window to values between minus infinity and now (we only look into the past, not into the future), for the backward-fill we restrict the window to values between now and infinity (we only look into the future, we don’t look into the past). The code below shows how to implement this."
},
{
"code": null,
"e": 4477,
"s": 4238,
"text": "Note, that if we want to use interpolation instead of forward or backward fill, we need to know the time difference between the previous, existing and the next, existing read value. Therefore, we need to keep the readtime_existent column."
},
{
"code": null,
"e": 5637,
"s": 4477,
"text": "from pyspark.sql import Windowimport syswindow_ff = Window.partitionBy('house')\\ .orderBy('readtime')\\ .rowsBetween(-sys.maxsize, 0) window_bf = Window.partitionBy('house')\\ .orderBy('readtime')\\ .rowsBetween(0, sys.maxsize) # create series containing the filled valuesread_last = func.last(df_all_dates['readvalue'], ignorenulls=True)\\ .over(window_ff)readtime_last = func.last(df_all_dates['readtime_existent'], ignorenulls=True)\\ .over(window_ff)read_next = func.first(df_all_dates['readvalue'], ignorenulls=True)\\ .over(window_bf)readtime_next = func.first(df_all_dates['readtime_existent'], ignorenulls=True)\\ .over(window_bf)# add columns to the dataframedf_filled = df_all_dates.withColumn('readvalue_ff', read_last)\\ .withColumn('readtime_ff', readtime_last)\\ .withColumn('readvalue_bf', read_next)\\ .withColumn('readtime_bf', readtime_next)"
},
{
"code": null,
"e": 5839,
"s": 5637,
"text": "In the final step, we use the forward filled and backwards filled data to interpolate the read datetimes and the read values using a simple spline. This can again be done using a user-defined function."
},
{
"code": null,
"e": 5961,
"s": 5839,
"text": "This leaves us with a single dataframe containing all of the interpolation methods. This is how its structure looks like:"
},
{
"code": null,
"e": 6110,
"s": 5961,
"text": "Finally, we can visualize the results to observe the differences between the interpolation techniques. The opaque dots show the interpolated values."
},
{
"code": null,
"e": 6345,
"s": 6110,
"text": "We can clearly see how in the top figure, the gaps have been filled with the last known value, in the middle figure, the gaps have been filled with the next value to come and in the bottom figure, the difference has been interpolated."
},
{
"code": null,
"e": 6747,
"s": 6345,
"text": "In this post, we have seen how we can use PySpark to perform end-to-end interpolation of time series data. We have demonstrated, how we can use resample time series data and how we can use the Window function in combination with the first() and last() function to fill-in the generated missing values. We have then seen, how we can use a user-defined function to perform a simple spline-interpolation."
},
{
"code": null,
"e": 6855,
"s": 6747,
"text": "I hope this post helps to plug the gap of literature about end-to-end time series interpolation in PySpark."
}
] |
Count number of increasing sub-sequences : O(NlogN) - GeeksforGeeks
|
12 May, 2021
Given an array arr[] of length N, the task is to find the number of strictly increasing sub-sequences in the given array.
Examples:
Input: arr[] = {1, 2, 3} Output: 7 All increasing sub-sequences will be: 1) {1} 2) {2} 3) {3} 4) {1, 2} 5) {1, 3} 6) {2, 3} 7) {1, 2, 3} Thus, answer = 7Input: arr[] = {3, 2, 1} Output: 3
Approach: An O(N2) approach has already been discussed in this article. Here, an approach with O(NlogN) time using segment tree data structure will be discussed.In the previous article, the recurrence relation used was:
dp[i] = 1 + summation(dp[j]), where i <jarr[i]
Due to the fact that the entire sub-array arr[i+1...n-1] was being iterated for each state, an extra O(N) time was being used to solve it. Thus, the complexity was (N2).The idea is to avoid iterating the O(N) extra loop for each state and reducing its complexity to Log(N).Assumption: The number of strictly increasing sub-sequences starting from each index ‘i’, where i is greater than a number ‘k’ is known. Using this above assumption, the number of increasing sub-sequences starting from index ‘k’ can be found in log(N) time.Therefore, the summation for all the indexes ‘i’ greater than ‘k’ must be found. But the catch is arr[i] must be greater than arr[k]. To deal with the problem, the following can be done:
1. For each element of the array, its index is found in the array was sorted. Example – {7, 8, 1, 9, 4} Here, ranks will be:
7 -> 3 8 -> 4 1 -> 1 9 -> 5 4 -> 2
2. A segment tree of length ‘N’ is created to answer a range-sum query.
3. To answer the query while solving for index ‘k’, the rank of arr[k] is found first. Let’s say the rank is R. Then, in the segment tree, the range-sum from index {R to N-1} is found.
4. Then, the segment-tree is point updated as segment-(R-1) equals 1 + segtree-query(R, N-1) + segtree-query(R-1, R-1)
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define N 10000 // Segment tree arrayint seg[3 * N]; // Function for point update in segment treeint update(int in, int l, int r, int up_in, int val){ // Base case if (r < up_in || l > up_in) return seg[in]; // If l==r==up if (l == up_in and r == up_in) return seg[in] = val; // Mid element int m = (l + r) / 2; // Updating the segment tree return seg[in] = update(2 * in + 1, l, m, up_in, val) + update(2 * in + 2, m + 1, r, up_in, val);} // Function for the range sum-queryint query(int in, int l, int r, int l1, int r1){ // Base case if (l > r) return 0; if (r < l1 || l > r1) return 0; if (l1 <= l and r <= r1) return seg[in]; // Mid element int m = (l + r) / 2; // Calling for the left and the right subtree return query(2 * in + 1, l, m, l1, r1) + query(2 * in + 2, m + 1, r, l1, r1);} // Function to return the countint findCnt(int* arr, int n){ // Copying array arr to sort it int brr[n]; for (int i = 0; i < n; i++) brr[i] = arr[i]; // Sorting array brr sort(brr, brr + n); // Map to store the rank of each element map<int, int> r; for (int i = 0; i < n; i++) r[brr[i]] = i + 1; // dp array int dp[n] = { 0 }; // To store the final answer int ans = 0; // Updating the dp array for (int i = n - 1; i >= 0; i--) { // Rank of the element int rank = r[arr[i]]; // Solving the dp-states using segment tree dp[i] = 1 + query(0, 0, n - 1, rank, n - 1); // Updating the final answer ans += dp[i]; // Updating the segment tree update(0, 0, n - 1, rank - 1, dp[i] + query(0, 0, n - 1, rank - 1, rank - 1)); } // Returning the final answer return ans;} // Driver codeint main(){ int arr[] = { 1, 2, 10, 9 }; int n = sizeof(arr) / sizeof(int); cout << findCnt(arr, n); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ static final int N = 10000; // Segment tree array static int[] seg = new int[3 * N]; // Function for point update in segment tree static int update(int in, int l, int r, int up_in, int val) { // Base case if (r < up_in || l > up_in) return seg[in]; // If l==r==up if (l == up_in && r == up_in) return seg[in] = val; // Mid element int m = (l + r) / 2; // Updating the segment tree return seg[in] = update(2 * in + 1, l, m, up_in, val) + update(2 * in + 2, m + 1, r, up_in, val); } // Function for the range sum-query static int query(int in, int l, int r, int l1, int r1) { // Base case if (l > r) return 0; if (r < l1 || l > r1) return 0; if (l1 <= l && r <= r1) return seg[in]; // Mid element int m = (l + r) / 2; // Calling for the left and the right subtree return query(2 * in + 1, l, m, l1, r1) + query(2 * in + 2, m + 1, r, l1, r1); } // Function to return the count static int findCnt(int[] arr, int n) { // Copying array arr to sort it int[] brr = new int[n]; for (int i = 0; i < n; i++) brr[i] = arr[i]; // Sorting array brr Arrays.sort(brr); // Map to store the rank of each element HashMap<Integer, Integer> r = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) r.put(brr[i], i + 1); // dp array int dp[] = new int[n]; // To store the final answer int ans = 0; // Updating the dp array for (int i = n - 1; i >= 0; i--) { // Rank of the element int rank = r.get(arr[i]); // Solving the dp-states using segment tree dp[i] = 1 + query(0, 0, n - 1, rank, n - 1); // Updating the final answer ans += dp[i]; // Updating the segment tree update(0, 0, n - 1, rank - 1, dp[i] + query(0, 0, n - 1, rank - 1, rank - 1)); } // Returning the final answer return ans; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 10, 9 }; int n = arr.length; System.out.print(findCnt(arr, n)); }} // This code is contributed by PrinciRaj1992
# Python3 implementation of the approach N = 10000 # Segment tree arrayseg = [0] * (3 * N) # Function for point update in segment treedef update(In, l, r, up_In, val): # Base case if (r < up_In or l > up_In): return seg[In] # If l==r==up if (l == up_In and r == up_In): seg[In] = val return val # Mid element m = (l + r) // 2 # Updating the segment tree seg[In] = update(2 * In + 1, l, m, up_In, val) + update(2 * In + 2, m + 1, r, up_In, val) return seg[In] # Function for the range sum-querydef query(In, l, r, l1, r1): # Base case if (l > r): return 0 if (r < l1 or l > r1): return 0 if (l1 <= l and r <= r1): return seg[In] # Mid element m = (l + r) // 2 # CallIng for the left and the right subtree return query(2 * In + 1, l, m, l1, r1)+ query(2 * In + 2, m + 1, r, l1, r1) # Function to return the countdef fIndCnt(arr, n): # Copying array arr to sort it brr = [0] * n for i in range(n): brr[i] = arr[i] # Sorting array brr brr = sorted(brr) # Map to store the rank of each element r = dict() for i in range(n): r[brr[i]] = i + 1 # dp array dp = [0] * n # To store the final answer ans = 0 # Updating the dp array for i in range(n - 1, -1, -1): # Rank of the element rank = r[arr[i]] # Solving the dp-states using segment tree dp[i] = 1 + query(0, 0, n - 1, rank, n - 1) # UpdatIng the final answer ans += dp[i] # Updating the segment tree update(0, 0, n - 1, rank - 1,dp[i] + query(0, 0, n - 1, rank - 1, rank - 1)) # Returning the final answer return ans # Driver code arr = [1, 2, 10, 9]n = len(arr) print(fIndCnt(arr, n)) # This code is contributed by mohit kumar 29
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static readonly int N = 10000; // Segment tree array static int[] seg = new int[3 * N]; // Function for point update In segment tree static int update(int In, int l, int r, int up_in, int val) { // Base case if (r < up_in || l > up_in) return seg[In]; // If l==r==up if (l == up_in && r == up_in) return seg[In] = val; // Mid element int m = (l + r) / 2; // Updating the segment tree return seg[In] = update(2 * In + 1, l, m, up_in, val) + update(2 * In + 2, m + 1, r, up_in, val); } // Function for the range sum-query static int query(int In, int l, int r, int l1, int r1) { // Base case if (l > r) return 0; if (r < l1 || l > r1) return 0; if (l1 <= l && r <= r1) return seg[In]; // Mid element int m = (l + r) / 2; // Calling for the left and the right subtree return query(2 * In + 1, l, m, l1, r1) + query(2 * In + 2, m + 1, r, l1, r1); } // Function to return the count static int findCnt(int[] arr, int n) { // Copying array arr to sort it int[] brr = new int[n]; for (int i = 0; i < n; i++) brr[i] = arr[i]; // Sorting array brr Array.Sort(brr); // Map to store the rank of each element Dictionary<int, int> r = new Dictionary<int, int>(); for (int i = 0; i < n; i++) r.Add(brr[i], i + 1); // dp array int []dp = new int[n]; // To store the readonly answer int ans = 0; // Updating the dp array for (int i = n - 1; i >= 0; i--) { // Rank of the element int rank = r[arr[i]]; // Solving the dp-states using segment tree dp[i] = 1 + query(0, 0, n - 1, rank, n - 1); // Updating the readonly answer ans += dp[i]; // Updating the segment tree update(0, 0, n - 1, rank - 1, dp[i] + query(0, 0, n - 1, rank - 1, rank - 1)); } // Returning the readonly answer return ans; } // Driver code public static void Main(String[] args) { int []arr = { 1, 2, 10, 9 }; int n = arr.Length; Console.Write(findCnt(arr, n)); }} // This code is contributed by PrinciRaj1992
<script> // Javascript implementation of the approach var N = 10000; // Segment tree arrayvar seg = Array(3*N).fill(0); // Function for point update inVal segment treefunction update(inVal, l, r, up_in, val){ // Base case if (r < up_in || l > up_in) return seg[inVal]; // If l==r==up if (l == up_in && r == up_in) return seg[inVal] = val; // Mid element var m = parseInt((l + r) / 2); // Updating the segment tree seg[inVal] = update(2 * inVal + 1, l, m, up_in, val) + update(2 * inVal + 2, m + 1, r, up_in, val); return seg[inVal];} // Function for the range sum-queryfunction query(inVal, l, r, l1, r1){ // Base case if (l > r) return 0; if (r < l1 || l > r1) return 0; if (l1 <= l && r <= r1) return seg[inVal]; // Mid element var m = parseInt((l + r) / 2); // Calling for the left and the right subtree return query(2 * inVal + 1, l, m, l1, r1) + query(2 * inVal + 2, m + 1, r, l1, r1);} // Function to return the countfunction findCnt(arr, n){ // Copying array arr to sort it var brr = Array(n); for (var i = 0; i < n; i++) brr[i] = arr[i]; // Sorting array brr brr.sort((a, b)=> a-b); // Map to store the rank of each element var r = new Map(); for (var i = 0; i < n; i++) r[brr[i]] = i + 1; // dp array var dp = Array(n).fill(0); // To store the final answer var ans = 0; // Updating the dp array for (var i = n - 1; i >= 0; i--) { // Rank of the element var rank = r[arr[i]]; // Solving the dp-states using segment tree dp[i] = 1 + query(0, 0, n - 1, rank, n - 1); // Updating the final answer ans += dp[i]; // Updating the segment tree update(0, 0, n - 1, rank - 1, dp[i] + query(0, 0, n - 1, rank - 1, rank - 1)); } // Returning the final answer return ans;} // Driver codevar arr = [1, 2, 10, 9 ];var n = arr.length;document.write( findCnt(arr, n)); </script>
11
mohit kumar 29
princiraj1992
Akanksha_Rai
rrrtnx
Segment-Tree
subsequence
Advanced Data Structure
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Segment-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
2-3 Trees | (Search, Insert and Deletion)
Extendible Hashing (Dynamic approach to DBMS)
Advantages of Trie Data Structure
Cartesian Tree
Proof that Dominant Set of a Graph is NP-Complete
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
|
[
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n12 May, 2021"
},
{
"code": null,
"e": 24528,
"s": 24406,
"text": "Given an array arr[] of length N, the task is to find the number of strictly increasing sub-sequences in the given array."
},
{
"code": null,
"e": 24540,
"s": 24528,
"text": "Examples: "
},
{
"code": null,
"e": 24730,
"s": 24540,
"text": "Input: arr[] = {1, 2, 3} Output: 7 All increasing sub-sequences will be: 1) {1} 2) {2} 3) {3} 4) {1, 2} 5) {1, 3} 6) {2, 3} 7) {1, 2, 3} Thus, answer = 7Input: arr[] = {3, 2, 1} Output: 3 "
},
{
"code": null,
"e": 24952,
"s": 24730,
"text": "Approach: An O(N2) approach has already been discussed in this article. Here, an approach with O(NlogN) time using segment tree data structure will be discussed.In the previous article, the recurrence relation used was: "
},
{
"code": null,
"e": 25001,
"s": 24952,
"text": "dp[i] = 1 + summation(dp[j]), where i <jarr[i] "
},
{
"code": null,
"e": 25720,
"s": 25001,
"text": "Due to the fact that the entire sub-array arr[i+1...n-1] was being iterated for each state, an extra O(N) time was being used to solve it. Thus, the complexity was (N2).The idea is to avoid iterating the O(N) extra loop for each state and reducing its complexity to Log(N).Assumption: The number of strictly increasing sub-sequences starting from each index ‘i’, where i is greater than a number ‘k’ is known. Using this above assumption, the number of increasing sub-sequences starting from index ‘k’ can be found in log(N) time.Therefore, the summation for all the indexes ‘i’ greater than ‘k’ must be found. But the catch is arr[i] must be greater than arr[k]. To deal with the problem, the following can be done: "
},
{
"code": null,
"e": 25846,
"s": 25720,
"text": "1. For each element of the array, its index is found in the array was sorted. Example – {7, 8, 1, 9, 4} Here, ranks will be: "
},
{
"code": null,
"e": 25883,
"s": 25846,
"text": "7 -> 3 8 -> 4 1 -> 1 9 -> 5 4 -> 2 "
},
{
"code": null,
"e": 25955,
"s": 25883,
"text": "2. A segment tree of length ‘N’ is created to answer a range-sum query."
},
{
"code": null,
"e": 26140,
"s": 25955,
"text": "3. To answer the query while solving for index ‘k’, the rank of arr[k] is found first. Let’s say the rank is R. Then, in the segment tree, the range-sum from index {R to N-1} is found."
},
{
"code": null,
"e": 26259,
"s": 26140,
"text": "4. Then, the segment-tree is point updated as segment-(R-1) equals 1 + segtree-query(R, N-1) + segtree-query(R-1, R-1)"
},
{
"code": null,
"e": 26311,
"s": 26259,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26315,
"s": 26311,
"text": "C++"
},
{
"code": null,
"e": 26320,
"s": 26315,
"text": "Java"
},
{
"code": null,
"e": 26328,
"s": 26320,
"text": "Python3"
},
{
"code": null,
"e": 26331,
"s": 26328,
"text": "C#"
},
{
"code": null,
"e": 26342,
"s": 26331,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define N 10000 // Segment tree arrayint seg[3 * N]; // Function for point update in segment treeint update(int in, int l, int r, int up_in, int val){ // Base case if (r < up_in || l > up_in) return seg[in]; // If l==r==up if (l == up_in and r == up_in) return seg[in] = val; // Mid element int m = (l + r) / 2; // Updating the segment tree return seg[in] = update(2 * in + 1, l, m, up_in, val) + update(2 * in + 2, m + 1, r, up_in, val);} // Function for the range sum-queryint query(int in, int l, int r, int l1, int r1){ // Base case if (l > r) return 0; if (r < l1 || l > r1) return 0; if (l1 <= l and r <= r1) return seg[in]; // Mid element int m = (l + r) / 2; // Calling for the left and the right subtree return query(2 * in + 1, l, m, l1, r1) + query(2 * in + 2, m + 1, r, l1, r1);} // Function to return the countint findCnt(int* arr, int n){ // Copying array arr to sort it int brr[n]; for (int i = 0; i < n; i++) brr[i] = arr[i]; // Sorting array brr sort(brr, brr + n); // Map to store the rank of each element map<int, int> r; for (int i = 0; i < n; i++) r[brr[i]] = i + 1; // dp array int dp[n] = { 0 }; // To store the final answer int ans = 0; // Updating the dp array for (int i = n - 1; i >= 0; i--) { // Rank of the element int rank = r[arr[i]]; // Solving the dp-states using segment tree dp[i] = 1 + query(0, 0, n - 1, rank, n - 1); // Updating the final answer ans += dp[i]; // Updating the segment tree update(0, 0, n - 1, rank - 1, dp[i] + query(0, 0, n - 1, rank - 1, rank - 1)); } // Returning the final answer return ans;} // Driver codeint main(){ int arr[] = { 1, 2, 10, 9 }; int n = sizeof(arr) / sizeof(int); cout << findCnt(arr, n); return 0;}",
"e": 28378,
"s": 26342,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ static final int N = 10000; // Segment tree array static int[] seg = new int[3 * N]; // Function for point update in segment tree static int update(int in, int l, int r, int up_in, int val) { // Base case if (r < up_in || l > up_in) return seg[in]; // If l==r==up if (l == up_in && r == up_in) return seg[in] = val; // Mid element int m = (l + r) / 2; // Updating the segment tree return seg[in] = update(2 * in + 1, l, m, up_in, val) + update(2 * in + 2, m + 1, r, up_in, val); } // Function for the range sum-query static int query(int in, int l, int r, int l1, int r1) { // Base case if (l > r) return 0; if (r < l1 || l > r1) return 0; if (l1 <= l && r <= r1) return seg[in]; // Mid element int m = (l + r) / 2; // Calling for the left and the right subtree return query(2 * in + 1, l, m, l1, r1) + query(2 * in + 2, m + 1, r, l1, r1); } // Function to return the count static int findCnt(int[] arr, int n) { // Copying array arr to sort it int[] brr = new int[n]; for (int i = 0; i < n; i++) brr[i] = arr[i]; // Sorting array brr Arrays.sort(brr); // Map to store the rank of each element HashMap<Integer, Integer> r = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) r.put(brr[i], i + 1); // dp array int dp[] = new int[n]; // To store the final answer int ans = 0; // Updating the dp array for (int i = n - 1; i >= 0; i--) { // Rank of the element int rank = r.get(arr[i]); // Solving the dp-states using segment tree dp[i] = 1 + query(0, 0, n - 1, rank, n - 1); // Updating the final answer ans += dp[i]; // Updating the segment tree update(0, 0, n - 1, rank - 1, dp[i] + query(0, 0, n - 1, rank - 1, rank - 1)); } // Returning the final answer return ans; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 10, 9 }; int n = arr.length; System.out.print(findCnt(arr, n)); }} // This code is contributed by PrinciRaj1992",
"e": 30867,
"s": 28378,
"text": null
},
{
"code": "# Python3 implementation of the approach N = 10000 # Segment tree arrayseg = [0] * (3 * N) # Function for point update in segment treedef update(In, l, r, up_In, val): # Base case if (r < up_In or l > up_In): return seg[In] # If l==r==up if (l == up_In and r == up_In): seg[In] = val return val # Mid element m = (l + r) // 2 # Updating the segment tree seg[In] = update(2 * In + 1, l, m, up_In, val) + update(2 * In + 2, m + 1, r, up_In, val) return seg[In] # Function for the range sum-querydef query(In, l, r, l1, r1): # Base case if (l > r): return 0 if (r < l1 or l > r1): return 0 if (l1 <= l and r <= r1): return seg[In] # Mid element m = (l + r) // 2 # CallIng for the left and the right subtree return query(2 * In + 1, l, m, l1, r1)+ query(2 * In + 2, m + 1, r, l1, r1) # Function to return the countdef fIndCnt(arr, n): # Copying array arr to sort it brr = [0] * n for i in range(n): brr[i] = arr[i] # Sorting array brr brr = sorted(brr) # Map to store the rank of each element r = dict() for i in range(n): r[brr[i]] = i + 1 # dp array dp = [0] * n # To store the final answer ans = 0 # Updating the dp array for i in range(n - 1, -1, -1): # Rank of the element rank = r[arr[i]] # Solving the dp-states using segment tree dp[i] = 1 + query(0, 0, n - 1, rank, n - 1) # UpdatIng the final answer ans += dp[i] # Updating the segment tree update(0, 0, n - 1, rank - 1,dp[i] + query(0, 0, n - 1, rank - 1, rank - 1)) # Returning the final answer return ans # Driver code arr = [1, 2, 10, 9]n = len(arr) print(fIndCnt(arr, n)) # This code is contributed by mohit kumar 29",
"e": 32680,
"s": 30867,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static readonly int N = 10000; // Segment tree array static int[] seg = new int[3 * N]; // Function for point update In segment tree static int update(int In, int l, int r, int up_in, int val) { // Base case if (r < up_in || l > up_in) return seg[In]; // If l==r==up if (l == up_in && r == up_in) return seg[In] = val; // Mid element int m = (l + r) / 2; // Updating the segment tree return seg[In] = update(2 * In + 1, l, m, up_in, val) + update(2 * In + 2, m + 1, r, up_in, val); } // Function for the range sum-query static int query(int In, int l, int r, int l1, int r1) { // Base case if (l > r) return 0; if (r < l1 || l > r1) return 0; if (l1 <= l && r <= r1) return seg[In]; // Mid element int m = (l + r) / 2; // Calling for the left and the right subtree return query(2 * In + 1, l, m, l1, r1) + query(2 * In + 2, m + 1, r, l1, r1); } // Function to return the count static int findCnt(int[] arr, int n) { // Copying array arr to sort it int[] brr = new int[n]; for (int i = 0; i < n; i++) brr[i] = arr[i]; // Sorting array brr Array.Sort(brr); // Map to store the rank of each element Dictionary<int, int> r = new Dictionary<int, int>(); for (int i = 0; i < n; i++) r.Add(brr[i], i + 1); // dp array int []dp = new int[n]; // To store the readonly answer int ans = 0; // Updating the dp array for (int i = n - 1; i >= 0; i--) { // Rank of the element int rank = r[arr[i]]; // Solving the dp-states using segment tree dp[i] = 1 + query(0, 0, n - 1, rank, n - 1); // Updating the readonly answer ans += dp[i]; // Updating the segment tree update(0, 0, n - 1, rank - 1, dp[i] + query(0, 0, n - 1, rank - 1, rank - 1)); } // Returning the readonly answer return ans; } // Driver code public static void Main(String[] args) { int []arr = { 1, 2, 10, 9 }; int n = arr.Length; Console.Write(findCnt(arr, n)); }} // This code is contributed by PrinciRaj1992",
"e": 35211,
"s": 32680,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach var N = 10000; // Segment tree arrayvar seg = Array(3*N).fill(0); // Function for point update inVal segment treefunction update(inVal, l, r, up_in, val){ // Base case if (r < up_in || l > up_in) return seg[inVal]; // If l==r==up if (l == up_in && r == up_in) return seg[inVal] = val; // Mid element var m = parseInt((l + r) / 2); // Updating the segment tree seg[inVal] = update(2 * inVal + 1, l, m, up_in, val) + update(2 * inVal + 2, m + 1, r, up_in, val); return seg[inVal];} // Function for the range sum-queryfunction query(inVal, l, r, l1, r1){ // Base case if (l > r) return 0; if (r < l1 || l > r1) return 0; if (l1 <= l && r <= r1) return seg[inVal]; // Mid element var m = parseInt((l + r) / 2); // Calling for the left and the right subtree return query(2 * inVal + 1, l, m, l1, r1) + query(2 * inVal + 2, m + 1, r, l1, r1);} // Function to return the countfunction findCnt(arr, n){ // Copying array arr to sort it var brr = Array(n); for (var i = 0; i < n; i++) brr[i] = arr[i]; // Sorting array brr brr.sort((a, b)=> a-b); // Map to store the rank of each element var r = new Map(); for (var i = 0; i < n; i++) r[brr[i]] = i + 1; // dp array var dp = Array(n).fill(0); // To store the final answer var ans = 0; // Updating the dp array for (var i = n - 1; i >= 0; i--) { // Rank of the element var rank = r[arr[i]]; // Solving the dp-states using segment tree dp[i] = 1 + query(0, 0, n - 1, rank, n - 1); // Updating the final answer ans += dp[i]; // Updating the segment tree update(0, 0, n - 1, rank - 1, dp[i] + query(0, 0, n - 1, rank - 1, rank - 1)); } // Returning the final answer return ans;} // Driver codevar arr = [1, 2, 10, 9 ];var n = arr.length;document.write( findCnt(arr, n)); </script>",
"e": 37248,
"s": 35211,
"text": null
},
{
"code": null,
"e": 37251,
"s": 37248,
"text": "11"
},
{
"code": null,
"e": 37268,
"s": 37253,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 37282,
"s": 37268,
"text": "princiraj1992"
},
{
"code": null,
"e": 37295,
"s": 37282,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 37302,
"s": 37295,
"text": "rrrtnx"
},
{
"code": null,
"e": 37315,
"s": 37302,
"text": "Segment-Tree"
},
{
"code": null,
"e": 37327,
"s": 37315,
"text": "subsequence"
},
{
"code": null,
"e": 37351,
"s": 37327,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 37358,
"s": 37351,
"text": "Arrays"
},
{
"code": null,
"e": 37378,
"s": 37358,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37385,
"s": 37378,
"text": "Arrays"
},
{
"code": null,
"e": 37405,
"s": 37385,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37418,
"s": 37405,
"text": "Segment-Tree"
},
{
"code": null,
"e": 37516,
"s": 37418,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37525,
"s": 37516,
"text": "Comments"
},
{
"code": null,
"e": 37538,
"s": 37525,
"text": "Old Comments"
},
{
"code": null,
"e": 37580,
"s": 37538,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 37626,
"s": 37580,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 37660,
"s": 37626,
"text": "Advantages of Trie Data Structure"
},
{
"code": null,
"e": 37675,
"s": 37660,
"text": "Cartesian Tree"
},
{
"code": null,
"e": 37725,
"s": 37675,
"text": "Proof that Dominant Set of a Graph is NP-Complete"
},
{
"code": null,
"e": 37740,
"s": 37725,
"text": "Arrays in Java"
},
{
"code": null,
"e": 37756,
"s": 37740,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 37783,
"s": 37756,
"text": "Program for array rotation"
},
{
"code": null,
"e": 37831,
"s": 37783,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Optimal Cost Binary Search Trees
|
A Binary Search Tree (BST) is a tree where the key values are stored in the internal nodes. The external nodes are null nodes. The keys are ordered lexicographically, i.e. for each internal node all the keys in the left sub-tree are less than the keys in the node, and all the keys in the right sub-tree are greater.
When we know the frequency of searching each one of the keys, it is quite easy to compute the expected cost of accessing each node in the tree. An optimal binary search tree is a BST, which has minimal expected cost of locating each node
Search time of an element in a BST is O(n), whereas in a Balanced-BST search time is O(log n). Again the search time can be improved in Optimal Cost Binary Search Tree, placing the most frequently used data in the root and closer to the root element, while placing the least frequently used data near leaves and in leaves.
Here, the Optimal Binary Search Tree Algorithm is presented. First, we build a BST from a set of provided n number of distinct keys < k1, k2, k3, ... kn >. Here we assume, the probability of accessing a key Ki is pi. Some dummy keys (d0, d1, d2, ... dn) are added as some searches may be performed for the values which are not present in the Key set K. We assume, for each dummy key di probability of access is qi.
Optimal-Binary-Search-Tree(p, q, n)
e[1...n + 1, 0...n],
w[1...n + 1, 0...n],
root[1...n + 1, 0...n]
for i = 1 to n + 1 do
e[i, i - 1] := qi - 1
w[i, i - 1] := qi - 1
for l = 1 to n do
for i = 1 to n – l + 1 do
j = i + l – 1 e[i, j] := ∞
w[i, i] := w[i, i -1] + pj + qj
for r = i to j do
t := e[i, r - 1] + e[r + 1, j] + w[i, j]
if t < e[i, j]
e[i, j] := t
root[i, j] := r
return e and root
The algorithm requires O (n3) time, since three nested for loops are used. Each of these loops takes on at most n values.
Considering the following tree, the cost is 2.80, though this is not an optimal result.
To get an optimal solution, using the algorithm discussed in this chapter, the following tables are generated.
In the following tables, column index is i and row index is j.
From these tables, the optimal tree can be formed.
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2916,
"s": 2599,
"text": "A Binary Search Tree (BST) is a tree where the key values are stored in the internal nodes. The external nodes are null nodes. The keys are ordered lexicographically, i.e. for each internal node all the keys in the left sub-tree are less than the keys in the node, and all the keys in the right sub-tree are greater."
},
{
"code": null,
"e": 3154,
"s": 2916,
"text": "When we know the frequency of searching each one of the keys, it is quite easy to compute the expected cost of accessing each node in the tree. An optimal binary search tree is a BST, which has minimal expected cost of locating each node"
},
{
"code": null,
"e": 3477,
"s": 3154,
"text": "Search time of an element in a BST is O(n), whereas in a Balanced-BST search time is O(log n). Again the search time can be improved in Optimal Cost Binary Search Tree, placing the most frequently used data in the root and closer to the root element, while placing the least frequently used data near leaves and in leaves."
},
{
"code": null,
"e": 3892,
"s": 3477,
"text": "Here, the Optimal Binary Search Tree Algorithm is presented. First, we build a BST from a set of provided n number of distinct keys < k1, k2, k3, ... kn >. Here we assume, the probability of accessing a key Ki is pi. Some dummy keys (d0, d1, d2, ... dn) are added as some searches may be performed for the values which are not present in the Key set K. We assume, for each dummy key di probability of access is qi."
},
{
"code": null,
"e": 4373,
"s": 3892,
"text": "Optimal-Binary-Search-Tree(p, q, n) \ne[1...n + 1, 0...n], \nw[1...n + 1, 0...n], \nroot[1...n + 1, 0...n] \nfor i = 1 to n + 1 do \n e[i, i - 1] := qi - 1 \n w[i, i - 1] := qi - 1 \nfor l = 1 to n do \n for i = 1 to n – l + 1 do \n j = i + l – 1 e[i, j] := ∞ \n w[i, i] := w[i, i -1] + pj + qj \n for r = i to j do \n t := e[i, r - 1] + e[r + 1, j] + w[i, j] \n if t < e[i, j] \n e[i, j] := t \n root[i, j] := r \nreturn e and root \n"
},
{
"code": null,
"e": 4495,
"s": 4373,
"text": "The algorithm requires O (n3) time, since three nested for loops are used. Each of these loops takes on at most n values."
},
{
"code": null,
"e": 4583,
"s": 4495,
"text": "Considering the following tree, the cost is 2.80, though this is not an optimal result."
},
{
"code": null,
"e": 4694,
"s": 4583,
"text": "To get an optimal solution, using the algorithm discussed in this chapter, the following tables are generated."
},
{
"code": null,
"e": 4757,
"s": 4694,
"text": "In the following tables, column index is i and row index is j."
},
{
"code": null,
"e": 4808,
"s": 4757,
"text": "From these tables, the optimal tree can be formed."
},
{
"code": null,
"e": 4843,
"s": 4808,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4862,
"s": 4843,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4895,
"s": 4862,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4914,
"s": 4895,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4947,
"s": 4914,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4966,
"s": 4947,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5001,
"s": 4966,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5014,
"s": 5001,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 5046,
"s": 5014,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5059,
"s": 5046,
"text": " Zach Miller"
},
{
"code": null,
"e": 5092,
"s": 5059,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5106,
"s": 5092,
"text": " Sasha Miller"
},
{
"code": null,
"e": 5113,
"s": 5106,
"text": " Print"
},
{
"code": null,
"e": 5124,
"s": 5113,
"text": " Add Notes"
}
] |
AKTU 1st Year Sem 1 Solved Paper 2017-18 | COMP. SYSTEM & C PROGRAMMING | Sec B - GeeksforGeeks
|
30 Jan, 2019
Paper download link: Paper | Sem 1 | 2017-18
Time: 3hrsTotal Marks: 100
Note:-
There are three sections. Section A carries 20 marks, Section B carries 30 marks and Section C carries 50 marks.
Attempt all questions. Marks are indicated against each question.
Assume suitable data wherever necessary.
What is digital computer? Draw block diagram of digital computer and explain each components of it.Digital Computer: A digital computer can be defined as a programmable machine which reads the binary data passed as instructions, processes this binary data, and displays a calculated digital output. Therefore, Digital computers are those that work on the digital data.Details of Functional Components of a Digital ComputerInput Unit :The input unit consists of input devices that are attached to the computer. These devices take input and convert it into binary language that the computer understands. Some of the common input devices are keyboard, mouse, joystick, scanner etc.Central Processing Unit (CPU0 : Once the information is entered into the computer by the input device, the processor processes it. The CPU is called the brain of the computer because it is the control center of the computer. It first fetches instructions from memory and then interprets them so as to know what is to be done. If required, data is fetched from memory or input device. Thereafter CPU executes or performs the required computation and then either stores the output or displays on the output device. The CPU has three main components which are responsible for different functions – Arithmetic Logic Unit (ALU), Control Unit (CU) and Memory registersArithmetic and Logic Unit (ALU) : The ALU, as its name suggests performs mathematical calculations and takes logical decisions. Arithmetic calculations include addition, subtraction, multiplication and division. Logical decisions involve comparison of two data items to see which one is larger or smaller or equal.Control Unit : The Control unit coordinates and controls the data flow in and out of CPU and also controls all the operations of ALU, memory registers and also input/output units. It is also responsible for carrying out all the instructions stored in the program. It decodes the fetched instruction, interprets it and sends control signals to input/output devices until the required operation is done properly by ALU and memory.Memory Registers : A register is a temporary unit of memory in the CPU. These are used to store the data which is directly used by the processor. Registers can be of different sizes(16 bit, 32 bit, 64 bit and so on) and each register inside the CPU has a specific function like storing data, storing an instruction, storing address of a location in memory etc. The user registers can be used by an assembly language programmer for storing operands, intermediate results etc. Accumulator (ACC) is the main register in the ALU and contains one of the operands of an operation to be performed in the ALU.Memory : Memory attached to the CPU is used for storage of data and instructions and is called internal memory The internal memory is divided into many storage locations, each of which can store data or instructions. Each memory location is of the same size and has an address. With the help of the address, the computer can read any memory location easily without having to search the entire memory. when a program is executed, it’s data is copied to the internal memory ans is stored in the memory till the end of the execution. The internal memory is also called the Primary memory or Main memory. This memory is also called as RAM, i.e. Random Access Memory. The time of access of data is independent of its location in memory, therefore this memory is also called Random Access memory (RAM). Read this for different types of RAMsOutput Unit : The output unit consists of output devices that are attached with the computer. It converts the binary data coming from CPU to human understandable form. The common output devices are monitor, printer, plotter etc.Wrtie a program to check the number is palindrome or not. The program should accept any arbitrary number typed by user.Program to check whether the number is Palindrome or not:// C program to check whether a number// is Palindrome or not. #include <stdio.h> /* Iterative function to reverse digits of num*/int reverseDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Function to check if n is Palindrome*/int isPalindrome(int n){ // get the reverse of n int rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0;} /*Driver program to test reversDigits*/int main(){ int n; // Read n from user printf("Enter the number to checked: "); scanf("%d", &n); // Find if n is Palindrome and print printf("Is %d a Palindrome number? -> %s\n", n, isPalindrome(n) == 1 ? "true" : "false"); // Read n from user printf("\nEnter the number to checked: "); scanf("%d", &n); // Find if n is Palindrome and print printf("Is %d a Palindrome number? -> %s\n", n, isPalindrome(n) == 1 ? "true" : "false"); return 0;}Output:Enter the number to checked: 4562
Is 4562 a Palindrome number? -> false
Enter the number to checked: 2002
Is 2002 a Palindrome number? -> true
What is Operating System? Explain various types of functions performed by an Operating System.The fundamental goal of a Computer System is to execute user programs and to make tasks easier. Various application programs along with hardware system are used to perform this work. Operating System is a software which manages and control the entire set of resources and effectively utilize every part of a computer.The figure shows how OS acts as a medium between hardware unit and application programs.Functions of an Operating SystemAn operating system has variety of functions to perform. Some of the prominent functions of an operating system can be broadly outlined as:Processor Management: This deals with management of the Central Processing Unit (CPU). The operating system takes care of the allotment of CPU time to different processes. When a process finishes its CPU processing after executing for the allotted time period, this is called scheduling. There are various type of scheduling techniques that are used by the operating systems:Shortest Job First(SJF): Process which need the shortest CPU time are scheduled first.Round Robin Scheduling: Each process is assigned a fixed CPU execution time in cyclic way.Priority Based scheduling (Non Preemptive): In this scheduling, processes are scheduled according to their priorities, i.e., highest priority process is schedule first. If priorities of two processes match, then schedule according to arrival timeDevice Management:The Operating System communicates with hardware and the attached devices and maintains a balance between them and the CPU. This is all the more important because the CPU processing speed is much higher than thatof I/O devices. In order to optimize the CPU time, the operating system employstwo techniques – Buffering and Spooling.Buffering:In this technique, input and output data is temporarily stored in Input Buffer and Output Buffer. Once the signal for input or output is sent to or from the CPU respectively, the operating system through the device controller moves the data from the input device to the input buffer and for the output device to the output buffer. In case of input, if the buffer is full, the operating system sends a signal to the program which processes the data stored in the buffer. When the buffer becomes empty, the program informs the operating system which reloads the buffer and the input operation continues.Spooling (Simultaneous Peripheral Operation on Line):This is a device management technique used for processing of different tasks on the same input/output device. When there are various users on a network sharing the same resource then it can be a possibility that more than one user might give it a command at the same point of time. So, the operating system temporarily stores the data of every user on the hard disk of the computer to which the resource is attached. The individual user need not wait for the execution process to be completed. Instead the operating system sends the data from the hard disk to the resource one by one.Example: printerMemory management:In a computer, both the CPU and the I/O devices interact with the memory. When a program needs to be executed it is loaded onto the main memory till the execution is completed. Thereafter that memory space is freed and is available for other programs. The common memory management techniques used by the operating system are Partitioning and Virtual Memory.Partitioning:The total memory is divided into various partitions of same size or different sizes. This helps to accommodate number of programs in the memory. The partition can be fixed i.e. remains same for all the programs in the memory or variable i.e. memory is allocated when a program is loaded on to the memory. The later approach causes less wastage of memory but in due course of time, it may become fragmented.Virtual Memory:This is a technique used by the operating systems which allow the user can load the programs which are larger than the main memory of the computer. In this technique the program is executed even if the complete program can not be loaded inside the main memory leading to efficient memory utilization.File Management:The operating System manages the files, folders and directory systems on a computer. Any data on a computer is stored in the form of files and the operating system keeps information about all of them using File Allocation Table (FAT). The FAT stores general information about files like filename, type (text or binary), size, starting address and access mode (sequential/indexed sequential/direct/relative). The file manager of the operating system helps to create, edit, copy, allocate memory to the files and also updates the FAT. The operating system also takes care that files are opened with proper access rights to read or edit them.What is Structured programming approach? Highlight the advantages and disadvantages of structured programming.Structured Programming Approach, as the word suggests, can be defined as a programming approach in which the program is made as a single structure. It means that the code will execute the instruction by instruction one after the other. It doesn’t support the possibility of jumping from one instruction to some other with help of any statement like GOTO, etc. Therefore, the instructions in this approach will be executed in a serial and structured manner. The languages that support Structured programming approach are:CC++JavaC#..etcOn the contrary, in the Assembly languages like Microprocessor 8085, etc, the statements do not get executed in a structured manner. It allows jump statements like GOTO. So the program flow might be random.The structured program mainly consists of three types of elements:Selection StatementsSequence StatementsIteration StatementsThe structured program consists of well structured and separated modules. But the entry and exit in a Structured program is a single-time event. It means that the program uses single-entry and single-exit elements. Therefore a structured program is well maintained, neat and clean program. This is the reason why the Structured Programming Approach is well accepted in the programming world.Advantages of Structured Programming Approach:Easier to read and understandUser FrindlyEasier to MaintainMainly problem based instead of being machine basedDevelopment is easier as it requires less effort and timeEasier to DebugMachine-Independent, mostly.Disadvantages of Structured Programming Approach:Since it is Machine-Independent, So it takes time to convert into machine code.The converted machine code is not the same as for assembly language.The program depends upon changeable factors like data-types. Therefore it needs to be updated with the need on the go.Usually the development in this approach takes longer time as it is language dependent. Whereas in the case of assembly language, the development takes lesser time as it is fixed for the machine.What do you mean by sorting? Write a program in C to sort the elements of a given array of N positive integers. Also give the flow chart for the same.A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of element in the respective data structure.For example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character with lesser ASCII value will be placed first than the character with higher ASCII value.Flowchart of the Selection Sort:Program in C to sort the elements of a given array of N positive integers:// C program to sort the elements// of a given array of N positive integers #include <stdio.h> void swap(int* xp, int* yp){ int temp = *xp; *xp = *yp; *yp = temp;} void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n");} // Driver program to test above functionsint main(){ int arr[] = { 64, 25, 12, 22, 11 }; int n = sizeof(arr) / sizeof(arr[0]); selectionSort(arr, n); printf("Sorted array: \n"); printArray(arr, n); return 0;}
What is digital computer? Draw block diagram of digital computer and explain each components of it.Digital Computer: A digital computer can be defined as a programmable machine which reads the binary data passed as instructions, processes this binary data, and displays a calculated digital output. Therefore, Digital computers are those that work on the digital data.Details of Functional Components of a Digital ComputerInput Unit :The input unit consists of input devices that are attached to the computer. These devices take input and convert it into binary language that the computer understands. Some of the common input devices are keyboard, mouse, joystick, scanner etc.Central Processing Unit (CPU0 : Once the information is entered into the computer by the input device, the processor processes it. The CPU is called the brain of the computer because it is the control center of the computer. It first fetches instructions from memory and then interprets them so as to know what is to be done. If required, data is fetched from memory or input device. Thereafter CPU executes or performs the required computation and then either stores the output or displays on the output device. The CPU has three main components which are responsible for different functions – Arithmetic Logic Unit (ALU), Control Unit (CU) and Memory registersArithmetic and Logic Unit (ALU) : The ALU, as its name suggests performs mathematical calculations and takes logical decisions. Arithmetic calculations include addition, subtraction, multiplication and division. Logical decisions involve comparison of two data items to see which one is larger or smaller or equal.Control Unit : The Control unit coordinates and controls the data flow in and out of CPU and also controls all the operations of ALU, memory registers and also input/output units. It is also responsible for carrying out all the instructions stored in the program. It decodes the fetched instruction, interprets it and sends control signals to input/output devices until the required operation is done properly by ALU and memory.Memory Registers : A register is a temporary unit of memory in the CPU. These are used to store the data which is directly used by the processor. Registers can be of different sizes(16 bit, 32 bit, 64 bit and so on) and each register inside the CPU has a specific function like storing data, storing an instruction, storing address of a location in memory etc. The user registers can be used by an assembly language programmer for storing operands, intermediate results etc. Accumulator (ACC) is the main register in the ALU and contains one of the operands of an operation to be performed in the ALU.Memory : Memory attached to the CPU is used for storage of data and instructions and is called internal memory The internal memory is divided into many storage locations, each of which can store data or instructions. Each memory location is of the same size and has an address. With the help of the address, the computer can read any memory location easily without having to search the entire memory. when a program is executed, it’s data is copied to the internal memory ans is stored in the memory till the end of the execution. The internal memory is also called the Primary memory or Main memory. This memory is also called as RAM, i.e. Random Access Memory. The time of access of data is independent of its location in memory, therefore this memory is also called Random Access memory (RAM). Read this for different types of RAMsOutput Unit : The output unit consists of output devices that are attached with the computer. It converts the binary data coming from CPU to human understandable form. The common output devices are monitor, printer, plotter etc.
Details of Functional Components of a Digital Computer
Input Unit :The input unit consists of input devices that are attached to the computer. These devices take input and convert it into binary language that the computer understands. Some of the common input devices are keyboard, mouse, joystick, scanner etc.
Central Processing Unit (CPU0 : Once the information is entered into the computer by the input device, the processor processes it. The CPU is called the brain of the computer because it is the control center of the computer. It first fetches instructions from memory and then interprets them so as to know what is to be done. If required, data is fetched from memory or input device. Thereafter CPU executes or performs the required computation and then either stores the output or displays on the output device. The CPU has three main components which are responsible for different functions – Arithmetic Logic Unit (ALU), Control Unit (CU) and Memory registers
Arithmetic and Logic Unit (ALU) : The ALU, as its name suggests performs mathematical calculations and takes logical decisions. Arithmetic calculations include addition, subtraction, multiplication and division. Logical decisions involve comparison of two data items to see which one is larger or smaller or equal.
Control Unit : The Control unit coordinates and controls the data flow in and out of CPU and also controls all the operations of ALU, memory registers and also input/output units. It is also responsible for carrying out all the instructions stored in the program. It decodes the fetched instruction, interprets it and sends control signals to input/output devices until the required operation is done properly by ALU and memory.
Memory Registers : A register is a temporary unit of memory in the CPU. These are used to store the data which is directly used by the processor. Registers can be of different sizes(16 bit, 32 bit, 64 bit and so on) and each register inside the CPU has a specific function like storing data, storing an instruction, storing address of a location in memory etc. The user registers can be used by an assembly language programmer for storing operands, intermediate results etc. Accumulator (ACC) is the main register in the ALU and contains one of the operands of an operation to be performed in the ALU.
Memory : Memory attached to the CPU is used for storage of data and instructions and is called internal memory The internal memory is divided into many storage locations, each of which can store data or instructions. Each memory location is of the same size and has an address. With the help of the address, the computer can read any memory location easily without having to search the entire memory. when a program is executed, it’s data is copied to the internal memory ans is stored in the memory till the end of the execution. The internal memory is also called the Primary memory or Main memory. This memory is also called as RAM, i.e. Random Access Memory. The time of access of data is independent of its location in memory, therefore this memory is also called Random Access memory (RAM). Read this for different types of RAMs
Output Unit : The output unit consists of output devices that are attached with the computer. It converts the binary data coming from CPU to human understandable form. The common output devices are monitor, printer, plotter etc.
Wrtie a program to check the number is palindrome or not. The program should accept any arbitrary number typed by user.Program to check whether the number is Palindrome or not:// C program to check whether a number// is Palindrome or not. #include <stdio.h> /* Iterative function to reverse digits of num*/int reverseDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Function to check if n is Palindrome*/int isPalindrome(int n){ // get the reverse of n int rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0;} /*Driver program to test reversDigits*/int main(){ int n; // Read n from user printf("Enter the number to checked: "); scanf("%d", &n); // Find if n is Palindrome and print printf("Is %d a Palindrome number? -> %s\n", n, isPalindrome(n) == 1 ? "true" : "false"); // Read n from user printf("\nEnter the number to checked: "); scanf("%d", &n); // Find if n is Palindrome and print printf("Is %d a Palindrome number? -> %s\n", n, isPalindrome(n) == 1 ? "true" : "false"); return 0;}Output:Enter the number to checked: 4562
Is 4562 a Palindrome number? -> false
Enter the number to checked: 2002
Is 2002 a Palindrome number? -> true
// C program to check whether a number// is Palindrome or not. #include <stdio.h> /* Iterative function to reverse digits of num*/int reverseDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Function to check if n is Palindrome*/int isPalindrome(int n){ // get the reverse of n int rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0;} /*Driver program to test reversDigits*/int main(){ int n; // Read n from user printf("Enter the number to checked: "); scanf("%d", &n); // Find if n is Palindrome and print printf("Is %d a Palindrome number? -> %s\n", n, isPalindrome(n) == 1 ? "true" : "false"); // Read n from user printf("\nEnter the number to checked: "); scanf("%d", &n); // Find if n is Palindrome and print printf("Is %d a Palindrome number? -> %s\n", n, isPalindrome(n) == 1 ? "true" : "false"); return 0;}
Enter the number to checked: 4562
Is 4562 a Palindrome number? -> false
Enter the number to checked: 2002
Is 2002 a Palindrome number? -> true
What is Operating System? Explain various types of functions performed by an Operating System.The fundamental goal of a Computer System is to execute user programs and to make tasks easier. Various application programs along with hardware system are used to perform this work. Operating System is a software which manages and control the entire set of resources and effectively utilize every part of a computer.The figure shows how OS acts as a medium between hardware unit and application programs.Functions of an Operating SystemAn operating system has variety of functions to perform. Some of the prominent functions of an operating system can be broadly outlined as:Processor Management: This deals with management of the Central Processing Unit (CPU). The operating system takes care of the allotment of CPU time to different processes. When a process finishes its CPU processing after executing for the allotted time period, this is called scheduling. There are various type of scheduling techniques that are used by the operating systems:Shortest Job First(SJF): Process which need the shortest CPU time are scheduled first.Round Robin Scheduling: Each process is assigned a fixed CPU execution time in cyclic way.Priority Based scheduling (Non Preemptive): In this scheduling, processes are scheduled according to their priorities, i.e., highest priority process is schedule first. If priorities of two processes match, then schedule according to arrival timeDevice Management:The Operating System communicates with hardware and the attached devices and maintains a balance between them and the CPU. This is all the more important because the CPU processing speed is much higher than thatof I/O devices. In order to optimize the CPU time, the operating system employstwo techniques – Buffering and Spooling.Buffering:In this technique, input and output data is temporarily stored in Input Buffer and Output Buffer. Once the signal for input or output is sent to or from the CPU respectively, the operating system through the device controller moves the data from the input device to the input buffer and for the output device to the output buffer. In case of input, if the buffer is full, the operating system sends a signal to the program which processes the data stored in the buffer. When the buffer becomes empty, the program informs the operating system which reloads the buffer and the input operation continues.Spooling (Simultaneous Peripheral Operation on Line):This is a device management technique used for processing of different tasks on the same input/output device. When there are various users on a network sharing the same resource then it can be a possibility that more than one user might give it a command at the same point of time. So, the operating system temporarily stores the data of every user on the hard disk of the computer to which the resource is attached. The individual user need not wait for the execution process to be completed. Instead the operating system sends the data from the hard disk to the resource one by one.Example: printerMemory management:In a computer, both the CPU and the I/O devices interact with the memory. When a program needs to be executed it is loaded onto the main memory till the execution is completed. Thereafter that memory space is freed and is available for other programs. The common memory management techniques used by the operating system are Partitioning and Virtual Memory.Partitioning:The total memory is divided into various partitions of same size or different sizes. This helps to accommodate number of programs in the memory. The partition can be fixed i.e. remains same for all the programs in the memory or variable i.e. memory is allocated when a program is loaded on to the memory. The later approach causes less wastage of memory but in due course of time, it may become fragmented.Virtual Memory:This is a technique used by the operating systems which allow the user can load the programs which are larger than the main memory of the computer. In this technique the program is executed even if the complete program can not be loaded inside the main memory leading to efficient memory utilization.File Management:The operating System manages the files, folders and directory systems on a computer. Any data on a computer is stored in the form of files and the operating system keeps information about all of them using File Allocation Table (FAT). The FAT stores general information about files like filename, type (text or binary), size, starting address and access mode (sequential/indexed sequential/direct/relative). The file manager of the operating system helps to create, edit, copy, allocate memory to the files and also updates the FAT. The operating system also takes care that files are opened with proper access rights to read or edit them.
The figure shows how OS acts as a medium between hardware unit and application programs.
Functions of an Operating System
An operating system has variety of functions to perform. Some of the prominent functions of an operating system can be broadly outlined as:
Processor Management: This deals with management of the Central Processing Unit (CPU). The operating system takes care of the allotment of CPU time to different processes. When a process finishes its CPU processing after executing for the allotted time period, this is called scheduling. There are various type of scheduling techniques that are used by the operating systems:Shortest Job First(SJF): Process which need the shortest CPU time are scheduled first.Round Robin Scheduling: Each process is assigned a fixed CPU execution time in cyclic way.Priority Based scheduling (Non Preemptive): In this scheduling, processes are scheduled according to their priorities, i.e., highest priority process is schedule first. If priorities of two processes match, then schedule according to arrival time
Shortest Job First(SJF): Process which need the shortest CPU time are scheduled first.Round Robin Scheduling: Each process is assigned a fixed CPU execution time in cyclic way.Priority Based scheduling (Non Preemptive): In this scheduling, processes are scheduled according to their priorities, i.e., highest priority process is schedule first. If priorities of two processes match, then schedule according to arrival time
Shortest Job First(SJF): Process which need the shortest CPU time are scheduled first.
Round Robin Scheduling: Each process is assigned a fixed CPU execution time in cyclic way.
Priority Based scheduling (Non Preemptive): In this scheduling, processes are scheduled according to their priorities, i.e., highest priority process is schedule first. If priorities of two processes match, then schedule according to arrival time
Device Management:The Operating System communicates with hardware and the attached devices and maintains a balance between them and the CPU. This is all the more important because the CPU processing speed is much higher than thatof I/O devices. In order to optimize the CPU time, the operating system employstwo techniques – Buffering and Spooling.
Buffering:In this technique, input and output data is temporarily stored in Input Buffer and Output Buffer. Once the signal for input or output is sent to or from the CPU respectively, the operating system through the device controller moves the data from the input device to the input buffer and for the output device to the output buffer. In case of input, if the buffer is full, the operating system sends a signal to the program which processes the data stored in the buffer. When the buffer becomes empty, the program informs the operating system which reloads the buffer and the input operation continues.
Spooling (Simultaneous Peripheral Operation on Line):This is a device management technique used for processing of different tasks on the same input/output device. When there are various users on a network sharing the same resource then it can be a possibility that more than one user might give it a command at the same point of time. So, the operating system temporarily stores the data of every user on the hard disk of the computer to which the resource is attached. The individual user need not wait for the execution process to be completed. Instead the operating system sends the data from the hard disk to the resource one by one.Example: printer
Memory management:In a computer, both the CPU and the I/O devices interact with the memory. When a program needs to be executed it is loaded onto the main memory till the execution is completed. Thereafter that memory space is freed and is available for other programs. The common memory management techniques used by the operating system are Partitioning and Virtual Memory.
Partitioning:The total memory is divided into various partitions of same size or different sizes. This helps to accommodate number of programs in the memory. The partition can be fixed i.e. remains same for all the programs in the memory or variable i.e. memory is allocated when a program is loaded on to the memory. The later approach causes less wastage of memory but in due course of time, it may become fragmented.
Virtual Memory:This is a technique used by the operating systems which allow the user can load the programs which are larger than the main memory of the computer. In this technique the program is executed even if the complete program can not be loaded inside the main memory leading to efficient memory utilization.
File Management:The operating System manages the files, folders and directory systems on a computer. Any data on a computer is stored in the form of files and the operating system keeps information about all of them using File Allocation Table (FAT). The FAT stores general information about files like filename, type (text or binary), size, starting address and access mode (sequential/indexed sequential/direct/relative). The file manager of the operating system helps to create, edit, copy, allocate memory to the files and also updates the FAT. The operating system also takes care that files are opened with proper access rights to read or edit them.
What is Structured programming approach? Highlight the advantages and disadvantages of structured programming.Structured Programming Approach, as the word suggests, can be defined as a programming approach in which the program is made as a single structure. It means that the code will execute the instruction by instruction one after the other. It doesn’t support the possibility of jumping from one instruction to some other with help of any statement like GOTO, etc. Therefore, the instructions in this approach will be executed in a serial and structured manner. The languages that support Structured programming approach are:CC++JavaC#..etcOn the contrary, in the Assembly languages like Microprocessor 8085, etc, the statements do not get executed in a structured manner. It allows jump statements like GOTO. So the program flow might be random.The structured program mainly consists of three types of elements:Selection StatementsSequence StatementsIteration StatementsThe structured program consists of well structured and separated modules. But the entry and exit in a Structured program is a single-time event. It means that the program uses single-entry and single-exit elements. Therefore a structured program is well maintained, neat and clean program. This is the reason why the Structured Programming Approach is well accepted in the programming world.Advantages of Structured Programming Approach:Easier to read and understandUser FrindlyEasier to MaintainMainly problem based instead of being machine basedDevelopment is easier as it requires less effort and timeEasier to DebugMachine-Independent, mostly.Disadvantages of Structured Programming Approach:Since it is Machine-Independent, So it takes time to convert into machine code.The converted machine code is not the same as for assembly language.The program depends upon changeable factors like data-types. Therefore it needs to be updated with the need on the go.Usually the development in this approach takes longer time as it is language dependent. Whereas in the case of assembly language, the development takes lesser time as it is fixed for the machine.
C
C++
Java
C#..etc
..etc
On the contrary, in the Assembly languages like Microprocessor 8085, etc, the statements do not get executed in a structured manner. It allows jump statements like GOTO. So the program flow might be random.
The structured program mainly consists of three types of elements:
Selection Statements
Sequence Statements
Iteration Statements
The structured program consists of well structured and separated modules. But the entry and exit in a Structured program is a single-time event. It means that the program uses single-entry and single-exit elements. Therefore a structured program is well maintained, neat and clean program. This is the reason why the Structured Programming Approach is well accepted in the programming world.
Advantages of Structured Programming Approach:
Easier to read and understandUser FrindlyEasier to MaintainMainly problem based instead of being machine basedDevelopment is easier as it requires less effort and timeEasier to DebugMachine-Independent, mostly.
Easier to read and understand
User Frindly
Easier to Maintain
Mainly problem based instead of being machine based
Development is easier as it requires less effort and time
Easier to Debug
Machine-Independent, mostly.
Disadvantages of Structured Programming Approach:
Since it is Machine-Independent, So it takes time to convert into machine code.The converted machine code is not the same as for assembly language.The program depends upon changeable factors like data-types. Therefore it needs to be updated with the need on the go.Usually the development in this approach takes longer time as it is language dependent. Whereas in the case of assembly language, the development takes lesser time as it is fixed for the machine.
Since it is Machine-Independent, So it takes time to convert into machine code.
The converted machine code is not the same as for assembly language.
The program depends upon changeable factors like data-types. Therefore it needs to be updated with the need on the go.
Usually the development in this approach takes longer time as it is language dependent. Whereas in the case of assembly language, the development takes lesser time as it is fixed for the machine.
What do you mean by sorting? Write a program in C to sort the elements of a given array of N positive integers. Also give the flow chart for the same.A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of element in the respective data structure.For example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character with lesser ASCII value will be placed first than the character with higher ASCII value.Flowchart of the Selection Sort:Program in C to sort the elements of a given array of N positive integers:// C program to sort the elements// of a given array of N positive integers #include <stdio.h> void swap(int* xp, int* yp){ int temp = *xp; *xp = *yp; *yp = temp;} void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n");} // Driver program to test above functionsint main(){ int arr[] = { 64, 25, 12, 22, 11 }; int n = sizeof(arr) / sizeof(arr[0]); selectionSort(arr, n); printf("Sorted array: \n"); printArray(arr, n); return 0;}
For example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character with lesser ASCII value will be placed first than the character with higher ASCII value.
Flowchart of the Selection Sort:
Program in C to sort the elements of a given array of N positive integers:
// C program to sort the elements// of a given array of N positive integers #include <stdio.h> void swap(int* xp, int* yp){ int temp = *xp; *xp = *yp; *yp = temp;} void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n");} // Driver program to test above functionsint main(){ int arr[] = { 64, 25, 12, 22, 11 }; int n = sizeof(arr) / sizeof(arr[0]); selectionSort(arr, n); printf("Sorted array: \n"); printArray(arr, n); return 0;}
AKTU-question-papers
Articles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Tree Traversals (Inorder, Preorder and Postorder)
SQL | Join (Inner, Left, Right and Full Joins)
find command in Linux with examples
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Time Complexity and Space Complexity
Mutex vs Semaphore
Analysis of Algorithms | Set 3 (Asymptotic Notations)
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
Understanding "extern" keyword in C
SQL | Views
|
[
{
"code": null,
"e": 25399,
"s": 25371,
"text": "\n30 Jan, 2019"
},
{
"code": null,
"e": 25444,
"s": 25399,
"text": "Paper download link: Paper | Sem 1 | 2017-18"
},
{
"code": null,
"e": 25471,
"s": 25444,
"text": "Time: 3hrsTotal Marks: 100"
},
{
"code": null,
"e": 25478,
"s": 25471,
"text": "Note:-"
},
{
"code": null,
"e": 25591,
"s": 25478,
"text": "There are three sections. Section A carries 20 marks, Section B carries 30 marks and Section C carries 50 marks."
},
{
"code": null,
"e": 25657,
"s": 25591,
"text": "Attempt all questions. Marks are indicated against each question."
},
{
"code": null,
"e": 25698,
"s": 25657,
"text": "Assume suitable data wherever necessary."
},
{
"code": null,
"e": 39497,
"s": 25698,
"text": "What is digital computer? Draw block diagram of digital computer and explain each components of it.Digital Computer: A digital computer can be defined as a programmable machine which reads the binary data passed as instructions, processes this binary data, and displays a calculated digital output. Therefore, Digital computers are those that work on the digital data.Details of Functional Components of a Digital ComputerInput Unit :The input unit consists of input devices that are attached to the computer. These devices take input and convert it into binary language that the computer understands. Some of the common input devices are keyboard, mouse, joystick, scanner etc.Central Processing Unit (CPU0 : Once the information is entered into the computer by the input device, the processor processes it. The CPU is called the brain of the computer because it is the control center of the computer. It first fetches instructions from memory and then interprets them so as to know what is to be done. If required, data is fetched from memory or input device. Thereafter CPU executes or performs the required computation and then either stores the output or displays on the output device. The CPU has three main components which are responsible for different functions – Arithmetic Logic Unit (ALU), Control Unit (CU) and Memory registersArithmetic and Logic Unit (ALU) : The ALU, as its name suggests performs mathematical calculations and takes logical decisions. Arithmetic calculations include addition, subtraction, multiplication and division. Logical decisions involve comparison of two data items to see which one is larger or smaller or equal.Control Unit : The Control unit coordinates and controls the data flow in and out of CPU and also controls all the operations of ALU, memory registers and also input/output units. It is also responsible for carrying out all the instructions stored in the program. It decodes the fetched instruction, interprets it and sends control signals to input/output devices until the required operation is done properly by ALU and memory.Memory Registers : A register is a temporary unit of memory in the CPU. These are used to store the data which is directly used by the processor. Registers can be of different sizes(16 bit, 32 bit, 64 bit and so on) and each register inside the CPU has a specific function like storing data, storing an instruction, storing address of a location in memory etc. The user registers can be used by an assembly language programmer for storing operands, intermediate results etc. Accumulator (ACC) is the main register in the ALU and contains one of the operands of an operation to be performed in the ALU.Memory : Memory attached to the CPU is used for storage of data and instructions and is called internal memory The internal memory is divided into many storage locations, each of which can store data or instructions. Each memory location is of the same size and has an address. With the help of the address, the computer can read any memory location easily without having to search the entire memory. when a program is executed, it’s data is copied to the internal memory ans is stored in the memory till the end of the execution. The internal memory is also called the Primary memory or Main memory. This memory is also called as RAM, i.e. Random Access Memory. The time of access of data is independent of its location in memory, therefore this memory is also called Random Access memory (RAM). Read this for different types of RAMsOutput Unit : The output unit consists of output devices that are attached with the computer. It converts the binary data coming from CPU to human understandable form. The common output devices are monitor, printer, plotter etc.Wrtie a program to check the number is palindrome or not. The program should accept any arbitrary number typed by user.Program to check whether the number is Palindrome or not:// C program to check whether a number// is Palindrome or not. #include <stdio.h> /* Iterative function to reverse digits of num*/int reverseDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Function to check if n is Palindrome*/int isPalindrome(int n){ // get the reverse of n int rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0;} /*Driver program to test reversDigits*/int main(){ int n; // Read n from user printf(\"Enter the number to checked: \"); scanf(\"%d\", &n); // Find if n is Palindrome and print printf(\"Is %d a Palindrome number? -> %s\\n\", n, isPalindrome(n) == 1 ? \"true\" : \"false\"); // Read n from user printf(\"\\nEnter the number to checked: \"); scanf(\"%d\", &n); // Find if n is Palindrome and print printf(\"Is %d a Palindrome number? -> %s\\n\", n, isPalindrome(n) == 1 ? \"true\" : \"false\"); return 0;}Output:Enter the number to checked: 4562\nIs 4562 a Palindrome number? -> false\n\nEnter the number to checked: 2002\nIs 2002 a Palindrome number? -> true\nWhat is Operating System? Explain various types of functions performed by an Operating System.The fundamental goal of a Computer System is to execute user programs and to make tasks easier. Various application programs along with hardware system are used to perform this work. Operating System is a software which manages and control the entire set of resources and effectively utilize every part of a computer.The figure shows how OS acts as a medium between hardware unit and application programs.Functions of an Operating SystemAn operating system has variety of functions to perform. Some of the prominent functions of an operating system can be broadly outlined as:Processor Management: This deals with management of the Central Processing Unit (CPU). The operating system takes care of the allotment of CPU time to different processes. When a process finishes its CPU processing after executing for the allotted time period, this is called scheduling. There are various type of scheduling techniques that are used by the operating systems:Shortest Job First(SJF): Process which need the shortest CPU time are scheduled first.Round Robin Scheduling: Each process is assigned a fixed CPU execution time in cyclic way.Priority Based scheduling (Non Preemptive): In this scheduling, processes are scheduled according to their priorities, i.e., highest priority process is schedule first. If priorities of two processes match, then schedule according to arrival timeDevice Management:The Operating System communicates with hardware and the attached devices and maintains a balance between them and the CPU. This is all the more important because the CPU processing speed is much higher than thatof I/O devices. In order to optimize the CPU time, the operating system employstwo techniques – Buffering and Spooling.Buffering:In this technique, input and output data is temporarily stored in Input Buffer and Output Buffer. Once the signal for input or output is sent to or from the CPU respectively, the operating system through the device controller moves the data from the input device to the input buffer and for the output device to the output buffer. In case of input, if the buffer is full, the operating system sends a signal to the program which processes the data stored in the buffer. When the buffer becomes empty, the program informs the operating system which reloads the buffer and the input operation continues.Spooling (Simultaneous Peripheral Operation on Line):This is a device management technique used for processing of different tasks on the same input/output device. When there are various users on a network sharing the same resource then it can be a possibility that more than one user might give it a command at the same point of time. So, the operating system temporarily stores the data of every user on the hard disk of the computer to which the resource is attached. The individual user need not wait for the execution process to be completed. Instead the operating system sends the data from the hard disk to the resource one by one.Example: printerMemory management:In a computer, both the CPU and the I/O devices interact with the memory. When a program needs to be executed it is loaded onto the main memory till the execution is completed. Thereafter that memory space is freed and is available for other programs. The common memory management techniques used by the operating system are Partitioning and Virtual Memory.Partitioning:The total memory is divided into various partitions of same size or different sizes. This helps to accommodate number of programs in the memory. The partition can be fixed i.e. remains same for all the programs in the memory or variable i.e. memory is allocated when a program is loaded on to the memory. The later approach causes less wastage of memory but in due course of time, it may become fragmented.Virtual Memory:This is a technique used by the operating systems which allow the user can load the programs which are larger than the main memory of the computer. In this technique the program is executed even if the complete program can not be loaded inside the main memory leading to efficient memory utilization.File Management:The operating System manages the files, folders and directory systems on a computer. Any data on a computer is stored in the form of files and the operating system keeps information about all of them using File Allocation Table (FAT). The FAT stores general information about files like filename, type (text or binary), size, starting address and access mode (sequential/indexed sequential/direct/relative). The file manager of the operating system helps to create, edit, copy, allocate memory to the files and also updates the FAT. The operating system also takes care that files are opened with proper access rights to read or edit them.What is Structured programming approach? Highlight the advantages and disadvantages of structured programming.Structured Programming Approach, as the word suggests, can be defined as a programming approach in which the program is made as a single structure. It means that the code will execute the instruction by instruction one after the other. It doesn’t support the possibility of jumping from one instruction to some other with help of any statement like GOTO, etc. Therefore, the instructions in this approach will be executed in a serial and structured manner. The languages that support Structured programming approach are:CC++JavaC#..etcOn the contrary, in the Assembly languages like Microprocessor 8085, etc, the statements do not get executed in a structured manner. It allows jump statements like GOTO. So the program flow might be random.The structured program mainly consists of three types of elements:Selection StatementsSequence StatementsIteration StatementsThe structured program consists of well structured and separated modules. But the entry and exit in a Structured program is a single-time event. It means that the program uses single-entry and single-exit elements. Therefore a structured program is well maintained, neat and clean program. This is the reason why the Structured Programming Approach is well accepted in the programming world.Advantages of Structured Programming Approach:Easier to read and understandUser FrindlyEasier to MaintainMainly problem based instead of being machine basedDevelopment is easier as it requires less effort and timeEasier to DebugMachine-Independent, mostly.Disadvantages of Structured Programming Approach:Since it is Machine-Independent, So it takes time to convert into machine code.The converted machine code is not the same as for assembly language.The program depends upon changeable factors like data-types. Therefore it needs to be updated with the need on the go.Usually the development in this approach takes longer time as it is language dependent. Whereas in the case of assembly language, the development takes lesser time as it is fixed for the machine.What do you mean by sorting? Write a program in C to sort the elements of a given array of N positive integers. Also give the flow chart for the same.A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of element in the respective data structure.For example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character with lesser ASCII value will be placed first than the character with higher ASCII value.Flowchart of the Selection Sort:Program in C to sort the elements of a given array of N positive integers:// C program to sort the elements// of a given array of N positive integers #include <stdio.h> void swap(int* xp, int* yp){ int temp = *xp; *xp = *yp; *yp = temp;} void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver program to test above functionsint main(){ int arr[] = { 64, 25, 12, 22, 11 }; int n = sizeof(arr) / sizeof(arr[0]); selectionSort(arr, n); printf(\"Sorted array: \\n\"); printArray(arr, n); return 0;}"
},
{
"code": null,
"e": 43243,
"s": 39497,
"text": "What is digital computer? Draw block diagram of digital computer and explain each components of it.Digital Computer: A digital computer can be defined as a programmable machine which reads the binary data passed as instructions, processes this binary data, and displays a calculated digital output. Therefore, Digital computers are those that work on the digital data.Details of Functional Components of a Digital ComputerInput Unit :The input unit consists of input devices that are attached to the computer. These devices take input and convert it into binary language that the computer understands. Some of the common input devices are keyboard, mouse, joystick, scanner etc.Central Processing Unit (CPU0 : Once the information is entered into the computer by the input device, the processor processes it. The CPU is called the brain of the computer because it is the control center of the computer. It first fetches instructions from memory and then interprets them so as to know what is to be done. If required, data is fetched from memory or input device. Thereafter CPU executes or performs the required computation and then either stores the output or displays on the output device. The CPU has three main components which are responsible for different functions – Arithmetic Logic Unit (ALU), Control Unit (CU) and Memory registersArithmetic and Logic Unit (ALU) : The ALU, as its name suggests performs mathematical calculations and takes logical decisions. Arithmetic calculations include addition, subtraction, multiplication and division. Logical decisions involve comparison of two data items to see which one is larger or smaller or equal.Control Unit : The Control unit coordinates and controls the data flow in and out of CPU and also controls all the operations of ALU, memory registers and also input/output units. It is also responsible for carrying out all the instructions stored in the program. It decodes the fetched instruction, interprets it and sends control signals to input/output devices until the required operation is done properly by ALU and memory.Memory Registers : A register is a temporary unit of memory in the CPU. These are used to store the data which is directly used by the processor. Registers can be of different sizes(16 bit, 32 bit, 64 bit and so on) and each register inside the CPU has a specific function like storing data, storing an instruction, storing address of a location in memory etc. The user registers can be used by an assembly language programmer for storing operands, intermediate results etc. Accumulator (ACC) is the main register in the ALU and contains one of the operands of an operation to be performed in the ALU.Memory : Memory attached to the CPU is used for storage of data and instructions and is called internal memory The internal memory is divided into many storage locations, each of which can store data or instructions. Each memory location is of the same size and has an address. With the help of the address, the computer can read any memory location easily without having to search the entire memory. when a program is executed, it’s data is copied to the internal memory ans is stored in the memory till the end of the execution. The internal memory is also called the Primary memory or Main memory. This memory is also called as RAM, i.e. Random Access Memory. The time of access of data is independent of its location in memory, therefore this memory is also called Random Access memory (RAM). Read this for different types of RAMsOutput Unit : The output unit consists of output devices that are attached with the computer. It converts the binary data coming from CPU to human understandable form. The common output devices are monitor, printer, plotter etc."
},
{
"code": null,
"e": 43298,
"s": 43243,
"text": "Details of Functional Components of a Digital Computer"
},
{
"code": null,
"e": 43555,
"s": 43298,
"text": "Input Unit :The input unit consists of input devices that are attached to the computer. These devices take input and convert it into binary language that the computer understands. Some of the common input devices are keyboard, mouse, joystick, scanner etc."
},
{
"code": null,
"e": 44218,
"s": 43555,
"text": "Central Processing Unit (CPU0 : Once the information is entered into the computer by the input device, the processor processes it. The CPU is called the brain of the computer because it is the control center of the computer. It first fetches instructions from memory and then interprets them so as to know what is to be done. If required, data is fetched from memory or input device. Thereafter CPU executes or performs the required computation and then either stores the output or displays on the output device. The CPU has three main components which are responsible for different functions – Arithmetic Logic Unit (ALU), Control Unit (CU) and Memory registers"
},
{
"code": null,
"e": 44533,
"s": 44218,
"text": "Arithmetic and Logic Unit (ALU) : The ALU, as its name suggests performs mathematical calculations and takes logical decisions. Arithmetic calculations include addition, subtraction, multiplication and division. Logical decisions involve comparison of two data items to see which one is larger or smaller or equal."
},
{
"code": null,
"e": 44962,
"s": 44533,
"text": "Control Unit : The Control unit coordinates and controls the data flow in and out of CPU and also controls all the operations of ALU, memory registers and also input/output units. It is also responsible for carrying out all the instructions stored in the program. It decodes the fetched instruction, interprets it and sends control signals to input/output devices until the required operation is done properly by ALU and memory."
},
{
"code": null,
"e": 45564,
"s": 44962,
"text": "Memory Registers : A register is a temporary unit of memory in the CPU. These are used to store the data which is directly used by the processor. Registers can be of different sizes(16 bit, 32 bit, 64 bit and so on) and each register inside the CPU has a specific function like storing data, storing an instruction, storing address of a location in memory etc. The user registers can be used by an assembly language programmer for storing operands, intermediate results etc. Accumulator (ACC) is the main register in the ALU and contains one of the operands of an operation to be performed in the ALU."
},
{
"code": null,
"e": 46399,
"s": 45564,
"text": "Memory : Memory attached to the CPU is used for storage of data and instructions and is called internal memory The internal memory is divided into many storage locations, each of which can store data or instructions. Each memory location is of the same size and has an address. With the help of the address, the computer can read any memory location easily without having to search the entire memory. when a program is executed, it’s data is copied to the internal memory ans is stored in the memory till the end of the execution. The internal memory is also called the Primary memory or Main memory. This memory is also called as RAM, i.e. Random Access Memory. The time of access of data is independent of its location in memory, therefore this memory is also called Random Access memory (RAM). Read this for different types of RAMs"
},
{
"code": null,
"e": 46628,
"s": 46399,
"text": "Output Unit : The output unit consists of output devices that are attached with the computer. It converts the binary data coming from CPU to human understandable form. The common output devices are monitor, printer, plotter etc."
},
{
"code": null,
"e": 48029,
"s": 46628,
"text": "Wrtie a program to check the number is palindrome or not. The program should accept any arbitrary number typed by user.Program to check whether the number is Palindrome or not:// C program to check whether a number// is Palindrome or not. #include <stdio.h> /* Iterative function to reverse digits of num*/int reverseDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Function to check if n is Palindrome*/int isPalindrome(int n){ // get the reverse of n int rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0;} /*Driver program to test reversDigits*/int main(){ int n; // Read n from user printf(\"Enter the number to checked: \"); scanf(\"%d\", &n); // Find if n is Palindrome and print printf(\"Is %d a Palindrome number? -> %s\\n\", n, isPalindrome(n) == 1 ? \"true\" : \"false\"); // Read n from user printf(\"\\nEnter the number to checked: \"); scanf(\"%d\", &n); // Find if n is Palindrome and print printf(\"Is %d a Palindrome number? -> %s\\n\", n, isPalindrome(n) == 1 ? \"true\" : \"false\"); return 0;}Output:Enter the number to checked: 4562\nIs 4562 a Palindrome number? -> false\n\nEnter the number to checked: 2002\nIs 2002 a Palindrome number? -> true\n"
},
{
"code": "// C program to check whether a number// is Palindrome or not. #include <stdio.h> /* Iterative function to reverse digits of num*/int reverseDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Function to check if n is Palindrome*/int isPalindrome(int n){ // get the reverse of n int rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0;} /*Driver program to test reversDigits*/int main(){ int n; // Read n from user printf(\"Enter the number to checked: \"); scanf(\"%d\", &n); // Find if n is Palindrome and print printf(\"Is %d a Palindrome number? -> %s\\n\", n, isPalindrome(n) == 1 ? \"true\" : \"false\"); // Read n from user printf(\"\\nEnter the number to checked: \"); scanf(\"%d\", &n); // Find if n is Palindrome and print printf(\"Is %d a Palindrome number? -> %s\\n\", n, isPalindrome(n) == 1 ? \"true\" : \"false\"); return 0;}",
"e": 49103,
"s": 48029,
"text": null
},
{
"code": null,
"e": 49248,
"s": 49103,
"text": "Enter the number to checked: 4562\nIs 4562 a Palindrome number? -> false\n\nEnter the number to checked: 2002\nIs 2002 a Palindrome number? -> true\n"
},
{
"code": null,
"e": 54092,
"s": 49248,
"text": "What is Operating System? Explain various types of functions performed by an Operating System.The fundamental goal of a Computer System is to execute user programs and to make tasks easier. Various application programs along with hardware system are used to perform this work. Operating System is a software which manages and control the entire set of resources and effectively utilize every part of a computer.The figure shows how OS acts as a medium between hardware unit and application programs.Functions of an Operating SystemAn operating system has variety of functions to perform. Some of the prominent functions of an operating system can be broadly outlined as:Processor Management: This deals with management of the Central Processing Unit (CPU). The operating system takes care of the allotment of CPU time to different processes. When a process finishes its CPU processing after executing for the allotted time period, this is called scheduling. There are various type of scheduling techniques that are used by the operating systems:Shortest Job First(SJF): Process which need the shortest CPU time are scheduled first.Round Robin Scheduling: Each process is assigned a fixed CPU execution time in cyclic way.Priority Based scheduling (Non Preemptive): In this scheduling, processes are scheduled according to their priorities, i.e., highest priority process is schedule first. If priorities of two processes match, then schedule according to arrival timeDevice Management:The Operating System communicates with hardware and the attached devices and maintains a balance between them and the CPU. This is all the more important because the CPU processing speed is much higher than thatof I/O devices. In order to optimize the CPU time, the operating system employstwo techniques – Buffering and Spooling.Buffering:In this technique, input and output data is temporarily stored in Input Buffer and Output Buffer. Once the signal for input or output is sent to or from the CPU respectively, the operating system through the device controller moves the data from the input device to the input buffer and for the output device to the output buffer. In case of input, if the buffer is full, the operating system sends a signal to the program which processes the data stored in the buffer. When the buffer becomes empty, the program informs the operating system which reloads the buffer and the input operation continues.Spooling (Simultaneous Peripheral Operation on Line):This is a device management technique used for processing of different tasks on the same input/output device. When there are various users on a network sharing the same resource then it can be a possibility that more than one user might give it a command at the same point of time. So, the operating system temporarily stores the data of every user on the hard disk of the computer to which the resource is attached. The individual user need not wait for the execution process to be completed. Instead the operating system sends the data from the hard disk to the resource one by one.Example: printerMemory management:In a computer, both the CPU and the I/O devices interact with the memory. When a program needs to be executed it is loaded onto the main memory till the execution is completed. Thereafter that memory space is freed and is available for other programs. The common memory management techniques used by the operating system are Partitioning and Virtual Memory.Partitioning:The total memory is divided into various partitions of same size or different sizes. This helps to accommodate number of programs in the memory. The partition can be fixed i.e. remains same for all the programs in the memory or variable i.e. memory is allocated when a program is loaded on to the memory. The later approach causes less wastage of memory but in due course of time, it may become fragmented.Virtual Memory:This is a technique used by the operating systems which allow the user can load the programs which are larger than the main memory of the computer. In this technique the program is executed even if the complete program can not be loaded inside the main memory leading to efficient memory utilization.File Management:The operating System manages the files, folders and directory systems on a computer. Any data on a computer is stored in the form of files and the operating system keeps information about all of them using File Allocation Table (FAT). The FAT stores general information about files like filename, type (text or binary), size, starting address and access mode (sequential/indexed sequential/direct/relative). The file manager of the operating system helps to create, edit, copy, allocate memory to the files and also updates the FAT. The operating system also takes care that files are opened with proper access rights to read or edit them."
},
{
"code": null,
"e": 54181,
"s": 54092,
"text": "The figure shows how OS acts as a medium between hardware unit and application programs."
},
{
"code": null,
"e": 54214,
"s": 54181,
"text": "Functions of an Operating System"
},
{
"code": null,
"e": 54354,
"s": 54214,
"text": "An operating system has variety of functions to perform. Some of the prominent functions of an operating system can be broadly outlined as:"
},
{
"code": null,
"e": 55152,
"s": 54354,
"text": "Processor Management: This deals with management of the Central Processing Unit (CPU). The operating system takes care of the allotment of CPU time to different processes. When a process finishes its CPU processing after executing for the allotted time period, this is called scheduling. There are various type of scheduling techniques that are used by the operating systems:Shortest Job First(SJF): Process which need the shortest CPU time are scheduled first.Round Robin Scheduling: Each process is assigned a fixed CPU execution time in cyclic way.Priority Based scheduling (Non Preemptive): In this scheduling, processes are scheduled according to their priorities, i.e., highest priority process is schedule first. If priorities of two processes match, then schedule according to arrival time"
},
{
"code": null,
"e": 55575,
"s": 55152,
"text": "Shortest Job First(SJF): Process which need the shortest CPU time are scheduled first.Round Robin Scheduling: Each process is assigned a fixed CPU execution time in cyclic way.Priority Based scheduling (Non Preemptive): In this scheduling, processes are scheduled according to their priorities, i.e., highest priority process is schedule first. If priorities of two processes match, then schedule according to arrival time"
},
{
"code": null,
"e": 55662,
"s": 55575,
"text": "Shortest Job First(SJF): Process which need the shortest CPU time are scheduled first."
},
{
"code": null,
"e": 55753,
"s": 55662,
"text": "Round Robin Scheduling: Each process is assigned a fixed CPU execution time in cyclic way."
},
{
"code": null,
"e": 56000,
"s": 55753,
"text": "Priority Based scheduling (Non Preemptive): In this scheduling, processes are scheduled according to their priorities, i.e., highest priority process is schedule first. If priorities of two processes match, then schedule according to arrival time"
},
{
"code": null,
"e": 56349,
"s": 56000,
"text": "Device Management:The Operating System communicates with hardware and the attached devices and maintains a balance between them and the CPU. This is all the more important because the CPU processing speed is much higher than thatof I/O devices. In order to optimize the CPU time, the operating system employstwo techniques – Buffering and Spooling."
},
{
"code": null,
"e": 56961,
"s": 56349,
"text": "Buffering:In this technique, input and output data is temporarily stored in Input Buffer and Output Buffer. Once the signal for input or output is sent to or from the CPU respectively, the operating system through the device controller moves the data from the input device to the input buffer and for the output device to the output buffer. In case of input, if the buffer is full, the operating system sends a signal to the program which processes the data stored in the buffer. When the buffer becomes empty, the program informs the operating system which reloads the buffer and the input operation continues."
},
{
"code": null,
"e": 57615,
"s": 56961,
"text": "Spooling (Simultaneous Peripheral Operation on Line):This is a device management technique used for processing of different tasks on the same input/output device. When there are various users on a network sharing the same resource then it can be a possibility that more than one user might give it a command at the same point of time. So, the operating system temporarily stores the data of every user on the hard disk of the computer to which the resource is attached. The individual user need not wait for the execution process to be completed. Instead the operating system sends the data from the hard disk to the resource one by one.Example: printer"
},
{
"code": null,
"e": 57991,
"s": 57615,
"text": "Memory management:In a computer, both the CPU and the I/O devices interact with the memory. When a program needs to be executed it is loaded onto the main memory till the execution is completed. Thereafter that memory space is freed and is available for other programs. The common memory management techniques used by the operating system are Partitioning and Virtual Memory."
},
{
"code": null,
"e": 58411,
"s": 57991,
"text": "Partitioning:The total memory is divided into various partitions of same size or different sizes. This helps to accommodate number of programs in the memory. The partition can be fixed i.e. remains same for all the programs in the memory or variable i.e. memory is allocated when a program is loaded on to the memory. The later approach causes less wastage of memory but in due course of time, it may become fragmented."
},
{
"code": null,
"e": 58727,
"s": 58411,
"text": "Virtual Memory:This is a technique used by the operating systems which allow the user can load the programs which are larger than the main memory of the computer. In this technique the program is executed even if the complete program can not be loaded inside the main memory leading to efficient memory utilization."
},
{
"code": null,
"e": 59383,
"s": 58727,
"text": "File Management:The operating System manages the files, folders and directory systems on a computer. Any data on a computer is stored in the form of files and the operating system keeps information about all of them using File Allocation Table (FAT). The FAT stores general information about files like filename, type (text or binary), size, starting address and access mode (sequential/indexed sequential/direct/relative). The file manager of the operating system helps to create, edit, copy, allocate memory to the files and also updates the FAT. The operating system also takes care that files are opened with proper access rights to read or edit them."
},
{
"code": null,
"e": 61516,
"s": 59383,
"text": "What is Structured programming approach? Highlight the advantages and disadvantages of structured programming.Structured Programming Approach, as the word suggests, can be defined as a programming approach in which the program is made as a single structure. It means that the code will execute the instruction by instruction one after the other. It doesn’t support the possibility of jumping from one instruction to some other with help of any statement like GOTO, etc. Therefore, the instructions in this approach will be executed in a serial and structured manner. The languages that support Structured programming approach are:CC++JavaC#..etcOn the contrary, in the Assembly languages like Microprocessor 8085, etc, the statements do not get executed in a structured manner. It allows jump statements like GOTO. So the program flow might be random.The structured program mainly consists of three types of elements:Selection StatementsSequence StatementsIteration StatementsThe structured program consists of well structured and separated modules. But the entry and exit in a Structured program is a single-time event. It means that the program uses single-entry and single-exit elements. Therefore a structured program is well maintained, neat and clean program. This is the reason why the Structured Programming Approach is well accepted in the programming world.Advantages of Structured Programming Approach:Easier to read and understandUser FrindlyEasier to MaintainMainly problem based instead of being machine basedDevelopment is easier as it requires less effort and timeEasier to DebugMachine-Independent, mostly.Disadvantages of Structured Programming Approach:Since it is Machine-Independent, So it takes time to convert into machine code.The converted machine code is not the same as for assembly language.The program depends upon changeable factors like data-types. Therefore it needs to be updated with the need on the go.Usually the development in this approach takes longer time as it is language dependent. Whereas in the case of assembly language, the development takes lesser time as it is fixed for the machine."
},
{
"code": null,
"e": 61518,
"s": 61516,
"text": "C"
},
{
"code": null,
"e": 61522,
"s": 61518,
"text": "C++"
},
{
"code": null,
"e": 61527,
"s": 61522,
"text": "Java"
},
{
"code": null,
"e": 61535,
"s": 61527,
"text": "C#..etc"
},
{
"code": null,
"e": 61541,
"s": 61535,
"text": "..etc"
},
{
"code": null,
"e": 61748,
"s": 61541,
"text": "On the contrary, in the Assembly languages like Microprocessor 8085, etc, the statements do not get executed in a structured manner. It allows jump statements like GOTO. So the program flow might be random."
},
{
"code": null,
"e": 61815,
"s": 61748,
"text": "The structured program mainly consists of three types of elements:"
},
{
"code": null,
"e": 61836,
"s": 61815,
"text": "Selection Statements"
},
{
"code": null,
"e": 61856,
"s": 61836,
"text": "Sequence Statements"
},
{
"code": null,
"e": 61877,
"s": 61856,
"text": "Iteration Statements"
},
{
"code": null,
"e": 62269,
"s": 61877,
"text": "The structured program consists of well structured and separated modules. But the entry and exit in a Structured program is a single-time event. It means that the program uses single-entry and single-exit elements. Therefore a structured program is well maintained, neat and clean program. This is the reason why the Structured Programming Approach is well accepted in the programming world."
},
{
"code": null,
"e": 62316,
"s": 62269,
"text": "Advantages of Structured Programming Approach:"
},
{
"code": null,
"e": 62527,
"s": 62316,
"text": "Easier to read and understandUser FrindlyEasier to MaintainMainly problem based instead of being machine basedDevelopment is easier as it requires less effort and timeEasier to DebugMachine-Independent, mostly."
},
{
"code": null,
"e": 62557,
"s": 62527,
"text": "Easier to read and understand"
},
{
"code": null,
"e": 62570,
"s": 62557,
"text": "User Frindly"
},
{
"code": null,
"e": 62589,
"s": 62570,
"text": "Easier to Maintain"
},
{
"code": null,
"e": 62641,
"s": 62589,
"text": "Mainly problem based instead of being machine based"
},
{
"code": null,
"e": 62699,
"s": 62641,
"text": "Development is easier as it requires less effort and time"
},
{
"code": null,
"e": 62715,
"s": 62699,
"text": "Easier to Debug"
},
{
"code": null,
"e": 62744,
"s": 62715,
"text": "Machine-Independent, mostly."
},
{
"code": null,
"e": 62794,
"s": 62744,
"text": "Disadvantages of Structured Programming Approach:"
},
{
"code": null,
"e": 63255,
"s": 62794,
"text": "Since it is Machine-Independent, So it takes time to convert into machine code.The converted machine code is not the same as for assembly language.The program depends upon changeable factors like data-types. Therefore it needs to be updated with the need on the go.Usually the development in this approach takes longer time as it is language dependent. Whereas in the case of assembly language, the development takes lesser time as it is fixed for the machine."
},
{
"code": null,
"e": 63335,
"s": 63255,
"text": "Since it is Machine-Independent, So it takes time to convert into machine code."
},
{
"code": null,
"e": 63404,
"s": 63335,
"text": "The converted machine code is not the same as for assembly language."
},
{
"code": null,
"e": 63523,
"s": 63404,
"text": "The program depends upon changeable factors like data-types. Therefore it needs to be updated with the need on the go."
},
{
"code": null,
"e": 63719,
"s": 63523,
"text": "Usually the development in this approach takes longer time as it is language dependent. Whereas in the case of assembly language, the development takes lesser time as it is fixed for the machine."
},
{
"code": null,
"e": 65398,
"s": 63719,
"text": "What do you mean by sorting? Write a program in C to sort the elements of a given array of N positive integers. Also give the flow chart for the same.A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of element in the respective data structure.For example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character with lesser ASCII value will be placed first than the character with higher ASCII value.Flowchart of the Selection Sort:Program in C to sort the elements of a given array of N positive integers:// C program to sort the elements// of a given array of N positive integers #include <stdio.h> void swap(int* xp, int* yp){ int temp = *xp; *xp = *yp; *yp = temp;} void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver program to test above functionsint main(){ int arr[] = { 64, 25, 12, 22, 11 }; int n = sizeof(arr) / sizeof(arr[0]); selectionSort(arr, n); printf(\"Sorted array: \\n\"); printArray(arr, n); return 0;}"
},
{
"code": null,
"e": 65605,
"s": 65398,
"text": "For example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character with lesser ASCII value will be placed first than the character with higher ASCII value."
},
{
"code": null,
"e": 65638,
"s": 65605,
"text": "Flowchart of the Selection Sort:"
},
{
"code": null,
"e": 65713,
"s": 65638,
"text": "Program in C to sort the elements of a given array of N positive integers:"
},
{
"code": "// C program to sort the elements// of a given array of N positive integers #include <stdio.h> void swap(int* xp, int* yp){ int temp = *xp; *xp = *yp; *yp = temp;} void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver program to test above functionsint main(){ int arr[] = { 64, 25, 12, 22, 11 }; int n = sizeof(arr) / sizeof(arr[0]); selectionSort(arr, n); printf(\"Sorted array: \\n\"); printArray(arr, n); return 0;}",
"e": 66706,
"s": 65713,
"text": null
},
{
"code": null,
"e": 66727,
"s": 66706,
"text": "AKTU-question-papers"
},
{
"code": null,
"e": 66736,
"s": 66727,
"text": "Articles"
},
{
"code": null,
"e": 66834,
"s": 66736,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 66843,
"s": 66834,
"text": "Comments"
},
{
"code": null,
"e": 66856,
"s": 66843,
"text": "Old Comments"
},
{
"code": null,
"e": 66906,
"s": 66856,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 66953,
"s": 66906,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 66989,
"s": 66953,
"text": "find command in Linux with examples"
},
{
"code": null,
"e": 67042,
"s": 66989,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
},
{
"code": null,
"e": 67079,
"s": 67042,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 67098,
"s": 67079,
"text": "Mutex vs Semaphore"
},
{
"code": null,
"e": 67152,
"s": 67098,
"text": "Analysis of Algorithms | Set 3 (Asymptotic Notations)"
},
{
"code": null,
"e": 67215,
"s": 67152,
"text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)"
},
{
"code": null,
"e": 67251,
"s": 67215,
"text": "Understanding \"extern\" keyword in C"
}
] |
Bot realtime object detection in Overwatch on Ubuntu 18.04 | by Dmitriy Kisil | Towards Data Science
|
For doing that, ensure that you have installed Tensorflow. Preferably with GPU support for more speedup. Without that you will have smaller fps, training the model will take a fair amount of time and realtime performance may be not achievable.
Part1: Install Overwatch on Ubuntu 18.04
After few unsuccessfull attempts to install Overwatch using Wine and DXVK I am come for Flatpak, which seems very easy to run Windows apps on Linux. And so it is, except for a special moment with driver versions. More on this later.
Running those commands above installed Flatpak and Battle.net launcher:
sudo apt install flatpak gnome-software-plugin-flatpaksudo flatpak remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakreposudo flatpak remote-add --if-not-exists winepak https://dl.winepak.org/repo/winepak.flatpakreposudo flatpak install winepak com.blizzard.Overwatch
And after reboot PC type:
sudo flatpak run com.blizzard.Overwatch
and you will see that:
For the more FPS and smooth experience you will need to install additional nvidia drivers (because now game worked using OpenGL engine). In a few cases game will not run without graphical drivers at all.
Important: version of your current output from nvidia-smi command and flatpak version must be the same. Otherwise, you will get error when clicking on Play at Overwatch section in Battle.net launcher. And be ware, that’s you need both version of Flatpak drivers.
For example, currently I have this version of nvidia drivers:
Next step: I check if there is a driver for this version in Flatpak:
flatpak remote-ls flathub | grep nvidia
And yep, at FlatHub there is 410–104 version of Nvidia runtime packages (don’t place screen here because of huge output).
So I can then use those commands to install 32 and 64 bit versions in Flatpak (remind, that you need both versions!):
flatpak install flathub org.freedesktop.Platform.GL32.nvidia-410–104flatpak install flathub org.freedesktop.Platform.GL.nvidia-410-104
And if everything worked out you can start the game!
And last: for recording and getting more comfortable fps go to Options-Video and select a windowed mode, 1280*720 resolution, 30 fps lock and low settings . This allow you to achieve around 30/3 = 10 fps performance in game when model will working together while you are playing Overwatch. Yep, running model is exhaustive process and your GPU will worked on 100% . It depends on your GPU, actually. But on my 1060 it is true.
In next parts of this tutorial I will show you how to get training data for your model, train model(if you want) and make real-time detection when playing.
P.S.: If you stuck on choosing the right driver, please check this small article (you can found there more explanations too) how to overcome this problem:
www.linuxuprising.com
Part2: Record gameplay and prepare images for training
Let’s install those libraries, which allows us to capture game:
pip3 install --user pyscreenshotpip3 install --user mss
After installing Overwatch you can recording gameplay in real-time (around 80–100 fps) using simplestream.py.
Look at line 17: here you select part of the screen to capture. You need to fit your window game’s with values in monitor dictionary. Feel free to replace this line of code with values, with which you will are most comfortable. For example, I hardcoded them and fit Overwatch window in center of a screen; you might to prefer place window at the top left corner etc. Spend few minutes on it; you will do it only once.
Just type in console:
python3 simplestream.py
and return to game. When you will done, click on window frame and press Q. Script was finished and you can see output.avi file here. That’s your gameplay, on which model will be trained.
Important: For the first time you can use trained model from my repo and don’t make images, training model etc (so skip this and go to the next part). If you will be inspired by results, welcome to training your own model on your own data.
Get images
For extracting frames from output.avi you will need ffmpeg: so let’s install it!
pip3 install --user ffmpeg
Use ffmpeg to get frames from the created video (create folder /images first!):
ffmpeg -i output.avi -vf fps=10 images/thumb%04d.jpg -hide_banner
This get us 10 frames for each seconds from a video output.avi, and save those frames(images) in folder images.
Resize with python3 resizer.py
You can use now resizer.py to make pictures more smaller than now.
python3 resizer.py
I commented line 20, because found, that resolution 960*540 works the best for pictures with initial resolution around 1280*720. Pss! Line 20 and 21 make the same thing, so you can use which line you like the most). But don’t forget to comment another line — or your broke your images!(just kidding — in that case you resize each images two times and got a very terrible results).
Annotate with labelImg
Let’s annotate images. For this I am suggest using labelImg.
git clone https://github.com/tzutalin/labelImg.gitcd labelImgsudo apt-get install pyqt5-dev-toolssudo pip3 install -r requirements/requirements-linux-python3.txtmake qt5py3python3 labelImg.py
Why not pip3 install labelImg? Because I’m tried it and can’t just launch this program. So install from source is only one way, which worked for me. And you can try install from pip3, maybe you can launch this and save another few minutes on it.
I annotated images using one class — “bot”, because I want to detect bots (obviously, isn’t?). If you want to detect many classes — time, consumed on this part, will increase very much because your chance to mistake and select wrong class be very high (especially when you have many objects on frame).
So, now you need to annotate each image in images/train and images/test folders. It’s time consuming part, so be calm, attentive and don’t move fast.
Important: Delete bad frames without at least one class on it. If you miss at least one file you can’t create annotations for this image. And model training will not yet started, because you will have not equal amount of images and xml files (annotations)!
Create test and train directories
For this, using split.py:
python3 split.py
Code from this script:
After that place images folder in object_detection folder and go to tensorflow part (Part 3).
Part3: Tensorflow part
You can skip this part and use my trained model (I provided all the files at a github repo) for the first time. In both cases you will need to install those libraries:
pip3 install pillowpip3 install lxmlpip3 install jupyterpip3 install matplotlibpip3 install opencv-python opencv-contrib-pythonsudo apt install protobuf-compiler
This part is the most time consuming and you can stuck on many problems during this process. My guide based on awesome tutorial from here. It for the windows 10, but the differences are not so much. And only if you want to train own model on your own data (such detect Hanzo from quickplay match) you might to do all of this steps below.
Download models, reload protos, reload variables (don’t forget to change /home/dmitriy to /home/*your_username*/):
git clone https://github.com/tensorflow/models.gitcd models-master/researchprotoc object_detection/protos/*.proto — python_out=.export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slimsudo gedit ~/.bashrc export PYTHONPATH=$PYTHONPATH=/home/dmitriy/models/research:/home/dmitriy/models/research/slimsource ~/.bashrc
From research directory:
sudo python3 setup.py buildsudo python3 setup.py install
Then run (after annotating all of the images):
python3 xml_to_csv.py
This creates a train_labels.csv and test_labels.csv file in the \object_detection\images folder. Make changes in generate_tfrecord.py. For example, my file:
As you see, you need to change at line 30–35 all with your classes (in my case ‘bot’). All others you don’t need to change.After that (from object_detection folder):
python3 generate_tfrecord.py --csv_input=images/train_labels.csv --image_dir=images/train --output_path=train.recordpython3 generate_tfrecord.py --csv_input=images/test_labels.csv --image_dir=images/test --output_path=test.record
These generate a train.record and a test.record file in \object_detection. These will be used to train the new object detection classifier.
Download model from tensorflow zoo as config and put in object_detection/training folder:
wget http://download.tensorflow.org/models/object_detection/faster_rcnn_inception_v2_coco_2018_01_28.tar.gztar xvzf faster_rcnn_inception_v2_coco_2018_01_28.tar.gz
Make changes in labelmap.pbtxt. For example, my file:
So, for example, if you want to detect Hanzo class, rename bot to Hanzo.
Make then changes in faster_rcnn_inception_v2_pets.config.
Code:
Here we go:
change at line 9 num_classes to total number of your classes. For example, if I want to detect just one bot it would be 1;
change at line 106 fine_tune_checkpoint to path where your faster_rcnn_inception_v2_pets.config is placed;
change at line 112 nums_steps to how much you want to train the model (usually, 10–20k is enough);
change at line 122 input_path to where your train.record is;
change at line 124 label_map_path to where your labelmap.pbtxt is;
change at line 128 num_examples to the number of images you have in the \images\test directory;
change at line 136 input_path to where your train.record is;
change at line 138 label_map_path to where your labelmap.pbtxt is.
Be careful to change those paths correctly!
And place those files(labelmap.pbtxt and faster_rcnn_inception_v2_pets.config) in training folder.
Move train.py from legacy to main folder.
After that you can start training:
python3 train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config tensorboard --logdir=’training’
Be sure that inference_graph is empty or not created.
python3 export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_pets.config --trained_checkpoint_prefix training/model.ckpt-10000 --output_directory inference_graph
Feel free to change model.ckpt-number_of_epochs to your number. So, if your trained for 1000 epochs, change trained_checkpoint_prefix training/model.ckpt-10000 to trained_checkpoint_prefix training/model.ckpt-1000.
This creates a frozen_inference_graph.pb file in the \object_detection\inference_graph folder. The .pb file contains the object detection classifier.
For the next part of tutorial you need frozen_inference_graph and labelmap.pbtxt from \object_detection\training folder. Also faster_rcnn_inception_v2_pets.config, folder protos, utils, training and core.
So create object_detection folder somewhere and move all of that into it. For now you prepared to the last part (Part 4: Realtime detection).
Part4: Run realtime detection
After all the hard work above, this step become one of the easiest.
If you just want tested trained model, then download my repo using this command:
git clone https://github.com/Oysiyl/Bot-object-detection-in-Overwatch.git
Then rename this folder to object_detection and move to this folder.
I suggest you for the first time run Object_detection_image.py — to ensure, that everything works fine. So run those:
python3 Object_detection_image.py
And after around 5–10 seconds waiting for initializing Tensorflow and loading model into GPU memory, you will see this picture with recognized two boxes(press Q to exit):
Along with coordinates of detected boxes:
Code from script, which we will run after (realtime_detect_stream.py):
Run realtime_detect_stream.py (for exit click on frame window and press Q):
python3 realtime_detect_stream.py
Experience be more comfortable, if you have ultrawide monitor or just a second one. You will see realtime object_detection! I can’t show here a nice screen because I have only one FullHD monitor and on it actually the game window and window with recognized game are not fit.
Small tip: you can change 123 line to cv2.resize(img, (300, 300)) and get more robust picture (or select more small amount of pixels):
After exit you see that a file output2.avi has created. Here you can see video and see how well model will performed:
Extra part: Defeat the bots using trained model
Psss! After determining who is your enemy you can defeat him. So, opencv can detect coordinates of boxes with bots. And you can use pyautogui for defeating them!
pip3 install --user pyautoguisudo apt-get install python3-tk python3-dev
Different distances have a significant effect on accuracy. Look at this demonstration:
And this from larger distance (I am using WASD to go near the targets):
I tested it on the Widowmaker. So, the delay in one second allows her to aim and make a powerful shot instead of a weak shot without delay. You just walk toward the bot, opencv detect bot and build a box around him, and after that program try to make a shot. I made the point with possible position of the head in the box, so program will keep move camera to this point and click after achieving that point.
Be ware, that using time.sleep(1.0) cause losing 1 second in recording video, because program paused for 1 second (10 fps). You can change this line with time.sleep(1.0) to pyautogui.PAUSE=1.0 and added after click returns to default pyautogui settings (by following way — pyautogui.PAUSE=0.01). I shouldn’t recommend you this because programm accuracy will make some strange moves (such as shoot when moving toward the target point). Advantage using those method — your recording video will be complete, without losing 10 fps (1 second) each time when you take aim.
Important: for correct actions from pyautogui you need to change in game Options-Video-Display Mode and set to “Borderless Windowed”. Without that program can not correctly clicking and moving your camera in randomly position each time. Don’t forget that if you want to record this, you need change monitor dictionary (look at line 116), because your game window now will be borderless windowed instead of windowed before this.
This code insert in realtime_detect_stream.py after the name definition. If you can’t figure it out where to add, look at this complete example:
Short explanation by important lines of code:
In line 152 we are selected only boxes, which pass 90% limit detection; lines 167–181 — found coordinates for boxes; using if statement (lines 183–185) need for select and track only one boxes per frame. It’s important, because if model detect two or more boxes she will jumped from one to another without any actions (but it works not perfect and something buggy).
Then we found centerX and centerY coordinates — to this point our model will move. For moving calculated moveX and moveY. If move very big (line 191–194) we are make this move smaller — that improve accuracy of moves along with (line 195–198): if model are close (5 px or smaller) to target, make next move equal to 0(so no move on this axis will allowed, move on another axis which is great then 5). If we achieved “center” — model will perform our supposed set of actions (line 204–212). Here you can try used pyautogui.PAUSE along without time.sleep(1.0). If we not achieved “center” yet, then perform moves based on coordinates of current camera position (lines 214–226).
In next line for each frame draw a circle (point to which we want to move), and make many texts output, placed them directly on your frame for further monitoring (this is very-very helpful, when something going wrong). For example, when defeat_bots.py moves are not undestandable by you, those monitoring outputs can helps you to see, what model will do in next frame, which moves select, in which directions moves next, how much pixels... You can comment those outputs (lines 232–237).
And at line 240 opencv saved given frame to video, and then show you this frame (line 241). As always, press Q on keyboard will stop program and after saving video(line 250) opencv will close (line 251).
As you see from image below, model shot bot at the center and begin move toward next target. And it’s me activated ult, program can’t do that right now. I just be curious if ult having effort on model accuracy (and don’t found any). And I performed all the moves by character using WASD combination.
Run defeat_bots.py:
python3 defeat_bots.py
As usually, go to Overwatch in training room. If opencv detects at least one bot— program will move camera using mouse to this recognized bounding box and clicked until box are disappeared(bot are defeated). Yeahyy!
Bonus: It is not hard to test it on other heroes vs bots in training room. For example, changing actions at lines (204–212) to only pyautogui.click() allow you used such character, which main attack is left click:
As you see, detection is not depend on selected hero, and you can adopt script for almost any hero you want, taking into account differences in the gameplay of hero and which abilities he/she have.
Important: all in this article, especially extra part made with scientifically purpose and my curiosity. I am not recommended you used model against other players, because:
Zero: Model can’t detect when object is far away or hero see only part of objects. You need to train model understand effects (such as Reinhardt shield or ultimative ability each hero).
First: because you need to train model on around thousand (!!!) classes to recognize each hero (around 30 now) on each skin (don’t know how much).
Second: you needed to train on many different maps (model, trained on Oasis will almost not work on Antarctica because of different environment).
Third: my dataset with almost 600 images trained on 1000 steps should be enough for detect one class (bot) on one map without any skin (but you see this detection is far from ideal). Imagine, how much images you need to create and annotate to achieve something good. And how much computational power you will need for training to get good results and to achieve at least 60 frames per second in realtime.
Fourth: Model can’t move! I don’t know logic how to implement this now.
Also, because it is cheating and you should probably be banned, when playing with real people, not bots.
Hope you succeed and this work will inspire you to make more interesting model from this game or another (which you enjoy the most).
Have a nice day, you have deserved it!
|
[
{
"code": null,
"e": 416,
"s": 172,
"text": "For doing that, ensure that you have installed Tensorflow. Preferably with GPU support for more speedup. Without that you will have smaller fps, training the model will take a fair amount of time and realtime performance may be not achievable."
},
{
"code": null,
"e": 457,
"s": 416,
"text": "Part1: Install Overwatch on Ubuntu 18.04"
},
{
"code": null,
"e": 690,
"s": 457,
"text": "After few unsuccessfull attempts to install Overwatch using Wine and DXVK I am come for Flatpak, which seems very easy to run Windows apps on Linux. And so it is, except for a special moment with driver versions. More on this later."
},
{
"code": null,
"e": 762,
"s": 690,
"text": "Running those commands above installed Flatpak and Battle.net launcher:"
},
{
"code": null,
"e": 1058,
"s": 762,
"text": "sudo apt install flatpak gnome-software-plugin-flatpaksudo flatpak remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakreposudo flatpak remote-add --if-not-exists winepak https://dl.winepak.org/repo/winepak.flatpakreposudo flatpak install winepak com.blizzard.Overwatch"
},
{
"code": null,
"e": 1084,
"s": 1058,
"text": "And after reboot PC type:"
},
{
"code": null,
"e": 1124,
"s": 1084,
"text": "sudo flatpak run com.blizzard.Overwatch"
},
{
"code": null,
"e": 1147,
"s": 1124,
"text": "and you will see that:"
},
{
"code": null,
"e": 1351,
"s": 1147,
"text": "For the more FPS and smooth experience you will need to install additional nvidia drivers (because now game worked using OpenGL engine). In a few cases game will not run without graphical drivers at all."
},
{
"code": null,
"e": 1614,
"s": 1351,
"text": "Important: version of your current output from nvidia-smi command and flatpak version must be the same. Otherwise, you will get error when clicking on Play at Overwatch section in Battle.net launcher. And be ware, that’s you need both version of Flatpak drivers."
},
{
"code": null,
"e": 1676,
"s": 1614,
"text": "For example, currently I have this version of nvidia drivers:"
},
{
"code": null,
"e": 1745,
"s": 1676,
"text": "Next step: I check if there is a driver for this version in Flatpak:"
},
{
"code": null,
"e": 1785,
"s": 1745,
"text": "flatpak remote-ls flathub | grep nvidia"
},
{
"code": null,
"e": 1907,
"s": 1785,
"text": "And yep, at FlatHub there is 410–104 version of Nvidia runtime packages (don’t place screen here because of huge output)."
},
{
"code": null,
"e": 2025,
"s": 1907,
"text": "So I can then use those commands to install 32 and 64 bit versions in Flatpak (remind, that you need both versions!):"
},
{
"code": null,
"e": 2160,
"s": 2025,
"text": "flatpak install flathub org.freedesktop.Platform.GL32.nvidia-410–104flatpak install flathub org.freedesktop.Platform.GL.nvidia-410-104"
},
{
"code": null,
"e": 2213,
"s": 2160,
"text": "And if everything worked out you can start the game!"
},
{
"code": null,
"e": 2640,
"s": 2213,
"text": "And last: for recording and getting more comfortable fps go to Options-Video and select a windowed mode, 1280*720 resolution, 30 fps lock and low settings . This allow you to achieve around 30/3 = 10 fps performance in game when model will working together while you are playing Overwatch. Yep, running model is exhaustive process and your GPU will worked on 100% . It depends on your GPU, actually. But on my 1060 it is true."
},
{
"code": null,
"e": 2796,
"s": 2640,
"text": "In next parts of this tutorial I will show you how to get training data for your model, train model(if you want) and make real-time detection when playing."
},
{
"code": null,
"e": 2951,
"s": 2796,
"text": "P.S.: If you stuck on choosing the right driver, please check this small article (you can found there more explanations too) how to overcome this problem:"
},
{
"code": null,
"e": 2973,
"s": 2951,
"text": "www.linuxuprising.com"
},
{
"code": null,
"e": 3028,
"s": 2973,
"text": "Part2: Record gameplay and prepare images for training"
},
{
"code": null,
"e": 3092,
"s": 3028,
"text": "Let’s install those libraries, which allows us to capture game:"
},
{
"code": null,
"e": 3148,
"s": 3092,
"text": "pip3 install --user pyscreenshotpip3 install --user mss"
},
{
"code": null,
"e": 3258,
"s": 3148,
"text": "After installing Overwatch you can recording gameplay in real-time (around 80–100 fps) using simplestream.py."
},
{
"code": null,
"e": 3676,
"s": 3258,
"text": "Look at line 17: here you select part of the screen to capture. You need to fit your window game’s with values in monitor dictionary. Feel free to replace this line of code with values, with which you will are most comfortable. For example, I hardcoded them and fit Overwatch window in center of a screen; you might to prefer place window at the top left corner etc. Spend few minutes on it; you will do it only once."
},
{
"code": null,
"e": 3698,
"s": 3676,
"text": "Just type in console:"
},
{
"code": null,
"e": 3722,
"s": 3698,
"text": "python3 simplestream.py"
},
{
"code": null,
"e": 3909,
"s": 3722,
"text": "and return to game. When you will done, click on window frame and press Q. Script was finished and you can see output.avi file here. That’s your gameplay, on which model will be trained."
},
{
"code": null,
"e": 4149,
"s": 3909,
"text": "Important: For the first time you can use trained model from my repo and don’t make images, training model etc (so skip this and go to the next part). If you will be inspired by results, welcome to training your own model on your own data."
},
{
"code": null,
"e": 4160,
"s": 4149,
"text": "Get images"
},
{
"code": null,
"e": 4241,
"s": 4160,
"text": "For extracting frames from output.avi you will need ffmpeg: so let’s install it!"
},
{
"code": null,
"e": 4268,
"s": 4241,
"text": "pip3 install --user ffmpeg"
},
{
"code": null,
"e": 4348,
"s": 4268,
"text": "Use ffmpeg to get frames from the created video (create folder /images first!):"
},
{
"code": null,
"e": 4414,
"s": 4348,
"text": "ffmpeg -i output.avi -vf fps=10 images/thumb%04d.jpg -hide_banner"
},
{
"code": null,
"e": 4526,
"s": 4414,
"text": "This get us 10 frames for each seconds from a video output.avi, and save those frames(images) in folder images."
},
{
"code": null,
"e": 4557,
"s": 4526,
"text": "Resize with python3 resizer.py"
},
{
"code": null,
"e": 4624,
"s": 4557,
"text": "You can use now resizer.py to make pictures more smaller than now."
},
{
"code": null,
"e": 4643,
"s": 4624,
"text": "python3 resizer.py"
},
{
"code": null,
"e": 5024,
"s": 4643,
"text": "I commented line 20, because found, that resolution 960*540 works the best for pictures with initial resolution around 1280*720. Pss! Line 20 and 21 make the same thing, so you can use which line you like the most). But don’t forget to comment another line — or your broke your images!(just kidding — in that case you resize each images two times and got a very terrible results)."
},
{
"code": null,
"e": 5047,
"s": 5024,
"text": "Annotate with labelImg"
},
{
"code": null,
"e": 5108,
"s": 5047,
"text": "Let’s annotate images. For this I am suggest using labelImg."
},
{
"code": null,
"e": 5300,
"s": 5108,
"text": "git clone https://github.com/tzutalin/labelImg.gitcd labelImgsudo apt-get install pyqt5-dev-toolssudo pip3 install -r requirements/requirements-linux-python3.txtmake qt5py3python3 labelImg.py"
},
{
"code": null,
"e": 5546,
"s": 5300,
"text": "Why not pip3 install labelImg? Because I’m tried it and can’t just launch this program. So install from source is only one way, which worked for me. And you can try install from pip3, maybe you can launch this and save another few minutes on it."
},
{
"code": null,
"e": 5848,
"s": 5546,
"text": "I annotated images using one class — “bot”, because I want to detect bots (obviously, isn’t?). If you want to detect many classes — time, consumed on this part, will increase very much because your chance to mistake and select wrong class be very high (especially when you have many objects on frame)."
},
{
"code": null,
"e": 5998,
"s": 5848,
"text": "So, now you need to annotate each image in images/train and images/test folders. It’s time consuming part, so be calm, attentive and don’t move fast."
},
{
"code": null,
"e": 6255,
"s": 5998,
"text": "Important: Delete bad frames without at least one class on it. If you miss at least one file you can’t create annotations for this image. And model training will not yet started, because you will have not equal amount of images and xml files (annotations)!"
},
{
"code": null,
"e": 6289,
"s": 6255,
"text": "Create test and train directories"
},
{
"code": null,
"e": 6315,
"s": 6289,
"text": "For this, using split.py:"
},
{
"code": null,
"e": 6332,
"s": 6315,
"text": "python3 split.py"
},
{
"code": null,
"e": 6355,
"s": 6332,
"text": "Code from this script:"
},
{
"code": null,
"e": 6449,
"s": 6355,
"text": "After that place images folder in object_detection folder and go to tensorflow part (Part 3)."
},
{
"code": null,
"e": 6472,
"s": 6449,
"text": "Part3: Tensorflow part"
},
{
"code": null,
"e": 6640,
"s": 6472,
"text": "You can skip this part and use my trained model (I provided all the files at a github repo) for the first time. In both cases you will need to install those libraries:"
},
{
"code": null,
"e": 6802,
"s": 6640,
"text": "pip3 install pillowpip3 install lxmlpip3 install jupyterpip3 install matplotlibpip3 install opencv-python opencv-contrib-pythonsudo apt install protobuf-compiler"
},
{
"code": null,
"e": 7140,
"s": 6802,
"text": "This part is the most time consuming and you can stuck on many problems during this process. My guide based on awesome tutorial from here. It for the windows 10, but the differences are not so much. And only if you want to train own model on your own data (such detect Hanzo from quickplay match) you might to do all of this steps below."
},
{
"code": null,
"e": 7255,
"s": 7140,
"text": "Download models, reload protos, reload variables (don’t forget to change /home/dmitriy to /home/*your_username*/):"
},
{
"code": null,
"e": 7561,
"s": 7255,
"text": "git clone https://github.com/tensorflow/models.gitcd models-master/researchprotoc object_detection/protos/*.proto — python_out=.export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slimsudo gedit ~/.bashrc export PYTHONPATH=$PYTHONPATH=/home/dmitriy/models/research:/home/dmitriy/models/research/slimsource ~/.bashrc"
},
{
"code": null,
"e": 7586,
"s": 7561,
"text": "From research directory:"
},
{
"code": null,
"e": 7643,
"s": 7586,
"text": "sudo python3 setup.py buildsudo python3 setup.py install"
},
{
"code": null,
"e": 7690,
"s": 7643,
"text": "Then run (after annotating all of the images):"
},
{
"code": null,
"e": 7712,
"s": 7690,
"text": "python3 xml_to_csv.py"
},
{
"code": null,
"e": 7869,
"s": 7712,
"text": "This creates a train_labels.csv and test_labels.csv file in the \\object_detection\\images folder. Make changes in generate_tfrecord.py. For example, my file:"
},
{
"code": null,
"e": 8035,
"s": 7869,
"text": "As you see, you need to change at line 30–35 all with your classes (in my case ‘bot’). All others you don’t need to change.After that (from object_detection folder):"
},
{
"code": null,
"e": 8265,
"s": 8035,
"text": "python3 generate_tfrecord.py --csv_input=images/train_labels.csv --image_dir=images/train --output_path=train.recordpython3 generate_tfrecord.py --csv_input=images/test_labels.csv --image_dir=images/test --output_path=test.record"
},
{
"code": null,
"e": 8405,
"s": 8265,
"text": "These generate a train.record and a test.record file in \\object_detection. These will be used to train the new object detection classifier."
},
{
"code": null,
"e": 8495,
"s": 8405,
"text": "Download model from tensorflow zoo as config and put in object_detection/training folder:"
},
{
"code": null,
"e": 8659,
"s": 8495,
"text": "wget http://download.tensorflow.org/models/object_detection/faster_rcnn_inception_v2_coco_2018_01_28.tar.gztar xvzf faster_rcnn_inception_v2_coco_2018_01_28.tar.gz"
},
{
"code": null,
"e": 8713,
"s": 8659,
"text": "Make changes in labelmap.pbtxt. For example, my file:"
},
{
"code": null,
"e": 8786,
"s": 8713,
"text": "So, for example, if you want to detect Hanzo class, rename bot to Hanzo."
},
{
"code": null,
"e": 8845,
"s": 8786,
"text": "Make then changes in faster_rcnn_inception_v2_pets.config."
},
{
"code": null,
"e": 8851,
"s": 8845,
"text": "Code:"
},
{
"code": null,
"e": 8863,
"s": 8851,
"text": "Here we go:"
},
{
"code": null,
"e": 8986,
"s": 8863,
"text": "change at line 9 num_classes to total number of your classes. For example, if I want to detect just one bot it would be 1;"
},
{
"code": null,
"e": 9093,
"s": 8986,
"text": "change at line 106 fine_tune_checkpoint to path where your faster_rcnn_inception_v2_pets.config is placed;"
},
{
"code": null,
"e": 9192,
"s": 9093,
"text": "change at line 112 nums_steps to how much you want to train the model (usually, 10–20k is enough);"
},
{
"code": null,
"e": 9253,
"s": 9192,
"text": "change at line 122 input_path to where your train.record is;"
},
{
"code": null,
"e": 9320,
"s": 9253,
"text": "change at line 124 label_map_path to where your labelmap.pbtxt is;"
},
{
"code": null,
"e": 9416,
"s": 9320,
"text": "change at line 128 num_examples to the number of images you have in the \\images\\test directory;"
},
{
"code": null,
"e": 9477,
"s": 9416,
"text": "change at line 136 input_path to where your train.record is;"
},
{
"code": null,
"e": 9544,
"s": 9477,
"text": "change at line 138 label_map_path to where your labelmap.pbtxt is."
},
{
"code": null,
"e": 9588,
"s": 9544,
"text": "Be careful to change those paths correctly!"
},
{
"code": null,
"e": 9687,
"s": 9588,
"text": "And place those files(labelmap.pbtxt and faster_rcnn_inception_v2_pets.config) in training folder."
},
{
"code": null,
"e": 9729,
"s": 9687,
"text": "Move train.py from legacy to main folder."
},
{
"code": null,
"e": 9764,
"s": 9729,
"text": "After that you can start training:"
},
{
"code": null,
"e": 9918,
"s": 9764,
"text": "python3 train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config tensorboard --logdir=’training’"
},
{
"code": null,
"e": 9972,
"s": 9918,
"text": "Be sure that inference_graph is empty or not created."
},
{
"code": null,
"e": 10190,
"s": 9972,
"text": "python3 export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_pets.config --trained_checkpoint_prefix training/model.ckpt-10000 --output_directory inference_graph"
},
{
"code": null,
"e": 10405,
"s": 10190,
"text": "Feel free to change model.ckpt-number_of_epochs to your number. So, if your trained for 1000 epochs, change trained_checkpoint_prefix training/model.ckpt-10000 to trained_checkpoint_prefix training/model.ckpt-1000."
},
{
"code": null,
"e": 10555,
"s": 10405,
"text": "This creates a frozen_inference_graph.pb file in the \\object_detection\\inference_graph folder. The .pb file contains the object detection classifier."
},
{
"code": null,
"e": 10760,
"s": 10555,
"text": "For the next part of tutorial you need frozen_inference_graph and labelmap.pbtxt from \\object_detection\\training folder. Also faster_rcnn_inception_v2_pets.config, folder protos, utils, training and core."
},
{
"code": null,
"e": 10902,
"s": 10760,
"text": "So create object_detection folder somewhere and move all of that into it. For now you prepared to the last part (Part 4: Realtime detection)."
},
{
"code": null,
"e": 10932,
"s": 10902,
"text": "Part4: Run realtime detection"
},
{
"code": null,
"e": 11000,
"s": 10932,
"text": "After all the hard work above, this step become one of the easiest."
},
{
"code": null,
"e": 11081,
"s": 11000,
"text": "If you just want tested trained model, then download my repo using this command:"
},
{
"code": null,
"e": 11155,
"s": 11081,
"text": "git clone https://github.com/Oysiyl/Bot-object-detection-in-Overwatch.git"
},
{
"code": null,
"e": 11224,
"s": 11155,
"text": "Then rename this folder to object_detection and move to this folder."
},
{
"code": null,
"e": 11342,
"s": 11224,
"text": "I suggest you for the first time run Object_detection_image.py — to ensure, that everything works fine. So run those:"
},
{
"code": null,
"e": 11376,
"s": 11342,
"text": "python3 Object_detection_image.py"
},
{
"code": null,
"e": 11547,
"s": 11376,
"text": "And after around 5–10 seconds waiting for initializing Tensorflow and loading model into GPU memory, you will see this picture with recognized two boxes(press Q to exit):"
},
{
"code": null,
"e": 11589,
"s": 11547,
"text": "Along with coordinates of detected boxes:"
},
{
"code": null,
"e": 11660,
"s": 11589,
"text": "Code from script, which we will run after (realtime_detect_stream.py):"
},
{
"code": null,
"e": 11736,
"s": 11660,
"text": "Run realtime_detect_stream.py (for exit click on frame window and press Q):"
},
{
"code": null,
"e": 11770,
"s": 11736,
"text": "python3 realtime_detect_stream.py"
},
{
"code": null,
"e": 12045,
"s": 11770,
"text": "Experience be more comfortable, if you have ultrawide monitor or just a second one. You will see realtime object_detection! I can’t show here a nice screen because I have only one FullHD monitor and on it actually the game window and window with recognized game are not fit."
},
{
"code": null,
"e": 12180,
"s": 12045,
"text": "Small tip: you can change 123 line to cv2.resize(img, (300, 300)) and get more robust picture (or select more small amount of pixels):"
},
{
"code": null,
"e": 12298,
"s": 12180,
"text": "After exit you see that a file output2.avi has created. Here you can see video and see how well model will performed:"
},
{
"code": null,
"e": 12346,
"s": 12298,
"text": "Extra part: Defeat the bots using trained model"
},
{
"code": null,
"e": 12508,
"s": 12346,
"text": "Psss! After determining who is your enemy you can defeat him. So, opencv can detect coordinates of boxes with bots. And you can use pyautogui for defeating them!"
},
{
"code": null,
"e": 12581,
"s": 12508,
"text": "pip3 install --user pyautoguisudo apt-get install python3-tk python3-dev"
},
{
"code": null,
"e": 12668,
"s": 12581,
"text": "Different distances have a significant effect on accuracy. Look at this demonstration:"
},
{
"code": null,
"e": 12740,
"s": 12668,
"text": "And this from larger distance (I am using WASD to go near the targets):"
},
{
"code": null,
"e": 13148,
"s": 12740,
"text": "I tested it on the Widowmaker. So, the delay in one second allows her to aim and make a powerful shot instead of a weak shot without delay. You just walk toward the bot, opencv detect bot and build a box around him, and after that program try to make a shot. I made the point with possible position of the head in the box, so program will keep move camera to this point and click after achieving that point."
},
{
"code": null,
"e": 13715,
"s": 13148,
"text": "Be ware, that using time.sleep(1.0) cause losing 1 second in recording video, because program paused for 1 second (10 fps). You can change this line with time.sleep(1.0) to pyautogui.PAUSE=1.0 and added after click returns to default pyautogui settings (by following way — pyautogui.PAUSE=0.01). I shouldn’t recommend you this because programm accuracy will make some strange moves (such as shoot when moving toward the target point). Advantage using those method — your recording video will be complete, without losing 10 fps (1 second) each time when you take aim."
},
{
"code": null,
"e": 14143,
"s": 13715,
"text": "Important: for correct actions from pyautogui you need to change in game Options-Video-Display Mode and set to “Borderless Windowed”. Without that program can not correctly clicking and moving your camera in randomly position each time. Don’t forget that if you want to record this, you need change monitor dictionary (look at line 116), because your game window now will be borderless windowed instead of windowed before this."
},
{
"code": null,
"e": 14288,
"s": 14143,
"text": "This code insert in realtime_detect_stream.py after the name definition. If you can’t figure it out where to add, look at this complete example:"
},
{
"code": null,
"e": 14334,
"s": 14288,
"text": "Short explanation by important lines of code:"
},
{
"code": null,
"e": 14700,
"s": 14334,
"text": "In line 152 we are selected only boxes, which pass 90% limit detection; lines 167–181 — found coordinates for boxes; using if statement (lines 183–185) need for select and track only one boxes per frame. It’s important, because if model detect two or more boxes she will jumped from one to another without any actions (but it works not perfect and something buggy)."
},
{
"code": null,
"e": 15376,
"s": 14700,
"text": "Then we found centerX and centerY coordinates — to this point our model will move. For moving calculated moveX and moveY. If move very big (line 191–194) we are make this move smaller — that improve accuracy of moves along with (line 195–198): if model are close (5 px or smaller) to target, make next move equal to 0(so no move on this axis will allowed, move on another axis which is great then 5). If we achieved “center” — model will perform our supposed set of actions (line 204–212). Here you can try used pyautogui.PAUSE along without time.sleep(1.0). If we not achieved “center” yet, then perform moves based on coordinates of current camera position (lines 214–226)."
},
{
"code": null,
"e": 15863,
"s": 15376,
"text": "In next line for each frame draw a circle (point to which we want to move), and make many texts output, placed them directly on your frame for further monitoring (this is very-very helpful, when something going wrong). For example, when defeat_bots.py moves are not undestandable by you, those monitoring outputs can helps you to see, what model will do in next frame, which moves select, in which directions moves next, how much pixels... You can comment those outputs (lines 232–237)."
},
{
"code": null,
"e": 16067,
"s": 15863,
"text": "And at line 240 opencv saved given frame to video, and then show you this frame (line 241). As always, press Q on keyboard will stop program and after saving video(line 250) opencv will close (line 251)."
},
{
"code": null,
"e": 16367,
"s": 16067,
"text": "As you see from image below, model shot bot at the center and begin move toward next target. And it’s me activated ult, program can’t do that right now. I just be curious if ult having effort on model accuracy (and don’t found any). And I performed all the moves by character using WASD combination."
},
{
"code": null,
"e": 16387,
"s": 16367,
"text": "Run defeat_bots.py:"
},
{
"code": null,
"e": 16410,
"s": 16387,
"text": "python3 defeat_bots.py"
},
{
"code": null,
"e": 16626,
"s": 16410,
"text": "As usually, go to Overwatch in training room. If opencv detects at least one bot— program will move camera using mouse to this recognized bounding box and clicked until box are disappeared(bot are defeated). Yeahyy!"
},
{
"code": null,
"e": 16840,
"s": 16626,
"text": "Bonus: It is not hard to test it on other heroes vs bots in training room. For example, changing actions at lines (204–212) to only pyautogui.click() allow you used such character, which main attack is left click:"
},
{
"code": null,
"e": 17038,
"s": 16840,
"text": "As you see, detection is not depend on selected hero, and you can adopt script for almost any hero you want, taking into account differences in the gameplay of hero and which abilities he/she have."
},
{
"code": null,
"e": 17211,
"s": 17038,
"text": "Important: all in this article, especially extra part made with scientifically purpose and my curiosity. I am not recommended you used model against other players, because:"
},
{
"code": null,
"e": 17397,
"s": 17211,
"text": "Zero: Model can’t detect when object is far away or hero see only part of objects. You need to train model understand effects (such as Reinhardt shield or ultimative ability each hero)."
},
{
"code": null,
"e": 17544,
"s": 17397,
"text": "First: because you need to train model on around thousand (!!!) classes to recognize each hero (around 30 now) on each skin (don’t know how much)."
},
{
"code": null,
"e": 17690,
"s": 17544,
"text": "Second: you needed to train on many different maps (model, trained on Oasis will almost not work on Antarctica because of different environment)."
},
{
"code": null,
"e": 18095,
"s": 17690,
"text": "Third: my dataset with almost 600 images trained on 1000 steps should be enough for detect one class (bot) on one map without any skin (but you see this detection is far from ideal). Imagine, how much images you need to create and annotate to achieve something good. And how much computational power you will need for training to get good results and to achieve at least 60 frames per second in realtime."
},
{
"code": null,
"e": 18167,
"s": 18095,
"text": "Fourth: Model can’t move! I don’t know logic how to implement this now."
},
{
"code": null,
"e": 18272,
"s": 18167,
"text": "Also, because it is cheating and you should probably be banned, when playing with real people, not bots."
},
{
"code": null,
"e": 18405,
"s": 18272,
"text": "Hope you succeed and this work will inspire you to make more interesting model from this game or another (which you enjoy the most)."
}
] |
C++ Data Types | Practice | GeeksforGeeks
|
Read a value and store it in the appropriate C++ Data Type.
Example 1:
Input:
2 h 2.555
Output:
2
h
2.555
Explanation:
The three inputs are printed in order.
Your Task:
Your task is to complete each of the given functions
cppIntType() : read an integer input, store it in appropriate data type and return it.
cppCharType() : read a character input, store it in appropriate data type and return it.
cppFloatType() : read a float input, store it in appropriate data type and return it.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
0
anushavennapoosa20021 month ago
class Solution { public: int cppIntType() { // code here int a; cin>>a; return a; } char cppCharType() { // code here char b; cin>>b; return b; } float cppFloatType() { // code here float c; cin>>c; return c; }};
0
0niharika22 months ago
int cppIntType() { int x; cin>>x; return x; } char cppCharType() { char c; cin>>c; return c; } float cppFloatType() { float f; cin>>f; return f; }
+3
shivamguptakrm3 months ago
class Solution {
public:
int cppIntType() {
// code here
int a;
cin>>a;
return a;
}
char cppCharType() {
// code here
char b;
cin>>b;
return b;
}
float cppFloatType() {
// code here
float c;
cin>> c;
return c;
}
};
+1
aadeshabhigyan093 months ago
class Solution { public: int cppIntType() { // code here int a; cin >> a; return a; } char cppCharType() { // code here char b; cin >> b; return b; } float cppFloatType() { // code here float c; cin >> c; return c; }};
0
gauravverma9918187053 months ago
#include<iostrem>
using namespace std;
int main(){
\\Code Here\\
int a;
string s;
float f;
cin>>a>>b>>c;
cout<<a<<"\n"<<s<<"\n"<<f;
return 0;
0
Yogeshwari Harode11 months ago
Yogeshwari Harode
C++ Data TypesEasiest Codehttps://github.com/yogeshwa...
0
Yogeshwari Harode11 months ago
Yogeshwari Harode
C++ Data Types Very Easy Codehttps://github.com/yogeshwa...
0
Arjun Patidar11 months ago
Arjun Patidar
class Solution { public: int cppIntType() { int a; cin>>a; return a; }
char cppCharType() { char b; cin>>b; return b; }
float cppFloatType() { float c; cin>> c; return c; }};
0
Shubham Chaudhari1 year ago
Shubham Chaudhari
PLease update the function name.. all functions have the same name and thus causing error in c++
0
Yogeshwari Harode2 years ago
Yogeshwari Harode
https://github.com/yogeshwa...
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": 287,
"s": 226,
"text": "Read a value and store it in the appropriate C++ Data Type. "
},
{
"code": null,
"e": 298,
"s": 287,
"text": "Example 1:"
},
{
"code": null,
"e": 388,
"s": 298,
"text": "Input: \n2 h 2.555\nOutput:\n2\nh\n2.555 \nExplanation:\nThe three inputs are printed in order.\n"
},
{
"code": null,
"e": 721,
"s": 390,
"text": "Your Task:\nYour task is to complete each of the given functions \ncppIntType() : read an integer input, store it in appropriate data type and return it. \ncppCharType() : read a character input, store it in appropriate data type and return it. \ncppFloatType() : read a float input, store it in appropriate data type and return it. "
},
{
"code": null,
"e": 784,
"s": 721,
"text": "\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 788,
"s": 786,
"text": "0"
},
{
"code": null,
"e": 820,
"s": 788,
"text": "anushavennapoosa20021 month ago"
},
{
"code": null,
"e": 1124,
"s": 820,
"text": "class Solution { public: int cppIntType() { // code here int a; cin>>a; return a; } char cppCharType() { // code here char b; cin>>b; return b; } float cppFloatType() { // code here float c; cin>>c; return c; }}; "
},
{
"code": null,
"e": 1126,
"s": 1124,
"text": "0"
},
{
"code": null,
"e": 1149,
"s": 1126,
"text": "0niharika22 months ago"
},
{
"code": null,
"e": 1366,
"s": 1149,
"text": "int cppIntType() { int x; cin>>x; return x; } char cppCharType() { char c; cin>>c; return c; } float cppFloatType() { float f; cin>>f; return f; }"
},
{
"code": null,
"e": 1369,
"s": 1366,
"text": "+3"
},
{
"code": null,
"e": 1396,
"s": 1369,
"text": "shivamguptakrm3 months ago"
},
{
"code": null,
"e": 1743,
"s": 1396,
"text": "class Solution {\n public:\n int cppIntType() {\n // code here\n int a;\n cin>>a;\n return a;\n }\n \n char cppCharType() {\n // code here\n char b;\n cin>>b;\n return b;\n }\n \n float cppFloatType() {\n // code here\n float c;\n cin>> c;\n return c;\n }\n};"
},
{
"code": null,
"e": 1746,
"s": 1743,
"text": "+1"
},
{
"code": null,
"e": 1775,
"s": 1746,
"text": "aadeshabhigyan093 months ago"
},
{
"code": null,
"e": 2084,
"s": 1775,
"text": "class Solution { public: int cppIntType() { // code here int a; cin >> a; return a; } char cppCharType() { // code here char b; cin >> b; return b; } float cppFloatType() { // code here float c; cin >> c; return c; }};"
},
{
"code": null,
"e": 2086,
"s": 2084,
"text": "0"
},
{
"code": null,
"e": 2119,
"s": 2086,
"text": "gauravverma9918187053 months ago"
},
{
"code": null,
"e": 2261,
"s": 2119,
"text": "#include<iostrem>\nusing namespace std;\nint main(){\n\\\\Code Here\\\\\nint a;\nstring s;\nfloat f;\ncin>>a>>b>>c;\ncout<<a<<\"\\n\"<<s<<\"\\n\"<<f;\nreturn 0;"
},
{
"code": null,
"e": 2263,
"s": 2261,
"text": "0"
},
{
"code": null,
"e": 2294,
"s": 2263,
"text": "Yogeshwari Harode11 months ago"
},
{
"code": null,
"e": 2312,
"s": 2294,
"text": "Yogeshwari Harode"
},
{
"code": null,
"e": 2369,
"s": 2312,
"text": "C++ Data TypesEasiest Codehttps://github.com/yogeshwa..."
},
{
"code": null,
"e": 2371,
"s": 2369,
"text": "0"
},
{
"code": null,
"e": 2402,
"s": 2371,
"text": "Yogeshwari Harode11 months ago"
},
{
"code": null,
"e": 2420,
"s": 2402,
"text": "Yogeshwari Harode"
},
{
"code": null,
"e": 2480,
"s": 2420,
"text": "C++ Data Types Very Easy Codehttps://github.com/yogeshwa..."
},
{
"code": null,
"e": 2482,
"s": 2480,
"text": "0"
},
{
"code": null,
"e": 2509,
"s": 2482,
"text": "Arjun Patidar11 months ago"
},
{
"code": null,
"e": 2523,
"s": 2509,
"text": "Arjun Patidar"
},
{
"code": null,
"e": 2622,
"s": 2523,
"text": "class Solution { public: int cppIntType() { int a; cin>>a; return a; }"
},
{
"code": null,
"e": 2699,
"s": 2622,
"text": " char cppCharType() { char b; cin>>b; return b; }"
},
{
"code": null,
"e": 2782,
"s": 2699,
"text": " float cppFloatType() { float c; cin>> c; return c; }};"
},
{
"code": null,
"e": 2784,
"s": 2782,
"text": "0"
},
{
"code": null,
"e": 2812,
"s": 2784,
"text": "Shubham Chaudhari1 year ago"
},
{
"code": null,
"e": 2830,
"s": 2812,
"text": "Shubham Chaudhari"
},
{
"code": null,
"e": 2927,
"s": 2830,
"text": "PLease update the function name.. all functions have the same name and thus causing error in c++"
},
{
"code": null,
"e": 2929,
"s": 2927,
"text": "0"
},
{
"code": null,
"e": 2958,
"s": 2929,
"text": "Yogeshwari Harode2 years ago"
},
{
"code": null,
"e": 2976,
"s": 2958,
"text": "Yogeshwari Harode"
},
{
"code": null,
"e": 3007,
"s": 2976,
"text": "https://github.com/yogeshwa..."
},
{
"code": null,
"e": 3153,
"s": 3007,
"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": 3189,
"s": 3153,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3199,
"s": 3189,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3209,
"s": 3199,
"text": "\nContest\n"
},
{
"code": null,
"e": 3272,
"s": 3209,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3420,
"s": 3272,
"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": 3628,
"s": 3420,
"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": 3734,
"s": 3628,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Indonesia’s Poverty Profile. Exploration of Indonesia County Level... | by Redi Sunarta | Towards Data Science
|
The issue of poverty has always been one of the main topics of discussion in various economic and social forums. Poverty is considered a serious problem and must be resolved because it has a high social cost. Poverty itself is usually defined as the inability of an individual to meet basic needs in the form of goods, such as food and clean water, as well as services, such as access to education and health.
Formally, the ability to meet these basic needs is measured in terms of expenditure or individual income. In Indonesia, Central Bureau of Statistics (Badan Pusat Statistik) uses the average expenditure variable as a benchmark which divided into basic food and non-food needs. An individual is categorized as poor if he has expenditure below the poverty line.
Indonesia’s poverty line is calculated from the sum of the value of expenditure of minimum food needs equal to 2100 kilocalories and minimum needs for housing, clothing, education, and health per capita per day. In March 2019, Indonesia’s poverty line was recorded at IDR425,250 per capita/month (approximately $1 per capita/day) with the composition of the Food is 73.66%.
Based on that nominal poverty line, the percentage of poor people in Indonesia is 9.41% or around 25.14 million people and the concentration of origin of the poor population is still dominated by rural residents, even with a poverty rate benchmark, 12.85% compared to 6.89% for urban. In aggregate, these results showed a decrease of 0.41 percentage point compared to the previous year.
The trend of decreasing the number of poor people and poverty rates indeed also occurs in other parts of the earth. This phenomenon began since the end of the second world war and the practice of colonization. This period of peace and independence provides opportunities for ex-colonial countries that are pockets of world poverty to make changes in their countries. Then it results in more inclusive economic growth and finally reduces poverty.
In the Indonesian context, it is noted that each government always has a main program specifically for poverty reduction, even though it has a different name like Takesra, Kukesra, PKH, BPNT, BLSM, Raskin, and many other. However, it is generally given in the form of subsidies or cash assistance. The recipient of the subsidy or cash transfer was selected based on data from the local government to determine the eligibility of the recipient. Even so, there are still many reports about the inaccuracy of program objectives provided. Therefore, the process of disaggregation of poverty data is quite important because it does not only look at the development of poverty rates that are seen to continue to decline.
I will disaggregate to the county level because only up to that level is data available. More specific level data is available only in a few provinces. Even then, it usually has a publication lag from Indonesia’s Central Bureau of Statistics for up to one year. The main picture above is an initial illustration of the distribution of changes (two-point annual data) in the number of poor people in all counties from 2013 compared to 2018, in March. It is clear that almost all counties in Java have succeeded in reducing the number of poor people they have. This can happen because Java has the highest number of poor people, so it is reasonable to be the top priority in every poverty alleviation program. In addition, Java is also the center of Indonesia’s economy and politics
Meanwhile, if I rank by county with the best decrease in the number of poor people in the period, Buton Regency is the best county in that category (out of 494 counties). The local government of Buton Regency should deserve an award for their hard work. Cheers.
But if I look in more detail by comparing these changes with population growth. Buton Regency’s achievement was not as bright as before because as a large decrease in the number of poor peoples followed by a large population decline as well, -65% compared to -62%. This is also evidenced by the change in Headcount Index which only changed 1.58 percent, meaning that if the population of Buton Regency remained constant for the whole year, the poor population would only decrease by 4,113 people. So basically, the number of poor people in Buton Regency has decreased by only 10% over the past five years. Thus, if I only see a reduction in the number of poor people, I don’t think that’s right enough.
What if the population increase as additional requirements for a reward, I assume that poor people are significant effecting growth county population. As a result, 333 counties met these additional requirements and sadly only three of the top fifteen in the graph above fall into this additional category. As a result, the top three counties with different ratio or delta on that two variable, respectively Tolikara Regency, Tanatidung Regency, and Gunung Sitoli City. Because, although the population continues to increase every year, they managed to reduce the number of poor people as well and that really needs hard work.
Ok now, let's talk more about the poverty line. I told you before that Indonesia has a poverty line approximately $1 per capita/day nominally. Then, for your information, Indonesia has positive skewness of expenditure distribution. Thus, if I increase the poverty line to 1.5x, the poverty rate of Indonesia will be increased up to 40%. In other words, many Indonesian middle-income class is in poor prone conditions. In reality, during this five-year period, there were 143 counties that had increased the number of poor people, along with the increasing poverty line from year to year. Although on average the county per capita income has increased. Thus, that county economic growth is not pro-poor.
seaborn.boxplot(showfliers=False, ...)
The headcount index only measures the proportion of the poor to the population. If you want to focus only on consumption distribution of poor group, then P1 and P2 are commonly used. P1 is used to calculate the average distance of consumption of poor people with the poverty line. Meanwhile, P2 calculates the variance in consumption among the poor population. The higher the value of those two indices, the more bad indication.
The chart above shows the condition of the three indexes in all observation counties with “x” as the arithmetic mean. The graph shows that the poverty rate has declined, but P1 and P2 are relatively stagnant. Intuitively, this can explain that poverty programs are difficult to help poor people who are in the lowest percentile. On the other hand, if the poverty program is proven to push poor people who are near the poverty line out of the poverty zone, then the poverty program so far can be said to touch almost all poor people because on average the expenditure of the poor has increased. However, I do not have data whether the increase in expenditure is only in nominal terms, in other words only as compensation for an increase in inflation. I couldn't find a convincing answer yet.
P1 and P2 index in 2015 and 2016 caught my attention. It is clear when the proportion of poor people decreases, the P1 and P2 indexes actually increase. That year was the start of Joko Widodo’s Cabinet government and made major changes in the current state budget structure. Joko Widodo’s government cut a lot of subsidies that the previous government used to divert to infrastructure projects. The cuts in subsidies have really hit the poor. Although then the budget is adjusted, especially nearing the election year in 2019.
The achievement of the decline in the number of poor people during this decade, however, should be appreciated. This at least shows the seriousness of the government in efforts to overcome this poverty problem. However, the problem of distribution inequality — both within the community economy class and between counties — still a big job where almost half of Indonesia’s population is very vulnerable to becoming poor.
Why I always mention the government in this poverty problem. Because the government is the only party that has the ability to share the cake of economic growth. Where the poor do not have enough capital and power to grow in society. Thank you for reading my story so far. I hope you all get to know more about poverty conditions in Indonesia. In this story, I only explored the poverty dataset, not touching too much the relationship of poverty with other related variables. Even I didn’t use a fancy model at all. Maybe next time, I’ll try to write and discuss. Best Regard.
|
[
{
"code": null,
"e": 582,
"s": 172,
"text": "The issue of poverty has always been one of the main topics of discussion in various economic and social forums. Poverty is considered a serious problem and must be resolved because it has a high social cost. Poverty itself is usually defined as the inability of an individual to meet basic needs in the form of goods, such as food and clean water, as well as services, such as access to education and health."
},
{
"code": null,
"e": 941,
"s": 582,
"text": "Formally, the ability to meet these basic needs is measured in terms of expenditure or individual income. In Indonesia, Central Bureau of Statistics (Badan Pusat Statistik) uses the average expenditure variable as a benchmark which divided into basic food and non-food needs. An individual is categorized as poor if he has expenditure below the poverty line."
},
{
"code": null,
"e": 1315,
"s": 941,
"text": "Indonesia’s poverty line is calculated from the sum of the value of expenditure of minimum food needs equal to 2100 kilocalories and minimum needs for housing, clothing, education, and health per capita per day. In March 2019, Indonesia’s poverty line was recorded at IDR425,250 per capita/month (approximately $1 per capita/day) with the composition of the Food is 73.66%."
},
{
"code": null,
"e": 1702,
"s": 1315,
"text": "Based on that nominal poverty line, the percentage of poor people in Indonesia is 9.41% or around 25.14 million people and the concentration of origin of the poor population is still dominated by rural residents, even with a poverty rate benchmark, 12.85% compared to 6.89% for urban. In aggregate, these results showed a decrease of 0.41 percentage point compared to the previous year."
},
{
"code": null,
"e": 2148,
"s": 1702,
"text": "The trend of decreasing the number of poor people and poverty rates indeed also occurs in other parts of the earth. This phenomenon began since the end of the second world war and the practice of colonization. This period of peace and independence provides opportunities for ex-colonial countries that are pockets of world poverty to make changes in their countries. Then it results in more inclusive economic growth and finally reduces poverty."
},
{
"code": null,
"e": 2863,
"s": 2148,
"text": "In the Indonesian context, it is noted that each government always has a main program specifically for poverty reduction, even though it has a different name like Takesra, Kukesra, PKH, BPNT, BLSM, Raskin, and many other. However, it is generally given in the form of subsidies or cash assistance. The recipient of the subsidy or cash transfer was selected based on data from the local government to determine the eligibility of the recipient. Even so, there are still many reports about the inaccuracy of program objectives provided. Therefore, the process of disaggregation of poverty data is quite important because it does not only look at the development of poverty rates that are seen to continue to decline."
},
{
"code": null,
"e": 3644,
"s": 2863,
"text": "I will disaggregate to the county level because only up to that level is data available. More specific level data is available only in a few provinces. Even then, it usually has a publication lag from Indonesia’s Central Bureau of Statistics for up to one year. The main picture above is an initial illustration of the distribution of changes (two-point annual data) in the number of poor people in all counties from 2013 compared to 2018, in March. It is clear that almost all counties in Java have succeeded in reducing the number of poor people they have. This can happen because Java has the highest number of poor people, so it is reasonable to be the top priority in every poverty alleviation program. In addition, Java is also the center of Indonesia’s economy and politics"
},
{
"code": null,
"e": 3906,
"s": 3644,
"text": "Meanwhile, if I rank by county with the best decrease in the number of poor people in the period, Buton Regency is the best county in that category (out of 494 counties). The local government of Buton Regency should deserve an award for their hard work. Cheers."
},
{
"code": null,
"e": 4609,
"s": 3906,
"text": "But if I look in more detail by comparing these changes with population growth. Buton Regency’s achievement was not as bright as before because as a large decrease in the number of poor peoples followed by a large population decline as well, -65% compared to -62%. This is also evidenced by the change in Headcount Index which only changed 1.58 percent, meaning that if the population of Buton Regency remained constant for the whole year, the poor population would only decrease by 4,113 people. So basically, the number of poor people in Buton Regency has decreased by only 10% over the past five years. Thus, if I only see a reduction in the number of poor people, I don’t think that’s right enough."
},
{
"code": null,
"e": 5235,
"s": 4609,
"text": "What if the population increase as additional requirements for a reward, I assume that poor people are significant effecting growth county population. As a result, 333 counties met these additional requirements and sadly only three of the top fifteen in the graph above fall into this additional category. As a result, the top three counties with different ratio or delta on that two variable, respectively Tolikara Regency, Tanatidung Regency, and Gunung Sitoli City. Because, although the population continues to increase every year, they managed to reduce the number of poor people as well and that really needs hard work."
},
{
"code": null,
"e": 5938,
"s": 5235,
"text": "Ok now, let's talk more about the poverty line. I told you before that Indonesia has a poverty line approximately $1 per capita/day nominally. Then, for your information, Indonesia has positive skewness of expenditure distribution. Thus, if I increase the poverty line to 1.5x, the poverty rate of Indonesia will be increased up to 40%. In other words, many Indonesian middle-income class is in poor prone conditions. In reality, during this five-year period, there were 143 counties that had increased the number of poor people, along with the increasing poverty line from year to year. Although on average the county per capita income has increased. Thus, that county economic growth is not pro-poor."
},
{
"code": null,
"e": 5977,
"s": 5938,
"text": "seaborn.boxplot(showfliers=False, ...)"
},
{
"code": null,
"e": 6406,
"s": 5977,
"text": "The headcount index only measures the proportion of the poor to the population. If you want to focus only on consumption distribution of poor group, then P1 and P2 are commonly used. P1 is used to calculate the average distance of consumption of poor people with the poverty line. Meanwhile, P2 calculates the variance in consumption among the poor population. The higher the value of those two indices, the more bad indication."
},
{
"code": null,
"e": 7197,
"s": 6406,
"text": "The chart above shows the condition of the three indexes in all observation counties with “x” as the arithmetic mean. The graph shows that the poverty rate has declined, but P1 and P2 are relatively stagnant. Intuitively, this can explain that poverty programs are difficult to help poor people who are in the lowest percentile. On the other hand, if the poverty program is proven to push poor people who are near the poverty line out of the poverty zone, then the poverty program so far can be said to touch almost all poor people because on average the expenditure of the poor has increased. However, I do not have data whether the increase in expenditure is only in nominal terms, in other words only as compensation for an increase in inflation. I couldn't find a convincing answer yet."
},
{
"code": null,
"e": 7724,
"s": 7197,
"text": "P1 and P2 index in 2015 and 2016 caught my attention. It is clear when the proportion of poor people decreases, the P1 and P2 indexes actually increase. That year was the start of Joko Widodo’s Cabinet government and made major changes in the current state budget structure. Joko Widodo’s government cut a lot of subsidies that the previous government used to divert to infrastructure projects. The cuts in subsidies have really hit the poor. Although then the budget is adjusted, especially nearing the election year in 2019."
},
{
"code": null,
"e": 8145,
"s": 7724,
"text": "The achievement of the decline in the number of poor people during this decade, however, should be appreciated. This at least shows the seriousness of the government in efforts to overcome this poverty problem. However, the problem of distribution inequality — both within the community economy class and between counties — still a big job where almost half of Indonesia’s population is very vulnerable to becoming poor."
}
] |
Python String Methods. A summary of the most commonly used... | by Robert Alterman | Towards Data Science
|
In Python, data in text form is known as a string. To designate data as a string, the text must be surrounded by single (‘ ’) or double (“ ”) quotes. Names, locations, objects, sentences, even numbers can be strings, as long as they are surrounded by quotes. Once you have a string, you are able to manipulate that string using what’s known as a ‘method.’ To use a method, you simply write the string followed by .[method](). For example, to run the upper() method on the string ‘pizza’, you would just write ‘pizza’.upper(); if ‘pizza’ were set to a variable, you would do that variable.upper(). Some methods accept what are known as ‘arguments,’ which go in the parenthesis and further define what the method will do. The Python language has a lot of built-in methods, like upper(), that allow you to easily alter strings.
These methods all perform simple manipulations on strings and take no arguments.
The upper() method converts every letter in a string to uppercase:
Syntax: string.upper()'pizza'.upper() --> 'PIZZA'
The lower() method converts every letter in a string to lowercase:
Syntax: string.lower()'PIZZA'.lower() --> 'pizza'
The title() method capitalizes the first letter of every word in a string, like a title:
Syntax: string.title()'i love to eat pizza'.title() --> 'I Love To Eat Pizza'
The capitalize() method is similar to the title() method; however, only the first letter of the first word in a string gets capitalized, like a sentence:
Syntax: string.capitalize()'i love to eat pizza'.capitalize() --> 'I love to eat pizza'
Remember, all of these examples can also be written using variables:
food = 'pizza'food.upper() --> 'PIZZA'
The split() method converts a string into a list. The method can take two optional arguments. The first argument is the separator, which tells the code how you want the string to be split. By default, the string is split at any whitespace, but if you choose you can decide on any character(s) by which to split the string. The second argument specifies the maximum number of splits to be done. By default, this number is set to -1 which is all occurrences.
Syntax: string.split(separator, maxsplit)'I like to eat pizza'.split() --> ['I', 'like', 'to', 'eat', 'pizza']'I like to eat pizza'.split('e') -->['I lik', ' to ', 'at pizza']'I like to eat pizza'.split('e', 1) -->['I lik', ' to eat pizza']
Similar to split(), the partition() method splits a string by a specified character(s). However, with this method, the string is split into a tuple consisting of three items: everything before the match, the match itself, and everything after the match. By using partition() instead of split() you are able to keep the character(s) by which you split the string. This method takes one required argument — the separator, which tells the code how you want the string to be split. If the separator is not found in the string, a tuple with three items is still returned; however, it consists of the whole string, an empty string, and another empty string.
Syntax: string.partition(value)'I like to eat pizza'.partition(' to ') --> ('I like', ' to ', 'eat pizza')'I like to eat pizza'.partition(' drink ')--> ('I like to eat pizza', '', '')
The join() method is used to join all of the items in an iterable (list, dictionary, tuple, set, or even another string) to a string. The method takes one required argument, the iterable. The string that is used before the method is applied is inputted in between each item in the iterable. Oftentimes, a string consisting of solely a space (‘ ’ or “ ”) is used with the join() method to create spaces between words in an iterable.
Syntax: string.join(iterable)' '.join(['I', 'like', 'to', 'eat', 'pizza']) --> 'I like to eat pizza''x'.join(['I', 'like', 'to', 'eat', 'pizza'])--> 'Ixlikextoxeatxpizza''yummy'.join({'food':'Pizza', 'topping': 'pepperoni'})--> 'foodyummytopping'
The replace() method allows you to replace a specified value of a string with another value. This method takes three arguments, the first two of which are required. The first argument is the value of the string that you wish to replace and the second argument is the value that will be taking its spot. The third argument is an integer specifying the number of occurrences of the value you want to replace — the default is all occurrences.
Syntax: string.replace(oldvalue, newvalue, count)'I like to eat pizza'.replace('pizza', 'burgers')--> 'I like to eat burgers''I really really like to eat pizza'.replace('really', 'kind of', 1)--> 'I kind of really like to eat pizza'
The strip() method removes any characters of your choosing from the beginning or end of a string. The method can take one optional argument. By default, any leading or trailing whitespaces are removed from the string, but you can choose to instead remove any characters of your choice if you include them in a string as an argument.
Syntax: string.strip(characters)' pizza '.strip() --> 'pizza''..rjq,,pizza.rq,j.r'.strip('rjq.,') --> 'pizza'
The startswith() method returns True if the string starts with the specified value and False otherwise. The endswith() method works the same way but with the end of a string. These methods take three arguments, the first of which is required while the latter two are optional. The first argument is the value you are looking to see if the string starts/ends with. The second argument is an integer value specifying which index you want to start the search and the third argument is the value of the index where you want to end the search.
Syntax: string.[starts/ends]with(value, start, end)'I like to eat pizza'.startswith('I like') --> True'I like to eat pizza'.endswith('drink pizza') --> False'I like to eat pizza'.startswith('to', 7, 18) --> True'I like to eat pizza'.endswith('eat', 7, 18) --> False
The count() method tells you how many times a specified value appears in a string. This method takes three arguments, the first of which is required. The first argument is the value that you are searching for in the string. The second and third arguments are the positions where you want to start and end the search, respectively. By default, the second argument is 0, the beginning of the string, and the third argument is -1, the end of the string.
Syntax: string.count(value, start, end)'I really really like to eat pizza'.count('really') --> 2'I really really like to eat pizza'.count('really', 8, 20) --> 1
The find() and index() methods are nearly exactly the same in that they both return the index of the first occurrence of a specified value (the index of the first character of the specified value if the given value is multiple characters). The only difference between the two is that the find() method will return -1 if the value is not found in the string, while the index() method will result in an error if the value does not occur. Both methods take three arguments, the first of which is required. Like the count() method, the first argument is the value that you are searching for in the string, and the second and third arguments are the positions in which you want to start and end the search, respectively. By default, the second argument is 0, the beginning of the string, and the third argument is -1, the end of the string.
Syntax: string.[find/index](value, start, end)'I really really like to eat pizza'.find('really') --> 2'I really really like to eat pizza'.index('really') --> 2'I really really like to eat pizza'.find('really', 8, 20) --> 9'I really really like to eat pizza'.index('really', 8, 20) --> 9'I really really like to eat pizza'.find('hamburger') --> -1'I really really like to eat pizza'.index('hamburger') --> ERROR
And there you have it. With these aforementioned methods you should be set to perform most of the operations you will need on Python strings. To see all of the available string methods, make sure to check out the w3schools list.
Happy coding and be sure to check out my blog on Python list methods below!
|
[
{
"code": null,
"e": 872,
"s": 47,
"text": "In Python, data in text form is known as a string. To designate data as a string, the text must be surrounded by single (‘ ’) or double (“ ”) quotes. Names, locations, objects, sentences, even numbers can be strings, as long as they are surrounded by quotes. Once you have a string, you are able to manipulate that string using what’s known as a ‘method.’ To use a method, you simply write the string followed by .[method](). For example, to run the upper() method on the string ‘pizza’, you would just write ‘pizza’.upper(); if ‘pizza’ were set to a variable, you would do that variable.upper(). Some methods accept what are known as ‘arguments,’ which go in the parenthesis and further define what the method will do. The Python language has a lot of built-in methods, like upper(), that allow you to easily alter strings."
},
{
"code": null,
"e": 953,
"s": 872,
"text": "These methods all perform simple manipulations on strings and take no arguments."
},
{
"code": null,
"e": 1020,
"s": 953,
"text": "The upper() method converts every letter in a string to uppercase:"
},
{
"code": null,
"e": 1070,
"s": 1020,
"text": "Syntax: string.upper()'pizza'.upper() --> 'PIZZA'"
},
{
"code": null,
"e": 1137,
"s": 1070,
"text": "The lower() method converts every letter in a string to lowercase:"
},
{
"code": null,
"e": 1187,
"s": 1137,
"text": "Syntax: string.lower()'PIZZA'.lower() --> 'pizza'"
},
{
"code": null,
"e": 1276,
"s": 1187,
"text": "The title() method capitalizes the first letter of every word in a string, like a title:"
},
{
"code": null,
"e": 1354,
"s": 1276,
"text": "Syntax: string.title()'i love to eat pizza'.title() --> 'I Love To Eat Pizza'"
},
{
"code": null,
"e": 1508,
"s": 1354,
"text": "The capitalize() method is similar to the title() method; however, only the first letter of the first word in a string gets capitalized, like a sentence:"
},
{
"code": null,
"e": 1596,
"s": 1508,
"text": "Syntax: string.capitalize()'i love to eat pizza'.capitalize() --> 'I love to eat pizza'"
},
{
"code": null,
"e": 1665,
"s": 1596,
"text": "Remember, all of these examples can also be written using variables:"
},
{
"code": null,
"e": 1704,
"s": 1665,
"text": "food = 'pizza'food.upper() --> 'PIZZA'"
},
{
"code": null,
"e": 2161,
"s": 1704,
"text": "The split() method converts a string into a list. The method can take two optional arguments. The first argument is the separator, which tells the code how you want the string to be split. By default, the string is split at any whitespace, but if you choose you can decide on any character(s) by which to split the string. The second argument specifies the maximum number of splits to be done. By default, this number is set to -1 which is all occurrences."
},
{
"code": null,
"e": 2402,
"s": 2161,
"text": "Syntax: string.split(separator, maxsplit)'I like to eat pizza'.split() --> ['I', 'like', 'to', 'eat', 'pizza']'I like to eat pizza'.split('e') -->['I lik', ' to ', 'at pizza']'I like to eat pizza'.split('e', 1) -->['I lik', ' to eat pizza']"
},
{
"code": null,
"e": 3054,
"s": 2402,
"text": "Similar to split(), the partition() method splits a string by a specified character(s). However, with this method, the string is split into a tuple consisting of three items: everything before the match, the match itself, and everything after the match. By using partition() instead of split() you are able to keep the character(s) by which you split the string. This method takes one required argument — the separator, which tells the code how you want the string to be split. If the separator is not found in the string, a tuple with three items is still returned; however, it consists of the whole string, an empty string, and another empty string."
},
{
"code": null,
"e": 3238,
"s": 3054,
"text": "Syntax: string.partition(value)'I like to eat pizza'.partition(' to ') --> ('I like', ' to ', 'eat pizza')'I like to eat pizza'.partition(' drink ')--> ('I like to eat pizza', '', '')"
},
{
"code": null,
"e": 3670,
"s": 3238,
"text": "The join() method is used to join all of the items in an iterable (list, dictionary, tuple, set, or even another string) to a string. The method takes one required argument, the iterable. The string that is used before the method is applied is inputted in between each item in the iterable. Oftentimes, a string consisting of solely a space (‘ ’ or “ ”) is used with the join() method to create spaces between words in an iterable."
},
{
"code": null,
"e": 3917,
"s": 3670,
"text": "Syntax: string.join(iterable)' '.join(['I', 'like', 'to', 'eat', 'pizza']) --> 'I like to eat pizza''x'.join(['I', 'like', 'to', 'eat', 'pizza'])--> 'Ixlikextoxeatxpizza''yummy'.join({'food':'Pizza', 'topping': 'pepperoni'})--> 'foodyummytopping'"
},
{
"code": null,
"e": 4357,
"s": 3917,
"text": "The replace() method allows you to replace a specified value of a string with another value. This method takes three arguments, the first two of which are required. The first argument is the value of the string that you wish to replace and the second argument is the value that will be taking its spot. The third argument is an integer specifying the number of occurrences of the value you want to replace — the default is all occurrences."
},
{
"code": null,
"e": 4590,
"s": 4357,
"text": "Syntax: string.replace(oldvalue, newvalue, count)'I like to eat pizza'.replace('pizza', 'burgers')--> 'I like to eat burgers''I really really like to eat pizza'.replace('really', 'kind of', 1)--> 'I kind of really like to eat pizza'"
},
{
"code": null,
"e": 4923,
"s": 4590,
"text": "The strip() method removes any characters of your choosing from the beginning or end of a string. The method can take one optional argument. By default, any leading or trailing whitespaces are removed from the string, but you can choose to instead remove any characters of your choice if you include them in a string as an argument."
},
{
"code": null,
"e": 5037,
"s": 4923,
"text": "Syntax: string.strip(characters)' pizza '.strip() --> 'pizza''..rjq,,pizza.rq,j.r'.strip('rjq.,') --> 'pizza'"
},
{
"code": null,
"e": 5576,
"s": 5037,
"text": "The startswith() method returns True if the string starts with the specified value and False otherwise. The endswith() method works the same way but with the end of a string. These methods take three arguments, the first of which is required while the latter two are optional. The first argument is the value you are looking to see if the string starts/ends with. The second argument is an integer value specifying which index you want to start the search and the third argument is the value of the index where you want to end the search."
},
{
"code": null,
"e": 5842,
"s": 5576,
"text": "Syntax: string.[starts/ends]with(value, start, end)'I like to eat pizza'.startswith('I like') --> True'I like to eat pizza'.endswith('drink pizza') --> False'I like to eat pizza'.startswith('to', 7, 18) --> True'I like to eat pizza'.endswith('eat', 7, 18) --> False"
},
{
"code": null,
"e": 6293,
"s": 5842,
"text": "The count() method tells you how many times a specified value appears in a string. This method takes three arguments, the first of which is required. The first argument is the value that you are searching for in the string. The second and third arguments are the positions where you want to start and end the search, respectively. By default, the second argument is 0, the beginning of the string, and the third argument is -1, the end of the string."
},
{
"code": null,
"e": 6454,
"s": 6293,
"text": "Syntax: string.count(value, start, end)'I really really like to eat pizza'.count('really') --> 2'I really really like to eat pizza'.count('really', 8, 20) --> 1"
},
{
"code": null,
"e": 7290,
"s": 6454,
"text": "The find() and index() methods are nearly exactly the same in that they both return the index of the first occurrence of a specified value (the index of the first character of the specified value if the given value is multiple characters). The only difference between the two is that the find() method will return -1 if the value is not found in the string, while the index() method will result in an error if the value does not occur. Both methods take three arguments, the first of which is required. Like the count() method, the first argument is the value that you are searching for in the string, and the second and third arguments are the positions in which you want to start and end the search, respectively. By default, the second argument is 0, the beginning of the string, and the third argument is -1, the end of the string."
},
{
"code": null,
"e": 7701,
"s": 7290,
"text": "Syntax: string.[find/index](value, start, end)'I really really like to eat pizza'.find('really') --> 2'I really really like to eat pizza'.index('really') --> 2'I really really like to eat pizza'.find('really', 8, 20) --> 9'I really really like to eat pizza'.index('really', 8, 20) --> 9'I really really like to eat pizza'.find('hamburger') --> -1'I really really like to eat pizza'.index('hamburger') --> ERROR"
},
{
"code": null,
"e": 7930,
"s": 7701,
"text": "And there you have it. With these aforementioned methods you should be set to perform most of the operations you will need on Python strings. To see all of the available string methods, make sure to check out the w3schools list."
}
] |
Java & MySQL - PreparedStatement
|
The PreparedStatement interface extends the Statement interface, which gives you added functionality with a couple of advantages over a generic Statement object.
This statement gives you the flexibility of supplying arguments dynamically.
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker. You must supply values for every parameter before executing the SQL statement.
The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter. If you forget to supply the values, you will receive an SQLException.
Each parameter marker is referred by its ordinal position. The first marker represents position 1, the next position 2, and so forth. This method differs from that of Java array indices, which starts at 0.
All of the Statement object's methods for interacting with the database (a) execute(), (b) executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object. However, the methods are modified to use SQL statements that can input the parameters.
Just as you close a Statement object, for the same reason you should also close the PreparedStatement object.
A simple call to the close() method will do the job. If you close the Connection object first, it will close the PreparedStatement object as well. However, you should always explicitly close the PreparedStatement object to ensure proper cleanup.
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
pstmt.close();
}
We're using try with resources which handles the resource closure automatically. Following example demonstrates all of the above said concepts.
This code has been written based on the environment and database setup done in the previous chapter.
Copy and paste the following example in TestApplication.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestApplication {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Employees";
static final String UPDATE_QUERY = "UPDATE Employees set age=? WHERE id=?";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement stmt = conn.prepareStatement(UPDATE_QUERY);
) {
// Bind values into the parameters.
stmt.setInt(1, 35); // This would set age
stmt.setInt(2, 102); // This would set ID
// Let us update age of the record with ID = 102;
int rows = stmt.executeUpdate();
System.out.println("Rows impacted : " + rows );
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(QUERY);
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac TestApplication.java
C:\>
When you run TestApplication, it produces the following result −
C:\>java TestApplication
Return value is : false
Rows impacted : 1
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mehnaz, Last: Fatma
ID: 102, Age: 35, First: Zaid, Last: Khan
ID: 103, Age: 30, First: Sumit, Last: Mittal
C:\>
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": 2848,
"s": 2686,
"text": "The PreparedStatement interface extends the Statement interface, which gives you added functionality with a couple of advantages over a generic Statement object."
},
{
"code": null,
"e": 2925,
"s": 2848,
"text": "This statement gives you the flexibility of supplying arguments dynamically."
},
{
"code": null,
"e": 3131,
"s": 2925,
"text": "PreparedStatement pstmt = null;\ntry {\n String SQL = \"Update Employees SET age = ? WHERE id = ?\";\n pstmt = conn.prepareStatement(SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n . . .\n}"
},
{
"code": null,
"e": 3306,
"s": 3131,
"text": "All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker. You must supply values for every parameter before executing the SQL statement."
},
{
"code": null,
"e": 3522,
"s": 3306,
"text": "The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter. If you forget to supply the values, you will receive an SQLException."
},
{
"code": null,
"e": 3728,
"s": 3522,
"text": "Each parameter marker is referred by its ordinal position. The first marker represents position 1, the next position 2, and so forth. This method differs from that of Java array indices, which starts at 0."
},
{
"code": null,
"e": 3991,
"s": 3728,
"text": "All of the Statement object's methods for interacting with the database (a) execute(), (b) executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object. However, the methods are modified to use SQL statements that can input the parameters."
},
{
"code": null,
"e": 4101,
"s": 3991,
"text": "Just as you close a Statement object, for the same reason you should also close the PreparedStatement object."
},
{
"code": null,
"e": 4347,
"s": 4101,
"text": "A simple call to the close() method will do the job. If you close the Connection object first, it will close the PreparedStatement object as well. However, you should always explicitly close the PreparedStatement object to ensure proper cleanup."
},
{
"code": null,
"e": 4562,
"s": 4347,
"text": "PreparedStatement pstmt = null;\ntry {\n String SQL = \"Update Employees SET age = ? WHERE id = ?\";\n pstmt = conn.prepareStatement(SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n pstmt.close();\n}"
},
{
"code": null,
"e": 4706,
"s": 4562,
"text": "We're using try with resources which handles the resource closure automatically. Following example demonstrates all of the above said concepts."
},
{
"code": null,
"e": 4807,
"s": 4706,
"text": "This code has been written based on the environment and database setup done in the previous chapter."
},
{
"code": null,
"e": 4898,
"s": 4807,
"text": "Copy and paste the following example in TestApplication.java, compile and run as follows −"
},
{
"code": null,
"e": 6526,
"s": 4898,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\n\npublic class TestApplication {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Employees\";\n static final String UPDATE_QUERY = \"UPDATE Employees set age=? WHERE id=?\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n PreparedStatement stmt = conn.prepareStatement(UPDATE_QUERY);\n ) {\t\t \n // Bind values into the parameters.\n stmt.setInt(1, 35); // This would set age\n stmt.setInt(2, 102); // This would set ID\n\n // Let us update age of the record with ID = 102;\n int rows = stmt.executeUpdate();\n System.out.println(\"Rows impacted : \" + rows );\n\n // Let us select all the records and display them.\n ResultSet rs = stmt.executeQuery(QUERY);\t\t \n\n // Extract data from result set\n while (rs.next()) {\n // Retrieve by column name\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n rs.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 6576,
"s": 6526,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 6613,
"s": 6576,
"text": "C:\\>javac TestApplication.java\nC:\\>\n"
},
{
"code": null,
"e": 6678,
"s": 6613,
"text": "When you run TestApplication, it produces the following result −"
},
{
"code": null,
"e": 6924,
"s": 6678,
"text": "C:\\>java TestApplication\nReturn value is : false\nRows impacted : 1\nID: 100, Age: 18, First: Zara, Last: Ali\nID: 101, Age: 25, First: Mehnaz, Last: Fatma\nID: 102, Age: 35, First: Zaid, Last: Khan\nID: 103, Age: 30, First: Sumit, Last: Mittal\nC:\\>\n"
},
{
"code": null,
"e": 6957,
"s": 6924,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6973,
"s": 6957,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7006,
"s": 6973,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7022,
"s": 7006,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7057,
"s": 7022,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7071,
"s": 7057,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7105,
"s": 7071,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7119,
"s": 7105,
"text": " Tushar Kale"
},
{
"code": null,
"e": 7156,
"s": 7119,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7171,
"s": 7156,
"text": " Monica Mittal"
},
{
"code": null,
"e": 7204,
"s": 7171,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7223,
"s": 7204,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7230,
"s": 7223,
"text": " Print"
},
{
"code": null,
"e": 7241,
"s": 7230,
"text": " Add Notes"
}
] |
How to Get the Descriptive Statistics for Pandas DataFrame? - GeeksforGeeks
|
10 Jul, 2020
describe() method in Python Pandas is used to compute descriptive statistical data like count, unique values, mean, standard deviation, minimum and maximum value and many more. In this article, let’s learn to get the descriptive statistics for Pandas DataFrame.
Syntax:df[‘cname’].describe(percentiles = None, include = None, exclude = None)df.describe(percentiles = None, include = None, exclude = None)
Parameters:percentiles: represents percentile value that has to be returned by the function. Default values are 0.25, 0.5 and 0.75include: represents list of data types that has to be includedexclude: represents list of data types that has to be excluded
Example 1:
# Import packagefrom pandas import DataFrame # Create DataFramecart = {'Product': ['Mobile', 'AC', 'Mobile', 'Sofa', 'Laptop'], 'Price': [20000, 28000, 22000, 19000, 45000], 'Year': [2014, 2015, 2016, 2017, 2018] }df = DataFrame(cart, columns = ['Product', 'Price', 'Year']) # Original DataFrameprint("Original DataFrame:\n", df) # Describing descriptive statistics of Priceprint("\nDescriptive statistics of Price:\n")stats = df['Price'].describe()print(stats)
Output:Example 2:
# Import packagefrom pandas import DataFrame # Create DataFramecart = {'Product': ['Mobile', 'AC', 'Mobile', 'Sofa', 'Laptop'], 'Price': [20000, 28000, 22000, 19000, 45000], 'Year': [2014, 2015, 2016, 2017, 2018] }df = DataFrame(cart, columns = ['Product', 'Price', 'Year']) # Original DataFrameprint("Original DataFrame:\n", df) # Describing descriptive statistics of Yearprint("\nDescriptive statistics of year:\n")stats = df['Year'].describe()print(stats)
Output:Example 3:
# Import packagefrom pandas import DataFrame # Create DataFramecart = {'Product': ['Mobile', 'AC', 'Mobile', 'Sofa', 'Laptop'], 'Price': [20000, 28000, 22000, 19000, 45000], 'Year': [2014, 2015, 2016, 2017, 2018] }df = DataFrame(cart, columns = ['Product', 'Price', 'Year']) # Original DataFrameprint("Original DataFrame:\n", df) # Describing descriptive statistics of whole dataframeprint("\nDescriptive statistics of whole dataframe:\n")stats = df.describe(include = 'all')print(stats)
Output:Example 4:In this example, let’s print all the descriptive statistical data individually.
from pandas import DataFrame # Create DataFramecart = {'Product': ['Mobile', 'AC', 'Mobile', 'Sofa', 'Laptop'], 'Price': [20000, 28000, 22000, 19000, 45000], 'Year': [2014, 2015, 2016, 2017, 2018] }df = DataFrame(cart, columns = ['Product', 'Price', 'Year']) # Original DataFrameprint("Original DataFrame:\n", df) # Print Count of Priceprint("\nCount of Price:\n")counts = df['Price'].count()print(counts) # Print mean of Priceprint("\nMean of Price:\n")m = df['Price'].mean()print(m) # Print maximum value of Priceprint("\nMaximum value of Price:\n")mx = df['Price'].max()print(m) # Print standard deviation of Priceprint("\nStandard deviation of Price:\n")sd = df['Price'].std()print(sd)
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 25061,
"s": 25033,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 25323,
"s": 25061,
"text": "describe() method in Python Pandas is used to compute descriptive statistical data like count, unique values, mean, standard deviation, minimum and maximum value and many more. In this article, let’s learn to get the descriptive statistics for Pandas DataFrame."
},
{
"code": null,
"e": 25466,
"s": 25323,
"text": "Syntax:df[‘cname’].describe(percentiles = None, include = None, exclude = None)df.describe(percentiles = None, include = None, exclude = None)"
},
{
"code": null,
"e": 25721,
"s": 25466,
"text": "Parameters:percentiles: represents percentile value that has to be returned by the function. Default values are 0.25, 0.5 and 0.75include: represents list of data types that has to be includedexclude: represents list of data types that has to be excluded"
},
{
"code": null,
"e": 25732,
"s": 25721,
"text": "Example 1:"
},
{
"code": "# Import packagefrom pandas import DataFrame # Create DataFramecart = {'Product': ['Mobile', 'AC', 'Mobile', 'Sofa', 'Laptop'], 'Price': [20000, 28000, 22000, 19000, 45000], 'Year': [2014, 2015, 2016, 2017, 2018] }df = DataFrame(cart, columns = ['Product', 'Price', 'Year']) # Original DataFrameprint(\"Original DataFrame:\\n\", df) # Describing descriptive statistics of Priceprint(\"\\nDescriptive statistics of Price:\\n\")stats = df['Price'].describe()print(stats)",
"e": 26219,
"s": 25732,
"text": null
},
{
"code": null,
"e": 26237,
"s": 26219,
"text": "Output:Example 2:"
},
{
"code": "# Import packagefrom pandas import DataFrame # Create DataFramecart = {'Product': ['Mobile', 'AC', 'Mobile', 'Sofa', 'Laptop'], 'Price': [20000, 28000, 22000, 19000, 45000], 'Year': [2014, 2015, 2016, 2017, 2018] }df = DataFrame(cart, columns = ['Product', 'Price', 'Year']) # Original DataFrameprint(\"Original DataFrame:\\n\", df) # Describing descriptive statistics of Yearprint(\"\\nDescriptive statistics of year:\\n\")stats = df['Year'].describe()print(stats)",
"e": 26721,
"s": 26237,
"text": null
},
{
"code": null,
"e": 26739,
"s": 26721,
"text": "Output:Example 3:"
},
{
"code": "# Import packagefrom pandas import DataFrame # Create DataFramecart = {'Product': ['Mobile', 'AC', 'Mobile', 'Sofa', 'Laptop'], 'Price': [20000, 28000, 22000, 19000, 45000], 'Year': [2014, 2015, 2016, 2017, 2018] }df = DataFrame(cart, columns = ['Product', 'Price', 'Year']) # Original DataFrameprint(\"Original DataFrame:\\n\", df) # Describing descriptive statistics of whole dataframeprint(\"\\nDescriptive statistics of whole dataframe:\\n\")stats = df.describe(include = 'all')print(stats)",
"e": 27252,
"s": 26739,
"text": null
},
{
"code": null,
"e": 27349,
"s": 27252,
"text": "Output:Example 4:In this example, let’s print all the descriptive statistical data individually."
},
{
"code": "from pandas import DataFrame # Create DataFramecart = {'Product': ['Mobile', 'AC', 'Mobile', 'Sofa', 'Laptop'], 'Price': [20000, 28000, 22000, 19000, 45000], 'Year': [2014, 2015, 2016, 2017, 2018] }df = DataFrame(cart, columns = ['Product', 'Price', 'Year']) # Original DataFrameprint(\"Original DataFrame:\\n\", df) # Print Count of Priceprint(\"\\nCount of Price:\\n\")counts = df['Price'].count()print(counts) # Print mean of Priceprint(\"\\nMean of Price:\\n\")m = df['Price'].mean()print(m) # Print maximum value of Priceprint(\"\\nMaximum value of Price:\\n\")mx = df['Price'].max()print(m) # Print standard deviation of Priceprint(\"\\nStandard deviation of Price:\\n\")sd = df['Price'].std()print(sd)",
"e": 28067,
"s": 27349,
"text": null
},
{
"code": null,
"e": 28075,
"s": 28067,
"text": "Output:"
},
{
"code": null,
"e": 28099,
"s": 28075,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 28113,
"s": 28099,
"text": "Python-pandas"
},
{
"code": null,
"e": 28120,
"s": 28113,
"text": "Python"
},
{
"code": null,
"e": 28218,
"s": 28120,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28236,
"s": 28218,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28271,
"s": 28236,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28293,
"s": 28271,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28325,
"s": 28293,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28355,
"s": 28325,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28397,
"s": 28355,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28423,
"s": 28397,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28460,
"s": 28423,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28503,
"s": 28460,
"text": "Python program to convert a list to string"
}
] |
Text Classification with BERT in PyTorch | by Ruben Winastwan | Towards Data Science
|
Back in 2018, Google developed a powerful Transformer-based machine learning model for NLP applications that outperforms previous language models in different benchmark datasets. And this model is called BERT.
In this post, we’re going to use a pre-trained BERT model from Hugging Face for a text classification task. As you might already know, the main goal of the model in a text classification task is to categorize a text into one of the predefined labels or tags.
Specifically, soon we’re going to use the pre-trained BERT model to classify whether the text of a news article can be categorized as sport, politics, business, entertainment, or tech category.
But before we dive into the implementation, let’s talk about the concept behind BERT briefly.
BERT is an acronym for Bidirectional Encoder Representations from Transformers. The name itself gives us several clues to what BERT is all about.
BERT architecture consists of several Transformer encoders stacked together. Each Transformer encoder encapsulates two sub-layers: a self-attention layer and a feed-forward layer.
There are two different BERT models:
BERT base, which is a BERT model consists of 12 layers of Transformer encoder, 12 attention heads, 768 hidden size, and 110M parameters.BERT large, which is a BERT model consists of 24 layers of Transformer encoder,16 attention heads, 1024 hidden size, and 340 parameters.
BERT base, which is a BERT model consists of 12 layers of Transformer encoder, 12 attention heads, 768 hidden size, and 110M parameters.
BERT large, which is a BERT model consists of 24 layers of Transformer encoder,16 attention heads, 1024 hidden size, and 340 parameters.
There are at least two reasons why BERT is a powerful language model:
It is pre-trained on unlabeled data extracted from BooksCorpus, which has 800M words, and from Wikipedia, which has 2,500M words.As the name suggests, it is pre-trained by utilizing the bidirectional nature of the encoder stacks. This means that BERT learns information from a sequence of words not only from left to right, but also from right to left.
It is pre-trained on unlabeled data extracted from BooksCorpus, which has 800M words, and from Wikipedia, which has 2,500M words.
As the name suggests, it is pre-trained by utilizing the bidirectional nature of the encoder stacks. This means that BERT learns information from a sequence of words not only from left to right, but also from right to left.
BERT model expects a sequence of tokens (words) as an input. In each sequence of tokens, there are two special tokens that BERT would expect as an input:
[CLS]: This is the first token of every sequence, which stands for classification token.[SEP]: This is the token that makes BERT know which token belongs to which sequence. This special token is mainly important for a next sentence prediction task or question-answering task. If we only have one sequence, then this token will be appended to the end of the sequence.
[CLS]: This is the first token of every sequence, which stands for classification token.
[SEP]: This is the token that makes BERT know which token belongs to which sequence. This special token is mainly important for a next sentence prediction task or question-answering task. If we only have one sequence, then this token will be appended to the end of the sequence.
To make it more clear, let’s say we have a text consisting of the following short sentence:
As a first step, we need to transform this sentence into a sequence of tokens (words) and this process is called tokenization.
Although we have tokenized our input sentence, we need to do one more step. We need to reformat that sequence of tokens by adding[CLS] and [SEP] tokens before using it as an input to our BERT model.
Luckily, we only need one line of code to transform our input sentence into a sequence of tokens that BERT expects as we have seen above. We will use BertTokenizer to do this and you can see how we do this later on.
It is also important to note that the maximum size of tokens that can be fed into BERT model is 512. If the tokens in a sequence are less than 512, we can use padding to fill the unused token slots with [PAD] token. If the tokens in a sequence are longer than 512, then we need to do a truncation.
And that’s all that BERT expects as input.
BERT model then will output an embedding vector of size 768 in each of the tokens. We can use these vectors as an input for different kinds of NLP applications, whether it is text classification, next sentence prediction, Named-Entity-Recognition (NER), or question-answering.
For a text classification task, we focus our attention on the embedding vector output from the special [CLS] token. This means that we’re going to use the embedding vector of size 768 from [CLS] token as an input for our classifier, which then will output a vector of size the number of classes in our classification task.
Below is the illustration of the input and output of the BERT model.
Now we’re going to jump into our main topic to classify text with BERT. In this post, we’re going to use the BBC News Classification dataset. If you want to follow along, you can download the dataset on Kaggle.
This dataset is already in CSV format and it has 2126 different texts, each labeled under one of 5 categories: entertainment, sport, tech, business, or politics.
Let’s take a look at what the dataset looks like.
import pandas as pd
datapath = 'bbc-text.csv'
df = pd.read_csv(datapath)
df.head()
df.groupby(['category']).size().plot.bar()
<AxesSubplot:xlabel='category'>
As you can see, the dataframe only has two columns, which is category that will be our label, and text which will be our input data for BERT.
As you might already know from the previous section, we need to transform our text into the format that BERT expects by adding [CLS] and [SEP] tokens. We can do this easily with BertTokenizer class from Hugging Face.
First, we need to install Transformers library via pip:
pip install transformers
To make it easier for us to understand the output that we get from BertTokenizer, let’s use a short text as an example.
Here is the explanation of BertTokenizer parameters above:
padding : to pad each sequence to the maximum length that you specify.
max_length : the maximum length of each sequence. In this example we use 10, but for our actual dataset we will use 512, which is the maximum length of a sequence allowed for BERT.
truncation : if True, then the tokens in each sequence that exceed the maximum length will be truncated.
return_tensors : the type of tensors that will be returned. Since we’re using Pytorch, then we use pt. If you use Tensorflow, then you need to use tf .
The outputs that you see from bert_input variable above are necessary for our BERT model later on. But what do those outputs mean?
The first row is input_ids , which is the id representation of each token. We can actually decode these input ids into the actual tokens as follows:
The first row is input_ids , which is the id representation of each token. We can actually decode these input ids into the actual tokens as follows:
As you can see, the BertTokenizer takes care of all of the necessary transformations of the input text such that it’s ready to be used as an input for our BERT model. It adds [CLS], [SEP], and [PAD] tokens automatically. Since we specified the maximum length to be 10, then there are only two [PAD] tokens at the end.
2. The second row is token_type_ids , which is a binary mask that identifies in which sequence a token belongs. If we only have a single sequence, then all of the token type ids will be 0. For a text classification task, token_type_ids is an optional input for our BERT model.
3. The third row is attention_mask , which is a binary mask that identifies whether a token is a real word or just padding. If the token contains [CLS], [SEP], or any real word, then the mask would be 1. Meanwhile, if the token is just padding or [PAD], then the mask would be 0.
As you might notice, we use a pre-trained BertTokenizer from bert-base-cased model. This pre-trained tokenizer works well if the text in your dataset is in English.
If you have datasets from different languages, you might want to use bert-base-multilingual-cased. Specifically, if your dataset is in German, Dutch, Chinese, Japanese, or Finnish, you might want to use a tokenizer pre-trained specifically in these languages. You can check the name of the corresponding pre-trained tokenizer here.
To sum up, below is the illustration of what BertTokenizer does to our input sentence.
Now that we know what kind of output that we will get from BertTokenizer , let’s build a Dataset class for our news dataset that will serve as a class to generate our news data.
In the above implementation, we define a variable called labels , which is a dictionary that maps the category in the dataframe into the id representation of our label. Notice that we also call BertTokenizer in the __init__ function above to transform our input texts into the format that BERT expects.
After defining dataset class, let’s split our dataframe into training, validation, and test set with the proportion of 80:10:10.
So far, we have built a dataset class to generate our data. Now let’s build the actual model using a pre-trained BERT base model which has 12 layers of Transformer encoder.
If your dataset is not in English, it would be best if you use bert-base-multilingual-cased model. If your data is in German, Dutch, Chinese, Japanese, or Finnish, you can use the model pre-trained specifically in these languages. You can check the name of the corresponding pre-trained model here.
As you can see from the code above, BERT model outputs two variables:
The first variable, which we named _ in the code above, contains the embedding vectors of all of the tokens in a sequence.
The second variable, which we named pooled_output, contains the embedding vector of [CLS] token. For a text classification task, it is enough to use this embedding as an input for our classifier.
We then pass the pooled_output variable into a linear layer with ReLU activation function. At the end of the linear layer, we have a vector of size 5, each corresponds to a category of our labels (sport, business, politics, entertainment, and tech).
Now it’s time for us to train the model. The training loop will be a standard PyTorch training loop.
We train the model for 5 epochs and we use Adam as the optimizer, while the learning rate is set to 1e-6. We also need to use categorical cross entropy as our loss function since we’re dealing with multi-class classification.
It is recommended that you use GPU to train the model since BERT base model contains 110 million parameters.
After 5 epochs with the above configuration, you’ll get the following output as an example:
Obviously you might not get similar loss and accuracy values as the screenshot above due to the randomness of training process. If you haven’t got a good result after 5 epochs, try to increase the epochs to, let’s say, 10 or adjust the learning rate.
Now that we have trained the model, we can use the test data to evaluate the model’s performance on unseen data. Below is the function to evaluate the performance of the model on the test set.
After running the code above, I got the accuracy of 0.994 from the test data. The accuracy that you’ll get will obviously slightly differ from mine due to the randomness during the training process.
Now you know the step on how we can leverage a pre-trained BERT model from Hugging Face for a text classification task. I hope this post helps you to get started with BERT.
One thing to remember is that we can use the embedding vectors from BERT to do not only a sentence or text classification task, but also the more advanced NLP applications such as question answering, next sentence prediction, or Named-Entity-Recognition (NER) tasks.
You can find all of the code snippets demonstrated in this post in this notebook.
|
[
{
"code": null,
"e": 382,
"s": 172,
"text": "Back in 2018, Google developed a powerful Transformer-based machine learning model for NLP applications that outperforms previous language models in different benchmark datasets. And this model is called BERT."
},
{
"code": null,
"e": 641,
"s": 382,
"text": "In this post, we’re going to use a pre-trained BERT model from Hugging Face for a text classification task. As you might already know, the main goal of the model in a text classification task is to categorize a text into one of the predefined labels or tags."
},
{
"code": null,
"e": 835,
"s": 641,
"text": "Specifically, soon we’re going to use the pre-trained BERT model to classify whether the text of a news article can be categorized as sport, politics, business, entertainment, or tech category."
},
{
"code": null,
"e": 929,
"s": 835,
"text": "But before we dive into the implementation, let’s talk about the concept behind BERT briefly."
},
{
"code": null,
"e": 1075,
"s": 929,
"text": "BERT is an acronym for Bidirectional Encoder Representations from Transformers. The name itself gives us several clues to what BERT is all about."
},
{
"code": null,
"e": 1255,
"s": 1075,
"text": "BERT architecture consists of several Transformer encoders stacked together. Each Transformer encoder encapsulates two sub-layers: a self-attention layer and a feed-forward layer."
},
{
"code": null,
"e": 1292,
"s": 1255,
"text": "There are two different BERT models:"
},
{
"code": null,
"e": 1565,
"s": 1292,
"text": "BERT base, which is a BERT model consists of 12 layers of Transformer encoder, 12 attention heads, 768 hidden size, and 110M parameters.BERT large, which is a BERT model consists of 24 layers of Transformer encoder,16 attention heads, 1024 hidden size, and 340 parameters."
},
{
"code": null,
"e": 1702,
"s": 1565,
"text": "BERT base, which is a BERT model consists of 12 layers of Transformer encoder, 12 attention heads, 768 hidden size, and 110M parameters."
},
{
"code": null,
"e": 1839,
"s": 1702,
"text": "BERT large, which is a BERT model consists of 24 layers of Transformer encoder,16 attention heads, 1024 hidden size, and 340 parameters."
},
{
"code": null,
"e": 1909,
"s": 1839,
"text": "There are at least two reasons why BERT is a powerful language model:"
},
{
"code": null,
"e": 2262,
"s": 1909,
"text": "It is pre-trained on unlabeled data extracted from BooksCorpus, which has 800M words, and from Wikipedia, which has 2,500M words.As the name suggests, it is pre-trained by utilizing the bidirectional nature of the encoder stacks. This means that BERT learns information from a sequence of words not only from left to right, but also from right to left."
},
{
"code": null,
"e": 2392,
"s": 2262,
"text": "It is pre-trained on unlabeled data extracted from BooksCorpus, which has 800M words, and from Wikipedia, which has 2,500M words."
},
{
"code": null,
"e": 2616,
"s": 2392,
"text": "As the name suggests, it is pre-trained by utilizing the bidirectional nature of the encoder stacks. This means that BERT learns information from a sequence of words not only from left to right, but also from right to left."
},
{
"code": null,
"e": 2770,
"s": 2616,
"text": "BERT model expects a sequence of tokens (words) as an input. In each sequence of tokens, there are two special tokens that BERT would expect as an input:"
},
{
"code": null,
"e": 3137,
"s": 2770,
"text": "[CLS]: This is the first token of every sequence, which stands for classification token.[SEP]: This is the token that makes BERT know which token belongs to which sequence. This special token is mainly important for a next sentence prediction task or question-answering task. If we only have one sequence, then this token will be appended to the end of the sequence."
},
{
"code": null,
"e": 3226,
"s": 3137,
"text": "[CLS]: This is the first token of every sequence, which stands for classification token."
},
{
"code": null,
"e": 3505,
"s": 3226,
"text": "[SEP]: This is the token that makes BERT know which token belongs to which sequence. This special token is mainly important for a next sentence prediction task or question-answering task. If we only have one sequence, then this token will be appended to the end of the sequence."
},
{
"code": null,
"e": 3597,
"s": 3505,
"text": "To make it more clear, let’s say we have a text consisting of the following short sentence:"
},
{
"code": null,
"e": 3724,
"s": 3597,
"text": "As a first step, we need to transform this sentence into a sequence of tokens (words) and this process is called tokenization."
},
{
"code": null,
"e": 3923,
"s": 3724,
"text": "Although we have tokenized our input sentence, we need to do one more step. We need to reformat that sequence of tokens by adding[CLS] and [SEP] tokens before using it as an input to our BERT model."
},
{
"code": null,
"e": 4139,
"s": 3923,
"text": "Luckily, we only need one line of code to transform our input sentence into a sequence of tokens that BERT expects as we have seen above. We will use BertTokenizer to do this and you can see how we do this later on."
},
{
"code": null,
"e": 4437,
"s": 4139,
"text": "It is also important to note that the maximum size of tokens that can be fed into BERT model is 512. If the tokens in a sequence are less than 512, we can use padding to fill the unused token slots with [PAD] token. If the tokens in a sequence are longer than 512, then we need to do a truncation."
},
{
"code": null,
"e": 4480,
"s": 4437,
"text": "And that’s all that BERT expects as input."
},
{
"code": null,
"e": 4757,
"s": 4480,
"text": "BERT model then will output an embedding vector of size 768 in each of the tokens. We can use these vectors as an input for different kinds of NLP applications, whether it is text classification, next sentence prediction, Named-Entity-Recognition (NER), or question-answering."
},
{
"code": null,
"e": 5080,
"s": 4757,
"text": "For a text classification task, we focus our attention on the embedding vector output from the special [CLS] token. This means that we’re going to use the embedding vector of size 768 from [CLS] token as an input for our classifier, which then will output a vector of size the number of classes in our classification task."
},
{
"code": null,
"e": 5149,
"s": 5080,
"text": "Below is the illustration of the input and output of the BERT model."
},
{
"code": null,
"e": 5360,
"s": 5149,
"text": "Now we’re going to jump into our main topic to classify text with BERT. In this post, we’re going to use the BBC News Classification dataset. If you want to follow along, you can download the dataset on Kaggle."
},
{
"code": null,
"e": 5522,
"s": 5360,
"text": "This dataset is already in CSV format and it has 2126 different texts, each labeled under one of 5 categories: entertainment, sport, tech, business, or politics."
},
{
"code": null,
"e": 5572,
"s": 5522,
"text": "Let’s take a look at what the dataset looks like."
},
{
"code": null,
"e": 5593,
"s": 5572,
"text": "import pandas as pd\n"
},
{
"code": null,
"e": 5657,
"s": 5593,
"text": "datapath = 'bbc-text.csv'\ndf = pd.read_csv(datapath)\ndf.head()\n"
},
{
"code": null,
"e": 5701,
"s": 5657,
"text": "df.groupby(['category']).size().plot.bar()\n"
},
{
"code": null,
"e": 5733,
"s": 5701,
"text": "<AxesSubplot:xlabel='category'>"
},
{
"code": null,
"e": 5878,
"s": 5736,
"text": "As you can see, the dataframe only has two columns, which is category that will be our label, and text which will be our input data for BERT."
},
{
"code": null,
"e": 6095,
"s": 5878,
"text": "As you might already know from the previous section, we need to transform our text into the format that BERT expects by adding [CLS] and [SEP] tokens. We can do this easily with BertTokenizer class from Hugging Face."
},
{
"code": null,
"e": 6151,
"s": 6095,
"text": "First, we need to install Transformers library via pip:"
},
{
"code": null,
"e": 6176,
"s": 6151,
"text": "pip install transformers"
},
{
"code": null,
"e": 6296,
"s": 6176,
"text": "To make it easier for us to understand the output that we get from BertTokenizer, let’s use a short text as an example."
},
{
"code": null,
"e": 6355,
"s": 6296,
"text": "Here is the explanation of BertTokenizer parameters above:"
},
{
"code": null,
"e": 6426,
"s": 6355,
"text": "padding : to pad each sequence to the maximum length that you specify."
},
{
"code": null,
"e": 6607,
"s": 6426,
"text": "max_length : the maximum length of each sequence. In this example we use 10, but for our actual dataset we will use 512, which is the maximum length of a sequence allowed for BERT."
},
{
"code": null,
"e": 6712,
"s": 6607,
"text": "truncation : if True, then the tokens in each sequence that exceed the maximum length will be truncated."
},
{
"code": null,
"e": 6864,
"s": 6712,
"text": "return_tensors : the type of tensors that will be returned. Since we’re using Pytorch, then we use pt. If you use Tensorflow, then you need to use tf ."
},
{
"code": null,
"e": 6995,
"s": 6864,
"text": "The outputs that you see from bert_input variable above are necessary for our BERT model later on. But what do those outputs mean?"
},
{
"code": null,
"e": 7144,
"s": 6995,
"text": "The first row is input_ids , which is the id representation of each token. We can actually decode these input ids into the actual tokens as follows:"
},
{
"code": null,
"e": 7293,
"s": 7144,
"text": "The first row is input_ids , which is the id representation of each token. We can actually decode these input ids into the actual tokens as follows:"
},
{
"code": null,
"e": 7611,
"s": 7293,
"text": "As you can see, the BertTokenizer takes care of all of the necessary transformations of the input text such that it’s ready to be used as an input for our BERT model. It adds [CLS], [SEP], and [PAD] tokens automatically. Since we specified the maximum length to be 10, then there are only two [PAD] tokens at the end."
},
{
"code": null,
"e": 7888,
"s": 7611,
"text": "2. The second row is token_type_ids , which is a binary mask that identifies in which sequence a token belongs. If we only have a single sequence, then all of the token type ids will be 0. For a text classification task, token_type_ids is an optional input for our BERT model."
},
{
"code": null,
"e": 8168,
"s": 7888,
"text": "3. The third row is attention_mask , which is a binary mask that identifies whether a token is a real word or just padding. If the token contains [CLS], [SEP], or any real word, then the mask would be 1. Meanwhile, if the token is just padding or [PAD], then the mask would be 0."
},
{
"code": null,
"e": 8333,
"s": 8168,
"text": "As you might notice, we use a pre-trained BertTokenizer from bert-base-cased model. This pre-trained tokenizer works well if the text in your dataset is in English."
},
{
"code": null,
"e": 8665,
"s": 8333,
"text": "If you have datasets from different languages, you might want to use bert-base-multilingual-cased. Specifically, if your dataset is in German, Dutch, Chinese, Japanese, or Finnish, you might want to use a tokenizer pre-trained specifically in these languages. You can check the name of the corresponding pre-trained tokenizer here."
},
{
"code": null,
"e": 8752,
"s": 8665,
"text": "To sum up, below is the illustration of what BertTokenizer does to our input sentence."
},
{
"code": null,
"e": 8930,
"s": 8752,
"text": "Now that we know what kind of output that we will get from BertTokenizer , let’s build a Dataset class for our news dataset that will serve as a class to generate our news data."
},
{
"code": null,
"e": 9233,
"s": 8930,
"text": "In the above implementation, we define a variable called labels , which is a dictionary that maps the category in the dataframe into the id representation of our label. Notice that we also call BertTokenizer in the __init__ function above to transform our input texts into the format that BERT expects."
},
{
"code": null,
"e": 9362,
"s": 9233,
"text": "After defining dataset class, let’s split our dataframe into training, validation, and test set with the proportion of 80:10:10."
},
{
"code": null,
"e": 9535,
"s": 9362,
"text": "So far, we have built a dataset class to generate our data. Now let’s build the actual model using a pre-trained BERT base model which has 12 layers of Transformer encoder."
},
{
"code": null,
"e": 9834,
"s": 9535,
"text": "If your dataset is not in English, it would be best if you use bert-base-multilingual-cased model. If your data is in German, Dutch, Chinese, Japanese, or Finnish, you can use the model pre-trained specifically in these languages. You can check the name of the corresponding pre-trained model here."
},
{
"code": null,
"e": 9904,
"s": 9834,
"text": "As you can see from the code above, BERT model outputs two variables:"
},
{
"code": null,
"e": 10027,
"s": 9904,
"text": "The first variable, which we named _ in the code above, contains the embedding vectors of all of the tokens in a sequence."
},
{
"code": null,
"e": 10223,
"s": 10027,
"text": "The second variable, which we named pooled_output, contains the embedding vector of [CLS] token. For a text classification task, it is enough to use this embedding as an input for our classifier."
},
{
"code": null,
"e": 10473,
"s": 10223,
"text": "We then pass the pooled_output variable into a linear layer with ReLU activation function. At the end of the linear layer, we have a vector of size 5, each corresponds to a category of our labels (sport, business, politics, entertainment, and tech)."
},
{
"code": null,
"e": 10574,
"s": 10473,
"text": "Now it’s time for us to train the model. The training loop will be a standard PyTorch training loop."
},
{
"code": null,
"e": 10800,
"s": 10574,
"text": "We train the model for 5 epochs and we use Adam as the optimizer, while the learning rate is set to 1e-6. We also need to use categorical cross entropy as our loss function since we’re dealing with multi-class classification."
},
{
"code": null,
"e": 10909,
"s": 10800,
"text": "It is recommended that you use GPU to train the model since BERT base model contains 110 million parameters."
},
{
"code": null,
"e": 11001,
"s": 10909,
"text": "After 5 epochs with the above configuration, you’ll get the following output as an example:"
},
{
"code": null,
"e": 11252,
"s": 11001,
"text": "Obviously you might not get similar loss and accuracy values as the screenshot above due to the randomness of training process. If you haven’t got a good result after 5 epochs, try to increase the epochs to, let’s say, 10 or adjust the learning rate."
},
{
"code": null,
"e": 11445,
"s": 11252,
"text": "Now that we have trained the model, we can use the test data to evaluate the model’s performance on unseen data. Below is the function to evaluate the performance of the model on the test set."
},
{
"code": null,
"e": 11644,
"s": 11445,
"text": "After running the code above, I got the accuracy of 0.994 from the test data. The accuracy that you’ll get will obviously slightly differ from mine due to the randomness during the training process."
},
{
"code": null,
"e": 11817,
"s": 11644,
"text": "Now you know the step on how we can leverage a pre-trained BERT model from Hugging Face for a text classification task. I hope this post helps you to get started with BERT."
},
{
"code": null,
"e": 12084,
"s": 11817,
"text": "One thing to remember is that we can use the embedding vectors from BERT to do not only a sentence or text classification task, but also the more advanced NLP applications such as question answering, next sentence prediction, or Named-Entity-Recognition (NER) tasks."
}
] |
Sum of upper and lower triangles | Practice | GeeksforGeeks
|
Given a square matrix of size N*N, print the sum of upper and lower triangular elements. Upper Triangle consists of elements on the diagonal and above it. The lower triangle consists of elements on the diagonal and below it.
Example 1:
Input:
N = 3
mat[][] = {{6, 5, 4},
{1, 2, 5}
{7, 9, 7}}
Output: 29 32
Explanation:
The given matrix is
6 5 4
1 2 5
7 9 7
The elements of upper triangle are
6 5 4
2 5
7
Sum of these elements is 6+5+4+2+5+7=29
The elements of lower triangle are
6
1 2
7 9 7
Sum of these elements is 6+1+2+7+9+7= 32.
Example 2:
Input:
N = 2
mat[][] = {{1, 2},
{3, 4}}
Output: 7 8
Explanation:
Upper triangular matrix:
1 2
4
Sum of these elements are 7.
Lower triangular matrix:
1
3 4
Sum of these elements are 8.
Your Task:
You don't need to read input or print anything. Complete the function sumTriangles() that takes matrix and its size N as input parameters and returns the list of integers containing the sum of upper and lower triangle.
Expected Time Complexity: O(N * N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 100
1 <= matrix[i][j] <= 100
0
nikhilbarot16026 days ago
C++ Solution:
Time-Complexity: O (n * n) (0.05/1.05)
All test-cases passed
vector<int> sumTriangles(const vector<vector<int> >& matrix, int n)
{
vector<int> res;
int sum = 0;
for(int i = 0; i < n; i++){
for(int j = i; j < n; j++){
sum = sum + matrix[i][j];
}
}
res.push_back(sum);
sum = 0;
for(int i = n - 1; i >= 0; i--){
for(int j = i; j >= 0; j--){
sum = sum + matrix[i][j];
}
}
res.push_back(sum);
return res;
}
+1
sailendrachettri3 weeks ago
C++ Iterative approach
vector<int> sumTriangles(const vector<vector<int> >& matrix, int n)
{
int lower_t = 0;
int upper_t = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
lower_t += matrix[i][j];
// cout<<matrix[i][j]<<" ";
}
// cout<<endl;
}
for(int i = 0; i < n; i++){
for(int j = i; j < n; j++){
upper_t += matrix[i][j];
// cout<<matrix[i][j];
}
// cout<<endl;
}
return {upper_t, lower_t};
}
+1
kartikeyashokgautam1 month ago
Neat and Clean JAVA Solution :-
static ArrayList<Integer> sumTriangles(int matrix[][], int n) { int diaSum = 0; int lowSum = 0; int uppSum = 0; ArrayList<Integer> al = new ArrayList<>(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { // Diagonal Sum if(i==j) { diaSum+=matrix[i][j]; } // Lower Sum if(i>j) { lowSum+=matrix[i][j]; } // Upper Sum if(i<j) { uppSum+=matrix[i][j]; } } } al.add(uppSum+diaSum); al.add(lowSum+diaSum); return al; }
+1
kalyaniworkmail1 month ago
static ArrayList<Integer> sumTriangles(int matrix[][], int n) { // code here ArrayList<Integer> valList = new ArrayList<Integer>(); int sum1 = 0,sum2=0, diaSum = 0; for(int i=0;i<matrix.length;i++){ for(int j=i+1;j<matrix.length;j++){ sum1 = sum1 + matrix[i][j]; //sum of upper edges sum2 = sum2 + matrix[j][i]; //sum of lower edges } diaSum = diaSum + matrix[i][i]; //sum of diagonal } valList.add(sum1+diaSum); valList.add(sum2+diaSum); return valList; }
0
sachinsingh42231 month ago
vector<int> sumTriangles(const vector<vector<int> >& matrix, int n) { // code here vector<int>v;
int sum=0; for(int i=0;i<n;i++){ sum+=matrix[i][i]; } int U_sum=0; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ U_sum+=matrix[i][j]; } } U_sum+=sum; int D_sum=0; for(int i=n-1;i>=0;i--){ for(int j=i-1;j>=0;j--){ D_sum+=matrix[i][j]; } } D_sum+=sum; v.push_back(U_sum); v.push_back(D_sum); return v; }
0
pandasibasis741 month ago
vector<int> sumTriangles(const vector<vector<int> >& matrix, int n) { // code here vector<int> ans; int lowersum = 0; int uppersum = 0; for(int i=0;i<n;i++) { for(int j=0;j<=i;j++) { lowersum += matrix[i][j]; } } for(int i=0;i<n;i++) { for(int j=n-1;j>=i;j--) { uppersum += matrix[i][j]; } } ans.push_back(uppersum); ans.push_back(lowersum); return ans; }
0
moonu21032 months ago
Sum of upper and lower triangles (Java Solution)
class Solution
{
//Function to return sum of upper and lower triangles of a matrix.
static ArrayList<Integer> sumTriangles(int arr[][], int n)
{
// code here
int upperSum = 0, lowerSum = 0;
for (int i=0; i<n;i++)
{
for (int j=i; j<n; j++)
{
upperSum += arr[i][j];
lowerSum += arr[j][i];
}
}
ArrayList<Integer> res = new ArrayList<>();
res.add(upperSum);
res.add(lowerSum);
return res;
}
}
+1
sunghunet2 months ago
vector<int> sumTriangles(const vector<vector<int> >& matrix, int n)
{
// diag
int diagSum = 0;
for (int i = 0; i < n; i++) {
diagSum += matrix[i][i];
}
int lowerSum = 0, upperSum = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
upperSum += matrix[i][j];
lowerSum += matrix[j][i];
}
}
return vector<int>({ upperSum+ diagSum, lowerSum+ diagSum });
}
0
dsaconquered2 months ago
vector<int> sumTriangles(const vector<vector<int> >& matrix, int n) { // code here int uppersum=0; int lowersum=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j || i<j){ uppersum+=matrix[i][j]; } if(i==j || i>j){ lowersum+=matrix[i][j]; } } } vector<int>ans; ans.push_back(uppersum); ans.push_back(lowersum); return ans; }
0
imabheek2 months ago
/*JAVA*/ int sum_upper = 0, sum_lower = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(i <= j){sum_upper += matrix[i][j];} if(i >= j){sum_lower += matrix[i][j];} } } ArrayList<Integer> ls = new ArrayList<Integer>(); ls.add(sum_upper); ls.add(sum_lower); return ls;
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": 464,
"s": 226,
"text": "Given a square matrix of size N*N, print the sum of upper and lower triangular elements. Upper Triangle consists of elements on the diagonal and above it. The lower triangle consists of elements on the diagonal and below it. \n\nExample 1:"
},
{
"code": null,
"e": 790,
"s": 464,
"text": "Input:\nN = 3 \nmat[][] = {{6, 5, 4},\n {1, 2, 5}\n {7, 9, 7}}\nOutput: 29 32\nExplanation:\nThe given matrix is\n6 5 4\n1 2 5\n7 9 7\nThe elements of upper triangle are\n6 5 4\n 2 5\n 7\nSum of these elements is 6+5+4+2+5+7=29\nThe elements of lower triangle are\n6\n1 2\n7 9 7\nSum of these elements is 6+1+2+7+9+7= 32."
},
{
"code": null,
"e": 801,
"s": 790,
"text": "Example 2:"
},
{
"code": null,
"e": 1001,
"s": 801,
"text": "Input:\nN = 2\nmat[][] = {{1, 2},\n {3, 4}}\nOutput: 7 8\nExplanation:\nUpper triangular matrix:\n1 2\n 4\nSum of these elements are 7.\nLower triangular matrix:\n1\n3 4\nSum of these elements are 8.\n\n"
},
{
"code": null,
"e": 1353,
"s": 1001,
"text": "Your Task:\nYou don't need to read input or print anything. Complete the function sumTriangles() that takes matrix and its size N as input parameters and returns the list of integers containing the sum of upper and lower triangle. \n\nExpected Time Complexity: O(N * N)\nExpected Auxiliary Space: O(1)\n\nConstraints: \n1 <= N <= 100\n1 <= matrix[i][j] <= 100"
},
{
"code": null,
"e": 1355,
"s": 1353,
"text": "0"
},
{
"code": null,
"e": 1381,
"s": 1355,
"text": "nikhilbarot16026 days ago"
},
{
"code": null,
"e": 1395,
"s": 1381,
"text": "C++ Solution:"
},
{
"code": null,
"e": 1436,
"s": 1397,
"text": "Time-Complexity: O (n * n) (0.05/1.05)"
},
{
"code": null,
"e": 1458,
"s": 1436,
"text": "All test-cases passed"
},
{
"code": null,
"e": 2005,
"s": 1460,
"text": "vector<int> sumTriangles(const vector<vector<int> >& matrix, int n)\n {\n vector<int> res;\n int sum = 0;\n \n for(int i = 0; i < n; i++){\n for(int j = i; j < n; j++){\n sum = sum + matrix[i][j];\n }\n }\n res.push_back(sum);\n \n sum = 0;\n for(int i = n - 1; i >= 0; i--){\n for(int j = i; j >= 0; j--){\n sum = sum + matrix[i][j];\n }\n }\n res.push_back(sum);\n \n return res;\n \n }"
},
{
"code": null,
"e": 2008,
"s": 2005,
"text": "+1"
},
{
"code": null,
"e": 2036,
"s": 2008,
"text": "sailendrachettri3 weeks ago"
},
{
"code": null,
"e": 2059,
"s": 2036,
"text": "C++ Iterative approach"
},
{
"code": null,
"e": 2672,
"s": 2059,
"text": " vector<int> sumTriangles(const vector<vector<int> >& matrix, int n)\n {\n int lower_t = 0;\n int upper_t = 0;\n \n for(int i = 0; i < n; i++){\n for(int j = 0; j <= i; j++){\n lower_t += matrix[i][j];\n // cout<<matrix[i][j]<<\" \";\n }\n // cout<<endl;\n }\n \n for(int i = 0; i < n; i++){\n for(int j = i; j < n; j++){\n upper_t += matrix[i][j];\n // cout<<matrix[i][j];\n }\n // cout<<endl;\n }\n \n return {upper_t, lower_t};\n }"
},
{
"code": null,
"e": 2675,
"s": 2672,
"text": "+1"
},
{
"code": null,
"e": 2706,
"s": 2675,
"text": "kartikeyashokgautam1 month ago"
},
{
"code": null,
"e": 2738,
"s": 2706,
"text": "Neat and Clean JAVA Solution :-"
},
{
"code": null,
"e": 3383,
"s": 2740,
"text": "static ArrayList<Integer> sumTriangles(int matrix[][], int n) { int diaSum = 0; int lowSum = 0; int uppSum = 0; ArrayList<Integer> al = new ArrayList<>(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { // Diagonal Sum if(i==j) { diaSum+=matrix[i][j]; } // Lower Sum if(i>j) { lowSum+=matrix[i][j]; } // Upper Sum if(i<j) { uppSum+=matrix[i][j]; } } } al.add(uppSum+diaSum); al.add(lowSum+diaSum); return al; }"
},
{
"code": null,
"e": 3388,
"s": 3385,
"text": "+1"
},
{
"code": null,
"e": 3415,
"s": 3388,
"text": "kalyaniworkmail1 month ago"
},
{
"code": null,
"e": 3993,
"s": 3415,
"text": " static ArrayList<Integer> sumTriangles(int matrix[][], int n) { // code here ArrayList<Integer> valList = new ArrayList<Integer>(); int sum1 = 0,sum2=0, diaSum = 0; for(int i=0;i<matrix.length;i++){ for(int j=i+1;j<matrix.length;j++){ sum1 = sum1 + matrix[i][j]; //sum of upper edges sum2 = sum2 + matrix[j][i]; //sum of lower edges } diaSum = diaSum + matrix[i][i]; //sum of diagonal } valList.add(sum1+diaSum); valList.add(sum2+diaSum); return valList; }"
},
{
"code": null,
"e": 3995,
"s": 3993,
"text": "0"
},
{
"code": null,
"e": 4022,
"s": 3995,
"text": "sachinsingh42231 month ago"
},
{
"code": null,
"e": 4133,
"s": 4022,
"text": "vector<int> sumTriangles(const vector<vector<int> >& matrix, int n) { // code here vector<int>v;"
},
{
"code": null,
"e": 4620,
"s": 4133,
"text": " int sum=0; for(int i=0;i<n;i++){ sum+=matrix[i][i]; } int U_sum=0; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ U_sum+=matrix[i][j]; } } U_sum+=sum; int D_sum=0; for(int i=n-1;i>=0;i--){ for(int j=i-1;j>=0;j--){ D_sum+=matrix[i][j]; } } D_sum+=sum; v.push_back(U_sum); v.push_back(D_sum); return v; }"
},
{
"code": null,
"e": 4622,
"s": 4620,
"text": "0"
},
{
"code": null,
"e": 4648,
"s": 4622,
"text": "pandasibasis741 month ago"
},
{
"code": null,
"e": 5181,
"s": 4648,
"text": "vector<int> sumTriangles(const vector<vector<int> >& matrix, int n) { // code here vector<int> ans; int lowersum = 0; int uppersum = 0; for(int i=0;i<n;i++) { for(int j=0;j<=i;j++) { lowersum += matrix[i][j]; } } for(int i=0;i<n;i++) { for(int j=n-1;j>=i;j--) { uppersum += matrix[i][j]; } } ans.push_back(uppersum); ans.push_back(lowersum); return ans; }"
},
{
"code": null,
"e": 5183,
"s": 5181,
"text": "0"
},
{
"code": null,
"e": 5205,
"s": 5183,
"text": "moonu21032 months ago"
},
{
"code": null,
"e": 5254,
"s": 5205,
"text": "Sum of upper and lower triangles (Java Solution)"
},
{
"code": null,
"e": 5801,
"s": 5256,
"text": "class Solution\n{\n //Function to return sum of upper and lower triangles of a matrix.\n static ArrayList<Integer> sumTriangles(int arr[][], int n)\n {\n // code here\n int upperSum = 0, lowerSum = 0;\n for (int i=0; i<n;i++)\n {\n for (int j=i; j<n; j++)\n {\n upperSum += arr[i][j];\n lowerSum += arr[j][i];\n }\n }\n ArrayList<Integer> res = new ArrayList<>();\n res.add(upperSum);\n res.add(lowerSum);\n return res;\n }\n}"
},
{
"code": null,
"e": 5806,
"s": 5803,
"text": "+1"
},
{
"code": null,
"e": 5828,
"s": 5806,
"text": "sunghunet2 months ago"
},
{
"code": null,
"e": 6277,
"s": 5828,
"text": "vector<int> sumTriangles(const vector<vector<int> >& matrix, int n)\n{\n // diag\n int diagSum = 0;\n for (int i = 0; i < n; i++) {\n diagSum += matrix[i][i];\n }\n\n int lowerSum = 0, upperSum = 0;\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n upperSum += matrix[i][j];\n lowerSum += matrix[j][i];\n }\n }\n return vector<int>({ upperSum+ diagSum, lowerSum+ diagSum });\n}"
},
{
"code": null,
"e": 6279,
"s": 6277,
"text": "0"
},
{
"code": null,
"e": 6304,
"s": 6279,
"text": "dsaconquered2 months ago"
},
{
"code": null,
"e": 6818,
"s": 6304,
"text": " vector<int> sumTriangles(const vector<vector<int> >& matrix, int n) { // code here int uppersum=0; int lowersum=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j || i<j){ uppersum+=matrix[i][j]; } if(i==j || i>j){ lowersum+=matrix[i][j]; } } } vector<int>ans; ans.push_back(uppersum); ans.push_back(lowersum); return ans; }"
},
{
"code": null,
"e": 6820,
"s": 6818,
"text": "0"
},
{
"code": null,
"e": 6841,
"s": 6820,
"text": "imabheek2 months ago"
},
{
"code": null,
"e": 7184,
"s": 6841,
"text": "/*JAVA*/ int sum_upper = 0, sum_lower = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(i <= j){sum_upper += matrix[i][j];} if(i >= j){sum_lower += matrix[i][j];} } } ArrayList<Integer> ls = new ArrayList<Integer>(); ls.add(sum_upper); ls.add(sum_lower); return ls;"
},
{
"code": null,
"e": 7330,
"s": 7184,
"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": 7366,
"s": 7330,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7376,
"s": 7366,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7386,
"s": 7376,
"text": "\nContest\n"
},
{
"code": null,
"e": 7449,
"s": 7386,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7597,
"s": 7449,
"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": 7805,
"s": 7597,
"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": 7911,
"s": 7805,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Circular queues-Insertion and deletion operations in C++
|
A queue is an abstract data structure that contains a collection of elements. Queue implements the FIFO mechanism i.e the element that is inserted first is also deleted first.
Queue cane be one linear data structure. But it may create some problem if we implement queue using array. Sometimes by using some consecutive insert and delete operation, the front and rear position will change. In that moment, it will look like the queue has no space to insert elements into it. Even if there are some free spaces, that will not be used due to some logical problems. To overcome this problem, we will use the circular queue data structure.
A circular queue is a type of queue in which the last position is connected to the first position to make a circle.
insert(queue, key) −
begin
if front = 0 and rear = n – 1, or front = rear + 1, then queue is full, and return
otherwise
if front = -1, then front = 0 and rear = 0
else
if rear = n – 1, then, rear = 0, else rear := rear + 1
queue[rear] = key
end
delete(queue) −
begin
if front = -1 then queue is empty, and return
otherwise
item := queue[front]
if front = rear, then front and rear will be -1
else
if front = n – 1, then front := 0 else front := front + 1
end
#include <iostream>
using namespace std;
int cqueue[5];
int front = -1, rear = -1, n=5;
void insertCQ(int val) {
if ((front == 0 && rear == n-1) || (front == rear+1)) {
cout<<"Queue Overflow \n";
return;
}
if (front == -1) {
front = 0;
rear = 0;
}
else {
if (rear == n - 1)
rear = 0;
else
rear = rear + 1;
}
cqueue[rear] = val ;
}
void deleteCQ() {
if (front == -1) {
cout<<"Queue Underflow\n";
return ;
}
cout<<"Element deleted from queue is : "<<cqueue[front]<<endl;
if (front == rear) {
front = -1;
rear = -1;
}
else {
if (front == n - 1)
front = 0;
else
front = front + 1;
}
}
void displayCQ() {
int f = front, r = rear;
if (front == -1) {
cout<<"Queue is empty"<<endl;
return;
}
cout<<"Queue elements are :\n";
if (f <= r) {
while (f <= r){
cout<<cqueue[f]<<" ";
f++;
}
}
else {
while (f <= n - 1) {
cout<<cqueue[f]<<" ";
f++;
}
f = 0;
while (f <= r) {
cout<<cqueue[f]<<" ";
f++;
}
}
cout<<endl;
}
int main() {
int ch, val;
cout<<"1)Insert\n";
cout<<"2)Delete\n";
cout<<"3)Display\n";
cout<<"4)Exit\n";
do {
cout<<"Enter choice : "<<endl;
cin>>ch;
switch(ch) {
case 1:
cout<<"Input for insertion: "<<endl;
cin>>val;
insertCQ(val);
break;
case 2:
deleteCQ();
break;
case 3:
displayCQ();
break;
case 4:
cout<<"Exit\n";
break;
default: cout<<"Incorrect!\n";
}
} while(ch != 4);
return 0;
}
1)Insert
2)Delete
3)Display
4)Exit
Enter choice :
1
Input for insertion:
10
Enter choice :
1
Input for insertion:
20
Enter choice :
1
Input for insertion:
30
Enter choice :
1
Input for insertion:
40
Enter choice :
1
Input for insertion:
50
Enter choice :
3
Queue elements are :
10 20 30 40 50
Enter choice :
2
Element deleted from queue is : 10
Enter choice :
2
Element deleted from queue is : 20
Enter choice :
3
Queue elements are :
30 40 50
Enter choice :
4
Exit
|
[
{
"code": null,
"e": 1238,
"s": 1062,
"text": "A queue is an abstract data structure that contains a collection of elements. Queue implements the FIFO mechanism i.e the element that is inserted first is also deleted first."
},
{
"code": null,
"e": 1697,
"s": 1238,
"text": "Queue cane be one linear data structure. But it may create some problem if we implement queue using array. Sometimes by using some consecutive insert and delete operation, the front and rear position will change. In that moment, it will look like the queue has no space to insert elements into it. Even if there are some free spaces, that will not be used due to some logical problems. To overcome this problem, we will use the circular queue data structure."
},
{
"code": null,
"e": 1813,
"s": 1697,
"text": "A circular queue is a type of queue in which the last position is connected to the first position to make a circle."
},
{
"code": null,
"e": 1834,
"s": 1813,
"text": "insert(queue, key) −"
},
{
"code": null,
"e": 2079,
"s": 1834,
"text": "begin\n if front = 0 and rear = n – 1, or front = rear + 1, then queue is full, and return\n otherwise\n if front = -1, then front = 0 and rear = 0\n else\n if rear = n – 1, then, rear = 0, else rear := rear + 1\n queue[rear] = key\nend"
},
{
"code": null,
"e": 2095,
"s": 2079,
"text": "delete(queue) −"
},
{
"code": null,
"e": 2314,
"s": 2095,
"text": "begin\n if front = -1 then queue is empty, and return\n otherwise\n item := queue[front]\n if front = rear, then front and rear will be -1\n else\n if front = n – 1, then front := 0 else front := front + 1\nend"
},
{
"code": null,
"e": 4098,
"s": 2314,
"text": "#include <iostream>\nusing namespace std;\nint cqueue[5];\nint front = -1, rear = -1, n=5;\nvoid insertCQ(int val) {\n if ((front == 0 && rear == n-1) || (front == rear+1)) {\n cout<<\"Queue Overflow \\n\";\n return;\n }\n if (front == -1) {\n front = 0;\n rear = 0;\n }\n else {\n if (rear == n - 1)\n rear = 0;\n else\n rear = rear + 1;\n }\n cqueue[rear] = val ;\n}\nvoid deleteCQ() {\n if (front == -1) {\n cout<<\"Queue Underflow\\n\";\n return ;\n }\n cout<<\"Element deleted from queue is : \"<<cqueue[front]<<endl;\n if (front == rear) {\n front = -1;\n rear = -1;\n }\n else {\n if (front == n - 1)\n front = 0;\n else\n front = front + 1;\n }\n}\nvoid displayCQ() {\n int f = front, r = rear;\n if (front == -1) {\n cout<<\"Queue is empty\"<<endl;\n return;\n }\n cout<<\"Queue elements are :\\n\";\n if (f <= r) {\n while (f <= r){\n cout<<cqueue[f]<<\" \";\n f++;\n }\n }\n else {\n while (f <= n - 1) {\n cout<<cqueue[f]<<\" \";\n f++;\n }\n f = 0;\n while (f <= r) {\n cout<<cqueue[f]<<\" \";\n f++;\n }\n }\n cout<<endl;\n}\nint main() {\n int ch, val;\n cout<<\"1)Insert\\n\";\n cout<<\"2)Delete\\n\";\n cout<<\"3)Display\\n\";\n cout<<\"4)Exit\\n\";\n do {\n cout<<\"Enter choice : \"<<endl;\n cin>>ch;\n switch(ch) {\n case 1:\n cout<<\"Input for insertion: \"<<endl;\n cin>>val;\n insertCQ(val);\n break;\n case 2:\n deleteCQ();\n break;\n case 3:\n displayCQ();\n break;\n case 4:\n cout<<\"Exit\\n\";\n break;\n default: cout<<\"Incorrect!\\n\";\n }\n } while(ch != 4);\n return 0;\n}"
},
{
"code": null,
"e": 4564,
"s": 4098,
"text": "1)Insert\n2)Delete\n3)Display\n4)Exit\nEnter choice :\n1\nInput for insertion:\n10\nEnter choice :\n1\nInput for insertion:\n20\nEnter choice :\n1\nInput for insertion:\n30\nEnter choice :\n1\nInput for insertion:\n40\nEnter choice :\n1\nInput for insertion:\n50\nEnter choice :\n3\nQueue elements are :\n10 20 30 40 50\nEnter choice :\n2\nElement deleted from queue is : 10\nEnter choice :\n2\nElement deleted from queue is : 20\nEnter choice :\n3\nQueue elements are :\n30 40 50\nEnter choice :\n4\nExit"
}
] |
How to apply a tag to the azure resource group using PowerShell?
|
Like Azure VM, we can apply the azure tags to the resource group or any other resources. The tagging works on the resource ID and in azure, all the resources come with the resource ID property.
To apply the tag to the azure resource group, we first need to use get the resource group details to use its resource ID. The below code shows that how we can apply the new tag to the azure resource group.
PS C:\> $rg = Get-AzResourceGroup -Name AnsibleTestRG
PS C:\> $tag = @{Owner='Chirag'; CostCenter='USFinance'}
PS C:\> New-AZTag -ResourceId $rg.ResourceId -Tag $tag -Verbose
|
[
{
"code": null,
"e": 1256,
"s": 1062,
"text": "Like Azure VM, we can apply the azure tags to the resource group or any other resources. The tagging works on the resource ID and in azure, all the resources come with the resource ID property."
},
{
"code": null,
"e": 1462,
"s": 1256,
"text": "To apply the tag to the azure resource group, we first need to use get the resource group details to use its resource ID. The below code shows that how we can apply the new tag to the azure resource group."
},
{
"code": null,
"e": 1637,
"s": 1462,
"text": "PS C:\\> $rg = Get-AzResourceGroup -Name AnsibleTestRG\nPS C:\\> $tag = @{Owner='Chirag'; CostCenter='USFinance'}\nPS C:\\> New-AZTag -ResourceId $rg.ResourceId -Tag $tag -Verbose"
}
] |
close() - Unix, Linux System Call
|
Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
close - close a file descriptor
#include <unistd.h>
int close(int fd);
int close(int fd);
close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).
If fd is the last copy of a particular file descriptor the resources associated with it are freed; if the descriptor was the last reference to a file which has been removed using unlink(2) the file is deleted.
close() returns zero on success. On error, -1 is returned, and errno is set appropriately.
SVr4, 4.3BSD, POSIX.1-2001.
Not checking the return value of close() is a common but nevertheless serious programming error. It is quite possible that errors on a previous write(2)
operation are first reported at the final close(). Not checking the return value when closing the file may lead to silent loss of data. This can especially be observed with NFS
and with disk quota.
A successful close does not guarantee that the data has been successfully saved to disk, as the kernel defers writes. It is not common for a filesystem to flush the buffers when the stream is closed. If you need to be sure that the data is physically stored use
fsync(2). (It will depend on the disk hardware at this point.)
fcntl (2)
fcntl (2)
fsync (2)
fsync (2)
open (2)
open (2)
shutdown (2)
shutdown (2)
unlink (2)
unlink (2)
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1466,
"s": 1454,
"text": "Unix - Home"
},
{
"code": null,
"e": 1489,
"s": 1466,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1512,
"s": 1489,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1531,
"s": 1512,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1554,
"s": 1531,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1573,
"s": 1554,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1596,
"s": 1573,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1619,
"s": 1596,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1636,
"s": 1619,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1657,
"s": 1636,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1678,
"s": 1657,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1700,
"s": 1678,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1723,
"s": 1700,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1748,
"s": 1723,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1768,
"s": 1748,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1791,
"s": 1768,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1814,
"s": 1791,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1833,
"s": 1814,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1853,
"s": 1833,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 1880,
"s": 1853,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 1929,
"s": 1906,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 1952,
"s": 1929,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 1972,
"s": 1952,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 1999,
"s": 1972,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2025,
"s": 1999,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2052,
"s": 2025,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2078,
"s": 2052,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2125,
"s": 2100,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2148,
"s": 2125,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2167,
"s": 2148,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2192,
"s": 2167,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2212,
"s": 2192,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2233,
"s": 2212,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2255,
"s": 2233,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2273,
"s": 2255,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2284,
"s": 2273,
"text": "Who is Who"
},
{
"code": null,
"e": 2319,
"s": 2284,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2351,
"s": 2319,
"text": "close - close a file descriptor"
},
{
"code": null,
"e": 2394,
"s": 2351,
"text": "#include <unistd.h> \n\nint close(int fd); \n"
},
{
"code": null,
"e": 2416,
"s": 2394,
"text": "\nint close(int fd); \n"
},
{
"code": null,
"e": 2690,
"s": 2416,
"text": "close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock)."
},
{
"code": null,
"e": 2901,
"s": 2690,
"text": " If fd is the last copy of a particular file descriptor the resources associated with it are freed; if the descriptor was the last reference to a file which has been removed using unlink(2) the file is deleted."
},
{
"code": null,
"e": 2992,
"s": 2901,
"text": "close() returns zero on success. On error, -1 is returned, and errno is set appropriately."
},
{
"code": null,
"e": 3021,
"s": 2992,
"text": "SVr4, 4.3BSD, POSIX.1-2001. "
},
{
"code": null,
"e": 3376,
"s": 3021,
"text": "Not checking the return value of close() is a common but nevertheless serious programming error. It is quite possible that errors on a previous write(2)\noperation are first reported at the final close(). Not checking the return value when closing the file may lead to silent loss of data. This can especially be observed with NFS\nand with disk quota. "
},
{
"code": null,
"e": 3701,
"s": 3376,
"text": "A successful close does not guarantee that the data has been successfully saved to disk, as the kernel defers writes. It is not common for a filesystem to flush the buffers when the stream is closed. If you need to be sure that the data is physically stored use\nfsync(2). (It will depend on the disk hardware at this point.)"
},
{
"code": null,
"e": 3711,
"s": 3701,
"text": "fcntl (2)"
},
{
"code": null,
"e": 3721,
"s": 3711,
"text": "fcntl (2)"
},
{
"code": null,
"e": 3731,
"s": 3721,
"text": "fsync (2)"
},
{
"code": null,
"e": 3741,
"s": 3731,
"text": "fsync (2)"
},
{
"code": null,
"e": 3750,
"s": 3741,
"text": "open (2)"
},
{
"code": null,
"e": 3759,
"s": 3750,
"text": "open (2)"
},
{
"code": null,
"e": 3772,
"s": 3759,
"text": "shutdown (2)"
},
{
"code": null,
"e": 3785,
"s": 3772,
"text": "shutdown (2)"
},
{
"code": null,
"e": 3796,
"s": 3785,
"text": "unlink (2)"
},
{
"code": null,
"e": 3807,
"s": 3796,
"text": "unlink (2)"
},
{
"code": null,
"e": 3824,
"s": 3807,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 3859,
"s": 3824,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 3887,
"s": 3859,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3921,
"s": 3887,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3938,
"s": 3921,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3971,
"s": 3938,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3982,
"s": 3971,
"text": " Pradeep D"
},
{
"code": null,
"e": 4017,
"s": 3982,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4033,
"s": 4017,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 4066,
"s": 4033,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4078,
"s": 4066,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 4110,
"s": 4078,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4118,
"s": 4110,
"text": " Uplatz"
},
{
"code": null,
"e": 4125,
"s": 4118,
"text": " Print"
},
{
"code": null,
"e": 4136,
"s": 4125,
"text": " Add Notes"
}
] |
Spring - Logging with Log4J
|
This is a very easy-to-use Log4J functionality inside Spring applications. The following example will take you through simple steps to explain the simple integration between Log4J and Spring.
We assume you already have log4J installed on your machine. If you do not have it then you can download it from https://logging.apache.org/ and simply extract the zipped file in any folder. We will use only log4j-x.y.z.jar in our project.
Next, let us have a working Eclipse IDE in place and take the following steps to develop a Dynamic Form-based Web Application using Spring Web Framework −
Here is the content of HelloWorld.java file
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage() {
System.out.println("Your Message : " + message);
}
}
Following is the content of the second file MainApp.java
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.apache.log4j.Logger;
public class MainApp {
static Logger log = Logger.getLogger(MainApp.class.getName());
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
log.info("Going to create HelloWord Obj");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
log.info("Exiting the program");
}
}
You can generate debug and error message in a similar way as we have generated info messages. Now let us see the content of Beans.xml file
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
Following is the content of log4j.properties which defines the standard rules required for Log4J to produce log messages
# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Set the name of the file
log4j.appender.FILE.File=C:\\log.out
# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true
# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug
# Set the append to false, overwrite
log4j.appender.FILE.Append=false
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message in Eclipse console −
Your Message : Hello World!
If you check your C:\\ drive, then you should find your log file log.out with various log messages, like something as follows −
<!-- initialization log messages -->
Going to create HelloWord Obj
Returning cached instance of singleton bean 'helloWorld'
Exiting the program
Alternatively you can use Jakarta Commons Logging (JCL) API to generate a log in your Spring application. JCL can be downloaded from the https://jakarta.apache.org/commons/logging/. The only file we technically need out of this package is the commons-logging-x.y.z.jar file, which needs to be placed in your classpath in a similar way as you had put log4j-x.y.z.jar in the above example.
To use the logging functionality you need a org.apache.commons.logging.Log object and then you can call one of the following methods as per your requirment −
fatal(Object message)
error(Object message)
warn(Object message)
info(Object message)
debug(Object message)
trace(Object message)
Following is the replacement of MainApp.java, which makes use of JCL API
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.apache.commons.logging. Log;
import org.apache.commons.logging. LogFactory;
public class MainApp {
static Log log = LogFactory.getLog(MainApp.class.getName());
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
log.info("Going to create HelloWord Obj");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
log.info("Exiting the program");
}
}
You have to make sure that you have included commons-logging-x.y.z.jar file in your project, before compiling and running the program.
Now keeping the rest of the configuration and content unchanged in the above example, if you compile and run your application, you will get a similar result as what you got using Log4J API.
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2484,
"s": 2292,
"text": "This is a very easy-to-use Log4J functionality inside Spring applications. The following example will take you through simple steps to explain the simple integration between Log4J and Spring."
},
{
"code": null,
"e": 2723,
"s": 2484,
"text": "We assume you already have log4J installed on your machine. If you do not have it then you can download it from https://logging.apache.org/ and simply extract the zipped file in any folder. We will use only log4j-x.y.z.jar in our project."
},
{
"code": null,
"e": 2878,
"s": 2723,
"text": "Next, let us have a working Eclipse IDE in place and take the following steps to develop a Dynamic Form-based Web Application using Spring Web Framework −"
},
{
"code": null,
"e": 2922,
"s": 2878,
"text": "Here is the content of HelloWorld.java file"
},
{
"code": null,
"e": 3179,
"s": 2922,
"text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message;\n \n public void setMessage(String message){\n this.message = message;\n }\n public void getMessage() {\n System.out.println(\"Your Message : \" + message);\n }\n}"
},
{
"code": null,
"e": 3236,
"s": 3179,
"text": "Following is the content of the second file MainApp.java"
},
{
"code": null,
"e": 3842,
"s": 3236,
"text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport org.apache.log4j.Logger;\n\npublic class MainApp {\n static Logger log = Logger.getLogger(MainApp.class.getName());\n \n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n log.info(\"Going to create HelloWord Obj\");\n HelloWorld obj = (HelloWorld) context.getBean(\"helloWorld\");\n obj.getMessage();\n \n log.info(\"Exiting the program\");\n }\n}"
},
{
"code": null,
"e": 3981,
"s": 3842,
"text": "You can generate debug and error message in a similar way as we have generated info messages. Now let us see the content of Beans.xml file"
},
{
"code": null,
"e": 4432,
"s": 3981,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\">\n <property name = \"message\" value = \"Hello World!\"/>\n </bean>\n\n</beans>"
},
{
"code": null,
"e": 4553,
"s": 4432,
"text": "Following is the content of log4j.properties which defines the standard rules required for Log4J to produce log messages"
},
{
"code": null,
"e": 5144,
"s": 4553,
"text": "# Define the root logger with appender file\nlog4j.rootLogger = DEBUG, FILE\n\n# Define the file appender\nlog4j.appender.FILE=org.apache.log4j.FileAppender\n# Set the name of the file\nlog4j.appender.FILE.File=C:\\\\log.out\n\n# Set the immediate flush to true (default)\nlog4j.appender.FILE.ImmediateFlush=true\n\n# Set the threshold to debug mode\nlog4j.appender.FILE.Threshold=debug\n\n# Set the append to false, overwrite\nlog4j.appender.FILE.Append=false\n\n# Define the layout for file appender\nlog4j.appender.FILE.layout=org.apache.log4j.PatternLayout\nlog4j.appender.FILE.layout.conversionPattern=%m%n"
},
{
"code": null,
"e": 5345,
"s": 5144,
"text": "Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message in Eclipse console −"
},
{
"code": null,
"e": 5374,
"s": 5345,
"text": "Your Message : Hello World!\n"
},
{
"code": null,
"e": 5502,
"s": 5374,
"text": "If you check your C:\\\\ drive, then you should find your log file log.out with various log messages, like something as follows −"
},
{
"code": null,
"e": 5648,
"s": 5502,
"text": "<!-- initialization log messages -->\n\nGoing to create HelloWord Obj\nReturning cached instance of singleton bean 'helloWorld'\nExiting the program\n"
},
{
"code": null,
"e": 6037,
"s": 5648,
"text": "Alternatively you can use Jakarta Commons Logging (JCL) API to generate a log in your Spring application. JCL can be downloaded from the https://jakarta.apache.org/commons/logging/. The only file we technically need out of this package is the commons-logging-x.y.z.jar file, which needs to be placed in your classpath in a similar way as you had put log4j-x.y.z.jar in the above example."
},
{
"code": null,
"e": 6195,
"s": 6037,
"text": "To use the logging functionality you need a org.apache.commons.logging.Log object and then you can call one of the following methods as per your requirment −"
},
{
"code": null,
"e": 6217,
"s": 6195,
"text": "fatal(Object message)"
},
{
"code": null,
"e": 6239,
"s": 6217,
"text": "error(Object message)"
},
{
"code": null,
"e": 6260,
"s": 6239,
"text": "warn(Object message)"
},
{
"code": null,
"e": 6281,
"s": 6260,
"text": "info(Object message)"
},
{
"code": null,
"e": 6303,
"s": 6281,
"text": "debug(Object message)"
},
{
"code": null,
"e": 6325,
"s": 6303,
"text": "trace(Object message)"
},
{
"code": null,
"e": 6398,
"s": 6325,
"text": "Following is the replacement of MainApp.java, which makes use of JCL API"
},
{
"code": null,
"e": 7048,
"s": 6398,
"text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport org.apache.commons.logging. Log;\nimport org.apache.commons.logging. LogFactory;\n\npublic class MainApp {\n static Log log = LogFactory.getLog(MainApp.class.getName());\n\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n log.info(\"Going to create HelloWord Obj\");\n HelloWorld obj = (HelloWorld) context.getBean(\"helloWorld\");\n obj.getMessage();\n\n log.info(\"Exiting the program\");\n }\n}"
},
{
"code": null,
"e": 7183,
"s": 7048,
"text": "You have to make sure that you have included commons-logging-x.y.z.jar file in your project, before compiling and running the program."
},
{
"code": null,
"e": 7373,
"s": 7183,
"text": "Now keeping the rest of the configuration and content unchanged in the above example, if you compile and run your application, you will get a similar result as what you got using Log4J API."
},
{
"code": null,
"e": 7407,
"s": 7373,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 7421,
"s": 7407,
"text": " Karthikeya T"
},
{
"code": null,
"e": 7454,
"s": 7421,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7469,
"s": 7454,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 7504,
"s": 7469,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7516,
"s": 7504,
"text": " Senol Atac"
},
{
"code": null,
"e": 7551,
"s": 7516,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7563,
"s": 7551,
"text": " Senol Atac"
},
{
"code": null,
"e": 7598,
"s": 7563,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7610,
"s": 7598,
"text": " Senol Atac"
},
{
"code": null,
"e": 7643,
"s": 7610,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7655,
"s": 7643,
"text": " Senol Atac"
},
{
"code": null,
"e": 7662,
"s": 7655,
"text": " Print"
},
{
"code": null,
"e": 7673,
"s": 7662,
"text": " Add Notes"
}
] |
Django - Sitemap Framework - GeeksforGeeks
|
04 Jul, 2021
Prerequisites: Django Introduction and Installation
Search-Engines crawls and indexes the site’s URLs to show them in their search results. Search-Engines recommend the explicit submission of an XML file consisting of all the important and updated URLs of your site for faster crawling and indexing. Django comes up with a Sitemap Framework to ease out the process of generating the XML file and pinging the search engines to crawl.
Let’s understand the sitemap creation using Geeks For Geeks as an example. Suppose 100 articles are published each day on Geeks For Geeks, and we have to create an XML file consisting of the URLs of those articles.
Follow Django Introduction and Installation to set up a virtual environment and install Django.
Step 1: Start a project by following command
django-admin startproject geeks_site
Step 2: Change directory to geeks_site
cd geeks_site
Step 3: Create an app named blog
python manage.py startapp blog
Step 4: Add your app to the settings.py
Python3
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog.apps.BlogConfig',]
Step 5: Create a Model named Article in the blog app
Fields :title: To store the titles of the Article objectslastedit_date: To store the last updated dates of Article objects
title: To store the titles of the Article objects
lastedit_date: To store the last updated dates of Article objects
Method :get_absolute_url: Returns the absolute URL pointing to an object
get_absolute_url: Returns the absolute URL pointing to an object
models.py
Python3
class Article(models.Model): title = models.CharField(max_length=200) lastedit_date = models.DateTimeField() def get_absolute_url(self): return "/p/%i/" % self.id
Step 6: Register your model in blog/admin.py so that it shows up in the admin panel.
admin.py
Python3
# blog/admin.pyfrom django.contrib import admin from .models import Article admin.site.register(Article)
Step 7: Now, To migrate all your changes and start the server, run the following commands in your terminal
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Create a superuser account to log in to the admin panel
python manage.py createsuperuser
Now, Visit the admin panel at http://127.0.0.1:8000/admin/
Now, Let’s Install and Initialize the Django’s Sitemap Framework
To use the Sitemap Framework, you will need to make the following changes to your settings.py :
Sitemap Framework is not enabled by default in Django, so add the following to INSTALLED_APPS
django.contrib.sitemaps
Sitemap Framework uses another Django’s inbuilt Sites Framework for it’s functioning. Also, add the following to INSTALLED_APPS
django.contrib.sites
Then add the following after the INSTALLED_APPS list
SITE_ID = 1
Python3
# Application definitionINSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps, 'blog'] SITE_ID = 1
Step 1: Create a file named sitemap.py in your blog app
Step 2: Create a Sitemap class for your Article Model in sitemap.py
ArticleSitemap class overwrites the following two methods of Sitemap classitems: returns all the article objects, whose URLs will be included in XML filelastmod: returns the last modified date of an object using the lastedit_date field of Article Model in blog app
items: returns all the article objects, whose URLs will be included in XML file
lastmod: returns the last modified date of an object using the lastedit_date field of Article Model in blog app
sitemap.py
Python3
from django.contrib.sitemaps import Sitemapfrom .models import Article class ArticleSitemap(Sitemap): def items(self): return Article.objects.all() def lastmod(self, obj): return obj.lastedit_date
Step 3: Add these lines to your blog/urls.py.
Python3
from django.contrib.sitemaps.views import sitemapfrom blog.sitemap import ArticleSitemapfrom django.urls import path path('sitemap.xml', sitemap, {'sitemaps': {'article' : ArticleSitemap}}, name='django.contrib.sitemaps.views.sitemap')
Here ‘sitemap.xml‘ points to the sitemap view of the Sitemap Framework’s with ArticleSitemap class created in the previous step as required parameter in the specified format, i.e. {‘sitemaps’: {‘article’ : ArticleSitemap}
Now, again migrate all your changes and start the server
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Step 4: In the Article section, create some Articles. After clicking the add button you will see the below fields.
when you will click the Sites section you will something like this
Make the following changes to Sites section of Admin Panel
Now visit at http://127.0.0.1:8000/sitemap.xml in your local machine. The final XML file consisting of all URLs will be rendered as :
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 23954,
"s": 23901,
"text": "Prerequisites: Django Introduction and Installation "
},
{
"code": null,
"e": 24336,
"s": 23954,
"text": "Search-Engines crawls and indexes the site’s URLs to show them in their search results. Search-Engines recommend the explicit submission of an XML file consisting of all the important and updated URLs of your site for faster crawling and indexing. Django comes up with a Sitemap Framework to ease out the process of generating the XML file and pinging the search engines to crawl. "
},
{
"code": null,
"e": 24551,
"s": 24336,
"text": "Let’s understand the sitemap creation using Geeks For Geeks as an example. Suppose 100 articles are published each day on Geeks For Geeks, and we have to create an XML file consisting of the URLs of those articles."
},
{
"code": null,
"e": 24648,
"s": 24551,
"text": "Follow Django Introduction and Installation to set up a virtual environment and install Django."
},
{
"code": null,
"e": 24693,
"s": 24648,
"text": "Step 1: Start a project by following command"
},
{
"code": null,
"e": 24730,
"s": 24693,
"text": "django-admin startproject geeks_site"
},
{
"code": null,
"e": 24769,
"s": 24730,
"text": "Step 2: Change directory to geeks_site"
},
{
"code": null,
"e": 24783,
"s": 24769,
"text": "cd geeks_site"
},
{
"code": null,
"e": 24816,
"s": 24783,
"text": "Step 3: Create an app named blog"
},
{
"code": null,
"e": 24847,
"s": 24816,
"text": "python manage.py startapp blog"
},
{
"code": null,
"e": 24887,
"s": 24847,
"text": "Step 4: Add your app to the settings.py"
},
{
"code": null,
"e": 24895,
"s": 24887,
"text": "Python3"
},
{
"code": "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog.apps.BlogConfig',]",
"e": 25122,
"s": 24895,
"text": null
},
{
"code": null,
"e": 25175,
"s": 25122,
"text": "Step 5: Create a Model named Article in the blog app"
},
{
"code": null,
"e": 25298,
"s": 25175,
"text": "Fields :title: To store the titles of the Article objectslastedit_date: To store the last updated dates of Article objects"
},
{
"code": null,
"e": 25348,
"s": 25298,
"text": "title: To store the titles of the Article objects"
},
{
"code": null,
"e": 25414,
"s": 25348,
"text": "lastedit_date: To store the last updated dates of Article objects"
},
{
"code": null,
"e": 25487,
"s": 25414,
"text": "Method :get_absolute_url: Returns the absolute URL pointing to an object"
},
{
"code": null,
"e": 25552,
"s": 25487,
"text": "get_absolute_url: Returns the absolute URL pointing to an object"
},
{
"code": null,
"e": 25562,
"s": 25552,
"text": "models.py"
},
{
"code": null,
"e": 25570,
"s": 25562,
"text": "Python3"
},
{
"code": "class Article(models.Model): title = models.CharField(max_length=200) lastedit_date = models.DateTimeField() def get_absolute_url(self): return \"/p/%i/\" % self.id",
"e": 25751,
"s": 25570,
"text": null
},
{
"code": null,
"e": 25836,
"s": 25751,
"text": "Step 6: Register your model in blog/admin.py so that it shows up in the admin panel."
},
{
"code": null,
"e": 25845,
"s": 25836,
"text": "admin.py"
},
{
"code": null,
"e": 25853,
"s": 25845,
"text": "Python3"
},
{
"code": "# blog/admin.pyfrom django.contrib import admin from .models import Article admin.site.register(Article)",
"e": 25959,
"s": 25853,
"text": null
},
{
"code": null,
"e": 26067,
"s": 25959,
"text": "Step 7: Now, To migrate all your changes and start the server, run the following commands in your terminal "
},
{
"code": null,
"e": 26151,
"s": 26067,
"text": "python manage.py makemigrations\npython manage.py migrate\npython manage.py runserver"
},
{
"code": null,
"e": 26207,
"s": 26151,
"text": "Create a superuser account to log in to the admin panel"
},
{
"code": null,
"e": 26240,
"s": 26207,
"text": "python manage.py createsuperuser"
},
{
"code": null,
"e": 26299,
"s": 26240,
"text": "Now, Visit the admin panel at http://127.0.0.1:8000/admin/"
},
{
"code": null,
"e": 26364,
"s": 26299,
"text": "Now, Let’s Install and Initialize the Django’s Sitemap Framework"
},
{
"code": null,
"e": 26460,
"s": 26364,
"text": "To use the Sitemap Framework, you will need to make the following changes to your settings.py :"
},
{
"code": null,
"e": 26554,
"s": 26460,
"text": "Sitemap Framework is not enabled by default in Django, so add the following to INSTALLED_APPS"
},
{
"code": null,
"e": 26578,
"s": 26554,
"text": "django.contrib.sitemaps"
},
{
"code": null,
"e": 26706,
"s": 26578,
"text": "Sitemap Framework uses another Django’s inbuilt Sites Framework for it’s functioning. Also, add the following to INSTALLED_APPS"
},
{
"code": null,
"e": 26727,
"s": 26706,
"text": "django.contrib.sites"
},
{
"code": null,
"e": 26780,
"s": 26727,
"text": "Then add the following after the INSTALLED_APPS list"
},
{
"code": null,
"e": 26792,
"s": 26780,
"text": "SITE_ID = 1"
},
{
"code": null,
"e": 26800,
"s": 26792,
"text": "Python3"
},
{
"code": "# Application definitionINSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps, 'blog'] SITE_ID = 1",
"e": 27105,
"s": 26800,
"text": null
},
{
"code": null,
"e": 27161,
"s": 27105,
"text": "Step 1: Create a file named sitemap.py in your blog app"
},
{
"code": null,
"e": 27229,
"s": 27161,
"text": "Step 2: Create a Sitemap class for your Article Model in sitemap.py"
},
{
"code": null,
"e": 27494,
"s": 27229,
"text": "ArticleSitemap class overwrites the following two methods of Sitemap classitems: returns all the article objects, whose URLs will be included in XML filelastmod: returns the last modified date of an object using the lastedit_date field of Article Model in blog app"
},
{
"code": null,
"e": 27574,
"s": 27494,
"text": "items: returns all the article objects, whose URLs will be included in XML file"
},
{
"code": null,
"e": 27686,
"s": 27574,
"text": "lastmod: returns the last modified date of an object using the lastedit_date field of Article Model in blog app"
},
{
"code": null,
"e": 27697,
"s": 27686,
"text": "sitemap.py"
},
{
"code": null,
"e": 27705,
"s": 27697,
"text": "Python3"
},
{
"code": "from django.contrib.sitemaps import Sitemapfrom .models import Article class ArticleSitemap(Sitemap): def items(self): return Article.objects.all() def lastmod(self, obj): return obj.lastedit_date",
"e": 27931,
"s": 27705,
"text": null
},
{
"code": null,
"e": 27977,
"s": 27931,
"text": "Step 3: Add these lines to your blog/urls.py."
},
{
"code": null,
"e": 27985,
"s": 27977,
"text": "Python3"
},
{
"code": "from django.contrib.sitemaps.views import sitemapfrom blog.sitemap import ArticleSitemapfrom django.urls import path path('sitemap.xml', sitemap, {'sitemaps': {'article' : ArticleSitemap}}, name='django.contrib.sitemaps.views.sitemap')",
"e": 28228,
"s": 27985,
"text": null
},
{
"code": null,
"e": 28450,
"s": 28228,
"text": "Here ‘sitemap.xml‘ points to the sitemap view of the Sitemap Framework’s with ArticleSitemap class created in the previous step as required parameter in the specified format, i.e. {‘sitemaps’: {‘article’ : ArticleSitemap}"
},
{
"code": null,
"e": 28507,
"s": 28450,
"text": "Now, again migrate all your changes and start the server"
},
{
"code": null,
"e": 28591,
"s": 28507,
"text": "python manage.py makemigrations\npython manage.py migrate\npython manage.py runserver"
},
{
"code": null,
"e": 28707,
"s": 28591,
"text": "Step 4: In the Article section, create some Articles. After clicking the add button you will see the below fields. "
},
{
"code": null,
"e": 28774,
"s": 28707,
"text": "when you will click the Sites section you will something like this"
},
{
"code": null,
"e": 28833,
"s": 28774,
"text": "Make the following changes to Sites section of Admin Panel"
},
{
"code": null,
"e": 28967,
"s": 28833,
"text": "Now visit at http://127.0.0.1:8000/sitemap.xml in your local machine. The final XML file consisting of all URLs will be rendered as :"
},
{
"code": null,
"e": 28981,
"s": 28967,
"text": "Python Django"
},
{
"code": null,
"e": 28988,
"s": 28981,
"text": "Python"
},
{
"code": null,
"e": 29086,
"s": 28988,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29095,
"s": 29086,
"text": "Comments"
},
{
"code": null,
"e": 29108,
"s": 29095,
"text": "Old Comments"
},
{
"code": null,
"e": 29140,
"s": 29108,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29196,
"s": 29140,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29238,
"s": 29196,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29280,
"s": 29238,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29316,
"s": 29280,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 29355,
"s": 29316,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29377,
"s": 29355,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29408,
"s": 29377,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29435,
"s": 29408,
"text": "Python Classes and Objects"
}
] |
Program to find maximum product of contiguous subarray in Python
|
Suppose we have an array called nums, we have to find the product of elements of a contiguous subarray within an array (containing at least one number) which has the largest
product. So if the array is [1,9,2,0,2,5], the output will be 18, as contiguous subarray [1,9,2] has max product.
To solve this, we will follow these steps −
max_list := list of size nums, and fill with 0
min_list := list of size nums, and fill with 0
min_list := list of size nums, and fill with 0
for i in range 1 to length of numsmax_list[i] = max of max_list[i - 1]*nums[i], min_list[i - 1]*nums[i] and nums[i]min_list[i] = minof min_list[i - 1]*nums[i], nums[i], max_list[i - 1]*nums[i]
max_list[i] = max of max_list[i - 1]*nums[i], min_list[i - 1]*nums[i] and nums[i]
min_list[i] = minof min_list[i - 1]*nums[i], nums[i], max_list[i - 1]*nums[i]
return the max of max_list
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def maxProduct(self, nums):
max_list = [0] * len(nums)
min_list = [0] * len(nums)
max_list[0] = nums[0]
min_list[0] = nums[0]
for i in range(1,len(nums)):
max_list[i] = max(max(max_list[i-1]*nums[i],min_list[i-1]*nums[i]),nums[i])
min_list[i] = min(min(min_list[i-1]*nums[i],nums[i]),max_list[i-1]*nums[i])
return max(max_list)
ob1 = Solution()
print(ob1.maxProduct([1,9,2,0,2,5]))
[1,9,2,0,2,5]
18
|
[
{
"code": null,
"e": 1350,
"s": 1062,
"text": "Suppose we have an array called nums, we have to find the product of elements of a contiguous subarray within an array (containing at least one number) which has the largest\nproduct. So if the array is [1,9,2,0,2,5], the output will be 18, as contiguous subarray [1,9,2] has max product."
},
{
"code": null,
"e": 1394,
"s": 1350,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1441,
"s": 1394,
"text": "max_list := list of size nums, and fill with 0"
},
{
"code": null,
"e": 1488,
"s": 1441,
"text": "min_list := list of size nums, and fill with 0"
},
{
"code": null,
"e": 1535,
"s": 1488,
"text": "min_list := list of size nums, and fill with 0"
},
{
"code": null,
"e": 1728,
"s": 1535,
"text": "for i in range 1 to length of numsmax_list[i] = max of max_list[i - 1]*nums[i], min_list[i - 1]*nums[i] and nums[i]min_list[i] = minof min_list[i - 1]*nums[i], nums[i], max_list[i - 1]*nums[i]"
},
{
"code": null,
"e": 1810,
"s": 1728,
"text": "max_list[i] = max of max_list[i - 1]*nums[i], min_list[i - 1]*nums[i] and nums[i]"
},
{
"code": null,
"e": 1888,
"s": 1810,
"text": "min_list[i] = minof min_list[i - 1]*nums[i], nums[i], max_list[i - 1]*nums[i]"
},
{
"code": null,
"e": 1915,
"s": 1888,
"text": "return the max of max_list"
},
{
"code": null,
"e": 1985,
"s": 1915,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1996,
"s": 1985,
"text": " Live Demo"
},
{
"code": null,
"e": 2459,
"s": 1996,
"text": "class Solution(object):\n def maxProduct(self, nums):\n max_list = [0] * len(nums)\n min_list = [0] * len(nums)\n max_list[0] = nums[0]\n min_list[0] = nums[0]\n for i in range(1,len(nums)):\n max_list[i] = max(max(max_list[i-1]*nums[i],min_list[i-1]*nums[i]),nums[i])\n min_list[i] = min(min(min_list[i-1]*nums[i],nums[i]),max_list[i-1]*nums[i])\n return max(max_list)\nob1 = Solution()\nprint(ob1.maxProduct([1,9,2,0,2,5]))"
},
{
"code": null,
"e": 2473,
"s": 2459,
"text": "[1,9,2,0,2,5]"
},
{
"code": null,
"e": 2476,
"s": 2473,
"text": "18"
}
] |
Tips for Data Mapping and Replacing with Pandas and NumPy | by Chi Nguyen | Towards Data Science
|
In order to summarize main characteristics, spot anomalies, and visualize information, you should know how to rearrange and transform datasets. In other words, transforming data helps you play with your dataset, make sense of it, and gather as many insights as you can. In this article, I will show you some of my commonly used methods to play with data, and hope this would be helpful.
I will create a simple score dataset, which includes information about different classes’ grades.
Input: info = {'Class':['A1', 'A2', 'A3', 'A4','A5'], 'AverageScore':[3.2, 3.3, 2.1, 2.9, 'three']}data = pd.DataFrame(info)
Output:
As the Average Score of Class A5 in our data is a string object, I want to replace it with a corresponding number for easier data manipulation. The procedure to replace “three” with “3” is as following:
Input:data['AverageScore'] = data['AverageScore'].replace(['three'],'3')data['AverageScore'] = data['AverageScore'].astype('float')
Above is a simple case of replacing a value with another value in a specific column. For more reference, below are some more examples:
If you want to replace multiple values with multiple new values for a specific column, use this:
data['column name'] = data['column name'].replace(['1st old value','2nd old value',...],['1st new value','2nd new value',...])
In case you want to replace multiple values with a new value for a specific column:
data['column name'] = data['column name'].replace(['1st old value','2nd old value',...],'new value')
Suppose I want to add a column evaluating if the grade is good or bad, I will write down a mapping of each grade to the kind of corresponding assessment comment. This can be done in 4 different ways by using bins, pandas cut()function, np.digitize()function, np.select()or your own function with if . Let’s see how I am dealing with each method.
You only need to define your limits and category names, then apply them to a numeric column using pandas.cut(). In this case, I will define three intervals, which correspond to four bin limits, to evaluate each class’s score. In details:
0 < AverageScore ≤2: Below average
2 < AverageScore ≤ 3.1: Average
3.1 < AverageScore ≤5: Good
Input:bins = [0, 2, 3.1, 5]comment = ['Below Average', 'Average', 'Good']data['Evaluation'] = pd.cut(data['AverageScore'], bins, labels=comment)
Output:
The idea of Numpy.digitize() is to get the indices of the bins to which each value belongs. Similarly in this case, you can also define your bin boundaries and category names like the case with pd.cut(). What difference is to create an additional dictionary and use that dictionary to map the category names.
Input:bins = [0, 2, 3.1, 5]comment = ['Below Average', 'Average', 'Good']dictionary = dict(enumerate(comment, 1))data['Evaluation2'] = np.vectorize(dictionary.get)(np.digitize(data['AverageScore'], bins))
Output:
Numpy.select(condition list, choice list)method returns an array drawn from elements in choice list , depending on condition in the list. Therefore, we can easily obtain the desired values by stating the evaluation conditions, which are three intervals with limitation, and the corresponding choice list values. See the code below for reference.
Input:evaluate = [data['AverageScore'].between(0,2), data['AverageScore'].between(2,3.1), data['AverageScore'].between(3.1,5)]values = ['Below Average', 'Average', 'Good']data['Evaluate3'] = np.select(evaluate, values, 0)
Output:
You can even write your own function to apply. The logic is actually quite simple, as you can see:
Input: def evaluate(values): if values >=0 and values <=2: return 'Below Average' elif values >2 and values <= 3.1: return 'Average' else: return 'Good'#Applying functiondata['Evaluation4'] = data['AverageScore'].apply(lambda x: evaluate(x))
Output:
As you can see, all of the four solutions produce the same results. I just want to provide you with different approaches to this problem so that in the future you can apply these data manipulation flexibly in different scenarios.
Above are some of my tips for mapping and replacing data. What I want to convey here is, in some cases when you do exploratory data analysis, you may have to deal with multiple unexpected situations, therefore it’s useful to solve problem with more than one approach. Hope that my article can help you out someday. Good luck!
|
[
{
"code": null,
"e": 559,
"s": 172,
"text": "In order to summarize main characteristics, spot anomalies, and visualize information, you should know how to rearrange and transform datasets. In other words, transforming data helps you play with your dataset, make sense of it, and gather as many insights as you can. In this article, I will show you some of my commonly used methods to play with data, and hope this would be helpful."
},
{
"code": null,
"e": 657,
"s": 559,
"text": "I will create a simple score dataset, which includes information about different classes’ grades."
},
{
"code": null,
"e": 789,
"s": 657,
"text": "Input: info = {'Class':['A1', 'A2', 'A3', 'A4','A5'], 'AverageScore':[3.2, 3.3, 2.1, 2.9, 'three']}data = pd.DataFrame(info)"
},
{
"code": null,
"e": 797,
"s": 789,
"text": "Output:"
},
{
"code": null,
"e": 1000,
"s": 797,
"text": "As the Average Score of Class A5 in our data is a string object, I want to replace it with a corresponding number for easier data manipulation. The procedure to replace “three” with “3” is as following:"
},
{
"code": null,
"e": 1132,
"s": 1000,
"text": "Input:data['AverageScore'] = data['AverageScore'].replace(['three'],'3')data['AverageScore'] = data['AverageScore'].astype('float')"
},
{
"code": null,
"e": 1267,
"s": 1132,
"text": "Above is a simple case of replacing a value with another value in a specific column. For more reference, below are some more examples:"
},
{
"code": null,
"e": 1364,
"s": 1267,
"text": "If you want to replace multiple values with multiple new values for a specific column, use this:"
},
{
"code": null,
"e": 1491,
"s": 1364,
"text": "data['column name'] = data['column name'].replace(['1st old value','2nd old value',...],['1st new value','2nd new value',...])"
},
{
"code": null,
"e": 1575,
"s": 1491,
"text": "In case you want to replace multiple values with a new value for a specific column:"
},
{
"code": null,
"e": 1676,
"s": 1575,
"text": "data['column name'] = data['column name'].replace(['1st old value','2nd old value',...],'new value')"
},
{
"code": null,
"e": 2022,
"s": 1676,
"text": "Suppose I want to add a column evaluating if the grade is good or bad, I will write down a mapping of each grade to the kind of corresponding assessment comment. This can be done in 4 different ways by using bins, pandas cut()function, np.digitize()function, np.select()or your own function with if . Let’s see how I am dealing with each method."
},
{
"code": null,
"e": 2260,
"s": 2022,
"text": "You only need to define your limits and category names, then apply them to a numeric column using pandas.cut(). In this case, I will define three intervals, which correspond to four bin limits, to evaluate each class’s score. In details:"
},
{
"code": null,
"e": 2295,
"s": 2260,
"text": "0 < AverageScore ≤2: Below average"
},
{
"code": null,
"e": 2327,
"s": 2295,
"text": "2 < AverageScore ≤ 3.1: Average"
},
{
"code": null,
"e": 2355,
"s": 2327,
"text": "3.1 < AverageScore ≤5: Good"
},
{
"code": null,
"e": 2500,
"s": 2355,
"text": "Input:bins = [0, 2, 3.1, 5]comment = ['Below Average', 'Average', 'Good']data['Evaluation'] = pd.cut(data['AverageScore'], bins, labels=comment)"
},
{
"code": null,
"e": 2508,
"s": 2500,
"text": "Output:"
},
{
"code": null,
"e": 2817,
"s": 2508,
"text": "The idea of Numpy.digitize() is to get the indices of the bins to which each value belongs. Similarly in this case, you can also define your bin boundaries and category names like the case with pd.cut(). What difference is to create an additional dictionary and use that dictionary to map the category names."
},
{
"code": null,
"e": 3022,
"s": 2817,
"text": "Input:bins = [0, 2, 3.1, 5]comment = ['Below Average', 'Average', 'Good']dictionary = dict(enumerate(comment, 1))data['Evaluation2'] = np.vectorize(dictionary.get)(np.digitize(data['AverageScore'], bins))"
},
{
"code": null,
"e": 3030,
"s": 3022,
"text": "Output:"
},
{
"code": null,
"e": 3376,
"s": 3030,
"text": "Numpy.select(condition list, choice list)method returns an array drawn from elements in choice list , depending on condition in the list. Therefore, we can easily obtain the desired values by stating the evaluation conditions, which are three intervals with limitation, and the corresponding choice list values. See the code below for reference."
},
{
"code": null,
"e": 3598,
"s": 3376,
"text": "Input:evaluate = [data['AverageScore'].between(0,2), data['AverageScore'].between(2,3.1), data['AverageScore'].between(3.1,5)]values = ['Below Average', 'Average', 'Good']data['Evaluate3'] = np.select(evaluate, values, 0)"
},
{
"code": null,
"e": 3606,
"s": 3598,
"text": "Output:"
},
{
"code": null,
"e": 3705,
"s": 3606,
"text": "You can even write your own function to apply. The logic is actually quite simple, as you can see:"
},
{
"code": null,
"e": 3978,
"s": 3705,
"text": "Input: def evaluate(values): if values >=0 and values <=2: return 'Below Average' elif values >2 and values <= 3.1: return 'Average' else: return 'Good'#Applying functiondata['Evaluation4'] = data['AverageScore'].apply(lambda x: evaluate(x))"
},
{
"code": null,
"e": 3986,
"s": 3978,
"text": "Output:"
},
{
"code": null,
"e": 4216,
"s": 3986,
"text": "As you can see, all of the four solutions produce the same results. I just want to provide you with different approaches to this problem so that in the future you can apply these data manipulation flexibly in different scenarios."
}
] |
ELMo: Contextual language embedding | by Josh Taylor | Towards Data Science
|
This article will explore the latest in natural language modelling; deep contextualised word embeddings. The focus is more practical than theoretical with a worked example of how you can use the state-of-the-art ELMo model to review sentence similarity in a given document as well as creating a simple semantic search engine. The full code can be viewed in the Colab notebook here.
As we know, language is complex. Context can completely change the meaning of the individual words in a sentence. For example:
He kicked the bucket.
I have yet to cross-off all the items on my bucket list.
The bucket was filled with water.
In these sentences, whilst the word ‘bucket’ is always the same, it’s meaning is very different.
Whilst we can easily decipher these complexities in language, creating a model which can understand the different nuances of the meaning of words given the surrounding text is difficult.
It is for this reason that traditional word embeddings (word2vec, GloVe, fastText) fall short. They only have one representation per word, therefore they cannot capture how the meaning of each word can change based on surrounding context.
Enter ELMo. Developed in 2018 by AllenNLP, it goes beyond traditional embedding techniques. It uses a deep, bi-directional LSTM model to create word representations.
Rather than a dictionary of words and their corresponding vectors, ELMo analyses words within the context that they are used. It is also character based, allowing the model to form representations of out-of-vocabulary words.
This therefore means that the way ELMo is used is quite different to word2vec or fastText. Rather than having a dictionary ‘look-up’ of words and their corresponding vectors, ELMo instead creates vectors on-the-fly by passing text through the deep learning model.
Lets get started! I will add the main snippets of code here but if you want to review the full set of code (or indeed want the strange satisfaction that comes with clicking through each of the cells in a notebook), please see the corresponding Colab output here.
As per my last few posts, the data we will be using is based on Modern Slavery returns. These are mandatory statements by companies to communicate how they are addressing Modern Slavery both internally, and within their supply chains. We will be deep-diving into ASOS’s return in this article (a British, online fashion retailer).
If you are interested in seeing other posts in what is fast becoming a mini-series of NLP experiments performed on this dataset, I have included links to these at the end of this article.
1. Get the text data, clean and tokenize
It is amazing how simple this is to do using Python string functions and spaCy. Here we do some basic text cleaning by:
a) removing line breaks, tabs and excess whitespace as well as the mysterious ‘xa0’ character;
b) splitting the text into sentences using spaCy’s ‘.sents’ iterator.
ELMo can receive either a list of sentence strings or a list of lists (sentences and words). Here we have gone for the former. We know that ELMo is character based, therefore tokenizing words should not have any impact on performance.
nlp = spacy.load('en_core_web_md')#text represents our raw text documenttext = text.lower().replace('\n', ' ').replace('\t', ' ').replace('\xa0',' ') #get rid of problem charstext = ' '.join(text.split()) #a quick way of removing excess whitespacedoc = nlp(text)sentences = []for i in doc.sents: if len(i)>1: sentences.append(i.string.strip()) #tokenize into sentences
2. Get the ELMo model using TensorFlow Hub:
If you have not yet come across TensorFlow Hub, it is a massive time saver in serving-up a large number of pre-trained models for use in TensorFlow. Luckily for us, one of these models is ELMo. We can load in a fully trained model in just two few lines of code. How satisfying...
url = "https://tfhub.dev/google/elmo/2"embed = hub.Module(url)
To then use this model in anger we just need a few more lines of code to point it in the direction of our text document and create sentence vectors:
# This tells the model to run through the 'sentences' list and return the default output (1024 dimension sentence vectors).embeddings = embed( sentences, signature="default", as_dict=True)["default"]#Start a session and run ELMo to return the embeddings in variable xwith tf.Session() as sess: sess.run(tf.global_variables_initializer()) sess.run(tf.tables_initializer()) x = sess.run(embeddings)
3. Use visualisation to sense-check outputs
It is amazing how often visualisation is overlooked as a way of gaining greater understanding of data. Pictures speak a thousand words and we are going to create a chart of a thousand words to prove this point (actually it is 8,511 words).
Here we will use PCA and t-SNE to reduce the 1,024 dimensions which are output from ELMo down to 2 so that we can review the outputs from the model. I have included further reading on how this is achieved at the end of the article if you want to find out more.
from sklearn.decomposition import PCApca = PCA(n_components=50) #reduce down to 50 dimy = pca.fit_transform(x)from sklearn.manifold import TSNEy = TSNE(n_components=2).fit_transform(y) # further reduce to 2 dim using t-SNE
Using the amazing Plotly library, we can create a beautiful, interactive plot in no time at all. The below code shows how to render the results of our dimensionality reduction and join this back up to the sentence text. Colour has also been added based on the sentence length. As we are using Colab, the last line of code downloads the HTML file. This can be found below:
drive.google.com
The code to create this is below:
import plotly.plotly as pyimport plotly.graph_objs as gofrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotinit_notebook_mode(connected=True)data = [ go.Scatter( x=[i[0] for i in y], y=[i[1] for i in y], mode='markers', text=[i for i in sentences], marker=dict( size=16, color = [len(i) for i in sentences], #set color equal to a variable opacity= 0.8, colorscale='Viridis', showscale=False ) )]layout = go.Layout()layout = dict( yaxis = dict(zeroline = False), xaxis = dict(zeroline = False) )fig = go.Figure(data=data, layout=layout)file = plot(fig, filename='Sentence encode.html')from google.colab import filesfiles.download('Sentence encode.html')
Exploring this visualisation, we can see ELMo has done sterling work in grouping sentences by their semantic similarity. In fact it is quite incredible how effective the model is:
4. Create a semantic search engine:
Now that we are confident that our language model is working well, lets put it to work in a semantic search engine. The idea is that this will allow us to search through the text not by keywords but by semantic closeness to our search query.
This is actually really simple to implement:
First we take a search query and run ELMo over it;
We then use cosine similarity to compare this against the vectors in our text document;
We can then return the ’n’ closest matches to the search query from the document.
Google Colab has some great features to create form inputs which are perfect for this use case. For example, creating an input is as simple as adding #@param after a variable. The below shows this for a string input:
search_string = "example text" #@param {type:"string"}
In addition to using Colab form inputs, I have used ‘IPython.display.HTML’ to beautify the output text and some basic string matching to highlight common words between the search query and the results.
Lets put it to the test. Let us see what ASOS are doing with regards to a code of ethics in their Modern Slavery return:
This is magical! The matches go beyond keywords, the search engine clearly knows that ‘ethics’ and ethical are closely related. We find hits for both a code of integrity and also ethical standards and policies. Both relevant to our search query but not directly linked based on key words.
I hope you enjoyed the post. Please do leave comments if you have any questions or suggestions.
Below are my other posts in what is now becoming a mini series on NLP and exploration of companies Modern Slavery returns:
towardsdatascience.com
towardsdatascience.com
To find out more on the dimensionality reduction process used, I recommend the below post:
medium.com
Finally, for more information on state of the art language models, the below is a good read:
|
[
{
"code": null,
"e": 553,
"s": 171,
"text": "This article will explore the latest in natural language modelling; deep contextualised word embeddings. The focus is more practical than theoretical with a worked example of how you can use the state-of-the-art ELMo model to review sentence similarity in a given document as well as creating a simple semantic search engine. The full code can be viewed in the Colab notebook here."
},
{
"code": null,
"e": 680,
"s": 553,
"text": "As we know, language is complex. Context can completely change the meaning of the individual words in a sentence. For example:"
},
{
"code": null,
"e": 702,
"s": 680,
"text": "He kicked the bucket."
},
{
"code": null,
"e": 759,
"s": 702,
"text": "I have yet to cross-off all the items on my bucket list."
},
{
"code": null,
"e": 793,
"s": 759,
"text": "The bucket was filled with water."
},
{
"code": null,
"e": 890,
"s": 793,
"text": "In these sentences, whilst the word ‘bucket’ is always the same, it’s meaning is very different."
},
{
"code": null,
"e": 1077,
"s": 890,
"text": "Whilst we can easily decipher these complexities in language, creating a model which can understand the different nuances of the meaning of words given the surrounding text is difficult."
},
{
"code": null,
"e": 1316,
"s": 1077,
"text": "It is for this reason that traditional word embeddings (word2vec, GloVe, fastText) fall short. They only have one representation per word, therefore they cannot capture how the meaning of each word can change based on surrounding context."
},
{
"code": null,
"e": 1482,
"s": 1316,
"text": "Enter ELMo. Developed in 2018 by AllenNLP, it goes beyond traditional embedding techniques. It uses a deep, bi-directional LSTM model to create word representations."
},
{
"code": null,
"e": 1707,
"s": 1482,
"text": "Rather than a dictionary of words and their corresponding vectors, ELMo analyses words within the context that they are used. It is also character based, allowing the model to form representations of out-of-vocabulary words."
},
{
"code": null,
"e": 1971,
"s": 1707,
"text": "This therefore means that the way ELMo is used is quite different to word2vec or fastText. Rather than having a dictionary ‘look-up’ of words and their corresponding vectors, ELMo instead creates vectors on-the-fly by passing text through the deep learning model."
},
{
"code": null,
"e": 2234,
"s": 1971,
"text": "Lets get started! I will add the main snippets of code here but if you want to review the full set of code (or indeed want the strange satisfaction that comes with clicking through each of the cells in a notebook), please see the corresponding Colab output here."
},
{
"code": null,
"e": 2565,
"s": 2234,
"text": "As per my last few posts, the data we will be using is based on Modern Slavery returns. These are mandatory statements by companies to communicate how they are addressing Modern Slavery both internally, and within their supply chains. We will be deep-diving into ASOS’s return in this article (a British, online fashion retailer)."
},
{
"code": null,
"e": 2753,
"s": 2565,
"text": "If you are interested in seeing other posts in what is fast becoming a mini-series of NLP experiments performed on this dataset, I have included links to these at the end of this article."
},
{
"code": null,
"e": 2794,
"s": 2753,
"text": "1. Get the text data, clean and tokenize"
},
{
"code": null,
"e": 2914,
"s": 2794,
"text": "It is amazing how simple this is to do using Python string functions and spaCy. Here we do some basic text cleaning by:"
},
{
"code": null,
"e": 3009,
"s": 2914,
"text": "a) removing line breaks, tabs and excess whitespace as well as the mysterious ‘xa0’ character;"
},
{
"code": null,
"e": 3079,
"s": 3009,
"text": "b) splitting the text into sentences using spaCy’s ‘.sents’ iterator."
},
{
"code": null,
"e": 3314,
"s": 3079,
"text": "ELMo can receive either a list of sentence strings or a list of lists (sentences and words). Here we have gone for the former. We know that ELMo is character based, therefore tokenizing words should not have any impact on performance."
},
{
"code": null,
"e": 3687,
"s": 3314,
"text": "nlp = spacy.load('en_core_web_md')#text represents our raw text documenttext = text.lower().replace('\\n', ' ').replace('\\t', ' ').replace('\\xa0',' ') #get rid of problem charstext = ' '.join(text.split()) #a quick way of removing excess whitespacedoc = nlp(text)sentences = []for i in doc.sents: if len(i)>1: sentences.append(i.string.strip()) #tokenize into sentences"
},
{
"code": null,
"e": 3731,
"s": 3687,
"text": "2. Get the ELMo model using TensorFlow Hub:"
},
{
"code": null,
"e": 4011,
"s": 3731,
"text": "If you have not yet come across TensorFlow Hub, it is a massive time saver in serving-up a large number of pre-trained models for use in TensorFlow. Luckily for us, one of these models is ELMo. We can load in a fully trained model in just two few lines of code. How satisfying..."
},
{
"code": null,
"e": 4074,
"s": 4011,
"text": "url = \"https://tfhub.dev/google/elmo/2\"embed = hub.Module(url)"
},
{
"code": null,
"e": 4223,
"s": 4074,
"text": "To then use this model in anger we just need a few more lines of code to point it in the direction of our text document and create sentence vectors:"
},
{
"code": null,
"e": 4632,
"s": 4223,
"text": "# This tells the model to run through the 'sentences' list and return the default output (1024 dimension sentence vectors).embeddings = embed( sentences, signature=\"default\", as_dict=True)[\"default\"]#Start a session and run ELMo to return the embeddings in variable xwith tf.Session() as sess: sess.run(tf.global_variables_initializer()) sess.run(tf.tables_initializer()) x = sess.run(embeddings)"
},
{
"code": null,
"e": 4676,
"s": 4632,
"text": "3. Use visualisation to sense-check outputs"
},
{
"code": null,
"e": 4916,
"s": 4676,
"text": "It is amazing how often visualisation is overlooked as a way of gaining greater understanding of data. Pictures speak a thousand words and we are going to create a chart of a thousand words to prove this point (actually it is 8,511 words)."
},
{
"code": null,
"e": 5177,
"s": 4916,
"text": "Here we will use PCA and t-SNE to reduce the 1,024 dimensions which are output from ELMo down to 2 so that we can review the outputs from the model. I have included further reading on how this is achieved at the end of the article if you want to find out more."
},
{
"code": null,
"e": 5400,
"s": 5177,
"text": "from sklearn.decomposition import PCApca = PCA(n_components=50) #reduce down to 50 dimy = pca.fit_transform(x)from sklearn.manifold import TSNEy = TSNE(n_components=2).fit_transform(y) # further reduce to 2 dim using t-SNE"
},
{
"code": null,
"e": 5772,
"s": 5400,
"text": "Using the amazing Plotly library, we can create a beautiful, interactive plot in no time at all. The below code shows how to render the results of our dimensionality reduction and join this back up to the sentence text. Colour has also been added based on the sentence length. As we are using Colab, the last line of code downloads the HTML file. This can be found below:"
},
{
"code": null,
"e": 5789,
"s": 5772,
"text": "drive.google.com"
},
{
"code": null,
"e": 5823,
"s": 5789,
"text": "The code to create this is below:"
},
{
"code": null,
"e": 6615,
"s": 5823,
"text": "import plotly.plotly as pyimport plotly.graph_objs as gofrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotinit_notebook_mode(connected=True)data = [ go.Scatter( x=[i[0] for i in y], y=[i[1] for i in y], mode='markers', text=[i for i in sentences], marker=dict( size=16, color = [len(i) for i in sentences], #set color equal to a variable opacity= 0.8, colorscale='Viridis', showscale=False ) )]layout = go.Layout()layout = dict( yaxis = dict(zeroline = False), xaxis = dict(zeroline = False) )fig = go.Figure(data=data, layout=layout)file = plot(fig, filename='Sentence encode.html')from google.colab import filesfiles.download('Sentence encode.html')"
},
{
"code": null,
"e": 6795,
"s": 6615,
"text": "Exploring this visualisation, we can see ELMo has done sterling work in grouping sentences by their semantic similarity. In fact it is quite incredible how effective the model is:"
},
{
"code": null,
"e": 6831,
"s": 6795,
"text": "4. Create a semantic search engine:"
},
{
"code": null,
"e": 7073,
"s": 6831,
"text": "Now that we are confident that our language model is working well, lets put it to work in a semantic search engine. The idea is that this will allow us to search through the text not by keywords but by semantic closeness to our search query."
},
{
"code": null,
"e": 7118,
"s": 7073,
"text": "This is actually really simple to implement:"
},
{
"code": null,
"e": 7169,
"s": 7118,
"text": "First we take a search query and run ELMo over it;"
},
{
"code": null,
"e": 7257,
"s": 7169,
"text": "We then use cosine similarity to compare this against the vectors in our text document;"
},
{
"code": null,
"e": 7339,
"s": 7257,
"text": "We can then return the ’n’ closest matches to the search query from the document."
},
{
"code": null,
"e": 7556,
"s": 7339,
"text": "Google Colab has some great features to create form inputs which are perfect for this use case. For example, creating an input is as simple as adding #@param after a variable. The below shows this for a string input:"
},
{
"code": null,
"e": 7611,
"s": 7556,
"text": "search_string = \"example text\" #@param {type:\"string\"}"
},
{
"code": null,
"e": 7813,
"s": 7611,
"text": "In addition to using Colab form inputs, I have used ‘IPython.display.HTML’ to beautify the output text and some basic string matching to highlight common words between the search query and the results."
},
{
"code": null,
"e": 7934,
"s": 7813,
"text": "Lets put it to the test. Let us see what ASOS are doing with regards to a code of ethics in their Modern Slavery return:"
},
{
"code": null,
"e": 8223,
"s": 7934,
"text": "This is magical! The matches go beyond keywords, the search engine clearly knows that ‘ethics’ and ethical are closely related. We find hits for both a code of integrity and also ethical standards and policies. Both relevant to our search query but not directly linked based on key words."
},
{
"code": null,
"e": 8319,
"s": 8223,
"text": "I hope you enjoyed the post. Please do leave comments if you have any questions or suggestions."
},
{
"code": null,
"e": 8442,
"s": 8319,
"text": "Below are my other posts in what is now becoming a mini series on NLP and exploration of companies Modern Slavery returns:"
},
{
"code": null,
"e": 8465,
"s": 8442,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8488,
"s": 8465,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8579,
"s": 8488,
"text": "To find out more on the dimensionality reduction process used, I recommend the below post:"
},
{
"code": null,
"e": 8590,
"s": 8579,
"text": "medium.com"
}
] |
How a Preprocessor works in C/C++?
|
Here we will see how the preprocessors are working in C or C++. Let us see what are the preprocessors.
The preprocessors are the directives, which give instructions to the compiler to preprocess the information before actual compilation starts.
All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not C++ statements, so they do not end in a semicolon (;).
You already have seen a #include directive in all the examples. This macro is used to include a header file into the source file.
There are number of preprocessor directives supported by C++ like #include, #define, #if, #else, #line, etc. Let us see important directives −
The #define preprocessor directive creates symbolic constants. The symbolic constant is called a macro and the general form of the directive is −
#define macro-name replacement-text
#include <iostream>
using namespace std;
#define PI 3.14159
int main () {
cout << "Value of PI :" << PI << endl;
return 0;
}
Value of PI :3.14159
There are several directives, which can be used to compile selective portions of your program's source code.This process is called conditional compilation.
The conditional preprocessor construct is much like the ‘if’ selection structure. Consider the following preprocessor code −
#ifndef NULL
#define NULL 0
#endif
You can compile a program for debugging purpose. You can also turn on or off the debugging using a single macro as follows −
#ifdef DEBUG
cerr <<"Variable x = " << x << endl;
#endif
This causes the cerr statement to be compiled in the program if the symbolic constant DEBUG has been defined before directive #ifdef DEBUG. You can use #if 0 statment to comment out a portion of the program as follows −
#if 0
code prevented from compiling
#endif
#include <iostream>
using namespace std;
#define DEBUG
#define MIN(a,b) (((a)<(b)) ? a : b)
int main () {
int i, j;
i = 100;
j = 30;
#ifdef DEBUG
cerr <<"Trace: Inside main function" << endl;
#endif
#if 0
/* This is commented part */
cout << MKSTR(HELLO C++) << endl;
#endif
cout <<"The minimum is " << MIN(i, j) << endl;
#ifdef DEBUG
cerr <<"Trace: Coming out of main function" << endl;
#endif
return 0;
}
Trace: Inside main function
The minimum is 30
Trace: Coming out of main function
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "Here we will see how the preprocessors are working in C or C++. Let us see what are the preprocessors."
},
{
"code": null,
"e": 1307,
"s": 1165,
"text": "The preprocessors are the directives, which give instructions to the compiler to preprocess the information before actual compilation starts."
},
{
"code": null,
"e": 1522,
"s": 1307,
"text": "All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not C++ statements, so they do not end in a semicolon (;)."
},
{
"code": null,
"e": 1652,
"s": 1522,
"text": "You already have seen a #include directive in all the examples. This macro is used to include a header file into the source file."
},
{
"code": null,
"e": 1795,
"s": 1652,
"text": "There are number of preprocessor directives supported by C++ like #include, #define, #if, #else, #line, etc. Let us see important directives −"
},
{
"code": null,
"e": 1941,
"s": 1795,
"text": "The #define preprocessor directive creates symbolic constants. The symbolic constant is called a macro and the general form of the directive is −"
},
{
"code": null,
"e": 1977,
"s": 1941,
"text": "#define macro-name replacement-text"
},
{
"code": null,
"e": 2108,
"s": 1977,
"text": "#include <iostream>\nusing namespace std;\n#define PI 3.14159\nint main () {\n cout << \"Value of PI :\" << PI << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2129,
"s": 2108,
"text": "Value of PI :3.14159"
},
{
"code": null,
"e": 2285,
"s": 2129,
"text": "There are several directives, which can be used to compile selective portions of your program's source code.This process is called conditional compilation."
},
{
"code": null,
"e": 2410,
"s": 2285,
"text": "The conditional preprocessor construct is much like the ‘if’ selection structure. Consider the following preprocessor code −"
},
{
"code": null,
"e": 2445,
"s": 2410,
"text": "#ifndef NULL\n#define NULL 0\n#endif"
},
{
"code": null,
"e": 2570,
"s": 2445,
"text": "You can compile a program for debugging purpose. You can also turn on or off the debugging using a single macro as follows −"
},
{
"code": null,
"e": 2627,
"s": 2570,
"text": "#ifdef DEBUG\ncerr <<\"Variable x = \" << x << endl;\n#endif"
},
{
"code": null,
"e": 2847,
"s": 2627,
"text": "This causes the cerr statement to be compiled in the program if the symbolic constant DEBUG has been defined before directive #ifdef DEBUG. You can use #if 0 statment to comment out a portion of the program as follows −"
},
{
"code": null,
"e": 2890,
"s": 2847,
"text": "#if 0\ncode prevented from compiling\n#endif"
},
{
"code": null,
"e": 3351,
"s": 2890,
"text": "#include <iostream>\nusing namespace std;\n#define DEBUG\n#define MIN(a,b) (((a)<(b)) ? a : b)\nint main () {\n int i, j;\n i = 100;\n j = 30;\n #ifdef DEBUG\n cerr <<\"Trace: Inside main function\" << endl;\n #endif\n #if 0\n /* This is commented part */\n cout << MKSTR(HELLO C++) << endl;\n #endif\n cout <<\"The minimum is \" << MIN(i, j) << endl;\n #ifdef DEBUG\n cerr <<\"Trace: Coming out of main function\" << endl;\n #endif\n return 0;\n}"
},
{
"code": null,
"e": 3432,
"s": 3351,
"text": "Trace: Inside main function\nThe minimum is 30\nTrace: Coming out of main function"
}
] |
Flutter - Database Concepts
|
Flutter provides many advanced packages to work with databases. The most important packages are −
sqflite − Used to access and manipulate SQLite database, and
sqflite − Used to access and manipulate SQLite database, and
firebase_database − Used to access and manipulate cloud hosted NoSQL database from Google.
firebase_database − Used to access and manipulate cloud hosted NoSQL database from Google.
In this chapter, let us discuss each of them in detail.
SQLite database is the de-facto and standard SQL based embedded database engine. It is small and time-tested database engine. sqflite package provides a lot of functionality to work efficiently with SQLite database. It provides standard methods to manipulate SQLite database engine. The core functionality provided by sqflite package is as follows −
Create / Open (openDatabase method) a SQLite database.
Create / Open (openDatabase method) a SQLite database.
Execute SQL statement (execute method) against SQLite database.
Execute SQL statement (execute method) against SQLite database.
Advanced query methods (query method) to reduce to code required to query and get information from SQLite database.
Advanced query methods (query method) to reduce to code required to query and get information from SQLite database.
Let us create a product application to store and fetch product information from a standard SQLite database engine using sqflite package and understand the concept behind the SQLite database and sqflite package.
Create a new Flutter application in Android studio, product_sqlite_app.
Create a new Flutter application in Android studio, product_sqlite_app.
Replace the default startup code (main.dart) with our product_rest_app code.
Replace the default startup code (main.dart) with our product_rest_app code.
Copy the assets folder from product_nav_app to product_rest_app and add assets inside the *pubspec.yaml` file.
Copy the assets folder from product_nav_app to product_rest_app and add assets inside the *pubspec.yaml` file.
flutter:
assets:
- assets/appimages/floppy.png
- assets/appimages/iphone.png
- assets/appimages/laptop.png
- assets/appimages/pendrive.png
- assets/appimages/pixel.png
- assets/appimages/tablet.png
Configure sqflite package in the pubspec.yaml file as shown below −
Configure sqflite package in the pubspec.yaml file as shown below −
dependencies: sqflite: any
Use the latest version number of sqflite in place of any
Configure path_provider package in the pubspec.yaml file as shown below −
Configure path_provider package in the pubspec.yaml file as shown below −
dependencies: path_provider: any
Here, path_provider package is used to get temporary folder path of the system and path of the application. Use the latest version number of sqflite in place of any.
Here, path_provider package is used to get temporary folder path of the system and path of the application. Use the latest version number of sqflite in place of any.
Android studio will alert that the pubspec.yaml is updated.
Android studio will alert that the pubspec.yaml is updated.
Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application.
Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application.
In database, we need primary key, id as additional field along with Product properties like name, price, etc., So, add id property in the Product class. Also, add a new method, toMap to convert product object into Map object. fromMap and toMap are used to serialize and de- serialize the Product object and it is used in database manipulation methods.
In database, we need primary key, id as additional field along with Product properties like name, price, etc., So, add id property in the Product class. Also, add a new method, toMap to convert product object into Map object. fromMap and toMap are used to serialize and de- serialize the Product object and it is used in database manipulation methods.
class Product {
final int id;
final String name;
final String description;
final int price;
final String image;
static final columns = ["id", "name", "description", "price", "image"];
Product(this.id, this.name, this.description, this.price, this.image);
factory Product.fromMap(Map<String, dynamic> data) {
return Product(
data['id'],
data['name'],
data['description'],
data['price'],
data['image'],
);
}
Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"description": description,
"price": price,
"image": image
};
}
Create a new file, Database.dart in the lib folder to write SQLite related functionality.
Create a new file, Database.dart in the lib folder to write SQLite related functionality.
Import necessary import statement in Database.dart.
Import necessary import statement in Database.dart.
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'Product.dart';
Note the following points here −
async is used to write asynchronous methods.
io is used to access files and directories.
path is used to access dart core utility function related to file paths.
path_provider is used to get temporary and application path.
sqflite is used to manipulate SQLite database.
Note the following points here −
async is used to write asynchronous methods.
async is used to write asynchronous methods.
io is used to access files and directories.
io is used to access files and directories.
path is used to access dart core utility function related to file paths.
path is used to access dart core utility function related to file paths.
path_provider is used to get temporary and application path.
path_provider is used to get temporary and application path.
sqflite is used to manipulate SQLite database.
sqflite is used to manipulate SQLite database.
Create a new class SQLiteDbProvider
Create a new class SQLiteDbProvider
Declare a singleton based, static SQLiteDbProvider object as specified below −
Declare a singleton based, static SQLiteDbProvider object as specified below −
class SQLiteDbProvider {
SQLiteDbProvider._();
static final SQLiteDbProvider db = SQLiteDbProvider._();
static Database _database;
}
SQLiteDBProvoider object and its method can be accessed through the static db variable.
SQLiteDBProvoider object and its method can be accessed through the static db variable.
SQLiteDBProvoider.db.<emthod>
Create a method to get database (Future option) of type Future<Database>. Create product table and load initial data during the creation of the database itself.
Create a method to get database (Future option) of type Future<Database>. Create product table and load initial data during the creation of the database itself.
Future<Database> get database async {
if (_database != null)
return _database;
_database = await initDB();
return _database;
}
initDB() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "ProductDB.db");
return await openDatabase(
path,
version: 1,
onOpen: (db) {},
onCreate: (Database db, int version) async {
await db.execute(
"CREATE TABLE Product ("
"id INTEGER PRIMARY KEY,"
"name TEXT,"
"description TEXT,"
"price INTEGER,"
"image TEXT" ")"
);
await db.execute(
"INSERT INTO Product ('id', 'name', 'description', 'price', 'image')
values (?, ?, ?, ?, ?)",
[1, "iPhone", "iPhone is the stylist phone ever", 1000, "iphone.png"]
);
await db.execute(
"INSERT INTO Product ('id', 'name', 'description', 'price', 'image')
values (?, ?, ?, ?, ?)",
[2, "Pixel", "Pixel is the most feature phone ever", 800, "pixel.png"]
);
await db.execute(
"INSERT INTO Product ('id', 'name', 'description', 'price', 'image')
values (?, ?, ?, ?, ?)",
[3, "Laptop", "Laptop is most productive development tool", 2000, "laptop.png"]\
);
await db.execute(
"INSERT INTO Product ('id', 'name', 'description', 'price', 'image')
values (?, ?, ?, ?, ?)",
[4, "Tablet", "Laptop is most productive development tool", 1500, "tablet.png"]
);
await db.execute(
"INSERT INTO Product
('id', 'name', 'description', 'price', 'image')
values (?, ?, ?, ?, ?)",
[5, "Pendrive", "Pendrive is useful storage medium", 100, "pendrive.png"]
);
await db.execute(
"INSERT INTO Product
('id', 'name', 'description', 'price', 'image')
values (?, ?, ?, ?, ?)",
[6, "Floppy Drive", "Floppy drive is useful rescue storage medium", 20, "floppy.png"]
);
}
);
}
Here, we have used the following methods −
Here, we have used the following methods −
getApplicationDocumentsDirectory − Returns application directory path
getApplicationDocumentsDirectory − Returns application directory path
join − Used to create system specific path. We have used it to create database path.
join − Used to create system specific path. We have used it to create database path.
openDatabase − Used to open a SQLite database
openDatabase − Used to open a SQLite database
onOpen − Used to write code while opening a database
onOpen − Used to write code while opening a database
onCreate − Used to write code while a database is created for the first time
onCreate − Used to write code while a database is created for the first time
db.execute − Used to execute SQL queries. It accepts a query. If the query has placeholder (?), then it accepts values as list in the second argument.
db.execute − Used to execute SQL queries. It accepts a query. If the query has placeholder (?), then it accepts values as list in the second argument.
Write a method to get all products in the database −
Write a method to get all products in the database −
Future<List<Product>> getAllProducts() async {
final db = await database;
List<Map>
results = await db.query("Product", columns: Product.columns, orderBy: "id ASC");
List<Product> products = new List();
results.forEach((result) {
Product product = Product.fromMap(result);
products.add(product);
});
return products;
}
Here, we have done the following −
Here, we have done the following −
Used query method to fetch all the product information. query provides shortcut to query a table information without writing the entire query. query method will generate the proper query itself by using our input like columns, orderBy, etc.,
Used query method to fetch all the product information. query provides shortcut to query a table information without writing the entire query. query method will generate the proper query itself by using our input like columns, orderBy, etc.,
Used Product’s fromMap method to get product details by looping the results object, which holds all the rows in the table.
Used Product’s fromMap method to get product details by looping the results object, which holds all the rows in the table.
Write a method to get product specific to id
Write a method to get product specific to id
Future<Product> getProductById(int id) async {
final db = await database;
var result = await db.query("Product", where: "id = ", whereArgs: [id]);
return result.isNotEmpty ? Product.fromMap(result.first) : Null;
}
Here, we have used where and whereArgs to apply filters.
Here, we have used where and whereArgs to apply filters.
Create three methods - insert, update and delete method to insert, update and delete product from the database.
Create three methods - insert, update and delete method to insert, update and delete product from the database.
insert(Product product) async {
final db = await database;
var maxIdResult = await db.rawQuery(
"SELECT MAX(id)+1 as last_inserted_id FROM Product");
var id = maxIdResult.first["last_inserted_id"];
var result = await db.rawInsert(
"INSERT Into Product (id, name, description, price, image)"
" VALUES (?, ?, ?, ?, ?)",
[id, product.name, product.description, product.price, product.image]
);
return result;
}
update(Product product) async {
final db = await database;
var result = await db.update("Product", product.toMap(),
where: "id = ?", whereArgs: [product.id]); return result;
}
delete(int id) async {
final db = await database;
db.delete("Product", where: "id = ?", whereArgs: [id]);
}
The final code of the Database.dart is as follows −
The final code of the Database.dart is as follows −
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'Product.dart';
class SQLiteDbProvider {
SQLiteDbProvider._();
static final SQLiteDbProvider db = SQLiteDbProvider._();
static Database _database;
Future<Database> get database async {
if (_database != null)
return _database;
_database = await initDB();
return _database;
}
initDB() async {
Directory documentsDirectory = await
getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "ProductDB.db");
return await openDatabase(
path, version: 1,
onOpen: (db) {},
onCreate: (Database db, int version) async {
await db.execute(
"CREATE TABLE Product ("
"id INTEGER PRIMARY KEY,"
"name TEXT,"
"description TEXT,"
"price INTEGER,"
"image TEXT"")"
);
await db.execute(
"INSERT INTO Product ('id', 'name', 'description', 'price', 'image')
values (?, ?, ?, ?, ?)",
[1, "iPhone", "iPhone is the stylist phone ever", 1000, "iphone.png"]
);
await db.execute(
"INSERT INTO Product ('id', 'name', 'description', 'price', 'image')
values (?, ?, ?, ?, ?)",
[2, "Pixel", "Pixel is the most feature phone ever", 800, "pixel.png"]
);
await db.execute(
"INSERT INTO Product ('id', 'name', 'description', 'price', 'image')
values (?, ?, ?, ?, ?)",
[3, "Laptop", "Laptop is most productive development tool", 2000, "laptop.png"]
);
await db.execute(
"INSERT INTO Product ('id', 'name', 'description', 'price', 'image')
values (?, ?, ?, ?, ?)",
[4, "Tablet", "Laptop is most productive development tool", 1500, "tablet.png"]
);
await db.execute(
"INSERT INTO Product ('id', 'name', 'description', 'price', 'image')
values (?, ?, ?, ?, ?)",
[5, "Pendrive", "Pendrive is useful storage medium", 100, "pendrive.png"]
);
await db.execute(
"INSERT INTO Product ('id', 'name', 'description', 'price', 'image')
values (?, ?, ?, ?, ?)",
[6, "Floppy Drive", "Floppy drive is useful rescue storage medium", 20, "floppy.png"]
);
}
);
}
Future<List<Product>> getAllProducts() async {
final db = await database;
List<Map> results = await db.query(
"Product", columns: Product.columns, orderBy: "id ASC"
);
List<Product> products = new List();
results.forEach((result) {
Product product = Product.fromMap(result);
products.add(product);
});
return products;
}
Future<Product> getProductById(int id) async {
final db = await database;
var result = await db.query("Product", where: "id = ", whereArgs: [id]);
return result.isNotEmpty ? Product.fromMap(result.first) : Null;
}
insert(Product product) async {
final db = await database;
var maxIdResult = await db.rawQuery("SELECT MAX(id)+1 as last_inserted_id FROM Product");
var id = maxIdResult.first["last_inserted_id"];
var result = await db.rawInsert(
"INSERT Into Product (id, name, description, price, image)"
" VALUES (?, ?, ?, ?, ?)",
[id, product.name, product.description, product.price, product.image]
);
return result;
}
update(Product product) async {
final db = await database;
var result = await db.update(
"Product", product.toMap(), where: "id = ?", whereArgs: [product.id]
);
return result;
}
delete(int id) async {
final db = await database;
db.delete("Product", where: "id = ?", whereArgs: [id]);
}
}
Change the main method to get the product information.
Change the main method to get the product information.
void main() {
runApp(MyApp(products: SQLiteDbProvider.db.getAllProducts()));
}
Here, we have used the getAllProducts method to fetch all products from the database.
Here, we have used the getAllProducts method to fetch all products from the database.
Run the application and see the results. It will be similar to previous example, Accessing Product service API, except the product information is stored and fetched from the local SQLite database.
Run the application and see the results. It will be similar to previous example, Accessing Product service API, except the product information is stored and fetched from the local SQLite database.
Firebase is a BaaS app development platform. It provides many feature to speed up the mobile application development like authentication service, cloud storage, etc., One of the main feature of Firebase is Cloud Firestore, a cloud based real time NoSQL database.
Flutter provides a special package, cloud_firestore to program with Cloud Firestore. Let us create an online product store in the Cloud Firestore and create a application to access the product store.
Create a new Flutter application in Android studio, product_firebase_app.
Create a new Flutter application in Android studio, product_firebase_app.
Replace the default startup code (main.dart) with our product_rest_app code.
Replace the default startup code (main.dart) with our product_rest_app code.
Copy Product.dart file from product_rest_app into the lib folder.
Copy Product.dart file from product_rest_app into the lib folder.
class Product {
final String name;
final String description;
final int price;
final String image;
Product(this.name, this.description, this.price, this.image);
factory Product.fromMap(Map<String, dynamic> json) {
return Product(
json['name'],
json['description'],
json['price'],
json['image'],
);
}
}
Copy the assets folder from product_rest_app to product_firebase_app and add assets inside the pubspec.yaml file.
Copy the assets folder from product_rest_app to product_firebase_app and add assets inside the pubspec.yaml file.
flutter:
assets:
- assets/appimages/floppy.png
- assets/appimages/iphone.png
- assets/appimages/laptop.png
- assets/appimages/pendrive.png
- assets/appimages/pixel.png
- assets/appimages/tablet.png
Configure cloud_firestore package in the pubspec.yaml file as shown below −
Configure cloud_firestore package in the pubspec.yaml file as shown below −
dependencies: cloud_firestore: ^0.9.13+1
Here, use the latest version of the cloud_firestore package.
Here, use the latest version of the cloud_firestore package.
Android studio will alert that the pubspec.yaml is updated as shown here −
Android studio will alert that the pubspec.yaml is updated as shown here −
Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application.
Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application.
Create a project in the Firebase using the following steps −
Create a project in the Firebase using the following steps −
Create a Firebase account by selecting Free plan at https://firebase.google.com/pricing/.
Create a Firebase account by selecting Free plan at https://firebase.google.com/pricing/.
Once Firebase account is created, it will redirect to the project overview page. It list all the Firebase based project and provides an option to create a new project.
Once Firebase account is created, it will redirect to the project overview page. It list all the Firebase based project and provides an option to create a new project.
Click Add project and it will open a project creation page.
Click Add project and it will open a project creation page.
Enter products app db as project name and click Create project option.
Enter products app db as project name and click Create project option.
Go to *Firebase console.
Go to *Firebase console.
Click Project overview. It opens the project overview page.
Click Project overview. It opens the project overview page.
Click android icon. It will open project setting specific to Android development.
Click android icon. It will open project setting specific to Android development.
Enter Android Package name, com.tutorialspoint.flutterapp.product_firebase_app.
Enter Android Package name, com.tutorialspoint.flutterapp.product_firebase_app.
Click Register App. It generates a project configuration file, google_service.json.
Click Register App. It generates a project configuration file, google_service.json.
Download google_service.json and then move it into the project’s android/app directory. This file is the connection between our application and Firebase.
Download google_service.json and then move it into the project’s android/app directory. This file is the connection between our application and Firebase.
Open android/app/build.gradle and include the following code −
Open android/app/build.gradle and include the following code −
apply plugin: 'com.google.gms.google-services'
Open android/build.gradle and include the following configuration −
Open android/build.gradle and include the following configuration −
buildscript {
repositories {
// ...
}
dependencies {
// ...
classpath 'com.google.gms:google-services:3.2.1' // new
}
}
Here, the plugin and class path are used for the purpose of reading google_service.json file.
Open android/app/build.gradle and include the following code as well.
Open android/app/build.gradle and include the following code as well.
android {
defaultConfig {
...
multiDexEnabled true
}
...
}
dependencies {
...
compile 'com.android.support: multidex:1.0.3'
}
This dependency enables the android application to use multiple dex functionality.
Follow the remaining steps in the Firebase Console or just skip it.
Follow the remaining steps in the Firebase Console or just skip it.
Create a product store in the newly created project using the following steps −
Create a product store in the newly created project using the following steps −
Go to Firebase console.
Go to Firebase console.
Open the newly created project.
Open the newly created project.
Click the Database option in the left menu.
Click the Database option in the left menu.
Click Create database option.
Click Create database option.
Click Start in test mode and then Enable.
Click Start in test mode and then Enable.
Click Add collection. Enter product as collection name and then click Next.
Click Add collection. Enter product as collection name and then click Next.
Enter the sample product information as shown in the image here −
Enter the sample product information as shown in the image here −
Add addition product information using Add document options.
Add addition product information using Add document options.
Open main.dart file and import Cloud Firestore plugin file and remove http package.
Open main.dart file and import Cloud Firestore plugin file and remove http package.
import 'package:cloud_firestore/cloud_firestore.dart';
Remove parseProducts and update fetchProducts to fetch products from Cloud Firestore instead of Product service API.
Remove parseProducts and update fetchProducts to fetch products from Cloud Firestore instead of Product service API.
Stream<QuerySnapshot> fetchProducts() {
return Firestore.instance.collection('product').snapshots(); }
Here, Firestore.instance.collection method is used to access product collection available in the cloud store. Firestore.instance.collection provides many option to filter the collection to get the necessary documents. But, we have not applied any filter to get all product information.
Here, Firestore.instance.collection method is used to access product collection available in the cloud store. Firestore.instance.collection provides many option to filter the collection to get the necessary documents. But, we have not applied any filter to get all product information.
Cloud Firestore provides the collection through Dart Stream concept and so modify the products type in MyApp and MyHomePage widget from Future<list<Product>> to Stream<QuerySnapshot>.
Cloud Firestore provides the collection through Dart Stream concept and so modify the products type in MyApp and MyHomePage widget from Future<list<Product>> to Stream<QuerySnapshot>.
Change the build method of MyHomePage widget to use StreamBuilder instead of FutureBuilder.
Change the build method of MyHomePage widget to use StreamBuilder instead of FutureBuilder.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Product Navigation")),
body: Center(
child: StreamBuilder<QuerySnapshot>(
stream: products, builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
if(snapshot.hasData) {
List<DocumentSnapshot>
documents = snapshot.data.documents;
List<Product>
items = List<Product>();
for(var i = 0; i < documents.length; i++) {
DocumentSnapshot document = documents[i];
items.add(Product.fromMap(document.data));
}
return ProductBoxList(items: items);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
)
);
}
Here, we have fetched the product information as List<DocumentSnapshot> type. Since, our widget, ProductBoxList is not compatible with documents, we have converted the documents into List<Product> type and further used it.
Here, we have fetched the product information as List<DocumentSnapshot> type. Since, our widget, ProductBoxList is not compatible with documents, we have converted the documents into List<Product> type and further used it.
Finally, run the application and see the result. Since, we have used the same product information as that of SQLite application and changed the storage medium only, the resulting application looks identical to SQLite application application.
Finally, run the application and see the result. Since, we have used the same product information as that of SQLite application and changed the storage medium only, the resulting application looks identical to SQLite application application.
34 Lectures
4 hours
Sriyank Siddhartha
117 Lectures
10 hours
Frahaan Hussain
27 Lectures
1 hours
Skillbakerystudios
17 Lectures
51 mins
Harsh Kumar Khatri
17 Lectures
1.5 hours
Pramila Rawat
85 Lectures
16.5 hours
Rahul Agarwal
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2316,
"s": 2218,
"text": "Flutter provides many advanced packages to work with databases. The most important packages are −"
},
{
"code": null,
"e": 2377,
"s": 2316,
"text": "sqflite − Used to access and manipulate SQLite database, and"
},
{
"code": null,
"e": 2438,
"s": 2377,
"text": "sqflite − Used to access and manipulate SQLite database, and"
},
{
"code": null,
"e": 2529,
"s": 2438,
"text": "firebase_database − Used to access and manipulate cloud hosted NoSQL database from Google."
},
{
"code": null,
"e": 2620,
"s": 2529,
"text": "firebase_database − Used to access and manipulate cloud hosted NoSQL database from Google."
},
{
"code": null,
"e": 2676,
"s": 2620,
"text": "In this chapter, let us discuss each of them in detail."
},
{
"code": null,
"e": 3026,
"s": 2676,
"text": "SQLite database is the de-facto and standard SQL based embedded database engine. It is small and time-tested database engine. sqflite package provides a lot of functionality to work efficiently with SQLite database. It provides standard methods to manipulate SQLite database engine. The core functionality provided by sqflite package is as follows −"
},
{
"code": null,
"e": 3081,
"s": 3026,
"text": "Create / Open (openDatabase method) a SQLite database."
},
{
"code": null,
"e": 3136,
"s": 3081,
"text": "Create / Open (openDatabase method) a SQLite database."
},
{
"code": null,
"e": 3200,
"s": 3136,
"text": "Execute SQL statement (execute method) against SQLite database."
},
{
"code": null,
"e": 3264,
"s": 3200,
"text": "Execute SQL statement (execute method) against SQLite database."
},
{
"code": null,
"e": 3380,
"s": 3264,
"text": "Advanced query methods (query method) to reduce to code required to query and get information from SQLite database."
},
{
"code": null,
"e": 3496,
"s": 3380,
"text": "Advanced query methods (query method) to reduce to code required to query and get information from SQLite database."
},
{
"code": null,
"e": 3707,
"s": 3496,
"text": "Let us create a product application to store and fetch product information from a standard SQLite database engine using sqflite package and understand the concept behind the SQLite database and sqflite package."
},
{
"code": null,
"e": 3779,
"s": 3707,
"text": "Create a new Flutter application in Android studio, product_sqlite_app."
},
{
"code": null,
"e": 3851,
"s": 3779,
"text": "Create a new Flutter application in Android studio, product_sqlite_app."
},
{
"code": null,
"e": 3928,
"s": 3851,
"text": "Replace the default startup code (main.dart) with our product_rest_app code."
},
{
"code": null,
"e": 4005,
"s": 3928,
"text": "Replace the default startup code (main.dart) with our product_rest_app code."
},
{
"code": null,
"e": 4116,
"s": 4005,
"text": "Copy the assets folder from product_nav_app to product_rest_app and add assets inside the *pubspec.yaml` file."
},
{
"code": null,
"e": 4227,
"s": 4116,
"text": "Copy the assets folder from product_nav_app to product_rest_app and add assets inside the *pubspec.yaml` file."
},
{
"code": null,
"e": 4471,
"s": 4227,
"text": "flutter: \n assets: \n - assets/appimages/floppy.png \n - assets/appimages/iphone.png \n - assets/appimages/laptop.png \n - assets/appimages/pendrive.png \n - assets/appimages/pixel.png \n - assets/appimages/tablet.png"
},
{
"code": null,
"e": 4539,
"s": 4471,
"text": "Configure sqflite package in the pubspec.yaml file as shown below −"
},
{
"code": null,
"e": 4607,
"s": 4539,
"text": "Configure sqflite package in the pubspec.yaml file as shown below −"
},
{
"code": null,
"e": 4635,
"s": 4607,
"text": "dependencies: sqflite: any\n"
},
{
"code": null,
"e": 4692,
"s": 4635,
"text": "Use the latest version number of sqflite in place of any"
},
{
"code": null,
"e": 4766,
"s": 4692,
"text": "Configure path_provider package in the pubspec.yaml file as shown below −"
},
{
"code": null,
"e": 4840,
"s": 4766,
"text": "Configure path_provider package in the pubspec.yaml file as shown below −"
},
{
"code": null,
"e": 4874,
"s": 4840,
"text": "dependencies: path_provider: any\n"
},
{
"code": null,
"e": 5040,
"s": 4874,
"text": "Here, path_provider package is used to get temporary folder path of the system and path of the application. Use the latest version number of sqflite in place of any."
},
{
"code": null,
"e": 5206,
"s": 5040,
"text": "Here, path_provider package is used to get temporary folder path of the system and path of the application. Use the latest version number of sqflite in place of any."
},
{
"code": null,
"e": 5266,
"s": 5206,
"text": "Android studio will alert that the pubspec.yaml is updated."
},
{
"code": null,
"e": 5326,
"s": 5266,
"text": "Android studio will alert that the pubspec.yaml is updated."
},
{
"code": null,
"e": 5454,
"s": 5326,
"text": "Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application."
},
{
"code": null,
"e": 5582,
"s": 5454,
"text": "Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application."
},
{
"code": null,
"e": 5934,
"s": 5582,
"text": "In database, we need primary key, id as additional field along with Product properties like name, price, etc., So, add id property in the Product class. Also, add a new method, toMap to convert product object into Map object. fromMap and toMap are used to serialize and de- serialize the Product object and it is used in database manipulation methods."
},
{
"code": null,
"e": 6286,
"s": 5934,
"text": "In database, we need primary key, id as additional field along with Product properties like name, price, etc., So, add id property in the Product class. Also, add a new method, toMap to convert product object into Map object. fromMap and toMap are used to serialize and de- serialize the Product object and it is used in database manipulation methods."
},
{
"code": null,
"e": 6956,
"s": 6286,
"text": "class Product { \n final int id; \n final String name; \n final String description; \n final int price; \n final String image; \n static final columns = [\"id\", \"name\", \"description\", \"price\", \"image\"]; \n Product(this.id, this.name, this.description, this.price, this.image); \n factory Product.fromMap(Map<String, dynamic> data) {\n return Product( \n data['id'], \n data['name'], \n data['description'], \n data['price'], \n data['image'], \n ); \n } \n Map<String, dynamic> toMap() => {\n \"id\": id, \n \"name\": name, \n \"description\": description, \n \"price\": price, \n \"image\": image \n }; \n}"
},
{
"code": null,
"e": 7046,
"s": 6956,
"text": "Create a new file, Database.dart in the lib folder to write SQLite related functionality."
},
{
"code": null,
"e": 7136,
"s": 7046,
"text": "Create a new file, Database.dart in the lib folder to write SQLite related functionality."
},
{
"code": null,
"e": 7188,
"s": 7136,
"text": "Import necessary import statement in Database.dart."
},
{
"code": null,
"e": 7240,
"s": 7188,
"text": "Import necessary import statement in Database.dart."
},
{
"code": null,
"e": 7430,
"s": 7240,
"text": "import 'dart:async'; \nimport 'dart:io'; \nimport 'package:path/path.dart'; \nimport 'package:path_provider/path_provider.dart'; \nimport 'package:sqflite/sqflite.dart'; \nimport 'Product.dart';"
},
{
"code": null,
"e": 7736,
"s": 7430,
"text": "Note the following points here −\n\nasync is used to write asynchronous methods.\nio is used to access files and directories.\npath is used to access dart core utility function related to file paths.\npath_provider is used to get temporary and application path.\nsqflite is used to manipulate SQLite database.\n\n"
},
{
"code": null,
"e": 7769,
"s": 7736,
"text": "Note the following points here −"
},
{
"code": null,
"e": 7814,
"s": 7769,
"text": "async is used to write asynchronous methods."
},
{
"code": null,
"e": 7859,
"s": 7814,
"text": "async is used to write asynchronous methods."
},
{
"code": null,
"e": 7903,
"s": 7859,
"text": "io is used to access files and directories."
},
{
"code": null,
"e": 7947,
"s": 7903,
"text": "io is used to access files and directories."
},
{
"code": null,
"e": 8020,
"s": 7947,
"text": "path is used to access dart core utility function related to file paths."
},
{
"code": null,
"e": 8093,
"s": 8020,
"text": "path is used to access dart core utility function related to file paths."
},
{
"code": null,
"e": 8154,
"s": 8093,
"text": "path_provider is used to get temporary and application path."
},
{
"code": null,
"e": 8215,
"s": 8154,
"text": "path_provider is used to get temporary and application path."
},
{
"code": null,
"e": 8262,
"s": 8215,
"text": "sqflite is used to manipulate SQLite database."
},
{
"code": null,
"e": 8309,
"s": 8262,
"text": "sqflite is used to manipulate SQLite database."
},
{
"code": null,
"e": 8345,
"s": 8309,
"text": "Create a new class SQLiteDbProvider"
},
{
"code": null,
"e": 8381,
"s": 8345,
"text": "Create a new class SQLiteDbProvider"
},
{
"code": null,
"e": 8460,
"s": 8381,
"text": "Declare a singleton based, static SQLiteDbProvider object as specified below −"
},
{
"code": null,
"e": 8539,
"s": 8460,
"text": "Declare a singleton based, static SQLiteDbProvider object as specified below −"
},
{
"code": null,
"e": 8686,
"s": 8539,
"text": "class SQLiteDbProvider { \n SQLiteDbProvider._(); \n static final SQLiteDbProvider db = SQLiteDbProvider._(); \n static Database _database; \n}\n"
},
{
"code": null,
"e": 8774,
"s": 8686,
"text": "SQLiteDBProvoider object and its method can be accessed through the static db variable."
},
{
"code": null,
"e": 8862,
"s": 8774,
"text": "SQLiteDBProvoider object and its method can be accessed through the static db variable."
},
{
"code": null,
"e": 8893,
"s": 8862,
"text": "SQLiteDBProvoider.db.<emthod>\n"
},
{
"code": null,
"e": 9054,
"s": 8893,
"text": "Create a method to get database (Future option) of type Future<Database>. Create product table and load initial data during the creation of the database itself."
},
{
"code": null,
"e": 9215,
"s": 9054,
"text": "Create a method to get database (Future option) of type Future<Database>. Create product table and load initial data during the creation of the database itself."
},
{
"code": null,
"e": 11424,
"s": 9215,
"text": "Future<Database> get database async { \n if (_database != null) \n return _database; \n _database = await initDB(); \n return _database; \n}\ninitDB() async { \n Directory documentsDirectory = await getApplicationDocumentsDirectory(); \n String path = join(documentsDirectory.path, \"ProductDB.db\"); \n return await openDatabase(\n path, \n version: 1,\n onOpen: (db) {}, \n onCreate: (Database db, int version) async {\n await db.execute(\n \"CREATE TABLE Product (\"\n \"id INTEGER PRIMARY KEY,\"\n \"name TEXT,\"\n \"description TEXT,\"\n \"price INTEGER,\" \n \"image TEXT\" \")\"\n ); \n await db.execute(\n \"INSERT INTO Product ('id', 'name', 'description', 'price', 'image') \n values (?, ?, ?, ?, ?)\", \n [1, \"iPhone\", \"iPhone is the stylist phone ever\", 1000, \"iphone.png\"]\n ); \n await db.execute(\n \"INSERT INTO Product ('id', 'name', 'description', 'price', 'image') \n values (?, ?, ?, ?, ?)\", \n [2, \"Pixel\", \"Pixel is the most feature phone ever\", 800, \"pixel.png\"]\n ); \n await db.execute(\n \"INSERT INTO Product ('id', 'name', 'description', 'price', 'image') \n values (?, ?, ?, ?, ?)\", \n [3, \"Laptop\", \"Laptop is most productive development tool\", 2000, \"laptop.png\"]\\\n ); \n await db.execute( \n \"INSERT INTO Product ('id', 'name', 'description', 'price', 'image') \n values (?, ?, ?, ?, ?)\", \n [4, \"Tablet\", \"Laptop is most productive development tool\", 1500, \"tablet.png\"]\n );\n await db.execute( \n \"INSERT INTO Product \n ('id', 'name', 'description', 'price', 'image') \n values (?, ?, ?, ?, ?)\", \n [5, \"Pendrive\", \"Pendrive is useful storage medium\", 100, \"pendrive.png\"]\n );\n await db.execute( \n \"INSERT INTO Product \n ('id', 'name', 'description', 'price', 'image') \n values (?, ?, ?, ?, ?)\", \n [6, \"Floppy Drive\", \"Floppy drive is useful rescue storage medium\", 20, \"floppy.png\"]\n ); \n }\n ); \n}"
},
{
"code": null,
"e": 11467,
"s": 11424,
"text": "Here, we have used the following methods −"
},
{
"code": null,
"e": 11510,
"s": 11467,
"text": "Here, we have used the following methods −"
},
{
"code": null,
"e": 11580,
"s": 11510,
"text": "getApplicationDocumentsDirectory − Returns application directory path"
},
{
"code": null,
"e": 11650,
"s": 11580,
"text": "getApplicationDocumentsDirectory − Returns application directory path"
},
{
"code": null,
"e": 11735,
"s": 11650,
"text": "join − Used to create system specific path. We have used it to create database path."
},
{
"code": null,
"e": 11820,
"s": 11735,
"text": "join − Used to create system specific path. We have used it to create database path."
},
{
"code": null,
"e": 11866,
"s": 11820,
"text": "openDatabase − Used to open a SQLite database"
},
{
"code": null,
"e": 11912,
"s": 11866,
"text": "openDatabase − Used to open a SQLite database"
},
{
"code": null,
"e": 11965,
"s": 11912,
"text": "onOpen − Used to write code while opening a database"
},
{
"code": null,
"e": 12018,
"s": 11965,
"text": "onOpen − Used to write code while opening a database"
},
{
"code": null,
"e": 12095,
"s": 12018,
"text": "onCreate − Used to write code while a database is created for the first time"
},
{
"code": null,
"e": 12172,
"s": 12095,
"text": "onCreate − Used to write code while a database is created for the first time"
},
{
"code": null,
"e": 12323,
"s": 12172,
"text": "db.execute − Used to execute SQL queries. It accepts a query. If the query has placeholder (?), then it accepts values as list in the second argument."
},
{
"code": null,
"e": 12474,
"s": 12323,
"text": "db.execute − Used to execute SQL queries. It accepts a query. If the query has placeholder (?), then it accepts values as list in the second argument."
},
{
"code": null,
"e": 12527,
"s": 12474,
"text": "Write a method to get all products in the database −"
},
{
"code": null,
"e": 12580,
"s": 12527,
"text": "Write a method to get all products in the database −"
},
{
"code": null,
"e": 12946,
"s": 12580,
"text": "Future<List<Product>> getAllProducts() async { \n final db = await database; \n List<Map> \n results = await db.query(\"Product\", columns: Product.columns, orderBy: \"id ASC\"); \n \n List<Product> products = new List(); \n results.forEach((result) { \n Product product = Product.fromMap(result); \n products.add(product); \n }); \n return products; \n}"
},
{
"code": null,
"e": 12981,
"s": 12946,
"text": "Here, we have done the following −"
},
{
"code": null,
"e": 13016,
"s": 12981,
"text": "Here, we have done the following −"
},
{
"code": null,
"e": 13258,
"s": 13016,
"text": "Used query method to fetch all the product information. query provides shortcut to query a table information without writing the entire query. query method will generate the proper query itself by using our input like columns, orderBy, etc.,"
},
{
"code": null,
"e": 13500,
"s": 13258,
"text": "Used query method to fetch all the product information. query provides shortcut to query a table information without writing the entire query. query method will generate the proper query itself by using our input like columns, orderBy, etc.,"
},
{
"code": null,
"e": 13623,
"s": 13500,
"text": "Used Product’s fromMap method to get product details by looping the results object, which holds all the rows in the table."
},
{
"code": null,
"e": 13746,
"s": 13623,
"text": "Used Product’s fromMap method to get product details by looping the results object, which holds all the rows in the table."
},
{
"code": null,
"e": 13791,
"s": 13746,
"text": "Write a method to get product specific to id"
},
{
"code": null,
"e": 13836,
"s": 13791,
"text": "Write a method to get product specific to id"
},
{
"code": null,
"e": 14062,
"s": 13836,
"text": "Future<Product> getProductById(int id) async {\n final db = await database; \n var result = await db.query(\"Product\", where: \"id = \", whereArgs: [id]); \n return result.isNotEmpty ? Product.fromMap(result.first) : Null; \n}"
},
{
"code": null,
"e": 14120,
"s": 14062,
"text": "Here, we have used where and whereArgs to apply filters.\n"
},
{
"code": null,
"e": 14177,
"s": 14120,
"text": "Here, we have used where and whereArgs to apply filters."
},
{
"code": null,
"e": 14289,
"s": 14177,
"text": "Create three methods - insert, update and delete method to insert, update and delete product from the database."
},
{
"code": null,
"e": 14401,
"s": 14289,
"text": "Create three methods - insert, update and delete method to insert, update and delete product from the database."
},
{
"code": null,
"e": 15167,
"s": 14401,
"text": "insert(Product product) async { \n final db = await database; \n var maxIdResult = await db.rawQuery(\n \"SELECT MAX(id)+1 as last_inserted_id FROM Product\");\n\n var id = maxIdResult.first[\"last_inserted_id\"]; \n var result = await db.rawInsert(\n \"INSERT Into Product (id, name, description, price, image)\" \n \" VALUES (?, ?, ?, ?, ?)\", \n [id, product.name, product.description, product.price, product.image] \n ); \n return result; \n}\nupdate(Product product) async { \n final db = await database; \n var result = await db.update(\"Product\", product.toMap(), \n where: \"id = ?\", whereArgs: [product.id]); return result; \n} \ndelete(int id) async { \n final db = await database; \n db.delete(\"Product\", where: \"id = ?\", whereArgs: [id]); \n}"
},
{
"code": null,
"e": 15219,
"s": 15167,
"text": "The final code of the Database.dart is as follows −"
},
{
"code": null,
"e": 15271,
"s": 15219,
"text": "The final code of the Database.dart is as follows −"
},
{
"code": null,
"e": 19445,
"s": 15271,
"text": "import 'dart:async'; \nimport 'dart:io'; \nimport 'package:path/path.dart'; \nimport 'package:path_provider/path_provider.dart'; \nimport 'package:sqflite/sqflite.dart'; \nimport 'Product.dart'; \n\nclass SQLiteDbProvider {\n SQLiteDbProvider._(); \n static final SQLiteDbProvider db = SQLiteDbProvider._(); \n static Database _database; \n \n Future<Database> get database async {\n if (_database != null) \n return _database; \n _database = await initDB(); \n return _database; \n } \n initDB() async {\n Directory documentsDirectory = await \n getApplicationDocumentsDirectory(); \n String path = join(documentsDirectory.path, \"ProductDB.db\"); \n return await openDatabase(\n path, version: 1, \n onOpen: (db) {}, \n onCreate: (Database db, int version) async {\n await db.execute(\n \"CREATE TABLE Product (\" \n \"id INTEGER PRIMARY KEY,\" \n \"name TEXT,\" \n \"description TEXT,\" \n \"price INTEGER,\" \n \"image TEXT\"\")\"\n ); \n await db.execute(\n \"INSERT INTO Product ('id', 'name', 'description', 'price', 'image') \n values (?, ?, ?, ?, ?)\", \n [1, \"iPhone\", \"iPhone is the stylist phone ever\", 1000, \"iphone.png\"]\n ); \n await db.execute( \n \"INSERT INTO Product ('id', 'name', 'description', 'price', 'image') \n values (?, ?, ?, ?, ?)\", \n [2, \"Pixel\", \"Pixel is the most feature phone ever\", 800, \"pixel.png\"]\n );\n await db.execute(\n \"INSERT INTO Product ('id', 'name', 'description', 'price', 'image') \n values (?, ?, ?, ?, ?)\", \n [3, \"Laptop\", \"Laptop is most productive development tool\", 2000, \"laptop.png\"]\n ); \n await db.execute( \n \"INSERT INTO Product ('id', 'name', 'description', 'price', 'image') \n values (?, ?, ?, ?, ?)\", \n [4, \"Tablet\", \"Laptop is most productive development tool\", 1500, \"tablet.png\"]\n ); \n await db.execute( \n \"INSERT INTO Product ('id', 'name', 'description', 'price', 'image') \n values (?, ?, ?, ?, ?)\", \n [5, \"Pendrive\", \"Pendrive is useful storage medium\", 100, \"pendrive.png\"]\n );\n await db.execute( \n \"INSERT INTO Product ('id', 'name', 'description', 'price', 'image') \n values (?, ?, ?, ?, ?)\", \n [6, \"Floppy Drive\", \"Floppy drive is useful rescue storage medium\", 20, \"floppy.png\"]\n ); \n }\n ); \n }\n Future<List<Product>> getAllProducts() async {\n final db = await database; \n List<Map> results = await db.query(\n \"Product\", columns: Product.columns, orderBy: \"id ASC\"\n ); \n List<Product> products = new List(); \n results.forEach((result) {\n Product product = Product.fromMap(result); \n products.add(product); \n }); \n return products; \n } \n Future<Product> getProductById(int id) async {\n final db = await database; \n var result = await db.query(\"Product\", where: \"id = \", whereArgs: [id]); \n return result.isNotEmpty ? Product.fromMap(result.first) : Null; \n } \n insert(Product product) async { \n final db = await database; \n var maxIdResult = await db.rawQuery(\"SELECT MAX(id)+1 as last_inserted_id FROM Product\"); \n var id = maxIdResult.first[\"last_inserted_id\"]; \n var result = await db.rawInsert(\n \"INSERT Into Product (id, name, description, price, image)\" \n \" VALUES (?, ?, ?, ?, ?)\", \n [id, product.name, product.description, product.price, product.image] \n ); \n return result; \n } \n update(Product product) async { \n final db = await database; \n var result = await db.update(\n \"Product\", product.toMap(), where: \"id = ?\", whereArgs: [product.id]\n ); \n return result; \n } \n delete(int id) async { \n final db = await database; \n db.delete(\"Product\", where: \"id = ?\", whereArgs: [id]);\n } \n}"
},
{
"code": null,
"e": 19500,
"s": 19445,
"text": "Change the main method to get the product information."
},
{
"code": null,
"e": 19555,
"s": 19500,
"text": "Change the main method to get the product information."
},
{
"code": null,
"e": 19638,
"s": 19555,
"text": "void main() {\n runApp(MyApp(products: SQLiteDbProvider.db.getAllProducts())); \n}"
},
{
"code": null,
"e": 19724,
"s": 19638,
"text": "Here, we have used the getAllProducts method to fetch all products from the database."
},
{
"code": null,
"e": 19810,
"s": 19724,
"text": "Here, we have used the getAllProducts method to fetch all products from the database."
},
{
"code": null,
"e": 20007,
"s": 19810,
"text": "Run the application and see the results. It will be similar to previous example, Accessing Product service API, except the product information is stored and fetched from the local SQLite database."
},
{
"code": null,
"e": 20204,
"s": 20007,
"text": "Run the application and see the results. It will be similar to previous example, Accessing Product service API, except the product information is stored and fetched from the local SQLite database."
},
{
"code": null,
"e": 20467,
"s": 20204,
"text": "Firebase is a BaaS app development platform. It provides many feature to speed up the mobile application development like authentication service, cloud storage, etc., One of the main feature of Firebase is Cloud Firestore, a cloud based real time NoSQL database."
},
{
"code": null,
"e": 20667,
"s": 20467,
"text": "Flutter provides a special package, cloud_firestore to program with Cloud Firestore. Let us create an online product store in the Cloud Firestore and create a application to access the product store."
},
{
"code": null,
"e": 20741,
"s": 20667,
"text": "Create a new Flutter application in Android studio, product_firebase_app."
},
{
"code": null,
"e": 20815,
"s": 20741,
"text": "Create a new Flutter application in Android studio, product_firebase_app."
},
{
"code": null,
"e": 20892,
"s": 20815,
"text": "Replace the default startup code (main.dart) with our product_rest_app code."
},
{
"code": null,
"e": 20969,
"s": 20892,
"text": "Replace the default startup code (main.dart) with our product_rest_app code."
},
{
"code": null,
"e": 21035,
"s": 20969,
"text": "Copy Product.dart file from product_rest_app into the lib folder."
},
{
"code": null,
"e": 21101,
"s": 21035,
"text": "Copy Product.dart file from product_rest_app into the lib folder."
},
{
"code": null,
"e": 21487,
"s": 21101,
"text": "class Product { \n final String name; \n final String description; \n final int price; \n final String image; \n \n Product(this.name, this.description, this.price, this.image); \n factory Product.fromMap(Map<String, dynamic> json) {\n return Product( \n json['name'], \n json['description'], \n json['price'], \n json['image'], \n ); \n }\n}"
},
{
"code": null,
"e": 21601,
"s": 21487,
"text": "Copy the assets folder from product_rest_app to product_firebase_app and add assets inside the pubspec.yaml file."
},
{
"code": null,
"e": 21715,
"s": 21601,
"text": "Copy the assets folder from product_rest_app to product_firebase_app and add assets inside the pubspec.yaml file."
},
{
"code": null,
"e": 21940,
"s": 21715,
"text": "flutter:\n assets: \n - assets/appimages/floppy.png \n - assets/appimages/iphone.png \n - assets/appimages/laptop.png \n - assets/appimages/pendrive.png \n - assets/appimages/pixel.png \n - assets/appimages/tablet.png"
},
{
"code": null,
"e": 22016,
"s": 21940,
"text": "Configure cloud_firestore package in the pubspec.yaml file as shown below −"
},
{
"code": null,
"e": 22092,
"s": 22016,
"text": "Configure cloud_firestore package in the pubspec.yaml file as shown below −"
},
{
"code": null,
"e": 22134,
"s": 22092,
"text": "dependencies: cloud_firestore: ^0.9.13+1\n"
},
{
"code": null,
"e": 22195,
"s": 22134,
"text": "Here, use the latest version of the cloud_firestore package."
},
{
"code": null,
"e": 22256,
"s": 22195,
"text": "Here, use the latest version of the cloud_firestore package."
},
{
"code": null,
"e": 22331,
"s": 22256,
"text": "Android studio will alert that the pubspec.yaml is updated as shown here −"
},
{
"code": null,
"e": 22406,
"s": 22331,
"text": "Android studio will alert that the pubspec.yaml is updated as shown here −"
},
{
"code": null,
"e": 22534,
"s": 22406,
"text": "Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application."
},
{
"code": null,
"e": 22662,
"s": 22534,
"text": "Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application."
},
{
"code": null,
"e": 22723,
"s": 22662,
"text": "Create a project in the Firebase using the following steps −"
},
{
"code": null,
"e": 22784,
"s": 22723,
"text": "Create a project in the Firebase using the following steps −"
},
{
"code": null,
"e": 22874,
"s": 22784,
"text": "Create a Firebase account by selecting Free plan at https://firebase.google.com/pricing/."
},
{
"code": null,
"e": 22964,
"s": 22874,
"text": "Create a Firebase account by selecting Free plan at https://firebase.google.com/pricing/."
},
{
"code": null,
"e": 23132,
"s": 22964,
"text": "Once Firebase account is created, it will redirect to the project overview page. It list all the Firebase based project and provides an option to create a new project."
},
{
"code": null,
"e": 23300,
"s": 23132,
"text": "Once Firebase account is created, it will redirect to the project overview page. It list all the Firebase based project and provides an option to create a new project."
},
{
"code": null,
"e": 23360,
"s": 23300,
"text": "Click Add project and it will open a project creation page."
},
{
"code": null,
"e": 23420,
"s": 23360,
"text": "Click Add project and it will open a project creation page."
},
{
"code": null,
"e": 23491,
"s": 23420,
"text": "Enter products app db as project name and click Create project option."
},
{
"code": null,
"e": 23562,
"s": 23491,
"text": "Enter products app db as project name and click Create project option."
},
{
"code": null,
"e": 23587,
"s": 23562,
"text": "Go to *Firebase console."
},
{
"code": null,
"e": 23612,
"s": 23587,
"text": "Go to *Firebase console."
},
{
"code": null,
"e": 23672,
"s": 23612,
"text": "Click Project overview. It opens the project overview page."
},
{
"code": null,
"e": 23732,
"s": 23672,
"text": "Click Project overview. It opens the project overview page."
},
{
"code": null,
"e": 23814,
"s": 23732,
"text": "Click android icon. It will open project setting specific to Android development."
},
{
"code": null,
"e": 23896,
"s": 23814,
"text": "Click android icon. It will open project setting specific to Android development."
},
{
"code": null,
"e": 23976,
"s": 23896,
"text": "Enter Android Package name, com.tutorialspoint.flutterapp.product_firebase_app."
},
{
"code": null,
"e": 24056,
"s": 23976,
"text": "Enter Android Package name, com.tutorialspoint.flutterapp.product_firebase_app."
},
{
"code": null,
"e": 24140,
"s": 24056,
"text": "Click Register App. It generates a project configuration file, google_service.json."
},
{
"code": null,
"e": 24224,
"s": 24140,
"text": "Click Register App. It generates a project configuration file, google_service.json."
},
{
"code": null,
"e": 24378,
"s": 24224,
"text": "Download google_service.json and then move it into the project’s android/app directory. This file is the connection between our application and Firebase."
},
{
"code": null,
"e": 24532,
"s": 24378,
"text": "Download google_service.json and then move it into the project’s android/app directory. This file is the connection between our application and Firebase."
},
{
"code": null,
"e": 24595,
"s": 24532,
"text": "Open android/app/build.gradle and include the following code −"
},
{
"code": null,
"e": 24658,
"s": 24595,
"text": "Open android/app/build.gradle and include the following code −"
},
{
"code": null,
"e": 24706,
"s": 24658,
"text": "apply plugin: 'com.google.gms.google-services'\n"
},
{
"code": null,
"e": 24774,
"s": 24706,
"text": "Open android/build.gradle and include the following configuration −"
},
{
"code": null,
"e": 24842,
"s": 24774,
"text": "Open android/build.gradle and include the following configuration −"
},
{
"code": null,
"e": 25000,
"s": 24842,
"text": "buildscript {\n repositories { \n // ... \n } \n dependencies { \n // ... \n classpath 'com.google.gms:google-services:3.2.1' // new \n } \n}\n"
},
{
"code": null,
"e": 25094,
"s": 25000,
"text": "Here, the plugin and class path are used for the purpose of reading google_service.json file."
},
{
"code": null,
"e": 25164,
"s": 25094,
"text": "Open android/app/build.gradle and include the following code as well."
},
{
"code": null,
"e": 25234,
"s": 25164,
"text": "Open android/app/build.gradle and include the following code as well."
},
{
"code": null,
"e": 25393,
"s": 25234,
"text": "android {\n defaultConfig { \n ... \n multiDexEnabled true \n } \n ...\n}\ndependencies {\n ... \n compile 'com.android.support: multidex:1.0.3' \n}"
},
{
"code": null,
"e": 25476,
"s": 25393,
"text": "This dependency enables the android application to use multiple dex functionality."
},
{
"code": null,
"e": 25544,
"s": 25476,
"text": "Follow the remaining steps in the Firebase Console or just skip it."
},
{
"code": null,
"e": 25612,
"s": 25544,
"text": "Follow the remaining steps in the Firebase Console or just skip it."
},
{
"code": null,
"e": 25692,
"s": 25612,
"text": "Create a product store in the newly created project using the following steps −"
},
{
"code": null,
"e": 25772,
"s": 25692,
"text": "Create a product store in the newly created project using the following steps −"
},
{
"code": null,
"e": 25796,
"s": 25772,
"text": "Go to Firebase console."
},
{
"code": null,
"e": 25820,
"s": 25796,
"text": "Go to Firebase console."
},
{
"code": null,
"e": 25852,
"s": 25820,
"text": "Open the newly created project."
},
{
"code": null,
"e": 25884,
"s": 25852,
"text": "Open the newly created project."
},
{
"code": null,
"e": 25928,
"s": 25884,
"text": "Click the Database option in the left menu."
},
{
"code": null,
"e": 25972,
"s": 25928,
"text": "Click the Database option in the left menu."
},
{
"code": null,
"e": 26002,
"s": 25972,
"text": "Click Create database option."
},
{
"code": null,
"e": 26032,
"s": 26002,
"text": "Click Create database option."
},
{
"code": null,
"e": 26074,
"s": 26032,
"text": "Click Start in test mode and then Enable."
},
{
"code": null,
"e": 26116,
"s": 26074,
"text": "Click Start in test mode and then Enable."
},
{
"code": null,
"e": 26192,
"s": 26116,
"text": "Click Add collection. Enter product as collection name and then click Next."
},
{
"code": null,
"e": 26268,
"s": 26192,
"text": "Click Add collection. Enter product as collection name and then click Next."
},
{
"code": null,
"e": 26334,
"s": 26268,
"text": "Enter the sample product information as shown in the image here −"
},
{
"code": null,
"e": 26400,
"s": 26334,
"text": "Enter the sample product information as shown in the image here −"
},
{
"code": null,
"e": 26461,
"s": 26400,
"text": "Add addition product information using Add document options."
},
{
"code": null,
"e": 26522,
"s": 26461,
"text": "Add addition product information using Add document options."
},
{
"code": null,
"e": 26606,
"s": 26522,
"text": "Open main.dart file and import Cloud Firestore plugin file and remove http package."
},
{
"code": null,
"e": 26690,
"s": 26606,
"text": "Open main.dart file and import Cloud Firestore plugin file and remove http package."
},
{
"code": null,
"e": 26746,
"s": 26690,
"text": "import 'package:cloud_firestore/cloud_firestore.dart';\n"
},
{
"code": null,
"e": 26863,
"s": 26746,
"text": "Remove parseProducts and update fetchProducts to fetch products from Cloud Firestore instead of Product service API."
},
{
"code": null,
"e": 26980,
"s": 26863,
"text": "Remove parseProducts and update fetchProducts to fetch products from Cloud Firestore instead of Product service API."
},
{
"code": null,
"e": 27088,
"s": 26980,
"text": "Stream<QuerySnapshot> fetchProducts() { \n return Firestore.instance.collection('product').snapshots(); }\n"
},
{
"code": null,
"e": 27374,
"s": 27088,
"text": "Here, Firestore.instance.collection method is used to access product collection available in the cloud store. Firestore.instance.collection provides many option to filter the collection to get the necessary documents. But, we have not applied any filter to get all product information."
},
{
"code": null,
"e": 27660,
"s": 27374,
"text": "Here, Firestore.instance.collection method is used to access product collection available in the cloud store. Firestore.instance.collection provides many option to filter the collection to get the necessary documents. But, we have not applied any filter to get all product information."
},
{
"code": null,
"e": 27844,
"s": 27660,
"text": "Cloud Firestore provides the collection through Dart Stream concept and so modify the products type in MyApp and MyHomePage widget from Future<list<Product>> to Stream<QuerySnapshot>."
},
{
"code": null,
"e": 28028,
"s": 27844,
"text": "Cloud Firestore provides the collection through Dart Stream concept and so modify the products type in MyApp and MyHomePage widget from Future<list<Product>> to Stream<QuerySnapshot>."
},
{
"code": null,
"e": 28120,
"s": 28028,
"text": "Change the build method of MyHomePage widget to use StreamBuilder instead of FutureBuilder."
},
{
"code": null,
"e": 28212,
"s": 28120,
"text": "Change the build method of MyHomePage widget to use StreamBuilder instead of FutureBuilder."
},
{
"code": null,
"e": 29204,
"s": 28212,
"text": "@override \nWidget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(title: Text(\"Product Navigation\")), \n body: Center(\n child: StreamBuilder<QuerySnapshot>(\n stream: products, builder: (context, snapshot) {\n if (snapshot.hasError) print(snapshot.error); \n if(snapshot.hasData) {\n List<DocumentSnapshot> \n documents = snapshot.data.documents; \n \n List<Product> \n items = List<Product>(); \n \n for(var i = 0; i < documents.length; i++) { \n DocumentSnapshot document = documents[i]; \n items.add(Product.fromMap(document.data)); \n } \n return ProductBoxList(items: items);\n } else { \n return Center(child: CircularProgressIndicator()); \n }\n }, \n ), \n )\n ); \n}"
},
{
"code": null,
"e": 29427,
"s": 29204,
"text": "Here, we have fetched the product information as List<DocumentSnapshot> type. Since, our widget, ProductBoxList is not compatible with documents, we have converted the documents into List<Product> type and further used it."
},
{
"code": null,
"e": 29650,
"s": 29427,
"text": "Here, we have fetched the product information as List<DocumentSnapshot> type. Since, our widget, ProductBoxList is not compatible with documents, we have converted the documents into List<Product> type and further used it."
},
{
"code": null,
"e": 29892,
"s": 29650,
"text": "Finally, run the application and see the result. Since, we have used the same product information as that of SQLite application and changed the storage medium only, the resulting application looks identical to SQLite application application."
},
{
"code": null,
"e": 30134,
"s": 29892,
"text": "Finally, run the application and see the result. Since, we have used the same product information as that of SQLite application and changed the storage medium only, the resulting application looks identical to SQLite application application."
},
{
"code": null,
"e": 30167,
"s": 30134,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 30187,
"s": 30167,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 30222,
"s": 30187,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 30239,
"s": 30222,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 30272,
"s": 30239,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 30292,
"s": 30272,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 30324,
"s": 30292,
"text": "\n 17 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 30344,
"s": 30324,
"text": " Harsh Kumar Khatri"
},
{
"code": null,
"e": 30379,
"s": 30344,
"text": "\n 17 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 30394,
"s": 30379,
"text": " Pramila Rawat"
},
{
"code": null,
"e": 30430,
"s": 30394,
"text": "\n 85 Lectures \n 16.5 hours \n"
},
{
"code": null,
"e": 30445,
"s": 30430,
"text": " Rahul Agarwal"
},
{
"code": null,
"e": 30452,
"s": 30445,
"text": " Print"
},
{
"code": null,
"e": 30463,
"s": 30452,
"text": " Add Notes"
}
] |
How to remove specific characters from a string in Python?
|
The string class has a method replace that can be used to replace substrings in a string. We can use this method to replace characters we want to remove with an empty string. For example:
>>> "Hello people".replace("e", "")
"Hllo popl"
If you want to remove multiple characters from a string in a single line, it's better to use regular expressions. You can separate multiple characters by "|" and use the re.sub(chars_to_replace, string_to_replace_with, str). For example:
import re
print (re.sub("e|l", " ", "Hello people"))
OUTPUT
H o p op
Note: You can also use the [ ] to create group of characters to replace in regex.
|
[
{
"code": null,
"e": 1250,
"s": 1062,
"text": "The string class has a method replace that can be used to replace substrings in a string. We can use this method to replace characters we want to remove with an empty string. For example:"
},
{
"code": null,
"e": 1298,
"s": 1250,
"text": ">>> \"Hello people\".replace(\"e\", \"\")\n\"Hllo popl\""
},
{
"code": null,
"e": 1536,
"s": 1298,
"text": "If you want to remove multiple characters from a string in a single line, it's better to use regular expressions. You can separate multiple characters by \"|\" and use the re.sub(chars_to_replace, string_to_replace_with, str). For example:"
},
{
"code": null,
"e": 1589,
"s": 1536,
"text": "import re\nprint (re.sub(\"e|l\", \" \", \"Hello people\"))"
},
{
"code": null,
"e": 1597,
"s": 1589,
"text": " OUTPUT"
},
{
"code": null,
"e": 1608,
"s": 1597,
"text": "H o p op"
},
{
"code": null,
"e": 1691,
"s": 1608,
"text": " Note: You can also use the [ ] to create group of characters to replace in regex."
}
] |
Split single column into multiple columns in PySpark DataFrame - GeeksforGeeks
|
09 May, 2021
pyspark.sql.functions provide a function split() which is used to split DataFrame string Column into multiple columns.
Syntax: pyspark.sql.functions.split(str, pattern, limit=- 1)
Parameters:
str: str is a Column or str to split.
pattern: It is a str parameter, a string that represents a regular expression. This should be a Java regular expression.
limit: It is an int parameter. Optional an integer value when specified controls the number of times the pattern is applied.limit > 0: The resulting array length must not be more than limit specified.limit <= 0: The pattern must be applied as many times as possible or till the limit.
limit > 0: The resulting array length must not be more than limit specified.
limit <= 0: The pattern must be applied as many times as possible or till the limit.
First Let’s create a DataFrame.
Python3
# installing pyspark!pip install pyspark # importing pysparkimport pyspark # importing SparkSessionfrom pyspark.sql import SparkSession # importing all from pyspark.sql.functionfrom pyspark.sql.functions import * # creating SparkSession objectspark=SparkSession.builder.appName("sparkdf").getOrCreate() # creating the row data for dataframedata = [('Jaya', 'Sinha', 'F', '1991-04-01'), ('Milan', 'Sharma', '', '2000-05-19'), ('Rohit', 'Verma', 'M', '1978-09-05'), ('Maria', 'Anne', 'F', '1967-12-01'), ('Jay', 'Mehta', 'M', '1980-02-17') ] # giving the column names for the dataframecolumns = ['First Name', 'Last Name', 'Gender', 'DOB'] # creating the dataframe dfdf = spark.createDataFrame(data, columns) # printing dataframe schemadf.printSchema() # show dataframedf.show()
Output:
DataFrame created
Example 1: Split column using withColumn()
In this example, we created a simple dataframe with the column ‘DOB’ which contains the date of birth in yyyy-mm-dd in string format. Using the split and withColumn() the column will be split into the year, month, and date column.
Python3
# split() function defining parameterssplit_cols = pyspark.sql.functions.split(df['DOB'], '-') # Now applying split() using withColumn()df1 = df.withColumn('Year', split_cols.getItem(0)) \ .withColumn('Month', split_cols.getItem(1)) \ .withColumn('Day', split_cols.getItem(2)) # show dfdf1.show()
Output:
Dataframe after splitting columns
Alternatively, we can also write like this, it will give the same output:
Python3
# defining split() along with withColumn()df2 = df.withColumn('Year', split(df['DOB'], '-').getItem(0)) \ .withColumn('Month', split(df['DOB'], '-').getItem(1)) \ .withColumn('Day', split(df['DOB'], '-').getItem(2)) # show df2df2.show()
Output:
In the above example we have used 2 parameters of split() i.e.’ str’ that contains the column name and ‘pattern’ contains the pattern type of the data present in that column and to split data from that position.
Example 2: Split column using select()
In this example we will use the same DataFrame df and split its ‘DOB’ column using .select():
Python3
# creating the row data for dataframedata = [('Jaya', 'Sinha', 'F', '1991-04-01'), ('Milan', 'Sharma', '', '2000-05-19'), ('Rohit', 'Verma', 'M', '1978-09-05'), ('Maria', 'Anne', 'F', '1967-12-01'), ('Jay', 'Mehta', 'M', '1980-02-17') ] # giving the column names for the dataframecolumns = ['First Name', 'Last Name', 'DOB'] # creating the dataframe dfdf = spark.createDataFrame(data, columns) # printing dataframe schemadf.printSchema() # show dataframedf.show() # defining split ()split_cols = pyspark.sql.functions.split(df['DOB'], '-') # applying split() using select()df3 = df.select('First Name', 'Last Name', 'Gender', 'DOB', split_cols.getItem(0).alias('year'), split_cols.getItem(1).alias('month'), split_cols.getItem(2).alias('day')) # show df3df3.show()
Output:
In the above example, we have not selected the ‘Gender’ column in select(), so it is not visible in resultant df3.
Example 3: Splitting another string column
Python3
# creating the row data for dataframedata = [('Jaya', 'Sinha'), ('Milan', 'Soni'), ('Rohit', 'Verma'), ('Maria', 'Anne'), ('Jay', 'Mehta')] # giving the column names for the dataframecolumns = ['First Name', 'Last Name'] # creating the dataframe dfdf = spark.createDataFrame(data, columns) # printing dataframe schemadf.printSchema() # show dataframedf.show() # defining split()split_cols = pyspark.sql.functions.split(df['Last Name'], '') # applying split() using .withColumn()df = df.withColumn('1', split_cols.getItem(0)) \ .withColumn('2', split_cols.getItem(1)) \ .withColumn('3', split_cols.getItem(2)) \ .withColumn('4', split_cols.getItem(3)) \ .withColumn('5', split_cols.getItem(4)) # show dfdf.show()
Output:
In the above example, we have taken only two columns First Name and Last Name and split the Last Name column values into single characters residing in multiple columns.
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n09 May, 2021"
},
{
"code": null,
"e": 24021,
"s": 23901,
"text": "pyspark.sql.functions provide a function split() which is used to split DataFrame string Column into multiple columns. "
},
{
"code": null,
"e": 24083,
"s": 24021,
"text": " Syntax: pyspark.sql.functions.split(str, pattern, limit=- 1)"
},
{
"code": null,
"e": 24095,
"s": 24083,
"text": "Parameters:"
},
{
"code": null,
"e": 24133,
"s": 24095,
"text": "str: str is a Column or str to split."
},
{
"code": null,
"e": 24254,
"s": 24133,
"text": "pattern: It is a str parameter, a string that represents a regular expression. This should be a Java regular expression."
},
{
"code": null,
"e": 24539,
"s": 24254,
"text": "limit: It is an int parameter. Optional an integer value when specified controls the number of times the pattern is applied.limit > 0: The resulting array length must not be more than limit specified.limit <= 0: The pattern must be applied as many times as possible or till the limit."
},
{
"code": null,
"e": 24616,
"s": 24539,
"text": "limit > 0: The resulting array length must not be more than limit specified."
},
{
"code": null,
"e": 24701,
"s": 24616,
"text": "limit <= 0: The pattern must be applied as many times as possible or till the limit."
},
{
"code": null,
"e": 24733,
"s": 24701,
"text": "First Let’s create a DataFrame."
},
{
"code": null,
"e": 24741,
"s": 24733,
"text": "Python3"
},
{
"code": "# installing pyspark!pip install pyspark # importing pysparkimport pyspark # importing SparkSessionfrom pyspark.sql import SparkSession # importing all from pyspark.sql.functionfrom pyspark.sql.functions import * # creating SparkSession objectspark=SparkSession.builder.appName(\"sparkdf\").getOrCreate() # creating the row data for dataframedata = [('Jaya', 'Sinha', 'F', '1991-04-01'), ('Milan', 'Sharma', '', '2000-05-19'), ('Rohit', 'Verma', 'M', '1978-09-05'), ('Maria', 'Anne', 'F', '1967-12-01'), ('Jay', 'Mehta', 'M', '1980-02-17') ] # giving the column names for the dataframecolumns = ['First Name', 'Last Name', 'Gender', 'DOB'] # creating the dataframe dfdf = spark.createDataFrame(data, columns) # printing dataframe schemadf.printSchema() # show dataframedf.show()",
"e": 25564,
"s": 24741,
"text": null
},
{
"code": null,
"e": 25572,
"s": 25564,
"text": "Output:"
},
{
"code": null,
"e": 25590,
"s": 25572,
"text": "DataFrame created"
},
{
"code": null,
"e": 25633,
"s": 25590,
"text": "Example 1: Split column using withColumn()"
},
{
"code": null,
"e": 25864,
"s": 25633,
"text": "In this example, we created a simple dataframe with the column ‘DOB’ which contains the date of birth in yyyy-mm-dd in string format. Using the split and withColumn() the column will be split into the year, month, and date column."
},
{
"code": null,
"e": 25872,
"s": 25864,
"text": "Python3"
},
{
"code": "# split() function defining parameterssplit_cols = pyspark.sql.functions.split(df['DOB'], '-') # Now applying split() using withColumn()df1 = df.withColumn('Year', split_cols.getItem(0)) \\ .withColumn('Month', split_cols.getItem(1)) \\ .withColumn('Day', split_cols.getItem(2)) # show dfdf1.show()",
"e": 26177,
"s": 25872,
"text": null
},
{
"code": null,
"e": 26185,
"s": 26177,
"text": "Output:"
},
{
"code": null,
"e": 26219,
"s": 26185,
"text": "Dataframe after splitting columns"
},
{
"code": null,
"e": 26293,
"s": 26219,
"text": "Alternatively, we can also write like this, it will give the same output:"
},
{
"code": null,
"e": 26301,
"s": 26293,
"text": "Python3"
},
{
"code": "# defining split() along with withColumn()df2 = df.withColumn('Year', split(df['DOB'], '-').getItem(0)) \\ .withColumn('Month', split(df['DOB'], '-').getItem(1)) \\ .withColumn('Day', split(df['DOB'], '-').getItem(2)) # show df2df2.show()",
"e": 26545,
"s": 26301,
"text": null
},
{
"code": null,
"e": 26553,
"s": 26545,
"text": "Output:"
},
{
"code": null,
"e": 26765,
"s": 26553,
"text": "In the above example we have used 2 parameters of split() i.e.’ str’ that contains the column name and ‘pattern’ contains the pattern type of the data present in that column and to split data from that position."
},
{
"code": null,
"e": 26804,
"s": 26765,
"text": "Example 2: Split column using select()"
},
{
"code": null,
"e": 26899,
"s": 26804,
"text": "In this example we will use the same DataFrame df and split its ‘DOB’ column using .select(): "
},
{
"code": null,
"e": 26907,
"s": 26899,
"text": "Python3"
},
{
"code": "# creating the row data for dataframedata = [('Jaya', 'Sinha', 'F', '1991-04-01'), ('Milan', 'Sharma', '', '2000-05-19'), ('Rohit', 'Verma', 'M', '1978-09-05'), ('Maria', 'Anne', 'F', '1967-12-01'), ('Jay', 'Mehta', 'M', '1980-02-17') ] # giving the column names for the dataframecolumns = ['First Name', 'Last Name', 'DOB'] # creating the dataframe dfdf = spark.createDataFrame(data, columns) # printing dataframe schemadf.printSchema() # show dataframedf.show() # defining split ()split_cols = pyspark.sql.functions.split(df['DOB'], '-') # applying split() using select()df3 = df.select('First Name', 'Last Name', 'Gender', 'DOB', split_cols.getItem(0).alias('year'), split_cols.getItem(1).alias('month'), split_cols.getItem(2).alias('day')) # show df3df3.show()",
"e": 27759,
"s": 26907,
"text": null
},
{
"code": null,
"e": 27767,
"s": 27759,
"text": "Output:"
},
{
"code": null,
"e": 27882,
"s": 27767,
"text": "In the above example, we have not selected the ‘Gender’ column in select(), so it is not visible in resultant df3."
},
{
"code": null,
"e": 27925,
"s": 27882,
"text": "Example 3: Splitting another string column"
},
{
"code": null,
"e": 27933,
"s": 27925,
"text": "Python3"
},
{
"code": "# creating the row data for dataframedata = [('Jaya', 'Sinha'), ('Milan', 'Soni'), ('Rohit', 'Verma'), ('Maria', 'Anne'), ('Jay', 'Mehta')] # giving the column names for the dataframecolumns = ['First Name', 'Last Name'] # creating the dataframe dfdf = spark.createDataFrame(data, columns) # printing dataframe schemadf.printSchema() # show dataframedf.show() # defining split()split_cols = pyspark.sql.functions.split(df['Last Name'], '') # applying split() using .withColumn()df = df.withColumn('1', split_cols.getItem(0)) \\ .withColumn('2', split_cols.getItem(1)) \\ .withColumn('3', split_cols.getItem(2)) \\ .withColumn('4', split_cols.getItem(3)) \\ .withColumn('5', split_cols.getItem(4)) # show dfdf.show()",
"e": 28691,
"s": 27933,
"text": null
},
{
"code": null,
"e": 28699,
"s": 28691,
"text": "Output:"
},
{
"code": null,
"e": 28868,
"s": 28699,
"text": "In the above example, we have taken only two columns First Name and Last Name and split the Last Name column values into single characters residing in multiple columns."
},
{
"code": null,
"e": 28875,
"s": 28868,
"text": "Picked"
},
{
"code": null,
"e": 28890,
"s": 28875,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 28897,
"s": 28890,
"text": "Python"
},
{
"code": null,
"e": 28995,
"s": 28897,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29004,
"s": 28995,
"text": "Comments"
},
{
"code": null,
"e": 29017,
"s": 29004,
"text": "Old Comments"
},
{
"code": null,
"e": 29049,
"s": 29017,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29105,
"s": 29049,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29147,
"s": 29105,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29189,
"s": 29147,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29225,
"s": 29189,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 29264,
"s": 29225,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29286,
"s": 29264,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29317,
"s": 29286,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29344,
"s": 29317,
"text": "Python Classes and Objects"
}
] |
How to use $ifNull with MongoDB aggregation?
|
The $ifNull evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value.
Let us first create a collection with documents −
> db.demo372.insertOne({"FirstName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e591aea2ae06a1609a00af6")
}
> db.demo372.insertOne({"FirstName":null});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e591aef2ae06a1609a00af7")
}
> db.demo372.insertOne({"FirstName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e591af42ae06a1609a00af8")
}
> db.demo372.insertOne({"FirstName":null});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e591afb2ae06a1609a00af9")
}
Display all documents from a collection with the help of find() method −
> db.demo372.find();
This will produce the following output −
{ "_id" : ObjectId("5e591aea2ae06a1609a00af6"), "FirstName" : "Chris" }
{ "_id" : ObjectId("5e591aef2ae06a1609a00af7"), "FirstName" : null }
{ "_id" : ObjectId("5e591af42ae06a1609a00af8"), "FirstName" : "David" }
{ "_id" : ObjectId("5e591afb2ae06a1609a00af9"), "FirstName" : null }
Following is the query to use $ifNull with aggregation−
> db.demo372.aggregate(
... [
... {
... $project: {
...
... FirstName: { $ifNull: [ "$FirstName", "NOT PROVIDED" ] }
... }
... }
... ]
... )
This will produce the following output −
{ "_id" : ObjectId("5e591aea2ae06a1609a00af6"), "FirstName" : "Chris" }
{ "_id" : ObjectId("5e591aef2ae06a1609a00af7"), "FirstName" : "NOT PROVIDED" }
{ "_id" : ObjectId("5e591af42ae06a1609a00af8"), "FirstName" : "David" }
{ "_id" : ObjectId("5e591afb2ae06a1609a00af9"), "FirstName" : "NOT PROVIDED" }
|
[
{
"code": null,
"e": 1187,
"s": 1062,
"text": "The $ifNull evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value."
},
{
"code": null,
"e": 1237,
"s": 1187,
"text": "Let us first create a collection with documents −"
},
{
"code": null,
"e": 1759,
"s": 1237,
"text": "> db.demo372.insertOne({\"FirstName\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e591aea2ae06a1609a00af6\")\n}\n> db.demo372.insertOne({\"FirstName\":null});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e591aef2ae06a1609a00af7\")\n}\n> db.demo372.insertOne({\"FirstName\":\"David\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e591af42ae06a1609a00af8\")\n}\n> db.demo372.insertOne({\"FirstName\":null});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e591afb2ae06a1609a00af9\")\n}"
},
{
"code": null,
"e": 1832,
"s": 1759,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1853,
"s": 1832,
"text": "> db.demo372.find();"
},
{
"code": null,
"e": 1894,
"s": 1853,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2176,
"s": 1894,
"text": "{ \"_id\" : ObjectId(\"5e591aea2ae06a1609a00af6\"), \"FirstName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e591aef2ae06a1609a00af7\"), \"FirstName\" : null }\n{ \"_id\" : ObjectId(\"5e591af42ae06a1609a00af8\"), \"FirstName\" : \"David\" }\n{ \"_id\" : ObjectId(\"5e591afb2ae06a1609a00af9\"), \"FirstName\" : null }"
},
{
"code": null,
"e": 2232,
"s": 2176,
"text": "Following is the query to use $ifNull with aggregation−"
},
{
"code": null,
"e": 2421,
"s": 2232,
"text": "> db.demo372.aggregate(\n... [\n... {\n... $project: {\n...\n... FirstName: { $ifNull: [ \"$FirstName\", \"NOT PROVIDED\" ] }\n... }\n... }\n... ]\n... )"
},
{
"code": null,
"e": 2462,
"s": 2421,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2764,
"s": 2462,
"text": "{ \"_id\" : ObjectId(\"5e591aea2ae06a1609a00af6\"), \"FirstName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e591aef2ae06a1609a00af7\"), \"FirstName\" : \"NOT PROVIDED\" }\n{ \"_id\" : ObjectId(\"5e591af42ae06a1609a00af8\"), \"FirstName\" : \"David\" }\n{ \"_id\" : ObjectId(\"5e591afb2ae06a1609a00af9\"), \"FirstName\" : \"NOT PROVIDED\" }"
}
] |
Count of numbers in Array ending with digits of number N - GeeksforGeeks
|
10 May, 2021
Given a number N and an array arr[] consisting of K numbers, the task is to find the count of numbers in the array which ends with any of the digit present in the number N.
Examples:
Input: N = 1731 arr[] = {57, 6786} Output: 1 Explanation: For 57, the last digit is 7 and since 7 is present is N, so the count is 1. For 6786, the last digit is 6 and since 6 is not present in N, the count remains 1.Input: N = 1324, arr[] = {23, 25, 12, 121} Output: 3
Naive Approach: The naive approach for this problem is that for every number in the array arr[], check if its last digit is equal to any of the digits in N. Increment the count for each of such number and print it at the end.Time Complexity: O(N * K), where N is the number and K is the number of elements in the array arr[]. Efficient Approach: The efficient approach for this problem is to perform a preprocessing.
Initially, create an array A[] of size 10.
This array acts as a hash which stores all the digits occurred in the number N.
After this, for every number in the array arr[], extract the last digit and check if this last digit has occurred or not in the array.
Increment the count for each of such number and print it at the end.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the count// of numbers in Array ending// with digits of number N #include <bits/stdc++.h>using namespace std; // Array to keep the// track of digits occurred// Initially all are 0(false)int digit[10] = { 0 }; // Function to initialize true// if the digit is presentvoid digitsPresent(int n){ // Variable to store the last digit int lastDigit; // Loop to iterate through every // digit of the number N while (n != 0) { lastDigit = n % 10; // Updating the array according // to the presence of the // digit in n at the array index digit[lastDigit] = true; n /= 10; }} // Function to check if the// numbers in the array// end with the digits of// the number Nint checkLastDigit(int num){ // Variable to store the count int count = 0; // Variable to store the last digit int lastDigit; lastDigit = num % 10; // Checking the presence of // the last digit in N if (digit[lastDigit] == true) count++; return count;} // Function to find// the required countvoid findCount(int N, int K, int arr[]){ int count = 0; for (int i = 0; i < K; i++) { count = checkLastDigit(arr[i]) == 1 ? count + 1 : count; } cout << count << endl;} // Driver codeint main(){ int N = 1731; // Preprocessing digitsPresent(N); int K = 5; int arr[] = { 57, 6786, 1111, 3, 9812 }; findCount(N, K, arr); return 0;}
// Java program to find the count// of numbers in Array ending// with digits of number Nclass GFG{ // Array to keep the// track of digits occurred// Initially all are 0(false)public static int[] digit = new int[10]; // Function to initialize 1(true)// if the digit is presentpublic static void digitsPresent(int n){ // Variable to store the last digit int lastDigit; // Loop to iterate through every // digit of the number N while (n != 0) { lastDigit = n % 10; // Updating the array according // to the presence of the // digit in n at the array index digit[lastDigit] = 1; n /= 10; }} // Function to check if the// numbers in the array// end with the digits of// the number Npublic static int checkLastDigit(int num){ // Variable to store the count int count = 0; // Variable to store the last digit int lastDigit; lastDigit = num % 10; // Checking the presence of // the last digit in N if (digit[lastDigit] == 1) count++; return count;} // Function to find// the required countpublic static void findCount(int N, int K, int arr[]){ int count = 0; for(int i = 0; i < K; i++) { count = checkLastDigit(arr[i]) == 1 ? count + 1 : count; } System.out.println(count);} // Driver codepublic static void main(String[] args){ int N = 1731; // Preprocessing digitsPresent(N); int K = 5; int arr[] = { 57, 6786, 1111, 3, 9812 }; findCount(N, K, arr);}} // This code is contributed by Sayantan Pal
# Python3 program to find the count# of numbers in Array ending# with digits of number N # Array to keep the# track of digits occurred# Initially all are 0(false)digit = [0] * 10 # Function to initialize true# if the digit is presentdef digitsPresent(n): # Variable to store the last digit lastDigit = 0; # Loop to iterate through every # digit of the number N while (n != 0): lastDigit = n % 10; # Updating the array according # to the presence of the # digit in n at the array index digit[int(lastDigit)] = 1; n /= 10; # Function to check if the numbers# in the array end with the digits# of the number Ndef checkLastDigit(num): # Variable to store the count count = 0; # Variable to store the last digit lastDigit = 0; lastDigit = num % 10; # Checking the presence of # the last digit in N if (digit[int(lastDigit)] == 1): count += 1 return count; # Function to find the required countdef findCount(N, K, arr): count = 0; for i in range(K): if checkLastDigit(arr[i]) == 1: count += 1 else: count print(count) # Driver codeN = 1731; # PreprocessingdigitsPresent(N); K = 5;arr = [ 57, 6786, 1111, 3, 9812 ]; findCount(N, K, arr); # This code is contributed by grand_master
// C# program to find the count// of numbers in Array ending// with digits of number Nusing System; class GFG{ // Array to keep the track of digits occurred// Initially all are 0(false)public static int []digit = new int[10]; // Function to initialize 1(true)// if the digit is presentpublic static void digitsPresent(int n){ // Variable to store the last digit int lastDigit; // Loop to iterate through every // digit of the number N while (n != 0) { lastDigit = n % 10; // Updating the array according to the // presence of the digit in n at the // array index digit[lastDigit] = 1; n /= 10; }} // Function to check if the numbers in the// array end with the digits of the number Npublic static int checkLastDigit(int num){ // Variable to store the count int count = 0; // Variable to store the last digit int lastDigit; lastDigit = num % 10; // Checking the presence of // the last digit in N if (digit[lastDigit] == 1) count++; return count;} // Function to find the required countpublic static void findCount(int N, int K, int []arr){ int count = 0; for(int i = 0; i < K; i++) { count = checkLastDigit(arr[i]) == 1 ? count + 1 : count; } Console.WriteLine(count);} // Driver codestatic public void Main(){ int N = 1731; // Preprocessing digitsPresent(N); int K = 5; int []arr = { 57, 6786, 1111, 3, 9812 }; findCount(N, K, arr);}} // This code is contributed by piyush3010
<script> // Javascript program to find the count// of numbers in Array ending// with digits of number N // Array to keep the// track of digits occurred// Initially all are 0(false)let digit = new Uint8Array(10); // Function to initialize true// if the digit is presentfunction digitsPresent(n){ // Variable to store the last digit let lastDigit; // Loop to iterate through every // digit of the number N while (n != 0) { lastDigit = n % 10; // Updating the array according // to the presence of the // digit in n at the array index digit[lastDigit] = true; n = Math.floor(n/10); }} // Function to check if the// numbers in the array// end with the digits of// the number Nfunction checkLastDigit(num){ // Variable to store the count let count = 0; // Variable to store the last digit let lastDigit; lastDigit = num % 10; // Checking the presence of // the last digit in N if (digit[lastDigit] == true) count++; return count;} // Function to find// the required countfunction findCount(N, K, arr){ let count = 0; for (let i = 0; i < K; i++) { count = checkLastDigit(arr[i]) == 1 ? count + 1 : count; } document.write(count + "<br>");} // Driver code let N = 1731; // Preprocessing digitsPresent(N); let K = 5; let arr = [ 57, 6786, 1111, 3, 9812 ]; findCount(N, K, arr); //This code is contributed by Mayank Tyagi</script>
3
Time Complexity:
O(N), where N is the given number for preprocessing.
O(K), where K is the number of queries to find answers for the queries.
grand_master
sayantanpal1
piyush3010
mayanktyagi1709
number-digits
Numbers
Arrays
Mathematical
School Programming
Arrays
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Program to find sum of elements in a given array
Building Heap from Array
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n10 May, 2021"
},
{
"code": null,
"e": 24970,
"s": 24796,
"text": "Given a number N and an array arr[] consisting of K numbers, the task is to find the count of numbers in the array which ends with any of the digit present in the number N. "
},
{
"code": null,
"e": 24982,
"s": 24970,
"text": "Examples: "
},
{
"code": null,
"e": 25254,
"s": 24982,
"text": "Input: N = 1731 arr[] = {57, 6786} Output: 1 Explanation: For 57, the last digit is 7 and since 7 is present is N, so the count is 1. For 6786, the last digit is 6 and since 6 is not present in N, the count remains 1.Input: N = 1324, arr[] = {23, 25, 12, 121} Output: 3 "
},
{
"code": null,
"e": 25673,
"s": 25254,
"text": "Naive Approach: The naive approach for this problem is that for every number in the array arr[], check if its last digit is equal to any of the digits in N. Increment the count for each of such number and print it at the end.Time Complexity: O(N * K), where N is the number and K is the number of elements in the array arr[]. Efficient Approach: The efficient approach for this problem is to perform a preprocessing. "
},
{
"code": null,
"e": 25716,
"s": 25673,
"text": "Initially, create an array A[] of size 10."
},
{
"code": null,
"e": 25796,
"s": 25716,
"text": "This array acts as a hash which stores all the digits occurred in the number N."
},
{
"code": null,
"e": 25931,
"s": 25796,
"text": "After this, for every number in the array arr[], extract the last digit and check if this last digit has occurred or not in the array."
},
{
"code": null,
"e": 26002,
"s": 25931,
"text": "Increment the count for each of such number and print it at the end. "
},
{
"code": null,
"e": 26055,
"s": 26002,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26059,
"s": 26055,
"text": "C++"
},
{
"code": null,
"e": 26064,
"s": 26059,
"text": "Java"
},
{
"code": null,
"e": 26072,
"s": 26064,
"text": "Python3"
},
{
"code": null,
"e": 26075,
"s": 26072,
"text": "C#"
},
{
"code": null,
"e": 26086,
"s": 26075,
"text": "Javascript"
},
{
"code": "// C++ program to find the count// of numbers in Array ending// with digits of number N #include <bits/stdc++.h>using namespace std; // Array to keep the// track of digits occurred// Initially all are 0(false)int digit[10] = { 0 }; // Function to initialize true// if the digit is presentvoid digitsPresent(int n){ // Variable to store the last digit int lastDigit; // Loop to iterate through every // digit of the number N while (n != 0) { lastDigit = n % 10; // Updating the array according // to the presence of the // digit in n at the array index digit[lastDigit] = true; n /= 10; }} // Function to check if the// numbers in the array// end with the digits of// the number Nint checkLastDigit(int num){ // Variable to store the count int count = 0; // Variable to store the last digit int lastDigit; lastDigit = num % 10; // Checking the presence of // the last digit in N if (digit[lastDigit] == true) count++; return count;} // Function to find// the required countvoid findCount(int N, int K, int arr[]){ int count = 0; for (int i = 0; i < K; i++) { count = checkLastDigit(arr[i]) == 1 ? count + 1 : count; } cout << count << endl;} // Driver codeint main(){ int N = 1731; // Preprocessing digitsPresent(N); int K = 5; int arr[] = { 57, 6786, 1111, 3, 9812 }; findCount(N, K, arr); return 0;}",
"e": 27588,
"s": 26086,
"text": null
},
{
"code": "// Java program to find the count// of numbers in Array ending// with digits of number Nclass GFG{ // Array to keep the// track of digits occurred// Initially all are 0(false)public static int[] digit = new int[10]; // Function to initialize 1(true)// if the digit is presentpublic static void digitsPresent(int n){ // Variable to store the last digit int lastDigit; // Loop to iterate through every // digit of the number N while (n != 0) { lastDigit = n % 10; // Updating the array according // to the presence of the // digit in n at the array index digit[lastDigit] = 1; n /= 10; }} // Function to check if the// numbers in the array// end with the digits of// the number Npublic static int checkLastDigit(int num){ // Variable to store the count int count = 0; // Variable to store the last digit int lastDigit; lastDigit = num % 10; // Checking the presence of // the last digit in N if (digit[lastDigit] == 1) count++; return count;} // Function to find// the required countpublic static void findCount(int N, int K, int arr[]){ int count = 0; for(int i = 0; i < K; i++) { count = checkLastDigit(arr[i]) == 1 ? count + 1 : count; } System.out.println(count);} // Driver codepublic static void main(String[] args){ int N = 1731; // Preprocessing digitsPresent(N); int K = 5; int arr[] = { 57, 6786, 1111, 3, 9812 }; findCount(N, K, arr);}} // This code is contributed by Sayantan Pal",
"e": 29171,
"s": 27588,
"text": null
},
{
"code": "# Python3 program to find the count# of numbers in Array ending# with digits of number N # Array to keep the# track of digits occurred# Initially all are 0(false)digit = [0] * 10 # Function to initialize true# if the digit is presentdef digitsPresent(n): # Variable to store the last digit lastDigit = 0; # Loop to iterate through every # digit of the number N while (n != 0): lastDigit = n % 10; # Updating the array according # to the presence of the # digit in n at the array index digit[int(lastDigit)] = 1; n /= 10; # Function to check if the numbers# in the array end with the digits# of the number Ndef checkLastDigit(num): # Variable to store the count count = 0; # Variable to store the last digit lastDigit = 0; lastDigit = num % 10; # Checking the presence of # the last digit in N if (digit[int(lastDigit)] == 1): count += 1 return count; # Function to find the required countdef findCount(N, K, arr): count = 0; for i in range(K): if checkLastDigit(arr[i]) == 1: count += 1 else: count print(count) # Driver codeN = 1731; # PreprocessingdigitsPresent(N); K = 5;arr = [ 57, 6786, 1111, 3, 9812 ]; findCount(N, K, arr); # This code is contributed by grand_master",
"e": 30514,
"s": 29171,
"text": null
},
{
"code": "// C# program to find the count// of numbers in Array ending// with digits of number Nusing System; class GFG{ // Array to keep the track of digits occurred// Initially all are 0(false)public static int []digit = new int[10]; // Function to initialize 1(true)// if the digit is presentpublic static void digitsPresent(int n){ // Variable to store the last digit int lastDigit; // Loop to iterate through every // digit of the number N while (n != 0) { lastDigit = n % 10; // Updating the array according to the // presence of the digit in n at the // array index digit[lastDigit] = 1; n /= 10; }} // Function to check if the numbers in the// array end with the digits of the number Npublic static int checkLastDigit(int num){ // Variable to store the count int count = 0; // Variable to store the last digit int lastDigit; lastDigit = num % 10; // Checking the presence of // the last digit in N if (digit[lastDigit] == 1) count++; return count;} // Function to find the required countpublic static void findCount(int N, int K, int []arr){ int count = 0; for(int i = 0; i < K; i++) { count = checkLastDigit(arr[i]) == 1 ? count + 1 : count; } Console.WriteLine(count);} // Driver codestatic public void Main(){ int N = 1731; // Preprocessing digitsPresent(N); int K = 5; int []arr = { 57, 6786, 1111, 3, 9812 }; findCount(N, K, arr);}} // This code is contributed by piyush3010",
"e": 32083,
"s": 30514,
"text": null
},
{
"code": "<script> // Javascript program to find the count// of numbers in Array ending// with digits of number N // Array to keep the// track of digits occurred// Initially all are 0(false)let digit = new Uint8Array(10); // Function to initialize true// if the digit is presentfunction digitsPresent(n){ // Variable to store the last digit let lastDigit; // Loop to iterate through every // digit of the number N while (n != 0) { lastDigit = n % 10; // Updating the array according // to the presence of the // digit in n at the array index digit[lastDigit] = true; n = Math.floor(n/10); }} // Function to check if the// numbers in the array// end with the digits of// the number Nfunction checkLastDigit(num){ // Variable to store the count let count = 0; // Variable to store the last digit let lastDigit; lastDigit = num % 10; // Checking the presence of // the last digit in N if (digit[lastDigit] == true) count++; return count;} // Function to find// the required countfunction findCount(N, K, arr){ let count = 0; for (let i = 0; i < K; i++) { count = checkLastDigit(arr[i]) == 1 ? count + 1 : count; } document.write(count + \"<br>\");} // Driver code let N = 1731; // Preprocessing digitsPresent(N); let K = 5; let arr = [ 57, 6786, 1111, 3, 9812 ]; findCount(N, K, arr); //This code is contributed by Mayank Tyagi</script>",
"e": 33602,
"s": 32083,
"text": null
},
{
"code": null,
"e": 33604,
"s": 33602,
"text": "3"
},
{
"code": null,
"e": 33621,
"s": 33604,
"text": "Time Complexity:"
},
{
"code": null,
"e": 33674,
"s": 33621,
"text": "O(N), where N is the given number for preprocessing."
},
{
"code": null,
"e": 33746,
"s": 33674,
"text": "O(K), where K is the number of queries to find answers for the queries."
},
{
"code": null,
"e": 33759,
"s": 33746,
"text": "grand_master"
},
{
"code": null,
"e": 33772,
"s": 33759,
"text": "sayantanpal1"
},
{
"code": null,
"e": 33783,
"s": 33772,
"text": "piyush3010"
},
{
"code": null,
"e": 33799,
"s": 33783,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 33813,
"s": 33799,
"text": "number-digits"
},
{
"code": null,
"e": 33821,
"s": 33813,
"text": "Numbers"
},
{
"code": null,
"e": 33828,
"s": 33821,
"text": "Arrays"
},
{
"code": null,
"e": 33841,
"s": 33828,
"text": "Mathematical"
},
{
"code": null,
"e": 33860,
"s": 33841,
"text": "School Programming"
},
{
"code": null,
"e": 33867,
"s": 33860,
"text": "Arrays"
},
{
"code": null,
"e": 33880,
"s": 33867,
"text": "Mathematical"
},
{
"code": null,
"e": 33888,
"s": 33880,
"text": "Numbers"
},
{
"code": null,
"e": 33986,
"s": 33888,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34011,
"s": 33986,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 34031,
"s": 34011,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 34069,
"s": 34031,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 34118,
"s": 34069,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 34143,
"s": 34118,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 34173,
"s": 34143,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34233,
"s": 34173,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34248,
"s": 34233,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34291,
"s": 34248,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to convert a value to a string in JavaScript?
|
There are 5 ways to convert a value to a string. They are
Concatenating empty strings
Concatenating empty strings
Template strings
Template strings
JSON. stringify
JSON. stringify
toString()
toString()
String()
String()
In the following example, all the above-mentioned methods were used to convert a value to a string and the final result was displayed as shown in the output.
Live Demo
<html>
<body>
<script>
const value = 123;
document.write((value + '') +" "+typeof (value + ''));
document.write("</br>");
document.write((`${value}`) +" "+typeof (`${value}`));
document.write("</br>");
document.write((JSON.stringify(value)) +" "+typeof (JSON.stringify(value)));
document.write("</br>");
document.write((value.toString()) +" "+typeof (value.toString()));
document.write("</br>");
document.write((String(value)) +" "+typeof(String(value)));
</script>
</body>
</html>
123 string
123 string
123 string
123 string
123 string
|
[
{
"code": null,
"e": 1121,
"s": 1062,
"text": "There are 5 ways to convert a value to a string. They are "
},
{
"code": null,
"e": 1149,
"s": 1121,
"text": "Concatenating empty strings"
},
{
"code": null,
"e": 1177,
"s": 1149,
"text": "Concatenating empty strings"
},
{
"code": null,
"e": 1195,
"s": 1177,
"text": "Template strings "
},
{
"code": null,
"e": 1213,
"s": 1195,
"text": "Template strings "
},
{
"code": null,
"e": 1230,
"s": 1213,
"text": "JSON. stringify "
},
{
"code": null,
"e": 1247,
"s": 1230,
"text": "JSON. stringify "
},
{
"code": null,
"e": 1258,
"s": 1247,
"text": "toString()"
},
{
"code": null,
"e": 1269,
"s": 1258,
"text": "toString()"
},
{
"code": null,
"e": 1278,
"s": 1269,
"text": "String()"
},
{
"code": null,
"e": 1287,
"s": 1278,
"text": "String()"
},
{
"code": null,
"e": 1445,
"s": 1287,
"text": "In the following example, all the above-mentioned methods were used to convert a value to a string and the final result was displayed as shown in the output."
},
{
"code": null,
"e": 1455,
"s": 1445,
"text": "Live Demo"
},
{
"code": null,
"e": 1967,
"s": 1455,
"text": "<html>\n<body>\n<script>\n const value = 123;\n document.write((value + '') +\" \"+typeof (value + ''));\n document.write(\"</br>\");\n document.write((`${value}`) +\" \"+typeof (`${value}`));\n document.write(\"</br>\");\n document.write((JSON.stringify(value)) +\" \"+typeof (JSON.stringify(value)));\n document.write(\"</br>\");\n document.write((value.toString()) +\" \"+typeof (value.toString()));\n document.write(\"</br>\");\n document.write((String(value)) +\" \"+typeof(String(value)));\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2022,
"s": 1967,
"text": "123 string\n123 string\n123 string\n123 string\n123 string"
}
] |
Validate Binary Search Tree in Python
|
Suppose we have a binary tree, determine to check whether it is a valid binary search tree (BST) or not. Assume a BST is defined as follows –
The left subtree of a node holds only nodes with keys smaller than the node's key.
The right subtree of a node holds only nodes with keys larger than the node's key.
Both the left and right subtrees must also be binary search trees.
So if the tree is like –
The output will be true.
To solve this, we will follow these steps –
Create one recursive function called solve(), this will take root, min and max, the method will be like
if root is null, then return true
if value of root <= min or value of root >= max, then return false
return the (solve(left of root, min, root value) AND solve(right of root, root value, max))
call the solve() method initially, by passing root, and – inf as min and inf as max.
Let us see the following implementation to get a better understanding −
Live Demo
class TreeNode:
def __init__(self, data, left = None, right = None):
self.data = data
self.left = left
self.right = right
def insert(temp,data):
que = []
que.append(temp)
while (len(que)):
temp = que[0]
que.pop(0)
if (not temp.left):
if data is not None:
temp.left = TreeNode(data)
else:
temp.left = TreeNode(0)
break
else:
que.append(temp.left)
if (not temp.right):
if data is not None:
temp.right = TreeNode(data)
else:
temp.right = TreeNode(0)
break
else:
que.append(temp.right)
def make_tree(elements):
Tree = TreeNode(elements[0])
for element in elements[1:]:
insert(Tree, element)
return Tree
class Solution(object):
def isValidBST(self, root):
return self.solve(root,-1000000000000000000000,1000000000000000000000)
def solve(self,root,min_val,max_val):
if root == None or root.data == 0:
return True
if (root.data <= min_val or root.data >=max_val):
return False
return self.solve(root.left,min_val,root.data) and self.solve(root.right,root.data,max_val)
ob1 = Solution()
tree = make_tree([3,1,4,None,2,None,5])
print(ob1.isValidBST(tree))
tree = make_tree([5,1,4,None,None,3,6])
print(ob1.isValidBST(tree))
[3,1,4,null,2,null,5]
[5,1,4,null,null,3,6]
true
false
|
[
{
"code": null,
"e": 1204,
"s": 1062,
"text": "Suppose we have a binary tree, determine to check whether it is a valid binary search tree (BST) or not. Assume a BST is defined as follows –"
},
{
"code": null,
"e": 1287,
"s": 1204,
"text": "The left subtree of a node holds only nodes with keys smaller than the node's key."
},
{
"code": null,
"e": 1370,
"s": 1287,
"text": "The right subtree of a node holds only nodes with keys larger than the node's key."
},
{
"code": null,
"e": 1437,
"s": 1370,
"text": "Both the left and right subtrees must also be binary search trees."
},
{
"code": null,
"e": 1462,
"s": 1437,
"text": "So if the tree is like –"
},
{
"code": null,
"e": 1487,
"s": 1462,
"text": "The output will be true."
},
{
"code": null,
"e": 1531,
"s": 1487,
"text": "To solve this, we will follow these steps –"
},
{
"code": null,
"e": 1635,
"s": 1531,
"text": "Create one recursive function called solve(), this will take root, min and max, the method will be like"
},
{
"code": null,
"e": 1669,
"s": 1635,
"text": "if root is null, then return true"
},
{
"code": null,
"e": 1736,
"s": 1669,
"text": "if value of root <= min or value of root >= max, then return false"
},
{
"code": null,
"e": 1828,
"s": 1736,
"text": "return the (solve(left of root, min, root value) AND solve(right of root, root value, max))"
},
{
"code": null,
"e": 1913,
"s": 1828,
"text": "call the solve() method initially, by passing root, and – inf as min and inf as max."
},
{
"code": null,
"e": 1985,
"s": 1913,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 1996,
"s": 1985,
"text": " Live Demo"
},
{
"code": null,
"e": 3360,
"s": 1996,
"text": "class TreeNode:\n def __init__(self, data, left = None, right = None):\n self.data = data\n self.left = left\n self.right = right\ndef insert(temp,data):\n que = []\n que.append(temp)\n while (len(que)):\n temp = que[0]\n que.pop(0)\n if (not temp.left):\n if data is not None:\n temp.left = TreeNode(data)\n else:\n temp.left = TreeNode(0)\n break\n else:\n que.append(temp.left)\n if (not temp.right):\n if data is not None:\n temp.right = TreeNode(data)\n else:\n temp.right = TreeNode(0)\n break\n else:\n que.append(temp.right)\ndef make_tree(elements):\n Tree = TreeNode(elements[0])\n for element in elements[1:]:\n insert(Tree, element)\n return Tree\nclass Solution(object):\n def isValidBST(self, root):\n return self.solve(root,-1000000000000000000000,1000000000000000000000)\n def solve(self,root,min_val,max_val):\n if root == None or root.data == 0:\n return True\n if (root.data <= min_val or root.data >=max_val):\n return False\n return self.solve(root.left,min_val,root.data) and self.solve(root.right,root.data,max_val)\nob1 = Solution()\ntree = make_tree([3,1,4,None,2,None,5])\nprint(ob1.isValidBST(tree))\ntree = make_tree([5,1,4,None,None,3,6])\nprint(ob1.isValidBST(tree))"
},
{
"code": null,
"e": 3404,
"s": 3360,
"text": "[3,1,4,null,2,null,5]\n[5,1,4,null,null,3,6]"
},
{
"code": null,
"e": 3415,
"s": 3404,
"text": "true\nfalse"
}
] |
Angular Material 7 - DatePicker
|
The <mat-datepicker>, an Angular Directive, is used to create a datepicker control using which date can be selected from a calendar or can be input directly using input box.
In this chapter, we will showcase the configuration required to draw a datepicker control using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatDatepickerModule, MatInputModule,MatNativeDateModule} from '@angular/material';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatDatepickerModule, MatInputModule,MatNativeDateModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified HTML host file app.component.html.
<mat-form-field>
<input matInput [matDatepicker] = "picker" placeholder = "Choose a date">
<mat-datepicker-toggle matSuffix [for] = "picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
Verify the result.
As first, we've created an input box and bind an datepicker named picker using [matDatepicker] attribute.
As first, we've created an input box and bind an datepicker named picker using [matDatepicker] attribute.
Then, we've created an datepicker named picker using mat-datepicker tag.
Then, we've created an datepicker named picker using mat-datepicker tag.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2929,
"s": 2755,
"text": "The <mat-datepicker>, an Angular Directive, is used to create a datepicker control using which date can be selected from a calendar or can be input directly using input box."
},
{
"code": null,
"e": 3043,
"s": 2929,
"text": "In this chapter, we will showcase the configuration required to draw a datepicker control using Angular Material."
},
{
"code": null,
"e": 3154,
"s": 3043,
"text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −"
},
{
"code": null,
"e": 3228,
"s": 3154,
"text": "Following is the content of the modified module descriptor app.module.ts."
},
{
"code": null,
"e": 3924,
"s": 3228,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatDatepickerModule, MatInputModule,MatNativeDateModule} from '@angular/material';\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatDatepickerModule, MatInputModule,MatNativeDateModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 4000,
"s": 3924,
"text": "Following is the content of the modified HTML host file app.component.html."
},
{
"code": null,
"e": 4235,
"s": 4000,
"text": "<mat-form-field>\n <input matInput [matDatepicker] = \"picker\" placeholder = \"Choose a date\">\n <mat-datepicker-toggle matSuffix [for] = \"picker\"></mat-datepicker-toggle>\n <mat-datepicker #picker></mat-datepicker>\n</mat-form-field>"
},
{
"code": null,
"e": 4254,
"s": 4235,
"text": "Verify the result."
},
{
"code": null,
"e": 4360,
"s": 4254,
"text": "As first, we've created an input box and bind an datepicker named picker using [matDatepicker] attribute."
},
{
"code": null,
"e": 4466,
"s": 4360,
"text": "As first, we've created an input box and bind an datepicker named picker using [matDatepicker] attribute."
},
{
"code": null,
"e": 4539,
"s": 4466,
"text": "Then, we've created an datepicker named picker using mat-datepicker tag."
},
{
"code": null,
"e": 4612,
"s": 4539,
"text": "Then, we've created an datepicker named picker using mat-datepicker tag."
},
{
"code": null,
"e": 4647,
"s": 4612,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4661,
"s": 4647,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4696,
"s": 4661,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4710,
"s": 4696,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4745,
"s": 4710,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4765,
"s": 4745,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 4800,
"s": 4765,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4817,
"s": 4800,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4850,
"s": 4817,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4862,
"s": 4850,
"text": " Senol Atac"
},
{
"code": null,
"e": 4897,
"s": 4862,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4909,
"s": 4897,
"text": " Senol Atac"
},
{
"code": null,
"e": 4916,
"s": 4909,
"text": " Print"
},
{
"code": null,
"e": 4927,
"s": 4916,
"text": " Add Notes"
}
] |
Difference between next() and hasNext() in java collections?
|
Java provides Iterator and ListIterator classes to retrieve the elements of the collection objects.
The hasNext() method of these interfaces returns true if the collection object has the next element else it returns false.
Live Demo
import java.util.ArrayList;
import java.util.Iterator;
public class hasNextExample{
public static void main(String[] args){
ArrayList <String> list = new ArrayList<String>();
//Instantiating an ArrayList object
list.add("JavaFX");
list.add("Java");
Iterator<String> it = list.iterator();
System.out.println(it.hasNext());
it.next();
System.out.println(it.hasNext());
it.next();
System.out.println(it.hasNext());
}
}
true
true
false
The next() methods of the Iterator and ListIterator returns the next element of the collection.
Live Demo
import java.util.ArrayList;
import java.util.Iterator;
public class nextExample{
public static void main(String[] args){
ArrayList <String> list = new ArrayList<String>();
//Instantiating an ArrayList object
list.add("JavaFX");
list.add("Java");
list.add("WebGL");
list.add("OpenCV");
list.add("OpenNLP");
list.add("JOGL");
list.add("Hadoop");
list.add("HBase");
list.add("Flume");
list.add("Mahout");
list.add("Impala");
System.out.println("Contents of the array list (first to last): ");
Iterator<String> it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
Contents of the array list (first to last):
JavaFX
Java
WebGL
OpenCV
OpenNLP
JOGL
Hadoop
HBase
Flume
Mahout
Impala
|
[
{
"code": null,
"e": 1162,
"s": 1062,
"text": "Java provides Iterator and ListIterator classes to retrieve the elements of the collection objects."
},
{
"code": null,
"e": 1285,
"s": 1162,
"text": "The hasNext() method of these interfaces returns true if the collection object has the next element else it returns false."
},
{
"code": null,
"e": 1296,
"s": 1285,
"text": " Live Demo"
},
{
"code": null,
"e": 1778,
"s": 1296,
"text": "import java.util.ArrayList;\nimport java.util.Iterator;\npublic class hasNextExample{\n public static void main(String[] args){\n ArrayList <String> list = new ArrayList<String>();\n //Instantiating an ArrayList object\n list.add(\"JavaFX\");\n list.add(\"Java\");\n Iterator<String> it = list.iterator();\n System.out.println(it.hasNext());\n it.next();\n System.out.println(it.hasNext());\n it.next();\n System.out.println(it.hasNext());\n }\n}"
},
{
"code": null,
"e": 1794,
"s": 1778,
"text": "true\ntrue\nfalse"
},
{
"code": null,
"e": 1890,
"s": 1794,
"text": "The next() methods of the Iterator and ListIterator returns the next element of the collection."
},
{
"code": null,
"e": 1901,
"s": 1890,
"text": " Live Demo"
},
{
"code": null,
"e": 2606,
"s": 1901,
"text": "import java.util.ArrayList;\nimport java.util.Iterator;\npublic class nextExample{\n public static void main(String[] args){\n ArrayList <String> list = new ArrayList<String>();\n //Instantiating an ArrayList object\n list.add(\"JavaFX\");\n list.add(\"Java\");\n list.add(\"WebGL\");\n list.add(\"OpenCV\");\n list.add(\"OpenNLP\");\n list.add(\"JOGL\");\n list.add(\"Hadoop\");\n list.add(\"HBase\");\n list.add(\"Flume\");\n list.add(\"Mahout\");\n list.add(\"Impala\");\n System.out.println(\"Contents of the array list (first to last): \");\n Iterator<String> it = list.iterator();\n while(it.hasNext()) {\n System.out.println(it.next());\n }\n }\n}"
},
{
"code": null,
"e": 2721,
"s": 2606,
"text": "Contents of the array list (first to last):\nJavaFX\nJava\nWebGL\nOpenCV\nOpenNLP\nJOGL\nHadoop\nHBase\nFlume\nMahout\nImpala"
}
] |
Can we have a return statement in the catch or, finally blocks in Java?
|
Yes, we can write a return statement of the method in catch and finally block.
There is a situation where a method will have a return type and we can return some value at any part of the method based on the conditions.
If we return a value in the catch block and we can return a value at the end of the method, the code will execute successfully.
If we return a value in the catch block and we can write a statement at the end of the method after return a value, the code will not execute so it became unreachable code as we know Java does not support unreachable codes.
If we return a value in the final block and no need of keeping a return value at the end of the method.
public class CatchReturn {
int calc() {
try {
int x=12/0;
} catch (Exception e) {
return 1;
}
return 10;
}
public static void main(String[] args) {
CatchReturn cr = new CatchReturn();
System.out.println(cr.calc());
}
}
1
public class FinallyReturn {
int calc() {
try {
return 10;
} catch(Exception e) {
return 20;
} finally {
return 30;
}
}
public static void main(String[] args) {
FinallyReturn fr = new FinallyReturn();
System.out.println(fr.calc());
}
}
30
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "Yes, we can write a return statement of the method in catch and finally block."
},
{
"code": null,
"e": 1281,
"s": 1141,
"text": "There is a situation where a method will have a return type and we can return some value at any part of the method based on the conditions."
},
{
"code": null,
"e": 1409,
"s": 1281,
"text": "If we return a value in the catch block and we can return a value at the end of the method, the code will execute successfully."
},
{
"code": null,
"e": 1633,
"s": 1409,
"text": "If we return a value in the catch block and we can write a statement at the end of the method after return a value, the code will not execute so it became unreachable code as we know Java does not support unreachable codes."
},
{
"code": null,
"e": 1737,
"s": 1633,
"text": "If we return a value in the final block and no need of keeping a return value at the end of the method."
},
{
"code": null,
"e": 2022,
"s": 1737,
"text": "public class CatchReturn {\n int calc() {\n try {\n int x=12/0;\n } catch (Exception e) {\n return 1;\n }\n return 10;\n }\n public static void main(String[] args) {\n CatchReturn cr = new CatchReturn();\n System.out.println(cr.calc());\n }\n}"
},
{
"code": null,
"e": 2024,
"s": 2022,
"text": "1"
},
{
"code": null,
"e": 2335,
"s": 2024,
"text": "public class FinallyReturn {\n int calc() {\n try {\n return 10;\n } catch(Exception e) {\n return 20;\n } finally {\n return 30;\n }\n }\n public static void main(String[] args) {\n FinallyReturn fr = new FinallyReturn();\n System.out.println(fr.calc());\n }\n}"
},
{
"code": null,
"e": 2338,
"s": 2335,
"text": "30"
}
] |
Node.js - Web Module
|
A Web Server is a software application which handles HTTP requests sent by the HTTP client, like web browsers, and returns web pages in response to the clients. Web servers usually deliver html documents along with images, style sheets, and scripts.
Most of the web servers support server-side scripts, using scripting languages or redirecting the task to an application server which retrieves data from a database and performs complex logic and then sends a result to the HTTP client through the Web server.
Apache web server is one of the most commonly used web servers. It is an open source project.
A Web application is usually divided into four layers −
Client − This layer consists of web browsers, mobile browsers or applications which can make HTTP requests to the web server.
Client − This layer consists of web browsers, mobile browsers or applications which can make HTTP requests to the web server.
Server − This layer has the Web server which can intercept the requests made by the clients and pass them the response.
Server − This layer has the Web server which can intercept the requests made by the clients and pass them the response.
Business − This layer contains the application server which is utilized by the web server to do the required processing. This layer interacts with the data layer via the database or some external programs.
Business − This layer contains the application server which is utilized by the web server to do the required processing. This layer interacts with the data layer via the database or some external programs.
Data − This layer contains the databases or any other source of data.
Data − This layer contains the databases or any other source of data.
Node.js provides an http module which can be used to create an HTTP client of a server. Following is the bare minimum structure of the HTTP server which listens at 8081 port.
Create a js file named server.js −
File: server.js
var http = require('http');
var fs = require('fs');
var url = require('url');
// Create a server
http.createServer( function (request, response) {
// Parse the request containing file name
var pathname = url.parse(request.url).pathname;
// Print the name of the file for which request is made.
console.log("Request for " + pathname + " received.");
// Read the requested file content from file system
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// HTTP Status: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
} else {
//Page found
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});
// Write the content of the file to response body
response.write(data.toString());
}
// Send the response body
response.end();
});
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
Next let's create the following html file named index.htm in the same directory where you created server.js.
File: index.htm
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>
Now let us run the server.js to see the result −
$ node server.js
Verify the Output.
Server running at http://127.0.0.1:8081/
Open http://127.0.0.1:8081/index.htm in any browser to see the following result.
Verify the Output at server end.
Server running at http://127.0.0.1:8081/
Request for /index.htm received.
A web client can be created using http module. Let's check the following example.
Create a js file named client.js −
File: client.js
var http = require('http');
// Options to be used by request
var options = {
host: 'localhost',
port: '8081',
path: '/index.htm'
};
// Callback function is used to deal with response
var callback = function(response) {
// Continuously update stream with data
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
// Data received completely.
console.log(body);
});
}
// Make a request to the server
var req = http.request(options, callback);
req.end();
Now run the client.js from a different command terminal other than server.js to see the result −
$ node client.js
Verify the Output.
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>
Verify the Output at server end.
Server running at http://127.0.0.1:8081/
Request for /index.htm received.
44 Lectures
7.5 hours
Eduonix Learning Solutions
88 Lectures
17 hours
Eduonix Learning Solutions
32 Lectures
1.5 hours
Richard Wells
8 Lectures
33 mins
Anant Rungta
9 Lectures
2.5 hours
SHIVPRASAD KOIRALA
97 Lectures
6 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2268,
"s": 2018,
"text": "A Web Server is a software application which handles HTTP requests sent by the HTTP client, like web browsers, and returns web pages in response to the clients. Web servers usually deliver html documents along with images, style sheets, and scripts."
},
{
"code": null,
"e": 2527,
"s": 2268,
"text": "Most of the web servers support server-side scripts, using scripting languages or redirecting the task to an application server which retrieves data from a database and performs complex logic and then sends a result to the HTTP client through the Web server."
},
{
"code": null,
"e": 2621,
"s": 2527,
"text": "Apache web server is one of the most commonly used web servers. It is an open source project."
},
{
"code": null,
"e": 2677,
"s": 2621,
"text": "A Web application is usually divided into four layers −"
},
{
"code": null,
"e": 2803,
"s": 2677,
"text": "Client − This layer consists of web browsers, mobile browsers or applications which can make HTTP requests to the web server."
},
{
"code": null,
"e": 2929,
"s": 2803,
"text": "Client − This layer consists of web browsers, mobile browsers or applications which can make HTTP requests to the web server."
},
{
"code": null,
"e": 3049,
"s": 2929,
"text": "Server − This layer has the Web server which can intercept the requests made by the clients and pass them the response."
},
{
"code": null,
"e": 3169,
"s": 3049,
"text": "Server − This layer has the Web server which can intercept the requests made by the clients and pass them the response."
},
{
"code": null,
"e": 3375,
"s": 3169,
"text": "Business − This layer contains the application server which is utilized by the web server to do the required processing. This layer interacts with the data layer via the database or some external programs."
},
{
"code": null,
"e": 3581,
"s": 3375,
"text": "Business − This layer contains the application server which is utilized by the web server to do the required processing. This layer interacts with the data layer via the database or some external programs."
},
{
"code": null,
"e": 3651,
"s": 3581,
"text": "Data − This layer contains the databases or any other source of data."
},
{
"code": null,
"e": 3721,
"s": 3651,
"text": "Data − This layer contains the databases or any other source of data."
},
{
"code": null,
"e": 3896,
"s": 3721,
"text": "Node.js provides an http module which can be used to create an HTTP client of a server. Following is the bare minimum structure of the HTTP server which listens at 8081 port."
},
{
"code": null,
"e": 3931,
"s": 3896,
"text": "Create a js file named server.js −"
},
{
"code": null,
"e": 3947,
"s": 3931,
"text": "File: server.js"
},
{
"code": null,
"e": 5109,
"s": 3947,
"text": "var http = require('http');\nvar fs = require('fs');\nvar url = require('url');\n\n// Create a server\nhttp.createServer( function (request, response) { \n // Parse the request containing file name\n var pathname = url.parse(request.url).pathname;\n \n // Print the name of the file for which request is made.\n console.log(\"Request for \" + pathname + \" received.\");\n \n // Read the requested file content from file system\n fs.readFile(pathname.substr(1), function (err, data) {\n if (err) {\n console.log(err);\n \n // HTTP Status: 404 : NOT FOUND\n // Content Type: text/plain\n response.writeHead(404, {'Content-Type': 'text/html'});\n } else {\t\n //Page found\t \n // HTTP Status: 200 : OK\n // Content Type: text/plain\n response.writeHead(200, {'Content-Type': 'text/html'});\t\n \n // Write the content of the file to response body\n response.write(data.toString());\t\t\n }\n \n // Send the response body \n response.end();\n }); \n}).listen(8081);\n\n// Console will print the message\nconsole.log('Server running at http://127.0.0.1:8081/');"
},
{
"code": null,
"e": 5218,
"s": 5109,
"text": "Next let's create the following html file named index.htm in the same directory where you created server.js."
},
{
"code": null,
"e": 5234,
"s": 5218,
"text": "File: index.htm"
},
{
"code": null,
"e": 5347,
"s": 5234,
"text": "<html>\n <head>\n <title>Sample Page</title>\n </head>\n \n <body>\n Hello World!\n </body>\n</html>"
},
{
"code": null,
"e": 5396,
"s": 5347,
"text": "Now let us run the server.js to see the result −"
},
{
"code": null,
"e": 5414,
"s": 5396,
"text": "$ node server.js\n"
},
{
"code": null,
"e": 5433,
"s": 5414,
"text": "Verify the Output."
},
{
"code": null,
"e": 5475,
"s": 5433,
"text": "Server running at http://127.0.0.1:8081/\n"
},
{
"code": null,
"e": 5556,
"s": 5475,
"text": "Open http://127.0.0.1:8081/index.htm in any browser to see the following result."
},
{
"code": null,
"e": 5589,
"s": 5556,
"text": "Verify the Output at server end."
},
{
"code": null,
"e": 5664,
"s": 5589,
"text": "Server running at http://127.0.0.1:8081/\nRequest for /index.htm received.\n"
},
{
"code": null,
"e": 5746,
"s": 5664,
"text": "A web client can be created using http module. Let's check the following example."
},
{
"code": null,
"e": 5781,
"s": 5746,
"text": "Create a js file named client.js −"
},
{
"code": null,
"e": 5797,
"s": 5781,
"text": "File: client.js"
},
{
"code": null,
"e": 6352,
"s": 5797,
"text": "var http = require('http');\n\n// Options to be used by request \nvar options = {\n host: 'localhost',\n port: '8081',\n path: '/index.htm' \n};\n\n// Callback function is used to deal with response\nvar callback = function(response) {\n // Continuously update stream with data\n var body = '';\n response.on('data', function(data) {\n body += data;\n });\n \n response.on('end', function() {\n // Data received completely.\n console.log(body);\n });\n}\n// Make a request to the server\nvar req = http.request(options, callback);\nreq.end();"
},
{
"code": null,
"e": 6449,
"s": 6352,
"text": "Now run the client.js from a different command terminal other than server.js to see the result −"
},
{
"code": null,
"e": 6467,
"s": 6449,
"text": "$ node client.js\n"
},
{
"code": null,
"e": 6486,
"s": 6467,
"text": "Verify the Output."
},
{
"code": null,
"e": 6600,
"s": 6486,
"text": "<html>\n <head>\n <title>Sample Page</title>\n </head>\n \n <body>\n Hello World!\n </body>\n</html>\n"
},
{
"code": null,
"e": 6633,
"s": 6600,
"text": "Verify the Output at server end."
},
{
"code": null,
"e": 6708,
"s": 6633,
"text": "Server running at http://127.0.0.1:8081/\nRequest for /index.htm received.\n"
},
{
"code": null,
"e": 6743,
"s": 6708,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6771,
"s": 6743,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6805,
"s": 6771,
"text": "\n 88 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 6833,
"s": 6805,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6868,
"s": 6833,
"text": "\n 32 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6883,
"s": 6868,
"text": " Richard Wells"
},
{
"code": null,
"e": 6914,
"s": 6883,
"text": "\n 8 Lectures \n 33 mins\n"
},
{
"code": null,
"e": 6928,
"s": 6914,
"text": " Anant Rungta"
},
{
"code": null,
"e": 6962,
"s": 6928,
"text": "\n 9 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6982,
"s": 6962,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7015,
"s": 6982,
"text": "\n 97 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7035,
"s": 7015,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 7042,
"s": 7035,
"text": " Print"
},
{
"code": null,
"e": 7053,
"s": 7042,
"text": " Add Notes"
}
] |
Project Idea | Smart Elevator
|
07 Feb, 2018
Introduction:
Nowadays, in large buildings, the conventional elevators have higher waiting time, higher traveling time, more power consumption. So there is a need to develop an algorithm which reduces the above problems. I have done this project as in intern at Smartron. I have developed an algorithm which reduces the waiting and travelling time in elevators.
I have used the concept of Internet of things in this project along with the usage of Arduino microcontroller.
Conceptual framework:
The keypad of the elevator is outside the lift in the lobby of the building. All the elevators on a particular floor of the building have a common keypad at the entrance of lobby. When a person presses his desired floor on the keypad, the system assigns a lift to him( which is on that floor or nearer to the floor).
How is the lift assigned to the user?
When a user presses his desired floor on the keypad, the system goes through the following steps:
1) It checks if any lift is on that floor, if yes, it assigns the lift.2) If no, it checks whether the user wants to go to an upper floor or lower floor from his current floor.3) It then assigns the lift which is going up and nearer to that floor.
The main constraint in this algorithm is that a lift can have a maximum on 4 stops. So when it checks a lift, it checks whether the lift has reached it’s maximum stops or no.
What’s the system and how it works?
Each lift is connected to an Arduino in the master-slave configuration. Each lift is a slave to a master Arduino which is responsible to assign the lift to the user.
Each lift maintains a queue(data structure). The number of elements in the queue is the maximum number of stops a lift can have.
The first element in the queue is its current floor. The subsequent elements are its destinations in order.
The master checks each queue and gets where all the lifts are from the first element of their queues.
The lift goes upwards when the difference between the current element and next element is positive and vice-versa.
I have used Arduino IDE for programming and hands-on Arduino kit to test.
This project is a POC to the smart elevator and it can be used for the further study on smart elevators( using artificial intelligence makes it really smart).
Pseudo Code:Master:
// declare arrays for the slaves(queues are implemented using arrays)
void setup(){
SPI.begin; // Begin SPI protocol
digitalWrite(SS,HIGH);
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV8);
}
void loop(){
// create as many functions as there are keypads in the building.
// inside each function
keypad1(){
// take keypad input.
// check all the filters and assign a lift
SPI.transfer(destination); // goes to selected slave
enqueue(destination); // added to selected slave queue
}
Keypad2(){
// take keypad input.
// check all the filters and assign a lift
SPI.transfer(destination); // goes to selected slave
enqueue(destination); // added to selected slave queue
}
}
Slave code:
// declare array for the slave (queue is implemented using array)
void setup(){
pinMode(MISO,OUTPUT);
SPCR |= _BV(SPE); // turn on slave mode
SPCR |= _BV(SPIE); // turn on interrupt
}
ISR(SPI_STC_vect){
// receive destination from master
// add to the queue
}
void loop(){
// always looks at the first element of the queue and goes to that floor.
// when the destination is reached, it is deleted from queue
// inform master about deletion so that it can update the queue for this slave
} ?
Sincerely,Sri Harsha
ProGeek
Project
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Implementing Web Scraping in Python with BeautifulSoup
OpenCV C++ Program for Face Detection
10 Best Web Development Projects For Your Resume
Twitter Sentiment Analysis using Python
A Group chat application in Java
Student Information Management System
Face Detection using Python and OpenCV with webcam
E-commerce Website using Django
Snake Game in C
Java Swing | Simple User Registration Form
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Feb, 2018"
},
{
"code": null,
"e": 68,
"s": 54,
"text": "Introduction:"
},
{
"code": null,
"e": 416,
"s": 68,
"text": "Nowadays, in large buildings, the conventional elevators have higher waiting time, higher traveling time, more power consumption. So there is a need to develop an algorithm which reduces the above problems. I have done this project as in intern at Smartron. I have developed an algorithm which reduces the waiting and travelling time in elevators."
},
{
"code": null,
"e": 527,
"s": 416,
"text": "I have used the concept of Internet of things in this project along with the usage of Arduino microcontroller."
},
{
"code": null,
"e": 549,
"s": 527,
"text": "Conceptual framework:"
},
{
"code": null,
"e": 866,
"s": 549,
"text": "The keypad of the elevator is outside the lift in the lobby of the building. All the elevators on a particular floor of the building have a common keypad at the entrance of lobby. When a person presses his desired floor on the keypad, the system assigns a lift to him( which is on that floor or nearer to the floor)."
},
{
"code": null,
"e": 904,
"s": 866,
"text": "How is the lift assigned to the user?"
},
{
"code": null,
"e": 1002,
"s": 904,
"text": "When a user presses his desired floor on the keypad, the system goes through the following steps:"
},
{
"code": null,
"e": 1250,
"s": 1002,
"text": "1) It checks if any lift is on that floor, if yes, it assigns the lift.2) If no, it checks whether the user wants to go to an upper floor or lower floor from his current floor.3) It then assigns the lift which is going up and nearer to that floor."
},
{
"code": null,
"e": 1425,
"s": 1250,
"text": "The main constraint in this algorithm is that a lift can have a maximum on 4 stops. So when it checks a lift, it checks whether the lift has reached it’s maximum stops or no."
},
{
"code": null,
"e": 1461,
"s": 1425,
"text": "What’s the system and how it works?"
},
{
"code": null,
"e": 1627,
"s": 1461,
"text": "Each lift is connected to an Arduino in the master-slave configuration. Each lift is a slave to a master Arduino which is responsible to assign the lift to the user."
},
{
"code": null,
"e": 1756,
"s": 1627,
"text": "Each lift maintains a queue(data structure). The number of elements in the queue is the maximum number of stops a lift can have."
},
{
"code": null,
"e": 1864,
"s": 1756,
"text": "The first element in the queue is its current floor. The subsequent elements are its destinations in order."
},
{
"code": null,
"e": 1966,
"s": 1864,
"text": "The master checks each queue and gets where all the lifts are from the first element of their queues."
},
{
"code": null,
"e": 2081,
"s": 1966,
"text": "The lift goes upwards when the difference between the current element and next element is positive and vice-versa."
},
{
"code": null,
"e": 2155,
"s": 2081,
"text": "I have used Arduino IDE for programming and hands-on Arduino kit to test."
},
{
"code": null,
"e": 2314,
"s": 2155,
"text": "This project is a POC to the smart elevator and it can be used for the further study on smart elevators( using artificial intelligence makes it really smart)."
},
{
"code": null,
"e": 2334,
"s": 2314,
"text": "Pseudo Code:Master:"
},
{
"code": null,
"e": 3589,
"s": 2334,
"text": "// declare arrays for the slaves(queues are implemented using arrays)\nvoid setup(){\n SPI.begin; // Begin SPI protocol\n digitalWrite(SS,HIGH);\n SPI.begin();\n SPI.setClockDivider(SPI_CLOCK_DIV8);\n}\nvoid loop(){\n // create as many functions as there are keypads in the building.\n // inside each function\n keypad1(){\n // take keypad input.\n // check all the filters and assign a lift \n SPI.transfer(destination); // goes to selected slave \n enqueue(destination); // added to selected slave queue\n }\n Keypad2(){\n // take keypad input.\n // check all the filters and assign a lift \n SPI.transfer(destination); // goes to selected slave \n enqueue(destination); // added to selected slave queue\n }\n}\n\nSlave code:\n\n// declare array for the slave (queue is implemented using array)\nvoid setup(){\n pinMode(MISO,OUTPUT);\n SPCR |= _BV(SPE); // turn on slave mode\n SPCR |= _BV(SPIE); // turn on interrupt\n}\nISR(SPI_STC_vect){\n // receive destination from master\n // add to the queue \n}\nvoid loop(){\n // always looks at the first element of the queue and goes to that floor. \n // when the destination is reached, it is deleted from queue\n // inform master about deletion so that it can update the queue for this slave\n} ?\n"
},
{
"code": null,
"e": 3610,
"s": 3589,
"text": "Sincerely,Sri Harsha"
},
{
"code": null,
"e": 3618,
"s": 3610,
"text": "ProGeek"
},
{
"code": null,
"e": 3626,
"s": 3618,
"text": "Project"
},
{
"code": null,
"e": 3724,
"s": 3626,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3779,
"s": 3724,
"text": "Implementing Web Scraping in Python with BeautifulSoup"
},
{
"code": null,
"e": 3817,
"s": 3779,
"text": "OpenCV C++ Program for Face Detection"
},
{
"code": null,
"e": 3866,
"s": 3817,
"text": "10 Best Web Development Projects For Your Resume"
},
{
"code": null,
"e": 3906,
"s": 3866,
"text": "Twitter Sentiment Analysis using Python"
},
{
"code": null,
"e": 3939,
"s": 3906,
"text": "A Group chat application in Java"
},
{
"code": null,
"e": 3977,
"s": 3939,
"text": "Student Information Management System"
},
{
"code": null,
"e": 4028,
"s": 3977,
"text": "Face Detection using Python and OpenCV with webcam"
},
{
"code": null,
"e": 4060,
"s": 4028,
"text": "E-commerce Website using Django"
},
{
"code": null,
"e": 4076,
"s": 4060,
"text": "Snake Game in C"
}
] |
Parameters for Feature Selection
|
29 Apr, 2018
Prerequisite : Introduction to Dimensionality Reduction
Dimensionality reduction is the process of reducing the number of random variables under consideration, by obtaining a set of principal variables. It can be divided into feature selection and feature extraction.
Dimensionality Reduction is an important factor in predictive modeling. Various proposed methods have introduced different approaches to do so by either graphically or by various other methods like filtering, wrapping or embedding. However, most of these approaches are based on some threshold values and benchmark algorithms that determine the optimality of the features in the dataset.
One motivation for dimensionality reduction is that higher dimensional data sets increase the time complexity and also the space required will be more. Also, all the features in the dataset might not be useful. Some may contribute no information at all, while some may contribute similar information as the other features. Selecting the optimal set of features will help us hence reduce the space and time complexity as well as increase the accuracy or purity of classification (or regression) and clustering (or association) for supervised and unsupervised learning respectively.
Feature selection has four different approaches such as filter approach, wrapper approach, embedded approach, and hybrid approach.
Wrapper approach : This approach has high computational complexity. It uses a learning algorithm to evaluate the accuracy produced by the use of the selected features in classification. Wrapper methods can give high classification accuracy for particular classifiers.Filter approach : A subset of features is selected by this approach without using any learning algorithm. Higher-dimensional datasets use this method and it is relatively faster than the wrapper-based approaches.Embedded approach : The applied learning algorithms determine the specificity of this approach and it selects the features during the process of training the data set.Hybrid approach : Both filter and wrapper-based methods are used in hybrid approach. This approach first selects the possible optimal feature set which is further tested by the wrapper approach. It hence uses the advantages of both filter and wrapper-based approach.
Wrapper approach : This approach has high computational complexity. It uses a learning algorithm to evaluate the accuracy produced by the use of the selected features in classification. Wrapper methods can give high classification accuracy for particular classifiers.
Filter approach : A subset of features is selected by this approach without using any learning algorithm. Higher-dimensional datasets use this method and it is relatively faster than the wrapper-based approaches.
Embedded approach : The applied learning algorithms determine the specificity of this approach and it selects the features during the process of training the data set.
Hybrid approach : Both filter and wrapper-based methods are used in hybrid approach. This approach first selects the possible optimal feature set which is further tested by the wrapper approach. It hence uses the advantages of both filter and wrapper-based approach.
The parameters are classified based on two factors –
The Similarity of information contributed by the features :
1. CORRELATIONThe features are classified as associated or similar mostly based on their correlation factor. In the data set, we have many features which are correlated. Now the problem with having correlated features is that, if f1 and f2 are two correlated features of a data set, then the classifying or regression model including both f1 and f2 will give the same as the predictive model compared to the scenario where either f1 or f2 was included in the dataset. This is because both f1 and f2 are correlated and hence they contribute the same information regarding the model in the data set. There are various methods to calculate the correlation factor, however, Pearson’s correlation coefficient is most widely used. The formula for Pearson’s correlation coefficient() is:
where
cov(X, Y) - covariance
sigma(X) - standard deviation of X
sigma(Y) - standard deviation of Y
Thus, the correlated features are irrelevant, as they all contribute similar information. Only one representative of the whole correlated or associated features would give the same classification or regression outcome. Hence these features are redundant and excluded for dimensionality reduction purposes after selecting a particular representative from each associated or correlated group of features using various algorithms. Quantum of information contributed by the features :
1. ENTROPYEntropy is the measure of the average information content. The higher the entropy, the higher is the information contribution by that feature. Entropy (H) can be formulated as:
where
X - discrete random variable X
P(X) - probability mass function
E - expected value operator,
I - information content of X.
I(X) - a random variable.
In Data Science, entropy of a feature f1 is calculated by excluding feature f1 and then calculating the entropy of the rest of the features. Now, the lower the entropy value (excluding f1) the higher will be the information content of f1. In this manner the entropy of all the features is calculated. At the end, either a threshold value or further relevancy check determines the optimality of the features on the basis of which features are selected. Entropy is mostly used for Unsupervised Learning as we do have a class field in the dataset and hence entropy of the features can give substantial information.
2. MUTUAL INFORMATIONIn information theory, mutual information I(X;Y) is the amount of uncertainty in X due to the knowledge of Y. Mathematically, mutual information is defined as
where
p(x, y) - joint probability function of X and Y,
p(x) - marginal probability distribution function of X
p(y) - marginal probability distribution function of Y
Mutual Information in Data science is mostly calculated to know the amount of information shared about the class by a feature. Hence is mostly used for dimensionality reduction in Supervised Learning. The features which have high mutual information value corresponding to the class in a supervised learning are considered optimal since they can influence the predictive model towards the right prediction and hence increase the accuracy of the model. Reference : http://www.cs.uccs.edu/~jkalita/papers/2014/HoqueExpertSystems2014.pdf
Advanced Computer Subject
Machine Learning
Technical Scripter
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Docker - COPY Instruction
Decision Tree Introduction with example
ML | Monte Carlo Tree Search (MCTS)
Getting started with Machine Learning
Agents in Artificial Intelligence
Search Algorithms in AI
Decision Tree Introduction with example
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Apr, 2018"
},
{
"code": null,
"e": 110,
"s": 54,
"text": "Prerequisite : Introduction to Dimensionality Reduction"
},
{
"code": null,
"e": 322,
"s": 110,
"text": "Dimensionality reduction is the process of reducing the number of random variables under consideration, by obtaining a set of principal variables. It can be divided into feature selection and feature extraction."
},
{
"code": null,
"e": 710,
"s": 322,
"text": "Dimensionality Reduction is an important factor in predictive modeling. Various proposed methods have introduced different approaches to do so by either graphically or by various other methods like filtering, wrapping or embedding. However, most of these approaches are based on some threshold values and benchmark algorithms that determine the optimality of the features in the dataset."
},
{
"code": null,
"e": 1291,
"s": 710,
"text": "One motivation for dimensionality reduction is that higher dimensional data sets increase the time complexity and also the space required will be more. Also, all the features in the dataset might not be useful. Some may contribute no information at all, while some may contribute similar information as the other features. Selecting the optimal set of features will help us hence reduce the space and time complexity as well as increase the accuracy or purity of classification (or regression) and clustering (or association) for supervised and unsupervised learning respectively."
},
{
"code": null,
"e": 1422,
"s": 1291,
"text": "Feature selection has four different approaches such as filter approach, wrapper approach, embedded approach, and hybrid approach."
},
{
"code": null,
"e": 2335,
"s": 1422,
"text": "Wrapper approach : This approach has high computational complexity. It uses a learning algorithm to evaluate the accuracy produced by the use of the selected features in classification. Wrapper methods can give high classification accuracy for particular classifiers.Filter approach : A subset of features is selected by this approach without using any learning algorithm. Higher-dimensional datasets use this method and it is relatively faster than the wrapper-based approaches.Embedded approach : The applied learning algorithms determine the specificity of this approach and it selects the features during the process of training the data set.Hybrid approach : Both filter and wrapper-based methods are used in hybrid approach. This approach first selects the possible optimal feature set which is further tested by the wrapper approach. It hence uses the advantages of both filter and wrapper-based approach."
},
{
"code": null,
"e": 2603,
"s": 2335,
"text": "Wrapper approach : This approach has high computational complexity. It uses a learning algorithm to evaluate the accuracy produced by the use of the selected features in classification. Wrapper methods can give high classification accuracy for particular classifiers."
},
{
"code": null,
"e": 2816,
"s": 2603,
"text": "Filter approach : A subset of features is selected by this approach without using any learning algorithm. Higher-dimensional datasets use this method and it is relatively faster than the wrapper-based approaches."
},
{
"code": null,
"e": 2984,
"s": 2816,
"text": "Embedded approach : The applied learning algorithms determine the specificity of this approach and it selects the features during the process of training the data set."
},
{
"code": null,
"e": 3251,
"s": 2984,
"text": "Hybrid approach : Both filter and wrapper-based methods are used in hybrid approach. This approach first selects the possible optimal feature set which is further tested by the wrapper approach. It hence uses the advantages of both filter and wrapper-based approach."
},
{
"code": null,
"e": 3304,
"s": 3251,
"text": "The parameters are classified based on two factors –"
},
{
"code": null,
"e": 3364,
"s": 3304,
"text": "The Similarity of information contributed by the features :"
},
{
"code": null,
"e": 4145,
"s": 3364,
"text": "1. CORRELATIONThe features are classified as associated or similar mostly based on their correlation factor. In the data set, we have many features which are correlated. Now the problem with having correlated features is that, if f1 and f2 are two correlated features of a data set, then the classifying or regression model including both f1 and f2 will give the same as the predictive model compared to the scenario where either f1 or f2 was included in the dataset. This is because both f1 and f2 are correlated and hence they contribute the same information regarding the model in the data set. There are various methods to calculate the correlation factor, however, Pearson’s correlation coefficient is most widely used. The formula for Pearson’s correlation coefficient() is:"
},
{
"code": null,
"e": 4245,
"s": 4145,
"text": "where \ncov(X, Y) - covariance\nsigma(X) - standard deviation of X\nsigma(Y) - standard deviation of Y"
},
{
"code": null,
"e": 4726,
"s": 4245,
"text": "Thus, the correlated features are irrelevant, as they all contribute similar information. Only one representative of the whole correlated or associated features would give the same classification or regression outcome. Hence these features are redundant and excluded for dimensionality reduction purposes after selecting a particular representative from each associated or correlated group of features using various algorithms. Quantum of information contributed by the features :"
},
{
"code": null,
"e": 4913,
"s": 4726,
"text": "1. ENTROPYEntropy is the measure of the average information content. The higher the entropy, the higher is the information contribution by that feature. Entropy (H) can be formulated as:"
},
{
"code": null,
"e": 5069,
"s": 4913,
"text": "where\nX - discrete random variable X\nP(X) - probability mass function\nE - expected value operator, \nI - information content of X.\nI(X) - a random variable."
},
{
"code": null,
"e": 5681,
"s": 5069,
"text": "In Data Science, entropy of a feature f1 is calculated by excluding feature f1 and then calculating the entropy of the rest of the features. Now, the lower the entropy value (excluding f1) the higher will be the information content of f1. In this manner the entropy of all the features is calculated. At the end, either a threshold value or further relevancy check determines the optimality of the features on the basis of which features are selected. Entropy is mostly used for Unsupervised Learning as we do have a class field in the dataset and hence entropy of the features can give substantial information."
},
{
"code": null,
"e": 5861,
"s": 5681,
"text": "2. MUTUAL INFORMATIONIn information theory, mutual information I(X;Y) is the amount of uncertainty in X due to the knowledge of Y. Mathematically, mutual information is defined as"
},
{
"code": null,
"e": 6027,
"s": 5861,
"text": "where \np(x, y) - joint probability function of X and Y,\np(x) - marginal probability distribution function of X\np(y) - marginal probability distribution function of Y"
},
{
"code": null,
"e": 6561,
"s": 6027,
"text": "Mutual Information in Data science is mostly calculated to know the amount of information shared about the class by a feature. Hence is mostly used for dimensionality reduction in Supervised Learning. The features which have high mutual information value corresponding to the class in a supervised learning are considered optimal since they can influence the predictive model towards the right prediction and hence increase the accuracy of the model. Reference : http://www.cs.uccs.edu/~jkalita/papers/2014/HoqueExpertSystems2014.pdf"
},
{
"code": null,
"e": 6587,
"s": 6561,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 6604,
"s": 6587,
"text": "Machine Learning"
},
{
"code": null,
"e": 6623,
"s": 6604,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6640,
"s": 6623,
"text": "Machine Learning"
},
{
"code": null,
"e": 6738,
"s": 6640,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6761,
"s": 6738,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 6787,
"s": 6761,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 6827,
"s": 6787,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 6863,
"s": 6827,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 6901,
"s": 6863,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 6935,
"s": 6901,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 6959,
"s": 6935,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 6999,
"s": 6959,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 7040,
"s": 6999,
"text": "Introduction to Recurrent Neural Network"
}
] |
How to round off a number in Python?
|
Python has an inbuilt round() function to round off a number.
The round() method in Python takes two parameters −
The first one is the number to be rounded off.
The first one is the number to be rounded off.
The second one specifies the number of digits to which the number must be rounded off.
The second one specifies the number of digits to which the number must be rounded off.
Here, the second parameter is optional.
If second parameter is not specified, then the round() method returns the integer using floor() and ceil().
It will look for the digits after the decimal.
If those are less than 5, it returns the floor() of the number passed.
If those are less than 5, it returns the floor() of the number passed.
Whereas if the digits after decimal are greater than 5, it returns the ceil() of the number passed.
Whereas if the digits after decimal are greater than 5, it returns the ceil() of the number passed.
If integer number is passed, then the same number is returned.
If integer number is passed, then the same number is returned.
It will be more clear from the implementation below −
The number to be rounded off is passed to the round() function. The output of round() in this case will always be an integer value.
Let us understand with an example.
Live Demo
print(round(15))
print(round(15.2))
print(round(15.8))
print(round(15.128))
print(round(15.89))
15
15
16
15
16
The explanation of all the print statements −
Integer 15 is passed, and the same integer is returned, hence output 15.
Integer 15 is passed, and the same integer is returned, hence output 15.
Number 15.2 is passed, the digits after decimal are less than 5, hence floor of 15.2 is returned, hence output 15.
Number 15.2 is passed, the digits after decimal are less than 5, hence floor of 15.2 is returned, hence output 15.
Number 15.8 is passed, the digits after decimal are greater than 5, hence ceil of 15.8 is returned, hence output 16.
Number 15.8 is passed, the digits after decimal are greater than 5, hence ceil of 15.8 is returned, hence output 16.
Number 15.128 is passed, the digits after decimal are less than 500, hence floor of 15.128 is returned, hence output 15.
Number 15.128 is passed, the digits after decimal are less than 500, hence floor of 15.128 is returned, hence output 15.
Number 15.89 is passed, the digits after decimal are greater than 50, hence ceil of 15.89 is returned, hence output 16.
Number 15.89 is passed, the digits after decimal are greater than 50, hence ceil of 15.89 is returned, hence output 16.
Note: All the outputs are integer values.
The second parameter gives the number of digits to which the number must be rounded off.
Live Demo
print(round(15,2))
print(round(15.2789,3))
print(round(15.82,1))
print(round(15.128,2))
print(round(15.8902,2))
15
15.279
15.8
15.13
15.89
The working of round() function, in this case, is the same as we calculate round off of a number mathematically.
In the case of integer value, the same integer value is returned, else the floating number rounded off to the specified number of digits is returned.
The number is 15.2789 and the number of digits is 3. The 4th digit after decimal is greater than 5, hence the 3rd digit (the last specified digit) will be incremented by 1. Hence the output will be 15.279.
The number is 15.2789 and the number of digits is 3. The 4th digit after decimal is greater than 5, hence the 3rd digit (the last specified digit) will be incremented by 1. Hence the output will be 15.279.
The number is 15.82 and the number of digits is 1. The 2
nd digit after decimal is less than 5, hence the 1st digit is not incremented by 1. Hence the output will be 15.8.
The number is 15.82 and the number of digits is 1. The 2
nd digit after decimal is less than 5, hence the 1st digit is not incremented by 1. Hence the output will be 15.8.
|
[
{
"code": null,
"e": 1249,
"s": 1187,
"text": "Python has an inbuilt round() function to round off a number."
},
{
"code": null,
"e": 1301,
"s": 1249,
"text": "The round() method in Python takes two parameters −"
},
{
"code": null,
"e": 1348,
"s": 1301,
"text": "The first one is the number to be rounded off."
},
{
"code": null,
"e": 1395,
"s": 1348,
"text": "The first one is the number to be rounded off."
},
{
"code": null,
"e": 1482,
"s": 1395,
"text": "The second one specifies the number of digits to which the number must be rounded off."
},
{
"code": null,
"e": 1569,
"s": 1482,
"text": "The second one specifies the number of digits to which the number must be rounded off."
},
{
"code": null,
"e": 1609,
"s": 1569,
"text": "Here, the second parameter is optional."
},
{
"code": null,
"e": 1717,
"s": 1609,
"text": "If second parameter is not specified, then the round() method returns the integer using floor() and ceil()."
},
{
"code": null,
"e": 1764,
"s": 1717,
"text": "It will look for the digits after the decimal."
},
{
"code": null,
"e": 1835,
"s": 1764,
"text": "If those are less than 5, it returns the floor() of the number passed."
},
{
"code": null,
"e": 1906,
"s": 1835,
"text": "If those are less than 5, it returns the floor() of the number passed."
},
{
"code": null,
"e": 2006,
"s": 1906,
"text": "Whereas if the digits after decimal are greater than 5, it returns the ceil() of the number passed."
},
{
"code": null,
"e": 2106,
"s": 2006,
"text": "Whereas if the digits after decimal are greater than 5, it returns the ceil() of the number passed."
},
{
"code": null,
"e": 2169,
"s": 2106,
"text": "If integer number is passed, then the same number is returned."
},
{
"code": null,
"e": 2232,
"s": 2169,
"text": "If integer number is passed, then the same number is returned."
},
{
"code": null,
"e": 2286,
"s": 2232,
"text": "It will be more clear from the implementation below −"
},
{
"code": null,
"e": 2418,
"s": 2286,
"text": "The number to be rounded off is passed to the round() function. The output of round() in this case will always be an integer value."
},
{
"code": null,
"e": 2453,
"s": 2418,
"text": "Let us understand with an example."
},
{
"code": null,
"e": 2464,
"s": 2453,
"text": " Live Demo"
},
{
"code": null,
"e": 2560,
"s": 2464,
"text": "print(round(15))\nprint(round(15.2))\nprint(round(15.8))\nprint(round(15.128))\nprint(round(15.89))"
},
{
"code": null,
"e": 2575,
"s": 2560,
"text": "15\n15\n16\n15\n16"
},
{
"code": null,
"e": 2621,
"s": 2575,
"text": "The explanation of all the print statements −"
},
{
"code": null,
"e": 2694,
"s": 2621,
"text": "Integer 15 is passed, and the same integer is returned, hence output 15."
},
{
"code": null,
"e": 2767,
"s": 2694,
"text": "Integer 15 is passed, and the same integer is returned, hence output 15."
},
{
"code": null,
"e": 2882,
"s": 2767,
"text": "Number 15.2 is passed, the digits after decimal are less than 5, hence floor of 15.2 is returned, hence output 15."
},
{
"code": null,
"e": 2997,
"s": 2882,
"text": "Number 15.2 is passed, the digits after decimal are less than 5, hence floor of 15.2 is returned, hence output 15."
},
{
"code": null,
"e": 3114,
"s": 2997,
"text": "Number 15.8 is passed, the digits after decimal are greater than 5, hence ceil of 15.8 is returned, hence output 16."
},
{
"code": null,
"e": 3231,
"s": 3114,
"text": "Number 15.8 is passed, the digits after decimal are greater than 5, hence ceil of 15.8 is returned, hence output 16."
},
{
"code": null,
"e": 3352,
"s": 3231,
"text": "Number 15.128 is passed, the digits after decimal are less than 500, hence floor of 15.128 is returned, hence output 15."
},
{
"code": null,
"e": 3473,
"s": 3352,
"text": "Number 15.128 is passed, the digits after decimal are less than 500, hence floor of 15.128 is returned, hence output 15."
},
{
"code": null,
"e": 3593,
"s": 3473,
"text": "Number 15.89 is passed, the digits after decimal are greater than 50, hence ceil of 15.89 is returned, hence output 16."
},
{
"code": null,
"e": 3713,
"s": 3593,
"text": "Number 15.89 is passed, the digits after decimal are greater than 50, hence ceil of 15.89 is returned, hence output 16."
},
{
"code": null,
"e": 3755,
"s": 3713,
"text": "Note: All the outputs are integer values."
},
{
"code": null,
"e": 3844,
"s": 3755,
"text": "The second parameter gives the number of digits to which the number must be rounded off."
},
{
"code": null,
"e": 3855,
"s": 3844,
"text": " Live Demo"
},
{
"code": null,
"e": 3967,
"s": 3855,
"text": "print(round(15,2))\nprint(round(15.2789,3))\nprint(round(15.82,1))\nprint(round(15.128,2))\nprint(round(15.8902,2))"
},
{
"code": null,
"e": 3994,
"s": 3967,
"text": "15\n15.279\n15.8\n15.13\n15.89"
},
{
"code": null,
"e": 4107,
"s": 3994,
"text": "The working of round() function, in this case, is the same as we calculate round off of a number mathematically."
},
{
"code": null,
"e": 4257,
"s": 4107,
"text": "In the case of integer value, the same integer value is returned, else the floating number rounded off to the specified number of digits is returned."
},
{
"code": null,
"e": 4463,
"s": 4257,
"text": "The number is 15.2789 and the number of digits is 3. The 4th digit after decimal is greater than 5, hence the 3rd digit (the last specified digit) will be incremented by 1. Hence the output will be 15.279."
},
{
"code": null,
"e": 4669,
"s": 4463,
"text": "The number is 15.2789 and the number of digits is 3. The 4th digit after decimal is greater than 5, hence the 3rd digit (the last specified digit) will be incremented by 1. Hence the output will be 15.279."
},
{
"code": null,
"e": 4841,
"s": 4669,
"text": "The number is 15.82 and the number of digits is 1. The 2\nnd digit after decimal is less than 5, hence the 1st digit is not incremented by 1. Hence the output will be 15.8."
},
{
"code": null,
"e": 5013,
"s": 4841,
"text": "The number is 15.82 and the number of digits is 1. The 2\nnd digit after decimal is less than 5, hence the 1st digit is not incremented by 1. Hence the output will be 15.8."
}
] |
HTTP headers | Accept-Language
|
31 Oct, 2019
This HTTP Accept-Language header tells the server about all the languages that the client can understand. With the help of content negotiation, there will be a set of supported languages in the HTTP Accept-Language proposal then the server selects one of the proposals of those languages and place that in the content-language header. In a few cases users can change the languages manually otherwise server detects the supported language by the browser’s language. But remember one thing that it is recommended that the server never overrides an explicit decision. If the user is comfortable with a language that does not list on the server language then the server can not serve the matching language to the client in that case 406 Not Acceptable status code will be sent.
Syntax:
This is the specific language selection syntax.Accept-Language: <language>
Accept-Language: <language>
This syntax works as a wild card (selects all languages).Accept-Language: *
Accept-Language: *
Note: Multiple languages can be listed by using commas and the optional.Directives: This header accepts two directives as mentioned above and described below:
<language>: This consists of a 2-3 letter base language tag representing the language, followed by sub-tags separated by ‘-‘ . The extra information is the region and country variant (like ‘en-US’ or ‘fr-CA’)
*: It is used as a wildcard for any language present.
Note: The ;q= it defines the factor weighting, value placed in an order of preference expressed using a relative quality valueExamples:
In this example single value is on Accept-Language header that is English of US.accept-language: en-US
accept-language: en-US
In this example double value is on Accept-Language header that is English of US and French of Canada.Accept-Language: en-US,fr-CA
Accept-Language: en-US,fr-CA
In this example single value is on Accept-Language header that is English of US with the factor weighting.accept-language: en-US,en;q=0.9
accept-language: en-US,en;q=0.9
To check this Accept-Language in action go to Inspect Element -> Network check the request header for Accept-Language like below, Accept-Language is highlighted you can see.Supported Browsers: The browsers are compatible with HTTP Accept-Language header are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
Roadmap to Learn JavaScript For Beginners
How to create footer to stay at the bottom of a Web page?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 802,
"s": 28,
"text": "This HTTP Accept-Language header tells the server about all the languages that the client can understand. With the help of content negotiation, there will be a set of supported languages in the HTTP Accept-Language proposal then the server selects one of the proposals of those languages and place that in the content-language header. In a few cases users can change the languages manually otherwise server detects the supported language by the browser’s language. But remember one thing that it is recommended that the server never overrides an explicit decision. If the user is comfortable with a language that does not list on the server language then the server can not serve the matching language to the client in that case 406 Not Acceptable status code will be sent."
},
{
"code": null,
"e": 810,
"s": 802,
"text": "Syntax:"
},
{
"code": null,
"e": 885,
"s": 810,
"text": "This is the specific language selection syntax.Accept-Language: <language>"
},
{
"code": null,
"e": 913,
"s": 885,
"text": "Accept-Language: <language>"
},
{
"code": null,
"e": 989,
"s": 913,
"text": "This syntax works as a wild card (selects all languages).Accept-Language: *"
},
{
"code": null,
"e": 1008,
"s": 989,
"text": "Accept-Language: *"
},
{
"code": null,
"e": 1167,
"s": 1008,
"text": "Note: Multiple languages can be listed by using commas and the optional.Directives: This header accepts two directives as mentioned above and described below:"
},
{
"code": null,
"e": 1376,
"s": 1167,
"text": "<language>: This consists of a 2-3 letter base language tag representing the language, followed by sub-tags separated by ‘-‘ . The extra information is the region and country variant (like ‘en-US’ or ‘fr-CA’)"
},
{
"code": null,
"e": 1430,
"s": 1376,
"text": "*: It is used as a wildcard for any language present."
},
{
"code": null,
"e": 1566,
"s": 1430,
"text": "Note: The ;q= it defines the factor weighting, value placed in an order of preference expressed using a relative quality valueExamples:"
},
{
"code": null,
"e": 1669,
"s": 1566,
"text": "In this example single value is on Accept-Language header that is English of US.accept-language: en-US"
},
{
"code": null,
"e": 1692,
"s": 1669,
"text": "accept-language: en-US"
},
{
"code": null,
"e": 1822,
"s": 1692,
"text": "In this example double value is on Accept-Language header that is English of US and French of Canada.Accept-Language: en-US,fr-CA"
},
{
"code": null,
"e": 1851,
"s": 1822,
"text": "Accept-Language: en-US,fr-CA"
},
{
"code": null,
"e": 1989,
"s": 1851,
"text": "In this example single value is on Accept-Language header that is English of US with the factor weighting.accept-language: en-US,en;q=0.9"
},
{
"code": null,
"e": 2021,
"s": 1989,
"text": "accept-language: en-US,en;q=0.9"
},
{
"code": null,
"e": 2293,
"s": 2021,
"text": "To check this Accept-Language in action go to Inspect Element -> Network check the request header for Accept-Language like below, Accept-Language is highlighted you can see.Supported Browsers: The browsers are compatible with HTTP Accept-Language header are listed below:"
},
{
"code": null,
"e": 2307,
"s": 2293,
"text": "Google Chrome"
},
{
"code": null,
"e": 2325,
"s": 2307,
"text": "Internet Explorer"
},
{
"code": null,
"e": 2333,
"s": 2325,
"text": "Firefox"
},
{
"code": null,
"e": 2340,
"s": 2333,
"text": "Safari"
},
{
"code": null,
"e": 2346,
"s": 2340,
"text": "Opera"
},
{
"code": null,
"e": 2359,
"s": 2346,
"text": "HTTP-headers"
},
{
"code": null,
"e": 2366,
"s": 2359,
"text": "Picked"
},
{
"code": null,
"e": 2383,
"s": 2366,
"text": "Web Technologies"
},
{
"code": null,
"e": 2481,
"s": 2383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2542,
"s": 2481,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2585,
"s": 2542,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2657,
"s": 2585,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2697,
"s": 2657,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2721,
"s": 2697,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2754,
"s": 2721,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 2814,
"s": 2754,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2856,
"s": 2814,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2914,
"s": 2856,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
How to update parent state in ReactJS ?
|
22 Dec, 2020
We can pass a function setting the state from the parent to the child component as a prop.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
Filename: App.js
Javascript
import React, { Component } from "react";class App extends Component { state = { text: 'click me' } // Function to update state handleUpdate = (newtext) => { this.setState({ text: newtext }) } render() { return ( <div> <Child text={this.state.text} // Passing a function to child updateState={this.handleUpdate}> </Child> </div> ); }}class Child extends Component { render() { return ( <button // Using parent props to update parent state onClick={() => this.props .updateState('parent state changed')}> {this.props.text} </button> ) }} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: You will see the following button on the screen:
Before Click
After clicking on the button, the following will be the output:
After Click
Picked
react-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": "\n22 Dec, 2020"
},
{
"code": null,
"e": 119,
"s": 28,
"text": "We can pass a function setting the state from the parent to the child component as a prop."
},
{
"code": null,
"e": 147,
"s": 119,
"text": "Creating React Application:"
},
{
"code": null,
"e": 211,
"s": 147,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 243,
"s": 211,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 343,
"s": 243,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 357,
"s": 343,
"text": "cd foldername"
},
{
"code": null,
"e": 409,
"s": 357,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 427,
"s": 409,
"text": "Project Structure"
},
{
"code": null,
"e": 444,
"s": 427,
"text": "Filename: App.js"
},
{
"code": null,
"e": 455,
"s": 444,
"text": "Javascript"
},
{
"code": "import React, { Component } from \"react\";class App extends Component { state = { text: 'click me' } // Function to update state handleUpdate = (newtext) => { this.setState({ text: newtext }) } render() { return ( <div> <Child text={this.state.text} // Passing a function to child updateState={this.handleUpdate}> </Child> </div> ); }}class Child extends Component { render() { return ( <button // Using parent props to update parent state onClick={() => this.props .updateState('parent state changed')}> {this.props.text} </button> ) }} export default App;",
"e": 1144,
"s": 455,
"text": null
},
{
"code": null,
"e": 1257,
"s": 1144,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 1267,
"s": 1257,
"text": "npm start"
},
{
"code": null,
"e": 1324,
"s": 1267,
"text": "Output: You will see the following button on the screen:"
},
{
"code": null,
"e": 1337,
"s": 1324,
"text": "Before Click"
},
{
"code": null,
"e": 1401,
"s": 1337,
"text": "After clicking on the button, the following will be the output:"
},
{
"code": null,
"e": 1413,
"s": 1401,
"text": "After Click"
},
{
"code": null,
"e": 1420,
"s": 1413,
"text": "Picked"
},
{
"code": null,
"e": 1429,
"s": 1420,
"text": "react-js"
},
{
"code": null,
"e": 1440,
"s": 1429,
"text": "JavaScript"
},
{
"code": null,
"e": 1457,
"s": 1440,
"text": "Web Technologies"
}
] |
Razorpay Integration in Django
|
22 Jul, 2021
Payments are an integral part of the online ecosystem, be it at e-commerce stores to process the orders or a simple donation to someone. Integrating a payment gateway into your website can be a tedious process. Let us have a look at how you can integrate Razorpay into a Django website.
We will build a basic replica of Buy Me Coffee, uhh Buy Me Chai where users can give donations to us.
The integration process though remains the same for whatever you are building. Let’s break down the whole process into simple steps.
Make sure you are done with the django installation. Create a new project called dj_razorpay and then start a new app called payment. Add “payment” to the list of installed_apps in the settings.py file. Also, apply the migrations.
INSTALLED_APPS = [
...
'payment',
...
]
First, create an account on Razorpay’s website, you simply have to signup with your email and password and add some basic information such as your phone number.
Inside the setting screen, click on Create a new key option your key will be generated. You will get Key ID and Key Secret. Currently our payments will be in “test mode” i.e no real transaction would happen and the payment options are also limited. To accept real money and unlock more payment options you need to complete your KYC and provide your bank details. The integration process remains the same irrespective of the mode.
Note: You will be shown the Key Secret only once, so immediately copy it somewhere.
Now add the Key Id and Key Secret to settings.py file.
RAZOR_KEY_ID = YOUR_KEY_ID
RAZOR_KEY_SECRET = YOUR_KEY_SECRET
Before we move ahead let’s install razorpay’s python package.
pip install razorpay
This is the main step of the process. First, we need to understand how payment works in Razorpay.
Create a Razor Order from our Django Server.Pass Order Id and Other Options to the Frontend.The user clicks the payment button and pays with one of the payment methods.Razorpay handles Payment Success and Failure.On Failure, Razorpay facilitates retry of the payments.On Success, Razorpay makes a post request to a callback URL on our server.Verify the payment signature, to confirm that payment is authentic and isn’t tampered with.Once verified, capture the payment and render the success page.
Create a Razor Order from our Django Server.
Pass Order Id and Other Options to the Frontend.
The user clicks the payment button and pays with one of the payment methods.
Razorpay handles Payment Success and Failure.
On Failure, Razorpay facilitates retry of the payments.
On Success, Razorpay makes a post request to a callback URL on our server.
Verify the payment signature, to confirm that payment is authentic and isn’t tampered with.
Once verified, capture the payment and render the success page.
See code comments for more details.
Note: Amount in Razorpay works in subunits of currency i.e Rs 500 would become 50000 paise.
Python3
from django.shortcuts import renderimport razorpayfrom django.conf import settingsfrom django.views.decorators.csrf import csrf_exemptfrom django.http import HttpResponseBadRequest # authorize razorpay client with API Keys.razorpay_client = razorpay.Client( auth=(settings.RAZOR_KEY_ID, settings.RAZOR_KEY_SECRET)) def homepage(request): currency = 'INR' amount = 20000 # Rs. 200 # Create a Razorpay Order razorpay_order = razorpay_client.order.create(dict(amount=amount, currency=currency, payment_capture='0')) # order id of newly created order. razorpay_order_id = razorpay_order['id'] callback_url = 'paymenthandler/' # we need to pass these details to frontend. context = {} context['razorpay_order_id'] = razorpay_order_id context['razorpay_merchant_key'] = settings.RAZOR_KEY_ID context['razorpay_amount'] = amount context['currency'] = currency context['callback_url'] = callback_url return render(request, 'index.html', context=context) # we need to csrf_exempt this url as# POST request will be made by Razorpay# and it won't have the csrf token.@csrf_exemptdef paymenthandler(request): # only accept POST request. if request.method == "POST": try: # get the required parameters from post request. payment_id = request.POST.get('razorpay_payment_id', '') razorpay_order_id = request.POST.get('razorpay_order_id', '') signature = request.POST.get('razorpay_signature', '') params_dict = { 'razorpay_order_id': razorpay_order_id, 'razorpay_payment_id': payment_id, 'razorpay_signature': signature } # verify the payment signature. result = razorpay_client.utility.verify_payment_signature( params_dict) if result is None: amount = 20000 # Rs. 200 try: # capture the payemt razorpay_client.payment.capture(payment_id, amount) # render success page on successful caputre of payment return render(request, 'paymentsuccess.html') except: # if there is an error while capturing payment. return render(request, 'paymentfail.html') else: # if signature verification fails. return render(request, 'paymentfail.html') except: # if we don't find the required parameters in POST data return HttpResponseBadRequest() else: # if other than POST request is made. return HttpResponseBadRequest()
Note: It is necessary to capture the payment, otherwise it would be auto refunded to the payer.
Now map the above views to the urls in the urls.py.
Python3
# dj_razorpay/urls.py from django.contrib import adminfrom django.urls import pathfrom payment import views urlpatterns = [ path('', views.homepage, name='index'), path('paymenthandler/', views.paymenthandler, name='paymenthandler'), path('admin/', admin.site.urls),]
We need to pass the Razorpay order id and other options mentioned in the previous step. First load the Razorpay’s javascript code that would render the payment window and initialize it with the options received from the backend. Add an event listener to the payment button so the payment window gets opened once it is clicked.
Here we are rendering the payment button on the homepage itself. We would also need another two pages for payment success and failure.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>GFG</title> <style> * { box-sizing: border-box; padding: 0px; margin: 0px; font-family: cursive; } html, body { height: 100%; } body { background-color: #f1f5f8; display: flex; justify-content: center; align-items: center; } .card { background-color: white; padding: 25px; border: 1px solid #bbbbbb; border-radius: 5px; box-shadow: 1px 1px 10px 0px rgb(0 0 0 / 25%); } .title { text-align: center; letter-spacing: 1px; } .muted { color: #8e7f7f; display: block; margin-bottom: 10px; text-align: center; } .btn_container { padding: 20px; text-align: center; } .btn { border-radius: 4px; cursor: pointer; padding: 4px 8px; background-color: #ffaaa7; color: white; font-size: 1.2em; font-weight: 600; letter-spacing: 1px; } </style> </head> <body> <div class="card"> <h1 class="title">Buy Me a Chai </h1> <small class="muted" >If you like my work, you can support me by donating ₹200</small > <div class="btn_container"> <!-- Payment Button --> <button class="btn" id="pay-btn">Donate</button> </div> </div> </body> <!-- Razorpay's Javascript code. --> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { // Enter the Key ID generated from the Dashboard key: "{{ razorpay_merchant_key }}", // Amount is in currency subunits. // Default currency is INR. Hence, // 50000 refers to 50000 paise amount: "{{ razorpay_amount }}", currency: "{{ currency }}", // Your/store name. name: "Dj Razorpay", // Pass the `id` obtained in the response of Step 1 order_id: "{{ razorpay_order_id }}", callback_url: "{{ callback_url }}", }; // initialise razorpay with the options. var rzp1 = new Razorpay(options); // add event listener to the payment button. document.getElementById("pay-btn").onclick = function (e) { rzp1.open(); e.preventDefault(); }; </script></html>
Now let’s fire up the server and check if everything is working fine!
python manage.py runserver
We successfully received the payment!! You can check these payments in Razorpay’s dashboard.
akshaysingh98088
Django-Projects
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 339,
"s": 52,
"text": "Payments are an integral part of the online ecosystem, be it at e-commerce stores to process the orders or a simple donation to someone. Integrating a payment gateway into your website can be a tedious process. Let us have a look at how you can integrate Razorpay into a Django website."
},
{
"code": null,
"e": 443,
"s": 339,
"text": "We will build a basic replica of Buy Me Coffee, uhh Buy Me Chai where users can give donations to us. "
},
{
"code": null,
"e": 576,
"s": 443,
"text": "The integration process though remains the same for whatever you are building. Let’s break down the whole process into simple steps."
},
{
"code": null,
"e": 807,
"s": 576,
"text": "Make sure you are done with the django installation. Create a new project called dj_razorpay and then start a new app called payment. Add “payment” to the list of installed_apps in the settings.py file. Also, apply the migrations."
},
{
"code": null,
"e": 859,
"s": 807,
"text": "INSTALLED_APPS = [\n ...\n 'payment',\n ...\n]"
},
{
"code": null,
"e": 1021,
"s": 859,
"text": "First, create an account on Razorpay’s website, you simply have to signup with your email and password and add some basic information such as your phone number. "
},
{
"code": null,
"e": 1452,
"s": 1021,
"text": "Inside the setting screen, click on Create a new key option your key will be generated. You will get Key ID and Key Secret. Currently our payments will be in “test mode” i.e no real transaction would happen and the payment options are also limited. To accept real money and unlock more payment options you need to complete your KYC and provide your bank details. The integration process remains the same irrespective of the mode."
},
{
"code": null,
"e": 1536,
"s": 1452,
"text": "Note: You will be shown the Key Secret only once, so immediately copy it somewhere."
},
{
"code": null,
"e": 1591,
"s": 1536,
"text": "Now add the Key Id and Key Secret to settings.py file."
},
{
"code": null,
"e": 1653,
"s": 1591,
"text": "RAZOR_KEY_ID = YOUR_KEY_ID\nRAZOR_KEY_SECRET = YOUR_KEY_SECRET"
},
{
"code": null,
"e": 1715,
"s": 1653,
"text": "Before we move ahead let’s install razorpay’s python package."
},
{
"code": null,
"e": 1736,
"s": 1715,
"text": "pip install razorpay"
},
{
"code": null,
"e": 1834,
"s": 1736,
"text": "This is the main step of the process. First, we need to understand how payment works in Razorpay."
},
{
"code": null,
"e": 2331,
"s": 1834,
"text": "Create a Razor Order from our Django Server.Pass Order Id and Other Options to the Frontend.The user clicks the payment button and pays with one of the payment methods.Razorpay handles Payment Success and Failure.On Failure, Razorpay facilitates retry of the payments.On Success, Razorpay makes a post request to a callback URL on our server.Verify the payment signature, to confirm that payment is authentic and isn’t tampered with.Once verified, capture the payment and render the success page."
},
{
"code": null,
"e": 2376,
"s": 2331,
"text": "Create a Razor Order from our Django Server."
},
{
"code": null,
"e": 2425,
"s": 2376,
"text": "Pass Order Id and Other Options to the Frontend."
},
{
"code": null,
"e": 2502,
"s": 2425,
"text": "The user clicks the payment button and pays with one of the payment methods."
},
{
"code": null,
"e": 2548,
"s": 2502,
"text": "Razorpay handles Payment Success and Failure."
},
{
"code": null,
"e": 2604,
"s": 2548,
"text": "On Failure, Razorpay facilitates retry of the payments."
},
{
"code": null,
"e": 2679,
"s": 2604,
"text": "On Success, Razorpay makes a post request to a callback URL on our server."
},
{
"code": null,
"e": 2771,
"s": 2679,
"text": "Verify the payment signature, to confirm that payment is authentic and isn’t tampered with."
},
{
"code": null,
"e": 2835,
"s": 2771,
"text": "Once verified, capture the payment and render the success page."
},
{
"code": null,
"e": 2871,
"s": 2835,
"text": "See code comments for more details."
},
{
"code": null,
"e": 2964,
"s": 2871,
"text": "Note: Amount in Razorpay works in subunits of currency i.e Rs 500 would become 50000 paise. "
},
{
"code": null,
"e": 2972,
"s": 2964,
"text": "Python3"
},
{
"code": "from django.shortcuts import renderimport razorpayfrom django.conf import settingsfrom django.views.decorators.csrf import csrf_exemptfrom django.http import HttpResponseBadRequest # authorize razorpay client with API Keys.razorpay_client = razorpay.Client( auth=(settings.RAZOR_KEY_ID, settings.RAZOR_KEY_SECRET)) def homepage(request): currency = 'INR' amount = 20000 # Rs. 200 # Create a Razorpay Order razorpay_order = razorpay_client.order.create(dict(amount=amount, currency=currency, payment_capture='0')) # order id of newly created order. razorpay_order_id = razorpay_order['id'] callback_url = 'paymenthandler/' # we need to pass these details to frontend. context = {} context['razorpay_order_id'] = razorpay_order_id context['razorpay_merchant_key'] = settings.RAZOR_KEY_ID context['razorpay_amount'] = amount context['currency'] = currency context['callback_url'] = callback_url return render(request, 'index.html', context=context) # we need to csrf_exempt this url as# POST request will be made by Razorpay# and it won't have the csrf token.@csrf_exemptdef paymenthandler(request): # only accept POST request. if request.method == \"POST\": try: # get the required parameters from post request. payment_id = request.POST.get('razorpay_payment_id', '') razorpay_order_id = request.POST.get('razorpay_order_id', '') signature = request.POST.get('razorpay_signature', '') params_dict = { 'razorpay_order_id': razorpay_order_id, 'razorpay_payment_id': payment_id, 'razorpay_signature': signature } # verify the payment signature. result = razorpay_client.utility.verify_payment_signature( params_dict) if result is None: amount = 20000 # Rs. 200 try: # capture the payemt razorpay_client.payment.capture(payment_id, amount) # render success page on successful caputre of payment return render(request, 'paymentsuccess.html') except: # if there is an error while capturing payment. return render(request, 'paymentfail.html') else: # if signature verification fails. return render(request, 'paymentfail.html') except: # if we don't find the required parameters in POST data return HttpResponseBadRequest() else: # if other than POST request is made. return HttpResponseBadRequest()",
"e": 5761,
"s": 2972,
"text": null
},
{
"code": null,
"e": 5857,
"s": 5761,
"text": "Note: It is necessary to capture the payment, otherwise it would be auto refunded to the payer."
},
{
"code": null,
"e": 5909,
"s": 5857,
"text": "Now map the above views to the urls in the urls.py."
},
{
"code": null,
"e": 5917,
"s": 5909,
"text": "Python3"
},
{
"code": "# dj_razorpay/urls.py from django.contrib import adminfrom django.urls import pathfrom payment import views urlpatterns = [ path('', views.homepage, name='index'), path('paymenthandler/', views.paymenthandler, name='paymenthandler'), path('admin/', admin.site.urls),]",
"e": 6194,
"s": 5917,
"text": null
},
{
"code": null,
"e": 6521,
"s": 6194,
"text": "We need to pass the Razorpay order id and other options mentioned in the previous step. First load the Razorpay’s javascript code that would render the payment window and initialize it with the options received from the backend. Add an event listener to the payment button so the payment window gets opened once it is clicked."
},
{
"code": null,
"e": 6656,
"s": 6521,
"text": "Here we are rendering the payment button on the homepage itself. We would also need another two pages for payment success and failure."
},
{
"code": null,
"e": 6661,
"s": 6656,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>GFG</title> <style> * { box-sizing: border-box; padding: 0px; margin: 0px; font-family: cursive; } html, body { height: 100%; } body { background-color: #f1f5f8; display: flex; justify-content: center; align-items: center; } .card { background-color: white; padding: 25px; border: 1px solid #bbbbbb; border-radius: 5px; box-shadow: 1px 1px 10px 0px rgb(0 0 0 / 25%); } .title { text-align: center; letter-spacing: 1px; } .muted { color: #8e7f7f; display: block; margin-bottom: 10px; text-align: center; } .btn_container { padding: 20px; text-align: center; } .btn { border-radius: 4px; cursor: pointer; padding: 4px 8px; background-color: #ffaaa7; color: white; font-size: 1.2em; font-weight: 600; letter-spacing: 1px; } </style> </head> <body> <div class=\"card\"> <h1 class=\"title\">Buy Me a Chai </h1> <small class=\"muted\" >If you like my work, you can support me by donating ₹200</small > <div class=\"btn_container\"> <!-- Payment Button --> <button class=\"btn\" id=\"pay-btn\">Donate</button> </div> </div> </body> <!-- Razorpay's Javascript code. --> <script src=\"https://checkout.razorpay.com/v1/checkout.js\"></script> <script> var options = { // Enter the Key ID generated from the Dashboard key: \"{{ razorpay_merchant_key }}\", // Amount is in currency subunits. // Default currency is INR. Hence, // 50000 refers to 50000 paise amount: \"{{ razorpay_amount }}\", currency: \"{{ currency }}\", // Your/store name. name: \"Dj Razorpay\", // Pass the `id` obtained in the response of Step 1 order_id: \"{{ razorpay_order_id }}\", callback_url: \"{{ callback_url }}\", }; // initialise razorpay with the options. var rzp1 = new Razorpay(options); // add event listener to the payment button. document.getElementById(\"pay-btn\").onclick = function (e) { rzp1.open(); e.preventDefault(); }; </script></html>",
"e": 9159,
"s": 6661,
"text": null
},
{
"code": null,
"e": 9233,
"s": 9162,
"text": "Now let’s fire up the server and check if everything is working fine! "
},
{
"code": null,
"e": 9260,
"s": 9233,
"text": "python manage.py runserver"
},
{
"code": null,
"e": 9355,
"s": 9262,
"text": "We successfully received the payment!! You can check these payments in Razorpay’s dashboard."
},
{
"code": null,
"e": 9372,
"s": 9355,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 9388,
"s": 9372,
"text": "Django-Projects"
},
{
"code": null,
"e": 9402,
"s": 9388,
"text": "Python Django"
},
{
"code": null,
"e": 9409,
"s": 9402,
"text": "Python"
},
{
"code": null,
"e": 9507,
"s": 9409,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9539,
"s": 9507,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 9566,
"s": 9539,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 9597,
"s": 9566,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 9620,
"s": 9597,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 9641,
"s": 9620,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 9697,
"s": 9641,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 9739,
"s": 9697,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 9781,
"s": 9739,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 9820,
"s": 9781,
"text": "Python | Get unique values from a list"
}
] |
How to get array structure with alert() in JavaScript?
|
06 Sep, 2019
Here is the code to see the array structure using alert() . Here below few techniquesare discussedApproach 1:
First take the values in a variable(lets arr).
Pass the array name in the alert() .
We can directly use the array name because arrayName automatically converted to arrayName.toString()
Example 1: This example follows the approach discussed above.
<!DOCTYPE HTML><html> <head> <title> How to get array structure with alert() in JavaScript? </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> Click here </button> <script> var el_up = document.getElementById("GFG_UP"); var arr = [1, 2, 4, 6, 9]; el_up.innerHTML = "Click on the button to see the array structure using Alert().<br> Array is = " + arr; function gfg_Run() { alert(arr); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
First take the values in a variable(lets arr).
Pass the array name in the alert() .
We can use .join() method for our simplicity to see the array elements each in a line.
Example 2: This example follows the approach discussed above.
<!DOCTYPE HTML><html> <head> <title> How to get array structure with alert() in JavaScript? </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> Click here </button> <script> var el_up = document.getElementById("GFG_UP"); var arr = [1, 2, 4, 6, 9]; el_up.innerHTML = "Click on the button to see the array structure using Alert().<br> Array is = " + arr; function gfg_Run() { alert(arr.join('\n')); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Sep, 2019"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "Here is the code to see the array structure using alert() . Here below few techniquesare discussedApproach 1:"
},
{
"code": null,
"e": 185,
"s": 138,
"text": "First take the values in a variable(lets arr)."
},
{
"code": null,
"e": 222,
"s": 185,
"text": "Pass the array name in the alert() ."
},
{
"code": null,
"e": 323,
"s": 222,
"text": "We can directly use the array name because arrayName automatically converted to arrayName.toString()"
},
{
"code": null,
"e": 385,
"s": 323,
"text": "Example 1: This example follows the approach discussed above."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to get array structure with alert() in JavaScript? </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Click here </button> <script> var el_up = document.getElementById(\"GFG_UP\"); var arr = [1, 2, 4, 6, 9]; el_up.innerHTML = \"Click on the button to see the array structure using Alert().<br> Array is = \" + arr; function gfg_Run() { alert(arr); } </script></body> </html>",
"e": 1081,
"s": 385,
"text": null
},
{
"code": null,
"e": 1089,
"s": 1081,
"text": "Output:"
},
{
"code": null,
"e": 1120,
"s": 1089,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 1150,
"s": 1120,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 1162,
"s": 1150,
"text": "Approach 2:"
},
{
"code": null,
"e": 1209,
"s": 1162,
"text": "First take the values in a variable(lets arr)."
},
{
"code": null,
"e": 1246,
"s": 1209,
"text": "Pass the array name in the alert() ."
},
{
"code": null,
"e": 1333,
"s": 1246,
"text": "We can use .join() method for our simplicity to see the array elements each in a line."
},
{
"code": null,
"e": 1395,
"s": 1333,
"text": "Example 2: This example follows the approach discussed above."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to get array structure with alert() in JavaScript? </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Click here </button> <script> var el_up = document.getElementById(\"GFG_UP\"); var arr = [1, 2, 4, 6, 9]; el_up.innerHTML = \"Click on the button to see the array structure using Alert().<br> Array is = \" + arr; function gfg_Run() { alert(arr.join('\\n')); } </script></body> </html>",
"e": 2093,
"s": 1395,
"text": null
},
{
"code": null,
"e": 2101,
"s": 2093,
"text": "Output:"
},
{
"code": null,
"e": 2132,
"s": 2101,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 2162,
"s": 2132,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 2178,
"s": 2162,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2189,
"s": 2178,
"text": "JavaScript"
},
{
"code": null,
"e": 2206,
"s": 2189,
"text": "Web Technologies"
},
{
"code": null,
"e": 2233,
"s": 2206,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2331,
"s": 2233,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2392,
"s": 2331,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2464,
"s": 2392,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2504,
"s": 2464,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2546,
"s": 2504,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2587,
"s": 2546,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2620,
"s": 2587,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2682,
"s": 2620,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2743,
"s": 2682,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2793,
"s": 2743,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Sum of array elements after reversing each element
|
09 Apr, 2021
Given an array arr[] consisting of N positive integers, the task is to find the sum of all array elements after reversing digits of every array element.
Examples:
Input: arr[] = {7, 234, 58100}Output: 18939Explanation:Modified array after reversing each array elements = {7, 432, 18500}.Therefore, the sum of the modified array = 7 + 432 + 18500 = 18939.
Input: arr[] = {0, 100, 220}Output: 320Explanation:Modified array after reversing each array elements = {0, 100, 220}.Therefore, the sum of the modified array = 0 + 100 + 220 = 320.
Approach: The idea is to reverse each number of the given array as per the given conditions and find sum of all array elements formed after reversing. Below steps to solve the problem:
Initialize a variable, say sum, to store the required sum.Initialize variable count as 0 and f as false to store count of ending 0s of arr[i] and flag to avoid all non-ending 0.Initialize rev as 0 to store reversal of each array element.Traverse the given array and for each array element do the following operation:Increment count and divide arr[i] by 10 until all the zeros at the end are traversed.Reset f with true that means all ending 0 digits have been considered.Now, reverse arr[i] by updating rev = rev*10 + arr[i] % 10 and arr[i] = arr[i]/10.After traversing each digit of arr[i], update rev = rev * Math.pow(10, count) to add all ending 0’s to the end of reversed number.For each reverse number in the above step, add that value to the resultant sum.
Initialize a variable, say sum, to store the required sum.
Initialize variable count as 0 and f as false to store count of ending 0s of arr[i] and flag to avoid all non-ending 0.
Initialize rev as 0 to store reversal of each array element.
Traverse the given array and for each array element do the following operation:Increment count and divide arr[i] by 10 until all the zeros at the end are traversed.Reset f with true that means all ending 0 digits have been considered.Now, reverse arr[i] by updating rev = rev*10 + arr[i] % 10 and arr[i] = arr[i]/10.After traversing each digit of arr[i], update rev = rev * Math.pow(10, count) to add all ending 0’s to the end of reversed number.
Increment count and divide arr[i] by 10 until all the zeros at the end are traversed.
Reset f with true that means all ending 0 digits have been considered.
Now, reverse arr[i] by updating rev = rev*10 + arr[i] % 10 and arr[i] = arr[i]/10.
After traversing each digit of arr[i], update rev = rev * Math.pow(10, count) to add all ending 0’s to the end of reversed number.
For each reverse number in the above step, add that value to the resultant sum.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the sum of elements// after reversing each element in arr[]void totalSum(int arr[], int n){ // Stores the final sum int sum = 0; // Traverse the given array for(int i = 0; i < n; i++) { // Stores count of ending 0s int count = 0; int rev = 0, num = arr[i]; // Flag to avoid count of 0s // that doesn't ends with 0s bool f = false; while (num > 0) { // Count of ending 0s while (num > 0 && !f && num % 10 == 0) { count++; num = num / 10; } // Update flag with true f = true; // Reversing the num if (num > 0) { rev = rev * 10 + num % 10; num = num / 10; } } // Add all ending 0s to // end of rev if (count > 0) rev = rev * pow(10, count); // Update sum sum = sum + rev; } // Print total sum cout << sum;} // Driver Codeint main(){ // Given arr[] int arr[] = { 7, 234, 58100 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call totalSum(arr, n); return 0;} // This code is contributed by akhilsaini
// Java program for the above approach import java.util.*; class GFG { // Function to find the sum of elements // after reversing each element in arr[] static void totalSum(int[] arr) { // Stores the final sum int sum = 0; // Traverse the given array for (int i = 0; i < arr.length; i++) { // Stores count of ending 0s int count = 0; int rev = 0, num = arr[i]; // Flag to avoid count of 0s // that doesn't ends with 0s boolean f = false; while (num > 0) { // Count of ending 0s while (num > 0 && !f && num % 10 == 0) { count++; num = num / 10; } // Update flag with true f = true; // Reversing the num if (num > 0) { rev = rev * 10 + num % 10; num = num / 10; } } // Add all ending 0s to // end of rev if (count > 0) rev = rev * (int)Math.pow(10, count); // Update sum sum = sum + rev; } // Print total sum System.out.print(sum); } // Driver Code public static void main(String[] args) { // Given arr[] int[] arr = { 7, 234, 58100 }; // Function Call totalSum(arr); }}
# Python3 program for the above approach # Function to find the sum of elements# after reversing each element in arr[]def totalSum(arr, n): # Stores the final sum sums = 0 # Traverse the given array for i in range(0, n): # Stores count of ending 0s count = 0 rev = 0 num = arr[i] # Flag to avoid count of 0s # that doesn't ends with 0s f = False while num > 0: # Count of ending 0s while (num > 0 and f == False and num % 10 == 0): count = count + 1 num = num // 10 # Update flag with true f = True # Reversing the num if num > 0: rev = rev * 10 + num % 10 num = num // 10 # Add all ending 0s to # end of rev if (count > 0): rev = rev * pow(10, count) # Update sum sums = sums + rev # Print total sum print(sums) # Driver Codeif __name__ == "__main__": # Given arr[] arr = [ 7, 234, 58100 ] n = len(arr) # Function call totalSum(arr, n) # This code is contributed by akhilsaini
// C# program for the above approachusing System; class GFG{ // Function to find the sum of elements// after reversing each element in arr[]static void totalSum(int[] arr){ // Stores the final sum int sum = 0; // Traverse the given array for(int i = 0; i < arr.Length; i++) { // Stores count of ending 0s int count = 0; int rev = 0, num = arr[i]; // Flag to avoid count of 0s // that doesn't ends with 0s bool f = false; while (num > 0) { // Count of ending 0s while (num > 0 && !f && num % 10 == 0) { count++; num = num / 10; } // Update flag with true f = true; // Reversing the num if (num > 0) { rev = rev * 10 + num % 10; num = num / 10; } } // Add all ending 0s to // end of rev if (count > 0) rev = rev * (int)Math.Pow(10, count); // Update sum sum = sum + rev; } // Print total sum Console.Write(sum);} // Driver Codestatic public void Main(){ // Given arr[] int[] arr = { 7, 234, 58100 }; // Function call totalSum(arr);}} // This code is contributed by akhilsaini
<script> // Javascript program for the above approach // Function to find the sum of elements// after reversing each element in arr[]function totalSum(arr, n){ // Stores the final sum let sum = 0; // Traverse the given array for(let i = 0; i < n; i++) { // Stores count of ending 0s let count = 0; let rev = 0, num = arr[i]; // Flag to avoid count of 0s // that doesn't ends with 0s let f = false; while (num > 0) { // Count of ending 0s while (num > 0 && !f && num % 10 == 0) { count++; num = Math.floor(num / 10); } // Update flag with true f = true; // Reversing the num if (num > 0) { rev = rev * 10 + num % 10; num = Math.floor(num / 10); } } // Add all ending 0s to // end of rev if (count > 0) rev = rev * Math.pow(10, count); // Update sum sum = sum + rev; } // Print total sum document.write(sum);} // Driver Code // Given arr[] let arr = [ 7, 234, 58100 ]; let n = arr.length; // Function call totalSum(arr, n); // This code is contributed by Mayank Tyagi </script>
18939
Time Complexity: O(N*log10M), where N denotes the length of the array and M denotes maximum array element. Auxiliary Space: O(1)
akhilsaini
mayanktyagi1709
array-rearrange
number-digits
Reverse
Arrays
Mathematical
School Programming
Arrays
Mathematical
Reverse
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": 52,
"s": 24,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 205,
"s": 52,
"text": "Given an array arr[] consisting of N positive integers, the task is to find the sum of all array elements after reversing digits of every array element."
},
{
"code": null,
"e": 215,
"s": 205,
"text": "Examples:"
},
{
"code": null,
"e": 407,
"s": 215,
"text": "Input: arr[] = {7, 234, 58100}Output: 18939Explanation:Modified array after reversing each array elements = {7, 432, 18500}.Therefore, the sum of the modified array = 7 + 432 + 18500 = 18939."
},
{
"code": null,
"e": 589,
"s": 407,
"text": "Input: arr[] = {0, 100, 220}Output: 320Explanation:Modified array after reversing each array elements = {0, 100, 220}.Therefore, the sum of the modified array = 0 + 100 + 220 = 320."
},
{
"code": null,
"e": 774,
"s": 589,
"text": "Approach: The idea is to reverse each number of the given array as per the given conditions and find sum of all array elements formed after reversing. Below steps to solve the problem:"
},
{
"code": null,
"e": 1538,
"s": 774,
"text": "Initialize a variable, say sum, to store the required sum.Initialize variable count as 0 and f as false to store count of ending 0s of arr[i] and flag to avoid all non-ending 0.Initialize rev as 0 to store reversal of each array element.Traverse the given array and for each array element do the following operation:Increment count and divide arr[i] by 10 until all the zeros at the end are traversed.Reset f with true that means all ending 0 digits have been considered.Now, reverse arr[i] by updating rev = rev*10 + arr[i] % 10 and arr[i] = arr[i]/10.After traversing each digit of arr[i], update rev = rev * Math.pow(10, count) to add all ending 0’s to the end of reversed number.For each reverse number in the above step, add that value to the resultant sum."
},
{
"code": null,
"e": 1597,
"s": 1538,
"text": "Initialize a variable, say sum, to store the required sum."
},
{
"code": null,
"e": 1717,
"s": 1597,
"text": "Initialize variable count as 0 and f as false to store count of ending 0s of arr[i] and flag to avoid all non-ending 0."
},
{
"code": null,
"e": 1778,
"s": 1717,
"text": "Initialize rev as 0 to store reversal of each array element."
},
{
"code": null,
"e": 2226,
"s": 1778,
"text": "Traverse the given array and for each array element do the following operation:Increment count and divide arr[i] by 10 until all the zeros at the end are traversed.Reset f with true that means all ending 0 digits have been considered.Now, reverse arr[i] by updating rev = rev*10 + arr[i] % 10 and arr[i] = arr[i]/10.After traversing each digit of arr[i], update rev = rev * Math.pow(10, count) to add all ending 0’s to the end of reversed number."
},
{
"code": null,
"e": 2312,
"s": 2226,
"text": "Increment count and divide arr[i] by 10 until all the zeros at the end are traversed."
},
{
"code": null,
"e": 2383,
"s": 2312,
"text": "Reset f with true that means all ending 0 digits have been considered."
},
{
"code": null,
"e": 2467,
"s": 2383,
"text": "Now, reverse arr[i] by updating rev = rev*10 + arr[i] % 10 and arr[i] = arr[i]/10."
},
{
"code": null,
"e": 2598,
"s": 2467,
"text": "After traversing each digit of arr[i], update rev = rev * Math.pow(10, count) to add all ending 0’s to the end of reversed number."
},
{
"code": null,
"e": 2678,
"s": 2598,
"text": "For each reverse number in the above step, add that value to the resultant sum."
},
{
"code": null,
"e": 2729,
"s": 2678,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2733,
"s": 2729,
"text": "C++"
},
{
"code": null,
"e": 2738,
"s": 2733,
"text": "Java"
},
{
"code": null,
"e": 2746,
"s": 2738,
"text": "Python3"
},
{
"code": null,
"e": 2749,
"s": 2746,
"text": "C#"
},
{
"code": null,
"e": 2760,
"s": 2749,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the sum of elements// after reversing each element in arr[]void totalSum(int arr[], int n){ // Stores the final sum int sum = 0; // Traverse the given array for(int i = 0; i < n; i++) { // Stores count of ending 0s int count = 0; int rev = 0, num = arr[i]; // Flag to avoid count of 0s // that doesn't ends with 0s bool f = false; while (num > 0) { // Count of ending 0s while (num > 0 && !f && num % 10 == 0) { count++; num = num / 10; } // Update flag with true f = true; // Reversing the num if (num > 0) { rev = rev * 10 + num % 10; num = num / 10; } } // Add all ending 0s to // end of rev if (count > 0) rev = rev * pow(10, count); // Update sum sum = sum + rev; } // Print total sum cout << sum;} // Driver Codeint main(){ // Given arr[] int arr[] = { 7, 234, 58100 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call totalSum(arr, n); return 0;} // This code is contributed by akhilsaini",
"e": 4173,
"s": 2760,
"text": null
},
{
"code": "// Java program for the above approach import java.util.*; class GFG { // Function to find the sum of elements // after reversing each element in arr[] static void totalSum(int[] arr) { // Stores the final sum int sum = 0; // Traverse the given array for (int i = 0; i < arr.length; i++) { // Stores count of ending 0s int count = 0; int rev = 0, num = arr[i]; // Flag to avoid count of 0s // that doesn't ends with 0s boolean f = false; while (num > 0) { // Count of ending 0s while (num > 0 && !f && num % 10 == 0) { count++; num = num / 10; } // Update flag with true f = true; // Reversing the num if (num > 0) { rev = rev * 10 + num % 10; num = num / 10; } } // Add all ending 0s to // end of rev if (count > 0) rev = rev * (int)Math.pow(10, count); // Update sum sum = sum + rev; } // Print total sum System.out.print(sum); } // Driver Code public static void main(String[] args) { // Given arr[] int[] arr = { 7, 234, 58100 }; // Function Call totalSum(arr); }}",
"e": 5729,
"s": 4173,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the sum of elements# after reversing each element in arr[]def totalSum(arr, n): # Stores the final sum sums = 0 # Traverse the given array for i in range(0, n): # Stores count of ending 0s count = 0 rev = 0 num = arr[i] # Flag to avoid count of 0s # that doesn't ends with 0s f = False while num > 0: # Count of ending 0s while (num > 0 and f == False and num % 10 == 0): count = count + 1 num = num // 10 # Update flag with true f = True # Reversing the num if num > 0: rev = rev * 10 + num % 10 num = num // 10 # Add all ending 0s to # end of rev if (count > 0): rev = rev * pow(10, count) # Update sum sums = sums + rev # Print total sum print(sums) # Driver Codeif __name__ == \"__main__\": # Given arr[] arr = [ 7, 234, 58100 ] n = len(arr) # Function call totalSum(arr, n) # This code is contributed by akhilsaini",
"e": 6917,
"s": 5729,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the sum of elements// after reversing each element in arr[]static void totalSum(int[] arr){ // Stores the final sum int sum = 0; // Traverse the given array for(int i = 0; i < arr.Length; i++) { // Stores count of ending 0s int count = 0; int rev = 0, num = arr[i]; // Flag to avoid count of 0s // that doesn't ends with 0s bool f = false; while (num > 0) { // Count of ending 0s while (num > 0 && !f && num % 10 == 0) { count++; num = num / 10; } // Update flag with true f = true; // Reversing the num if (num > 0) { rev = rev * 10 + num % 10; num = num / 10; } } // Add all ending 0s to // end of rev if (count > 0) rev = rev * (int)Math.Pow(10, count); // Update sum sum = sum + rev; } // Print total sum Console.Write(sum);} // Driver Codestatic public void Main(){ // Given arr[] int[] arr = { 7, 234, 58100 }; // Function call totalSum(arr);}} // This code is contributed by akhilsaini",
"e": 8284,
"s": 6917,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the sum of elements// after reversing each element in arr[]function totalSum(arr, n){ // Stores the final sum let sum = 0; // Traverse the given array for(let i = 0; i < n; i++) { // Stores count of ending 0s let count = 0; let rev = 0, num = arr[i]; // Flag to avoid count of 0s // that doesn't ends with 0s let f = false; while (num > 0) { // Count of ending 0s while (num > 0 && !f && num % 10 == 0) { count++; num = Math.floor(num / 10); } // Update flag with true f = true; // Reversing the num if (num > 0) { rev = rev * 10 + num % 10; num = Math.floor(num / 10); } } // Add all ending 0s to // end of rev if (count > 0) rev = rev * Math.pow(10, count); // Update sum sum = sum + rev; } // Print total sum document.write(sum);} // Driver Code // Given arr[] let arr = [ 7, 234, 58100 ]; let n = arr.length; // Function call totalSum(arr, n); // This code is contributed by Mayank Tyagi </script>",
"e": 9652,
"s": 8284,
"text": null
},
{
"code": null,
"e": 9658,
"s": 9652,
"text": "18939"
},
{
"code": null,
"e": 9790,
"s": 9660,
"text": "Time Complexity: O(N*log10M), where N denotes the length of the array and M denotes maximum array element. Auxiliary Space: O(1) "
},
{
"code": null,
"e": 9801,
"s": 9790,
"text": "akhilsaini"
},
{
"code": null,
"e": 9817,
"s": 9801,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 9833,
"s": 9817,
"text": "array-rearrange"
},
{
"code": null,
"e": 9847,
"s": 9833,
"text": "number-digits"
},
{
"code": null,
"e": 9855,
"s": 9847,
"text": "Reverse"
},
{
"code": null,
"e": 9862,
"s": 9855,
"text": "Arrays"
},
{
"code": null,
"e": 9875,
"s": 9862,
"text": "Mathematical"
},
{
"code": null,
"e": 9894,
"s": 9875,
"text": "School Programming"
},
{
"code": null,
"e": 9901,
"s": 9894,
"text": "Arrays"
},
{
"code": null,
"e": 9914,
"s": 9901,
"text": "Mathematical"
},
{
"code": null,
"e": 9922,
"s": 9914,
"text": "Reverse"
},
{
"code": null,
"e": 10020,
"s": 9922,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10088,
"s": 10020,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 10132,
"s": 10088,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 10164,
"s": 10132,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 10212,
"s": 10164,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 10226,
"s": 10212,
"text": "Linear Search"
},
{
"code": null,
"e": 10256,
"s": 10226,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 10299,
"s": 10256,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 10359,
"s": 10299,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10374,
"s": 10359,
"text": "C++ Data Types"
}
] |
Decimal representation of given binary string is divisible by 5 or not
|
25 Jun, 2022
The problem is to check whether the decimal representation of the given binary number is divisible by 5 or not. Take care, the number could be very large and may not fit even in long long int. The approach should be such that there are zero or minimum number of multiplication and division operations. No leading 0’s are there in the input. Examples:
Input : 1010
Output : YES
(1010)2 = (10)10,
and 10 is divisible by 5.
Input : 10000101001
Output : YES
Approach: The following steps are:
Convert the binary number to base 4.Numbers in base 4 contains only 0, 1, 2, 3 as their digits.5 in base 4 is equivalent to 11.Now apply the rule of divisibility by 11 where you add all the digits at odd places and add all the digits at even places and then subtract one from the other. If the result is divisible by 11(which remember is 5), then the binary number is divisible by 5.
Convert the binary number to base 4.
Numbers in base 4 contains only 0, 1, 2, 3 as their digits.
5 in base 4 is equivalent to 11.
Now apply the rule of divisibility by 11 where you add all the digits at odd places and add all the digits at even places and then subtract one from the other. If the result is divisible by 11(which remember is 5), then the binary number is divisible by 5.
How to convert binary number to base 4 representation?
Check whether the length of binary string is even or odd.If odd, the add ‘0’ in the beginning of the string.Now, traverse the string from left to right.One by extract substrings of size 2 and add their equivalent decimal to the resultant string.
Check whether the length of binary string is even or odd.
If odd, the add ‘0’ in the beginning of the string.
Now, traverse the string from left to right.
One by extract substrings of size 2 and add their equivalent decimal to the resultant string.
C++
Java
Python 3
C#
Javascript
// C++ implementation to check whether decimal representation// of given binary number is divisible by 5 or not#include <bits/stdc++.h> using namespace std; // function to return equivalent base 4 number// of the given binary numberint equivalentBase4(string bin){ if (bin.compare("00") == 0) return 0; if (bin.compare("01") == 0) return 1; if (bin.compare("10") == 0) return 2; return 3;} // function to check whether the given binary// number is divisible by 5 or notstring isDivisibleBy5(string bin){ int l = bin.size(); if (l % 2 != 0) // add '0' in the beginning to make // length an even number bin = '0' + bin; // to store sum of digits at odd and // even places respectively int odd_sum, even_sum = 0; // variable check for odd place and // even place digit int isOddDigit = 1; for (int i = 0; i<bin.size(); i+= 2) { // if digit of base 4 is at odd place, then // add it to odd_sum if (isOddDigit) odd_sum += equivalentBase4(bin.substr(i, 2)); // else digit of base 4 is at even place, // add it to even_sum else even_sum += equivalentBase4(bin.substr(i, 2)); isOddDigit ^= 1; } // if this diff is divisible by 11(which is 5 in decimal) // then, the binary number is divisible by 5 if (abs(odd_sum - even_sum) % 5 == 0) return "Yes"; // else not divisible by 5 return "No"; } // Driver program to test aboveint main(){ string bin = "10000101001"; cout << isDivisibleBy5(bin); return 0;}
//Java implementation to check whether decimal representation//of given binary number is divisible by 5 or not class GFG{ // Method to return equivalent base 4 number // of the given binary number static int equivalentBase4(String bin) { if (bin.compareTo("00") == 0) return 0; if (bin.compareTo("01") == 0) return 1; if (bin.compareTo("10") == 0) return 2; return 3; } // Method to check whether the given binary // number is divisible by 5 or not static String isDivisibleBy5(String bin) { int l = bin.length(); if (l % 2 != 0) // add '0' in the beginning to make // length an even number bin = '0' + bin; // to store sum of digits at odd and // even places respectively int odd_sum=0, even_sum = 0; // variable check for odd place and // even place digit int isOddDigit = 1; for (int i = 0; i<bin.length(); i+= 2) { // if digit of base 4 is at odd place, then // add it to odd_sum if (isOddDigit != 0) odd_sum += equivalentBase4(bin.substring(i, i+2)); // else digit of base 4 is at even place, // add it to even_sum else even_sum += equivalentBase4(bin.substring(i, i+2)); isOddDigit ^= 1; } // if this diff is divisible by 11(which is 5 in decimal) // then, the binary number is divisible by 5 if (Math.abs(odd_sum - even_sum) % 5 == 0) return "Yes"; // else not divisible by 5 return "No"; } public static void main (String[] args) { String bin = "10000101001"; System.out.println(isDivisibleBy5(bin)); }}
# Python3 implementation to check whether# decimal representation of given binary# number is divisible by 5 or not # function to return equivalent base 4# number of the given binary numberdef equivalentBase4(bin): if(bin == "00"): return 0 if(bin == "01"): return 1 if(bin == "10"): return 2 if(bin == "11"): return 3 # function to check whether the given# binary number is divisible by 5 or not def isDivisibleBy5(bin): l = len(bin) if((l % 2) == 1): # add '0' in the beginning to # make length an even number bin = '0' + bin # to store sum of digits at odd # and even places respectively odd_sum = 0 even_sum = 0 isOddDigit = 1 for i in range(0, len(bin), 2): # if digit of base 4 is at odd place, # then add it to odd_sum if(isOddDigit): odd_sum += equivalentBase4(bin[i:i + 2]) # else digit of base 4 is at # even place, add it to even_sum else: even_sum += equivalentBase4(bin[i:i + 2]) isOddDigit = isOddDigit ^ 1 # if this diff is divisible by 11(which is # 5 in decimal) then, the binary number is # divisible by 5 if(abs(odd_sum - even_sum) % 5 == 0): return "Yes" else: return "No" # Driver Codeif __name__=="__main__": bin = "10000101001" print(isDivisibleBy5(bin)) # This code is contributed# by Sairahul Jella
// C# implementation to check whether// decimal representation of given// binary number is divisible by 5 or notusing System; class GFG{// Method to return equivalent base// 4 number of the given binary numberpublic static int equivalentBase4(string bin){ if (bin.CompareTo("00") == 0) { return 0; } if (bin.CompareTo("01") == 0) { return 1; } if (bin.CompareTo("10") == 0) { return 2; } return 3;} // Method to check whether the// given binary number is divisible// by 5 or notpublic static string isDivisibleBy5(string bin){ int l = bin.Length; if (l % 2 != 0) { // add '0' in the beginning to // make length an even number bin = '0' + bin; } // to store sum of digits at odd // and even places respectively int odd_sum = 0, even_sum = 0; // variable check for odd place // and even place digit int isOddDigit = 1; for (int i = 0; i < bin.Length; i += 2) { // if digit of base 4 is at odd // place, then add it to odd_sum if (isOddDigit != 0) { odd_sum += equivalentBase4( bin.Substring(i, 2)); } // else digit of base 4 is at even // place, add it to even_sum else { even_sum += equivalentBase4( bin.Substring(i, 2)); } isOddDigit ^= 1; } // if this diff is divisible by // 11(which is 5 in decimal) then, // the binary number is divisible by 5 if (Math.Abs(odd_sum - even_sum) % 5 == 0) { return "YES"; } // else not divisible by 5 return "NO"; } // Driver Codepublic static void Main(string[] args){ string bin = "10000101001"; Console.WriteLine(isDivisibleBy5(bin));}} // This code is contributed by Shrikant13
<script> // Javascript implementation to check whether// decimal representation of given binary// number is divisible by 5 or not // function to return equivalent base 4// number of the given binary numberfunction equivalentBase4(bin){ if(bin == "00") return 0 if(bin == "01") return 1 if(bin == "10") return 2 if(bin == "11") return 3} // function to check whether the given// binary number is divisible by 5 or not function isDivisibleBy5(bin){ let l = bin.length if((l % 2) == 1){ // add '0' in the beginning to // make length an even number bin = '0' + bin } // to store sum of digits at odd // and even places respectively let odd_sum = 0 let even_sum = 0 let isOddDigit = 1 for(let i=0;i<bin.length;i+=2){ // if digit of base 4 is at odd place, // then add it to odd_sum if(isOddDigit) odd_sum += equivalentBase4(bin.substring(i,i + 2)) // else digit of base 4 is at // even place, add it to even_sum else even_sum += equivalentBase4(bin.substring(i,i + 2)) isOddDigit = isOddDigit ^ 1 } // if this diff is divisible by 11(which is // 5 in decimal) then, the binary number is // divisible by 5 if(Math.abs(odd_sum - even_sum) % 5 == 0) return "Yes" else return "No"} // Driver Code let bin = "10000101001"document.writeln(isDivisibleBy5(bin)) // This code is contributed by shinjanpatra </script>
Output:
YES
Time Complexity: O(n), where n is the number of digits in the binary number. Auxiliary Space: O(1)
References: https://stackoverflow.com/questions/18473730/algorithm-in-hardware-to-find-out-if-number-is-divisible-by-five This article is contributed by Aarti_Rathi and Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
shrikanth13
Sairahul Jella
nidhi_biet
shinjanpatra
sachinvinod1904
binary-representation
binary-string
divisibility
large-numbers
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Top 50 String Coding Problems for Interviews
Convert string to char array in C++
Check whether two strings are anagram of each other
Reverse words in a given string
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Jun, 2022"
},
{
"code": null,
"e": 403,
"s": 52,
"text": "The problem is to check whether the decimal representation of the given binary number is divisible by 5 or not. Take care, the number could be very large and may not fit even in long long int. The approach should be such that there are zero or minimum number of multiplication and division operations. No leading 0’s are there in the input. Examples:"
},
{
"code": null,
"e": 507,
"s": 403,
"text": "Input : 1010\nOutput : YES\n(1010)2 = (10)10,\nand 10 is divisible by 5.\n\nInput : 10000101001\nOutput : YES"
},
{
"code": null,
"e": 542,
"s": 507,
"text": "Approach: The following steps are:"
},
{
"code": null,
"e": 926,
"s": 542,
"text": "Convert the binary number to base 4.Numbers in base 4 contains only 0, 1, 2, 3 as their digits.5 in base 4 is equivalent to 11.Now apply the rule of divisibility by 11 where you add all the digits at odd places and add all the digits at even places and then subtract one from the other. If the result is divisible by 11(which remember is 5), then the binary number is divisible by 5."
},
{
"code": null,
"e": 963,
"s": 926,
"text": "Convert the binary number to base 4."
},
{
"code": null,
"e": 1023,
"s": 963,
"text": "Numbers in base 4 contains only 0, 1, 2, 3 as their digits."
},
{
"code": null,
"e": 1056,
"s": 1023,
"text": "5 in base 4 is equivalent to 11."
},
{
"code": null,
"e": 1313,
"s": 1056,
"text": "Now apply the rule of divisibility by 11 where you add all the digits at odd places and add all the digits at even places and then subtract one from the other. If the result is divisible by 11(which remember is 5), then the binary number is divisible by 5."
},
{
"code": null,
"e": 1368,
"s": 1313,
"text": "How to convert binary number to base 4 representation?"
},
{
"code": null,
"e": 1614,
"s": 1368,
"text": "Check whether the length of binary string is even or odd.If odd, the add ‘0’ in the beginning of the string.Now, traverse the string from left to right.One by extract substrings of size 2 and add their equivalent decimal to the resultant string."
},
{
"code": null,
"e": 1672,
"s": 1614,
"text": "Check whether the length of binary string is even or odd."
},
{
"code": null,
"e": 1724,
"s": 1672,
"text": "If odd, the add ‘0’ in the beginning of the string."
},
{
"code": null,
"e": 1769,
"s": 1724,
"text": "Now, traverse the string from left to right."
},
{
"code": null,
"e": 1863,
"s": 1769,
"text": "One by extract substrings of size 2 and add their equivalent decimal to the resultant string."
},
{
"code": null,
"e": 1867,
"s": 1863,
"text": "C++"
},
{
"code": null,
"e": 1872,
"s": 1867,
"text": "Java"
},
{
"code": null,
"e": 1881,
"s": 1872,
"text": "Python 3"
},
{
"code": null,
"e": 1884,
"s": 1881,
"text": "C#"
},
{
"code": null,
"e": 1895,
"s": 1884,
"text": "Javascript"
},
{
"code": "// C++ implementation to check whether decimal representation// of given binary number is divisible by 5 or not#include <bits/stdc++.h> using namespace std; // function to return equivalent base 4 number// of the given binary numberint equivalentBase4(string bin){ if (bin.compare(\"00\") == 0) return 0; if (bin.compare(\"01\") == 0) return 1; if (bin.compare(\"10\") == 0) return 2; return 3;} // function to check whether the given binary// number is divisible by 5 or notstring isDivisibleBy5(string bin){ int l = bin.size(); if (l % 2 != 0) // add '0' in the beginning to make // length an even number bin = '0' + bin; // to store sum of digits at odd and // even places respectively int odd_sum, even_sum = 0; // variable check for odd place and // even place digit int isOddDigit = 1; for (int i = 0; i<bin.size(); i+= 2) { // if digit of base 4 is at odd place, then // add it to odd_sum if (isOddDigit) odd_sum += equivalentBase4(bin.substr(i, 2)); // else digit of base 4 is at even place, // add it to even_sum else even_sum += equivalentBase4(bin.substr(i, 2)); isOddDigit ^= 1; } // if this diff is divisible by 11(which is 5 in decimal) // then, the binary number is divisible by 5 if (abs(odd_sum - even_sum) % 5 == 0) return \"Yes\"; // else not divisible by 5 return \"No\"; } // Driver program to test aboveint main(){ string bin = \"10000101001\"; cout << isDivisibleBy5(bin); return 0;}",
"e": 3517,
"s": 1895,
"text": null
},
{
"code": "//Java implementation to check whether decimal representation//of given binary number is divisible by 5 or not class GFG{ // Method to return equivalent base 4 number // of the given binary number static int equivalentBase4(String bin) { if (bin.compareTo(\"00\") == 0) return 0; if (bin.compareTo(\"01\") == 0) return 1; if (bin.compareTo(\"10\") == 0) return 2; return 3; } // Method to check whether the given binary // number is divisible by 5 or not static String isDivisibleBy5(String bin) { int l = bin.length(); if (l % 2 != 0) // add '0' in the beginning to make // length an even number bin = '0' + bin; // to store sum of digits at odd and // even places respectively int odd_sum=0, even_sum = 0; // variable check for odd place and // even place digit int isOddDigit = 1; for (int i = 0; i<bin.length(); i+= 2) { // if digit of base 4 is at odd place, then // add it to odd_sum if (isOddDigit != 0) odd_sum += equivalentBase4(bin.substring(i, i+2)); // else digit of base 4 is at even place, // add it to even_sum else even_sum += equivalentBase4(bin.substring(i, i+2)); isOddDigit ^= 1; } // if this diff is divisible by 11(which is 5 in decimal) // then, the binary number is divisible by 5 if (Math.abs(odd_sum - even_sum) % 5 == 0) return \"Yes\"; // else not divisible by 5 return \"No\"; } public static void main (String[] args) { String bin = \"10000101001\"; System.out.println(isDivisibleBy5(bin)); }}",
"e": 5383,
"s": 3517,
"text": null
},
{
"code": "# Python3 implementation to check whether# decimal representation of given binary# number is divisible by 5 or not # function to return equivalent base 4# number of the given binary numberdef equivalentBase4(bin): if(bin == \"00\"): return 0 if(bin == \"01\"): return 1 if(bin == \"10\"): return 2 if(bin == \"11\"): return 3 # function to check whether the given# binary number is divisible by 5 or not def isDivisibleBy5(bin): l = len(bin) if((l % 2) == 1): # add '0' in the beginning to # make length an even number bin = '0' + bin # to store sum of digits at odd # and even places respectively odd_sum = 0 even_sum = 0 isOddDigit = 1 for i in range(0, len(bin), 2): # if digit of base 4 is at odd place, # then add it to odd_sum if(isOddDigit): odd_sum += equivalentBase4(bin[i:i + 2]) # else digit of base 4 is at # even place, add it to even_sum else: even_sum += equivalentBase4(bin[i:i + 2]) isOddDigit = isOddDigit ^ 1 # if this diff is divisible by 11(which is # 5 in decimal) then, the binary number is # divisible by 5 if(abs(odd_sum - even_sum) % 5 == 0): return \"Yes\" else: return \"No\" # Driver Codeif __name__==\"__main__\": bin = \"10000101001\" print(isDivisibleBy5(bin)) # This code is contributed# by Sairahul Jella",
"e": 6858,
"s": 5383,
"text": null
},
{
"code": "// C# implementation to check whether// decimal representation of given// binary number is divisible by 5 or notusing System; class GFG{// Method to return equivalent base// 4 number of the given binary numberpublic static int equivalentBase4(string bin){ if (bin.CompareTo(\"00\") == 0) { return 0; } if (bin.CompareTo(\"01\") == 0) { return 1; } if (bin.CompareTo(\"10\") == 0) { return 2; } return 3;} // Method to check whether the// given binary number is divisible// by 5 or notpublic static string isDivisibleBy5(string bin){ int l = bin.Length; if (l % 2 != 0) { // add '0' in the beginning to // make length an even number bin = '0' + bin; } // to store sum of digits at odd // and even places respectively int odd_sum = 0, even_sum = 0; // variable check for odd place // and even place digit int isOddDigit = 1; for (int i = 0; i < bin.Length; i += 2) { // if digit of base 4 is at odd // place, then add it to odd_sum if (isOddDigit != 0) { odd_sum += equivalentBase4( bin.Substring(i, 2)); } // else digit of base 4 is at even // place, add it to even_sum else { even_sum += equivalentBase4( bin.Substring(i, 2)); } isOddDigit ^= 1; } // if this diff is divisible by // 11(which is 5 in decimal) then, // the binary number is divisible by 5 if (Math.Abs(odd_sum - even_sum) % 5 == 0) { return \"YES\"; } // else not divisible by 5 return \"NO\"; } // Driver Codepublic static void Main(string[] args){ string bin = \"10000101001\"; Console.WriteLine(isDivisibleBy5(bin));}} // This code is contributed by Shrikant13",
"e": 8695,
"s": 6858,
"text": null
},
{
"code": "<script> // Javascript implementation to check whether// decimal representation of given binary// number is divisible by 5 or not // function to return equivalent base 4// number of the given binary numberfunction equivalentBase4(bin){ if(bin == \"00\") return 0 if(bin == \"01\") return 1 if(bin == \"10\") return 2 if(bin == \"11\") return 3} // function to check whether the given// binary number is divisible by 5 or not function isDivisibleBy5(bin){ let l = bin.length if((l % 2) == 1){ // add '0' in the beginning to // make length an even number bin = '0' + bin } // to store sum of digits at odd // and even places respectively let odd_sum = 0 let even_sum = 0 let isOddDigit = 1 for(let i=0;i<bin.length;i+=2){ // if digit of base 4 is at odd place, // then add it to odd_sum if(isOddDigit) odd_sum += equivalentBase4(bin.substring(i,i + 2)) // else digit of base 4 is at // even place, add it to even_sum else even_sum += equivalentBase4(bin.substring(i,i + 2)) isOddDigit = isOddDigit ^ 1 } // if this diff is divisible by 11(which is // 5 in decimal) then, the binary number is // divisible by 5 if(Math.abs(odd_sum - even_sum) % 5 == 0) return \"Yes\" else return \"No\"} // Driver Code let bin = \"10000101001\"document.writeln(isDivisibleBy5(bin)) // This code is contributed by shinjanpatra </script>",
"e": 10250,
"s": 8695,
"text": null
},
{
"code": null,
"e": 10258,
"s": 10250,
"text": "Output:"
},
{
"code": null,
"e": 10262,
"s": 10258,
"text": "YES"
},
{
"code": null,
"e": 10361,
"s": 10262,
"text": "Time Complexity: O(n), where n is the number of digits in the binary number. Auxiliary Space: O(1)"
},
{
"code": null,
"e": 10921,
"s": 10361,
"text": "References: https://stackoverflow.com/questions/18473730/algorithm-in-hardware-to-find-out-if-number-is-divisible-by-five This article is contributed by Aarti_Rathi and Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 10933,
"s": 10921,
"text": "shrikanth13"
},
{
"code": null,
"e": 10948,
"s": 10933,
"text": "Sairahul Jella"
},
{
"code": null,
"e": 10959,
"s": 10948,
"text": "nidhi_biet"
},
{
"code": null,
"e": 10972,
"s": 10959,
"text": "shinjanpatra"
},
{
"code": null,
"e": 10988,
"s": 10972,
"text": "sachinvinod1904"
},
{
"code": null,
"e": 11010,
"s": 10988,
"text": "binary-representation"
},
{
"code": null,
"e": 11024,
"s": 11010,
"text": "binary-string"
},
{
"code": null,
"e": 11037,
"s": 11024,
"text": "divisibility"
},
{
"code": null,
"e": 11051,
"s": 11037,
"text": "large-numbers"
},
{
"code": null,
"e": 11059,
"s": 11051,
"text": "Strings"
},
{
"code": null,
"e": 11067,
"s": 11059,
"text": "Strings"
},
{
"code": null,
"e": 11165,
"s": 11067,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11240,
"s": 11165,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 11285,
"s": 11240,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 11342,
"s": 11285,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 11378,
"s": 11342,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 11416,
"s": 11378,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 11477,
"s": 11416,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 11522,
"s": 11477,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 11558,
"s": 11522,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 11610,
"s": 11558,
"text": "Check whether two strings are anagram of each other"
}
] |
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks
|
11 Sep, 2019
Consider a uniprocessor system executing three tasks T1, T2 and T3, each of which is composed of an infinite sequence of jobs (or instances) which arrive periodically at intervals of 3, 7 and 20 milliseconds, respectively. The priority of each task is the inverse of its period and the available tasks are scheduled in order of priority, with the highest priority task scheduled first. Each instance of T1, T2 and T3 requires an execution time of 1, 2 and 4 milliseconds, respectively. Given that all tasks initially arrive at the beginning of the 1st milliseconds and task preemptions are allowed, the first instance of T3 completes its execution at the end of ______________ milliseconds.(A) 5(B) 10(C) 12(D) 15Answer: (C)Explanation: Periods of T1, T2 and T3 are 3ms, 7ms and 20ms.
Since priority is inverse of period, T1 is the highest priority task, then T2 and finally T3
Every instance of T1 requires 1ms, that of T2 requires 2ms and that of T3 requires 4ms
Initially all T1, T2 and T3 are ready to get processor, T1 is preferred
Second instances of T1, T2, and T3 shall arrive at 3, 7, and 20 respectively.
Third instance of T1, T2 and T3 shall arrive at 6, 14, and 40 respectively.
Time-Interval Tasks
0-1 T1
1-2 T2
2-3 T2
3-4 T1 [Second Instance of T1 arrives]
4-5 T3
5-6 T3
6-7 T1 [Third Instance of T1 arrives]
[Therefore T3 is preempted]
7-8 T2 [Second instance of T2 arrives]
8-9 T2
9-10 T1 [Fourth Instance of T1 arrives]
10-11 T3
11-12 T3 [First Instance of T3 completed]
Quiz of this Question
Stranger1
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2012 | Question 40
C++ Program to count Vowels in a string using Pointer
|
[
{
"code": null,
"e": 23839,
"s": 23811,
"text": "\n11 Sep, 2019"
},
{
"code": null,
"e": 24624,
"s": 23839,
"text": "Consider a uniprocessor system executing three tasks T1, T2 and T3, each of which is composed of an infinite sequence of jobs (or instances) which arrive periodically at intervals of 3, 7 and 20 milliseconds, respectively. The priority of each task is the inverse of its period and the available tasks are scheduled in order of priority, with the highest priority task scheduled first. Each instance of T1, T2 and T3 requires an execution time of 1, 2 and 4 milliseconds, respectively. Given that all tasks initially arrive at the beginning of the 1st milliseconds and task preemptions are allowed, the first instance of T3 completes its execution at the end of ______________ milliseconds.(A) 5(B) 10(C) 12(D) 15Answer: (C)Explanation: Periods of T1, T2 and T3 are 3ms, 7ms and 20ms."
},
{
"code": null,
"e": 24717,
"s": 24624,
"text": "Since priority is inverse of period, T1 is the highest priority task, then T2 and finally T3"
},
{
"code": null,
"e": 24804,
"s": 24717,
"text": "Every instance of T1 requires 1ms, that of T2 requires 2ms and that of T3 requires 4ms"
},
{
"code": null,
"e": 24876,
"s": 24804,
"text": "Initially all T1, T2 and T3 are ready to get processor, T1 is preferred"
},
{
"code": null,
"e": 24954,
"s": 24876,
"text": "Second instances of T1, T2, and T3 shall arrive at 3, 7, and 20 respectively."
},
{
"code": null,
"e": 25030,
"s": 24954,
"text": "Third instance of T1, T2 and T3 shall arrive at 6, 14, and 40 respectively."
},
{
"code": null,
"e": 25600,
"s": 25030,
"text": "Time-Interval Tasks \n 0-1 T1 \n 1-2 T2 \n 2-3 T2 \n 3-4 T1 [Second Instance of T1 arrives] \n 4-5 T3 \n 5-6 T3 \n 6-7 T1 [Third Instance of T1 arrives] \n [Therefore T3 is preempted] \n 7-8 T2 [Second instance of T2 arrives] \n 8-9 T2\n 9-10 T1 [Fourth Instance of T1 arrives] \n10-11 T3\n11-12 T3 [First Instance of T3 completed]"
},
{
"code": null,
"e": 25622,
"s": 25600,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25632,
"s": 25622,
"text": "Stranger1"
},
{
"code": null,
"e": 25653,
"s": 25632,
"text": "GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 25679,
"s": 25653,
"text": "GATE-GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 25684,
"s": 25679,
"text": "GATE"
},
{
"code": null,
"e": 25782,
"s": 25684,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25791,
"s": 25782,
"text": "Comments"
},
{
"code": null,
"e": 25804,
"s": 25791,
"text": "Old Comments"
},
{
"code": null,
"e": 25846,
"s": 25804,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25888,
"s": 25846,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 25922,
"s": 25888,
"text": "GATE | GATE-CS-2001 | Question 23"
},
{
"code": null,
"e": 25964,
"s": 25922,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 25998,
"s": 25964,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 26040,
"s": 25998,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 65"
},
{
"code": null,
"e": 26073,
"s": 26040,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 26115,
"s": 26073,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 26149,
"s": 26115,
"text": "GATE | GATE CS 2012 | Question 40"
}
] |
Objective-C Typedef
|
The Objective-C programming language provides a keyword called typedef, which you can use to give a type a new name. Following is an example to define a term BYTE for one-byte numbers −
typedef unsigned char BYTE;
After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example:.
BYTE b1, b2;
By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows −
typedef unsigned char byte;
You can use typedef to give a name to user-defined data type as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows −
#import <Foundation/Foundation.h>
typedef struct Books {
NSString *title;
NSString *author;
NSString *subject;
int book_id;
} Book;
int main() {
Book book;
book.title = @"Objective-C Programming";
book.author = @"TutorialsPoint";
book.subject = @"Programming tutorial";
book.book_id = 100;
NSLog( @"Book title : %@\n", book.title);
NSLog( @"Book author : %@\n", book.author);
NSLog( @"Book subject : %@\n", book.subject);
NSLog( @"Book Id : %d\n", book.book_id);
return 0;
}
When the above code is compiled and executed, it produces the following result −
2013-09-12 12:21:53.745 demo[31183] Book title : Objective-C Programming
2013-09-12 12:21:53.745 demo[31183] Book author : TutorialsPoint
2013-09-12 12:21:53.745 demo[31183] Book subject : Programming tutorial
2013-09-12 12:21:53.745 demo[31183] Book Id : 100
The #define is a Objective-C directive, which is also used to define the aliases for various data types similar to typedef but with following differences −
The typedef is limited to giving symbolic names to types only whereas #define can be used to define alias for values as well, like you can define 1 as ONE, etc.
The typedef is limited to giving symbolic names to types only whereas #define can be used to define alias for values as well, like you can define 1 as ONE, etc.
The typedef interpretation is performed by the compiler where as #define statements are processed by the pre-processor.
The typedef interpretation is performed by the compiler where as #define statements are processed by the pre-processor.
Following is a simplest usage of #define −
#import <Foundation/Foundation.h>
#define TRUE 1
#define FALSE 0
int main( ) {
NSLog( @"Value of TRUE : %d\n", TRUE);
NSLog( @"Value of FALSE : %d\n", FALSE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
2013-09-12 12:23:37.993 demo[5160] Value of TRUE : 1
2013-09-12 12:23:37.994 demo[5160] Value of FALSE : 0
18 Lectures
1 hours
PARTHA MAJUMDAR
6 Lectures
25 mins
Ken Burke
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2746,
"s": 2560,
"text": "The Objective-C programming language provides a keyword called typedef, which you can use to give a type a new name. Following is an example to define a term BYTE for one-byte numbers −"
},
{
"code": null,
"e": 2774,
"s": 2746,
"text": "typedef unsigned char BYTE;"
},
{
"code": null,
"e": 2895,
"s": 2774,
"text": "After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example:."
},
{
"code": null,
"e": 2909,
"s": 2895,
"text": "BYTE b1, b2;"
},
{
"code": null,
"e": 3086,
"s": 2909,
"text": "By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows −"
},
{
"code": null,
"e": 3114,
"s": 3086,
"text": "typedef unsigned char byte;"
},
{
"code": null,
"e": 3338,
"s": 3114,
"text": "You can use typedef to give a name to user-defined data type as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows −"
},
{
"code": null,
"e": 3863,
"s": 3338,
"text": "#import <Foundation/Foundation.h>\n\ntypedef struct Books {\n NSString *title;\n NSString *author;\n NSString *subject;\n int book_id;\n} Book;\n \nint main() {\n Book book;\n book.title = @\"Objective-C Programming\";\n book.author = @\"TutorialsPoint\";\n book.subject = @\"Programming tutorial\";\n book.book_id = 100;\n \n NSLog( @\"Book title : %@\\n\", book.title);\n NSLog( @\"Book author : %@\\n\", book.author);\n NSLog( @\"Book subject : %@\\n\", book.subject);\n NSLog( @\"Book Id : %d\\n\", book.book_id);\n\n return 0;\n}"
},
{
"code": null,
"e": 3944,
"s": 3863,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4205,
"s": 3944,
"text": "2013-09-12 12:21:53.745 demo[31183] Book title : Objective-C Programming\n2013-09-12 12:21:53.745 demo[31183] Book author : TutorialsPoint\n2013-09-12 12:21:53.745 demo[31183] Book subject : Programming tutorial\n2013-09-12 12:21:53.745 demo[31183] Book Id : 100\n"
},
{
"code": null,
"e": 4362,
"s": 4205,
"text": "The #define is a Objective-C directive, which is also used to define the aliases for various data types similar to typedef but with following differences −"
},
{
"code": null,
"e": 4523,
"s": 4362,
"text": "The typedef is limited to giving symbolic names to types only whereas #define can be used to define alias for values as well, like you can define 1 as ONE, etc."
},
{
"code": null,
"e": 4684,
"s": 4523,
"text": "The typedef is limited to giving symbolic names to types only whereas #define can be used to define alias for values as well, like you can define 1 as ONE, etc."
},
{
"code": null,
"e": 4804,
"s": 4684,
"text": "The typedef interpretation is performed by the compiler where as #define statements are processed by the pre-processor."
},
{
"code": null,
"e": 4924,
"s": 4804,
"text": "The typedef interpretation is performed by the compiler where as #define statements are processed by the pre-processor."
},
{
"code": null,
"e": 4967,
"s": 4924,
"text": "Following is a simplest usage of #define −"
},
{
"code": null,
"e": 5153,
"s": 4967,
"text": "#import <Foundation/Foundation.h>\n \n#define TRUE 1\n#define FALSE 0\n \nint main( ) {\n NSLog( @\"Value of TRUE : %d\\n\", TRUE);\n NSLog( @\"Value of FALSE : %d\\n\", FALSE);\n\n return 0;\n}"
},
{
"code": null,
"e": 5234,
"s": 5153,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5342,
"s": 5234,
"text": "2013-09-12 12:23:37.993 demo[5160] Value of TRUE : 1\n2013-09-12 12:23:37.994 demo[5160] Value of FALSE : 0\n"
},
{
"code": null,
"e": 5375,
"s": 5342,
"text": "\n 18 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5392,
"s": 5375,
"text": " PARTHA MAJUMDAR"
},
{
"code": null,
"e": 5423,
"s": 5392,
"text": "\n 6 Lectures \n 25 mins\n"
},
{
"code": null,
"e": 5434,
"s": 5423,
"text": " Ken Burke"
},
{
"code": null,
"e": 5441,
"s": 5434,
"text": " Print"
},
{
"code": null,
"e": 5452,
"s": 5441,
"text": " Add Notes"
}
] |
Count numbers having 0 as a digit - GeeksforGeeks
|
24 Mar, 2021
Count how many integers from 1 to N contains 0’s as a digit.Examples:
Input: n = 9
Output: 0
Input: n = 107
Output: 17
The numbers having 0 are 10, 20,..90, 100, 101..107
Input: n = 155
Output: 24
The numbers having 0 are 10, 20,..90, 100, 101..110,
120, ..150.
The idea is to traverse all numbers from 1 to n. For every traversed number, traverse through its digits, if any digit is 0, increment count. Below is the implementation of the above idea :
C++
Java
Python3
C#
Javascript
// C++ program to count numbers from 1 to n with// 0 as a digit#include<bits/stdc++.h>using namespace std; // Returns 1 if x has 0, else 0int has0(int x){ // Traverse through all digits of // x to check if it has 0. while (x) { // If current digit is 0, return true if (x % 10 == 0) return 1; x /= 10; } return 0;} // Returns count of numbers from 1 to n with 0 as digitint getCount(int n){ // Initialize count of numbers having 0 as digit int count = 0; // Traverse through all numbers and for every number // check if it has 0. for (int i=1; i<=n; i++) count += has0(i); return count;} // Driver programint main(){ int n = 107; cout << "Count of numbers from 1" << " to " << n << " is " << getCount(n);}
// Java program to count numbers// from 1 to n with 0 as a digitimport java.io.*; class GFG { // Returns 1 if x has 0, else 0 static int has0(int x) { // Traverse through all digits // of x to check if it has 0. while (x != 0) { // If current digit is 0, // return true if (x % 10 == 0) return 1; x /= 10; } return 0; } // Returns count of numbers // from 1 to n with 0 as digit static int getCount(int n) { // Initialize count of // numbers having 0 as digit int count = 0; // Traverse through all numbers // and for every number // check if it has 0. for (int i = 1; i <= n; i++) count += has0(i); return count; } // Driver programpublic static void main(String args[]){ int n = 107; System.out.println("Count of numbers from 1" + " to " +n + " is " + getCount(n));}} // This code is contributed by Nikita Tiwari.
# Python3 program to count numbers# from 1 to n with 0 as a digit # Returns 1 if x has 0, else 0def has0(x) : # Traverse through all digits # of x to check if it has 0. while (x != 0) : # If current digit is 0, # return true if (x % 10 == 0) : return 1 x = x // 10 return 0 # Returns count of numbers# from 1 to n with 0 as digitdef getCount(n) : # Initialize count of numbers # having 0 as digit. count = 0 # Traverse through all numbers # and for every number check # if it has 0. for i in range(1, n + 1) : count = count + has0(i) return count # Driver programn = 107print("Count of numbers from 1", " to ", n , " is " , getCount(n)) # This code is contributed by Nikita tiwari.
// C# program to count numbers// from 1 to n with 0 as a digitusing System; class GFG{ // Returns 1 if x has 0, else 0 static int has0(int x) { // Traverse through all digits // of x to check if it has 0. while (x != 0) { // If current digit is 0, // return true if (x % 10 == 0) return 1; x /= 10; } return 0; } // Returns count of numbers // from 1 to n with 0 as digit static int getCount(int n) { // Initialize count of // numbers having 0 as digit int count = 0; // Traverse through all numbers // and for every number // check if it has 0. for (int i = 1; i <= n; i++) count += has0(i); return count; } // Driver Codepublic static void Main(){ int n = 107; Console.WriteLine("Count of numbers from 1" + " to " +n + " is " + getCount(n));}} // This code is contributed by Sam007
<script> // JavaScript program to count numbers from 1 to n with// 0 as a digit // Returns 1 if x has 0, else 0function has0(x){ // Traverse through all digits of // x to check if it has 0. while (x) { // If current digit is 0, return true if (x % 10 == 0) return 1; x = Math.floor(x / 10); } return 0;} // Returns count of numbers from 1 to n with 0 as digitfunction getCount(n){ // Initialize count of numbers having 0 as digit let count = 0; // Traverse through all numbers and for every number // check if it has 0. for (let i=1; i<=n; i++) count += has0(i); return count;} // Driver program let n = 107; document.write("Count of numbers from 1" + " to " + n + " is " + getCount(n)); // This code is contributed by Surbhi Tyagi. </script>
Output:
Count of numbers from 1 to 107 is 17
Refer below post for an optimized solution.Count numbers having 0 as a digitThis article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Sam007
nidhi_biet
surbhityagi15
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find GCD or HCF of two numbers
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Program for Decimal to Binary Conversion
Operators in C / C++
Euclidean algorithms (Basic and Extended)
The Knight's tour problem | Backtracking-1
|
[
{
"code": null,
"e": 25071,
"s": 25043,
"text": "\n24 Mar, 2021"
},
{
"code": null,
"e": 25142,
"s": 25071,
"text": "Count how many integers from 1 to N contains 0’s as a digit.Examples: "
},
{
"code": null,
"e": 25337,
"s": 25142,
"text": "Input: n = 9\nOutput: 0\n\nInput: n = 107\nOutput: 17\nThe numbers having 0 are 10, 20,..90, 100, 101..107\n\nInput: n = 155\nOutput: 24\nThe numbers having 0 are 10, 20,..90, 100, 101..110,\n120, ..150."
},
{
"code": null,
"e": 25528,
"s": 25337,
"text": "The idea is to traverse all numbers from 1 to n. For every traversed number, traverse through its digits, if any digit is 0, increment count. Below is the implementation of the above idea : "
},
{
"code": null,
"e": 25532,
"s": 25528,
"text": "C++"
},
{
"code": null,
"e": 25537,
"s": 25532,
"text": "Java"
},
{
"code": null,
"e": 25545,
"s": 25537,
"text": "Python3"
},
{
"code": null,
"e": 25548,
"s": 25545,
"text": "C#"
},
{
"code": null,
"e": 25559,
"s": 25548,
"text": "Javascript"
},
{
"code": "// C++ program to count numbers from 1 to n with// 0 as a digit#include<bits/stdc++.h>using namespace std; // Returns 1 if x has 0, else 0int has0(int x){ // Traverse through all digits of // x to check if it has 0. while (x) { // If current digit is 0, return true if (x % 10 == 0) return 1; x /= 10; } return 0;} // Returns count of numbers from 1 to n with 0 as digitint getCount(int n){ // Initialize count of numbers having 0 as digit int count = 0; // Traverse through all numbers and for every number // check if it has 0. for (int i=1; i<=n; i++) count += has0(i); return count;} // Driver programint main(){ int n = 107; cout << \"Count of numbers from 1\" << \" to \" << n << \" is \" << getCount(n);}",
"e": 26356,
"s": 25559,
"text": null
},
{
"code": "// Java program to count numbers// from 1 to n with 0 as a digitimport java.io.*; class GFG { // Returns 1 if x has 0, else 0 static int has0(int x) { // Traverse through all digits // of x to check if it has 0. while (x != 0) { // If current digit is 0, // return true if (x % 10 == 0) return 1; x /= 10; } return 0; } // Returns count of numbers // from 1 to n with 0 as digit static int getCount(int n) { // Initialize count of // numbers having 0 as digit int count = 0; // Traverse through all numbers // and for every number // check if it has 0. for (int i = 1; i <= n; i++) count += has0(i); return count; } // Driver programpublic static void main(String args[]){ int n = 107; System.out.println(\"Count of numbers from 1\" + \" to \" +n + \" is \" + getCount(n));}} // This code is contributed by Nikita Tiwari.",
"e": 27411,
"s": 26356,
"text": null
},
{
"code": "# Python3 program to count numbers# from 1 to n with 0 as a digit # Returns 1 if x has 0, else 0def has0(x) : # Traverse through all digits # of x to check if it has 0. while (x != 0) : # If current digit is 0, # return true if (x % 10 == 0) : return 1 x = x // 10 return 0 # Returns count of numbers# from 1 to n with 0 as digitdef getCount(n) : # Initialize count of numbers # having 0 as digit. count = 0 # Traverse through all numbers # and for every number check # if it has 0. for i in range(1, n + 1) : count = count + has0(i) return count # Driver programn = 107print(\"Count of numbers from 1\", \" to \", n , \" is \" , getCount(n)) # This code is contributed by Nikita tiwari.",
"e": 28220,
"s": 27411,
"text": null
},
{
"code": "// C# program to count numbers// from 1 to n with 0 as a digitusing System; class GFG{ // Returns 1 if x has 0, else 0 static int has0(int x) { // Traverse through all digits // of x to check if it has 0. while (x != 0) { // If current digit is 0, // return true if (x % 10 == 0) return 1; x /= 10; } return 0; } // Returns count of numbers // from 1 to n with 0 as digit static int getCount(int n) { // Initialize count of // numbers having 0 as digit int count = 0; // Traverse through all numbers // and for every number // check if it has 0. for (int i = 1; i <= n; i++) count += has0(i); return count; } // Driver Codepublic static void Main(){ int n = 107; Console.WriteLine(\"Count of numbers from 1\" + \" to \" +n + \" is \" + getCount(n));}} // This code is contributed by Sam007",
"e": 29264,
"s": 28220,
"text": null
},
{
"code": "<script> // JavaScript program to count numbers from 1 to n with// 0 as a digit // Returns 1 if x has 0, else 0function has0(x){ // Traverse through all digits of // x to check if it has 0. while (x) { // If current digit is 0, return true if (x % 10 == 0) return 1; x = Math.floor(x / 10); } return 0;} // Returns count of numbers from 1 to n with 0 as digitfunction getCount(n){ // Initialize count of numbers having 0 as digit let count = 0; // Traverse through all numbers and for every number // check if it has 0. for (let i=1; i<=n; i++) count += has0(i); return count;} // Driver program let n = 107; document.write(\"Count of numbers from 1\" + \" to \" + n + \" is \" + getCount(n)); // This code is contributed by Surbhi Tyagi. </script>",
"e": 30097,
"s": 29264,
"text": null
},
{
"code": null,
"e": 30105,
"s": 30097,
"text": "Output:"
},
{
"code": null,
"e": 30142,
"s": 30105,
"text": "Count of numbers from 1 to 107 is 17"
},
{
"code": null,
"e": 30389,
"s": 30142,
"text": "Refer below post for an optimized solution.Count numbers having 0 as a digitThis article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 30396,
"s": 30389,
"text": "Sam007"
},
{
"code": null,
"e": 30407,
"s": 30396,
"text": "nidhi_biet"
},
{
"code": null,
"e": 30421,
"s": 30407,
"text": "surbhityagi15"
},
{
"code": null,
"e": 30434,
"s": 30421,
"text": "Mathematical"
},
{
"code": null,
"e": 30447,
"s": 30434,
"text": "Mathematical"
},
{
"code": null,
"e": 30545,
"s": 30447,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30587,
"s": 30545,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 30611,
"s": 30587,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 30654,
"s": 30611,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 30668,
"s": 30654,
"text": "Prime Numbers"
},
{
"code": null,
"e": 30717,
"s": 30668,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30751,
"s": 30717,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 30792,
"s": 30751,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 30813,
"s": 30792,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 30855,
"s": 30813,
"text": "Euclidean algorithms (Basic and Extended)"
}
] |
Building a Simple Machine Learning Model on Breast Cancer Data | by vishabh goel | Towards Data Science
|
Breast cancer (BC) is one of the most common cancers among women worldwide, representing the majority of new cancer cases and cancer-related deaths according to global statistics, making it a significant public health problem in today’s society.
The early diagnosis of BC can improve the prognosis and chance of survival significantly, as it can promote timely clinical treatment to patients. Further accurate classification of benign tumors can prevent patients undergoing unnecessary treatments. Thus, the correct diagnosis of BC and classification of patients into malignant or benign groups is the subject of much research. Because of its unique advantages in critical features detection from complex BC datasets, machine learning (ML) is widely recognized as the methodology of choice in BC pattern classification and forecast modelling.
Classification and data mining methods are an effective way to classify data. Especially in medical field, where those methods are widely used in diagnosis and analysis to make decisions.
Mammography. The most important screening test for breast cancer is the mammogram. A mammogram is an X-ray of the breast. It can detect breast cancer up to two years before the tumor can be felt by you or your doctor.
Women age 40–45 or older who are at average risk of breast cancer should have a mammogram once a year.
Women at high risk should have yearly mammograms along with an MRI starting at age 30.
The following are some of the known risk factors for breast cancer. However, most cases of breast cancer cannot be linked to a specific cause. Talk to your doctor about your specific risk.
Age. The chance of getting breast cancer increases as women age. Nearly 80 percent of breast cancers are found in women over the age of 50.
Personal history of breast cancer. A woman who has had breast cancer in one breast is at an increased risk of developing cancer in her other breast.
Family history of breast cancer. A woman has a higher risk of breast cancer if her mother, sister or daughter had breast cancer, especially at a young age (before 40). Having other relatives with breast cancer may also raise the risk.
Genetic factors. Women with certain genetic mutations, including changes to the BRCA1 and BRCA2 genes, are at higher risk of developing breast cancer during their lifetime. Other gene changes may raise breast cancer risk as well.
Childbearing and menstrual history. The older a woman is when she has her first child, the greater her risk of breast cancer. Also at higher risk are:
Women who menstruate for the first time at an early age (before 12)
Women who go through menopause late (after age 55)
Women who’ve never had children
We will use the UCI Machine Learning Repository for breast cancer dataset.
http://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+%28diagnostic%29
The dataset used in this story is publicly available and was created by Dr. William H. Wolberg, physician at the University Of Wisconsin Hospital at Madison, Wisconsin, USA. To create the dataset Dr. Wolberg used fluid samples, taken from patients with solid breast masses and an easy-to-use graphical computer program called Xcyt, which is capable of perform the analysis of cytological features based on a digital scan. The program uses a curve-fitting algorithm, to compute ten features from each one of the cells in the sample, than it calculates the mean value, extreme value and standard error of each feature for the image, returning a 30 real-valuated vector
Attribute Information:
ID number 2) Diagnosis (M = malignant, B = benign) 3–32)
ID number 2) Diagnosis (M = malignant, B = benign) 3–32)
Ten real-valued features are computed for each cell nucleus:
radius (mean of distances from center to points on the perimeter)texture (standard deviation of gray-scale values)perimeterareasmoothness (local variation in radius lengths)compactness (perimeter2 / area — 1.0)concavity (severity of concave portions of the contour)concave points (number of concave portions of the contour)symmetryfractal dimension (“coastline approximation” — 1)
radius (mean of distances from center to points on the perimeter)
texture (standard deviation of gray-scale values)
perimeter
area
smoothness (local variation in radius lengths)
compactness (perimeter2 / area — 1.0)
concavity (severity of concave portions of the contour)
concave points (number of concave portions of the contour)
symmetry
fractal dimension (“coastline approximation” — 1)
The mean, standard error and “worst” or largest (mean of the three largest values) of these features were computed for each image, resulting in 30 features. For instance, field 3 is Mean Radius, field 13 is Radius SE, field 23 is Worst Radius.
This analysis aims to observe which features are most helpful in predicting malignant or benign cancer and to see general trends that may aid us in model selection and hyper parameter selection. The goal is to classify whether the breast cancer is benign or malignant. To achieve this i have used machine learning classification methods to fit a function that can predict the discrete class of new input.
We will be using Spyder to work on this dataset. We will first go with importing the necessary libraries and import our dataset to Spyder :
#importing the librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd#importing our cancer datasetdataset = pd.read_csv(‘cancer.csv')X = dataset.iloc[:, 1:31].valuesY = dataset.iloc[:, 31].values
We can examine the data set using the pandas’ head() method.
dataset.head()
We can find the dimensions of the data set using the panda dataset ‘shape’ attribute.
print("Cancer data set dimensions : {}".format(dataset.shape))Cancer data set dimensions : (569, 32)
We can observe that the data set contain 569 rows and 32 columns. ‘Diagnosis’ is the column which we are going to predict , which says if the cancer is M = malignant or B = benign. 1 means the cancer is malignant and 0 means benign. We can identify that out of the 569 persons, 357 are labeled as B (benign) and 212 as M (malignant).
Visualization of data is an imperative aspect of data science. It helps to understand data and also to explain the data to another person. Python has several interesting visualization libraries such as Matplotlib, Seaborn etc.
In this tutorial we will use pandas’ visualization which is built on top of matplotlib, to find the data distribution of the features.
Missing or Null Data points
We can find any missing or null data points of the data set (if there is any) using the following pandas function.
dataset.isnull().sum()dataset.isna().sum()
Categorical data are variables that contain label values rather than numeric values.The number of possible values is often limited to a fixed set.
For example, users are typically described by country, gender, age group etc.
We will use Label Encoder to label the categorical data. Label Encoder is the part of SciKit Learn library in Python and used to convert categorical data, or text data, into numbers, which our predictive models can better understand.
#Encoding categorical data valuesfrom sklearn.preprocessing import LabelEncoderlabelencoder_Y = LabelEncoder()Y = labelencoder_Y.fit_transform(Y)
The data we use is usually split into training data and test data. The training set contains a known output and the model learns on this data in order to be generalized to other data later on. We have the test dataset (or subset) in order to test our model’s prediction on this subset.
We will do this using SciKit-Learn library in Python using the train_test_split method.
# Splitting the dataset into the Training set and Test setfrom sklearn.model_selection import train_test_splitX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0)
Most of the times, your dataset will contain features highly varying in magnitudes, units and range. But since, most of the machine learning algorithms use Eucledian distance between two data points in their computations. We need to bring all features to the same level of magnitudes. This can be achieved by scaling. This means that you’re transforming your data so that it fits within a specific scale, like 0–100 or 0–1.
We will use StandardScaler method from SciKit-Learn library.
#Feature Scalingfrom sklearn.preprocessing import StandardScalersc = StandardScaler()X_train = sc.fit_transform(X_train)X_test = sc.transform(X_test)
This is the most exciting phase in Applying Machine Learning to any Dataset. It is also known as Algorithm selection for Predicting the best results.
Usually Data Scientists use different kinds of Machine Learning algorithms to the large data sets. But, at high level all those different algorithms can be classified in two groups : supervised learning and unsupervised learning.
Without wasting much time, I would just give a brief overview about these two types of learnings.
Supervised learning : Supervised learning is a type of system in which both input and desired output data are provided. Input and output data are labelled for classification to provide a learning basis for future data processing. Supervised learning problems can be further grouped into Regression and Classification problems.
A regression problem is when the output variable is a real or continuous value, such as “salary” or “weight”.
A classification problem is when the output variable is a category like filtering emails “spam” or “not spam”
Unsupervised Learning : Unsupervised learning is the algorithm using information that is neither classified nor labeled and allowing the algorithm to act on that information without guidance.
In our dataset we have the outcome variable or Dependent variable i.e Y having only two set of values, either M (Malign) or B(Benign). So we will use Classification algorithm of supervised learning.
We have different types of classification algorithms in Machine Learning :-
1. Logistic Regression
2. Nearest Neighbor
3. Support Vector Machines
4. Kernel SVM
5. Naïve Bayes
6. Decision Tree Algorithm
7. Random Forest Classification
Lets start applying the algorithms :
We will use sklearn library to import all the methods of classification algorithms.
We will use LogisticRegression method of model selection to use Logistic Regression Algorithm,
#Using Logistic Regression Algorithm to the Training Setfrom sklearn.linear_model import LogisticRegressionclassifier = LogisticRegression(random_state = 0)classifier.fit(X_train, Y_train)#Using KNeighborsClassifier Method of neighbors class to use Nearest Neighbor algorithmfrom sklearn.neighbors import KNeighborsClassifierclassifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)classifier.fit(X_train, Y_train)#Using SVC method of svm class to use Support Vector Machine Algorithmfrom sklearn.svm import SVCclassifier = SVC(kernel = 'linear', random_state = 0)classifier.fit(X_train, Y_train)#Using SVC method of svm class to use Kernel SVM Algorithmfrom sklearn.svm import SVCclassifier = SVC(kernel = 'rbf', random_state = 0)classifier.fit(X_train, Y_train)#Using GaussianNB method of naïve_bayes class to use Naïve Bayes Algorithmfrom sklearn.naive_bayes import GaussianNBclassifier = GaussianNB()classifier.fit(X_train, Y_train)#Using DecisionTreeClassifier of tree class to use Decision Tree Algorithmfrom sklearn.tree import DecisionTreeClassifierclassifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)classifier.fit(X_train, Y_train)#Using RandomForestClassifier method of ensemble class to use Random Forest Classification algorithmfrom sklearn.ensemble import RandomForestClassifierclassifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0)classifier.fit(X_train, Y_train)
We will now predict the test set results and check the accuracy with each of our model:
Y_pred = classifier.predict(X_test)
To check the accuracy we need to import confusion_matrix method of metrics class. The confusion matrix is a way of tabulating the number of mis-classifications, i.e., the number of predicted classes which ended up in a wrong classification bin based on the true classes.
from sklearn.metrics import confusion_matrixcm = confusion_matrix(Y_test, Y_pred)
We will use Classification Accuracy method to find the accuracy of our models. Classification Accuracy is what we usually mean, when we use the term accuracy. It is the ratio of number of correct predictions to the total number of input samples.
To check the correct prediction we have to check confusion matrix object and add the predicted results diagonally which will be number of correct prediction and then divide by total number of predictions.
After applying the different classification models, we have got below accuracies with different models:
1. Logistic Regression — 95.8%
2. Nearest Neighbor — 95.1%
3. Support Vector Machines — 97.2%
4. Kernel SVM — 96.5%
5. Naive Bayes — 91.6%
6. Decision Tree Algorithm — 95.8%
7. Random Forest Classification — 98.6%
So finally we have built our classification model and we can see that Random Forest Classification algorithm gives the best results for our dataset. Well its not always applicable to every dataset. To choose our model we always need to analyze our dataset and then apply our machine learning model.
This is a basic application of Machine Learning Model to any dataset. Feel free to ask questions if you have any doubts. Drop an email to: vishabh1010@gmail.com or contact me through linked-in.
You can find the code on github and try it on Ipython console.
Remember to always keep in mind the problem of overfitting and underfitting as well.
Hope you enjoyed the article.....
|
[
{
"code": null,
"e": 418,
"s": 172,
"text": "Breast cancer (BC) is one of the most common cancers among women worldwide, representing the majority of new cancer cases and cancer-related deaths according to global statistics, making it a significant public health problem in today’s society."
},
{
"code": null,
"e": 1015,
"s": 418,
"text": "The early diagnosis of BC can improve the prognosis and chance of survival significantly, as it can promote timely clinical treatment to patients. Further accurate classification of benign tumors can prevent patients undergoing unnecessary treatments. Thus, the correct diagnosis of BC and classification of patients into malignant or benign groups is the subject of much research. Because of its unique advantages in critical features detection from complex BC datasets, machine learning (ML) is widely recognized as the methodology of choice in BC pattern classification and forecast modelling."
},
{
"code": null,
"e": 1203,
"s": 1015,
"text": "Classification and data mining methods are an effective way to classify data. Especially in medical field, where those methods are widely used in diagnosis and analysis to make decisions."
},
{
"code": null,
"e": 1421,
"s": 1203,
"text": "Mammography. The most important screening test for breast cancer is the mammogram. A mammogram is an X-ray of the breast. It can detect breast cancer up to two years before the tumor can be felt by you or your doctor."
},
{
"code": null,
"e": 1524,
"s": 1421,
"text": "Women age 40–45 or older who are at average risk of breast cancer should have a mammogram once a year."
},
{
"code": null,
"e": 1611,
"s": 1524,
"text": "Women at high risk should have yearly mammograms along with an MRI starting at age 30."
},
{
"code": null,
"e": 1800,
"s": 1611,
"text": "The following are some of the known risk factors for breast cancer. However, most cases of breast cancer cannot be linked to a specific cause. Talk to your doctor about your specific risk."
},
{
"code": null,
"e": 1940,
"s": 1800,
"text": "Age. The chance of getting breast cancer increases as women age. Nearly 80 percent of breast cancers are found in women over the age of 50."
},
{
"code": null,
"e": 2089,
"s": 1940,
"text": "Personal history of breast cancer. A woman who has had breast cancer in one breast is at an increased risk of developing cancer in her other breast."
},
{
"code": null,
"e": 2324,
"s": 2089,
"text": "Family history of breast cancer. A woman has a higher risk of breast cancer if her mother, sister or daughter had breast cancer, especially at a young age (before 40). Having other relatives with breast cancer may also raise the risk."
},
{
"code": null,
"e": 2554,
"s": 2324,
"text": "Genetic factors. Women with certain genetic mutations, including changes to the BRCA1 and BRCA2 genes, are at higher risk of developing breast cancer during their lifetime. Other gene changes may raise breast cancer risk as well."
},
{
"code": null,
"e": 2705,
"s": 2554,
"text": "Childbearing and menstrual history. The older a woman is when she has her first child, the greater her risk of breast cancer. Also at higher risk are:"
},
{
"code": null,
"e": 2773,
"s": 2705,
"text": "Women who menstruate for the first time at an early age (before 12)"
},
{
"code": null,
"e": 2824,
"s": 2773,
"text": "Women who go through menopause late (after age 55)"
},
{
"code": null,
"e": 2856,
"s": 2824,
"text": "Women who’ve never had children"
},
{
"code": null,
"e": 2931,
"s": 2856,
"text": "We will use the UCI Machine Learning Repository for breast cancer dataset."
},
{
"code": null,
"e": 3011,
"s": 2931,
"text": "http://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+%28diagnostic%29"
},
{
"code": null,
"e": 3678,
"s": 3011,
"text": "The dataset used in this story is publicly available and was created by Dr. William H. Wolberg, physician at the University Of Wisconsin Hospital at Madison, Wisconsin, USA. To create the dataset Dr. Wolberg used fluid samples, taken from patients with solid breast masses and an easy-to-use graphical computer program called Xcyt, which is capable of perform the analysis of cytological features based on a digital scan. The program uses a curve-fitting algorithm, to compute ten features from each one of the cells in the sample, than it calculates the mean value, extreme value and standard error of each feature for the image, returning a 30 real-valuated vector"
},
{
"code": null,
"e": 3701,
"s": 3678,
"text": "Attribute Information:"
},
{
"code": null,
"e": 3758,
"s": 3701,
"text": "ID number 2) Diagnosis (M = malignant, B = benign) 3–32)"
},
{
"code": null,
"e": 3815,
"s": 3758,
"text": "ID number 2) Diagnosis (M = malignant, B = benign) 3–32)"
},
{
"code": null,
"e": 3876,
"s": 3815,
"text": "Ten real-valued features are computed for each cell nucleus:"
},
{
"code": null,
"e": 4257,
"s": 3876,
"text": "radius (mean of distances from center to points on the perimeter)texture (standard deviation of gray-scale values)perimeterareasmoothness (local variation in radius lengths)compactness (perimeter2 / area — 1.0)concavity (severity of concave portions of the contour)concave points (number of concave portions of the contour)symmetryfractal dimension (“coastline approximation” — 1)"
},
{
"code": null,
"e": 4323,
"s": 4257,
"text": "radius (mean of distances from center to points on the perimeter)"
},
{
"code": null,
"e": 4373,
"s": 4323,
"text": "texture (standard deviation of gray-scale values)"
},
{
"code": null,
"e": 4383,
"s": 4373,
"text": "perimeter"
},
{
"code": null,
"e": 4388,
"s": 4383,
"text": "area"
},
{
"code": null,
"e": 4435,
"s": 4388,
"text": "smoothness (local variation in radius lengths)"
},
{
"code": null,
"e": 4473,
"s": 4435,
"text": "compactness (perimeter2 / area — 1.0)"
},
{
"code": null,
"e": 4529,
"s": 4473,
"text": "concavity (severity of concave portions of the contour)"
},
{
"code": null,
"e": 4588,
"s": 4529,
"text": "concave points (number of concave portions of the contour)"
},
{
"code": null,
"e": 4597,
"s": 4588,
"text": "symmetry"
},
{
"code": null,
"e": 4647,
"s": 4597,
"text": "fractal dimension (“coastline approximation” — 1)"
},
{
"code": null,
"e": 4891,
"s": 4647,
"text": "The mean, standard error and “worst” or largest (mean of the three largest values) of these features were computed for each image, resulting in 30 features. For instance, field 3 is Mean Radius, field 13 is Radius SE, field 23 is Worst Radius."
},
{
"code": null,
"e": 5296,
"s": 4891,
"text": "This analysis aims to observe which features are most helpful in predicting malignant or benign cancer and to see general trends that may aid us in model selection and hyper parameter selection. The goal is to classify whether the breast cancer is benign or malignant. To achieve this i have used machine learning classification methods to fit a function that can predict the discrete class of new input."
},
{
"code": null,
"e": 5436,
"s": 5296,
"text": "We will be using Spyder to work on this dataset. We will first go with importing the necessary libraries and import our dataset to Spyder :"
},
{
"code": null,
"e": 5655,
"s": 5436,
"text": "#importing the librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd#importing our cancer datasetdataset = pd.read_csv(‘cancer.csv')X = dataset.iloc[:, 1:31].valuesY = dataset.iloc[:, 31].values"
},
{
"code": null,
"e": 5716,
"s": 5655,
"text": "We can examine the data set using the pandas’ head() method."
},
{
"code": null,
"e": 5731,
"s": 5716,
"text": "dataset.head()"
},
{
"code": null,
"e": 5817,
"s": 5731,
"text": "We can find the dimensions of the data set using the panda dataset ‘shape’ attribute."
},
{
"code": null,
"e": 5918,
"s": 5817,
"text": "print(\"Cancer data set dimensions : {}\".format(dataset.shape))Cancer data set dimensions : (569, 32)"
},
{
"code": null,
"e": 6252,
"s": 5918,
"text": "We can observe that the data set contain 569 rows and 32 columns. ‘Diagnosis’ is the column which we are going to predict , which says if the cancer is M = malignant or B = benign. 1 means the cancer is malignant and 0 means benign. We can identify that out of the 569 persons, 357 are labeled as B (benign) and 212 as M (malignant)."
},
{
"code": null,
"e": 6479,
"s": 6252,
"text": "Visualization of data is an imperative aspect of data science. It helps to understand data and also to explain the data to another person. Python has several interesting visualization libraries such as Matplotlib, Seaborn etc."
},
{
"code": null,
"e": 6614,
"s": 6479,
"text": "In this tutorial we will use pandas’ visualization which is built on top of matplotlib, to find the data distribution of the features."
},
{
"code": null,
"e": 6642,
"s": 6614,
"text": "Missing or Null Data points"
},
{
"code": null,
"e": 6757,
"s": 6642,
"text": "We can find any missing or null data points of the data set (if there is any) using the following pandas function."
},
{
"code": null,
"e": 6800,
"s": 6757,
"text": "dataset.isnull().sum()dataset.isna().sum()"
},
{
"code": null,
"e": 6947,
"s": 6800,
"text": "Categorical data are variables that contain label values rather than numeric values.The number of possible values is often limited to a fixed set."
},
{
"code": null,
"e": 7025,
"s": 6947,
"text": "For example, users are typically described by country, gender, age group etc."
},
{
"code": null,
"e": 7259,
"s": 7025,
"text": "We will use Label Encoder to label the categorical data. Label Encoder is the part of SciKit Learn library in Python and used to convert categorical data, or text data, into numbers, which our predictive models can better understand."
},
{
"code": null,
"e": 7405,
"s": 7259,
"text": "#Encoding categorical data valuesfrom sklearn.preprocessing import LabelEncoderlabelencoder_Y = LabelEncoder()Y = labelencoder_Y.fit_transform(Y)"
},
{
"code": null,
"e": 7691,
"s": 7405,
"text": "The data we use is usually split into training data and test data. The training set contains a known output and the model learns on this data in order to be generalized to other data later on. We have the test dataset (or subset) in order to test our model’s prediction on this subset."
},
{
"code": null,
"e": 7779,
"s": 7691,
"text": "We will do this using SciKit-Learn library in Python using the train_test_split method."
},
{
"code": null,
"e": 7983,
"s": 7779,
"text": "# Splitting the dataset into the Training set and Test setfrom sklearn.model_selection import train_test_splitX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0)"
},
{
"code": null,
"e": 8407,
"s": 7983,
"text": "Most of the times, your dataset will contain features highly varying in magnitudes, units and range. But since, most of the machine learning algorithms use Eucledian distance between two data points in their computations. We need to bring all features to the same level of magnitudes. This can be achieved by scaling. This means that you’re transforming your data so that it fits within a specific scale, like 0–100 or 0–1."
},
{
"code": null,
"e": 8468,
"s": 8407,
"text": "We will use StandardScaler method from SciKit-Learn library."
},
{
"code": null,
"e": 8618,
"s": 8468,
"text": "#Feature Scalingfrom sklearn.preprocessing import StandardScalersc = StandardScaler()X_train = sc.fit_transform(X_train)X_test = sc.transform(X_test)"
},
{
"code": null,
"e": 8768,
"s": 8618,
"text": "This is the most exciting phase in Applying Machine Learning to any Dataset. It is also known as Algorithm selection for Predicting the best results."
},
{
"code": null,
"e": 8998,
"s": 8768,
"text": "Usually Data Scientists use different kinds of Machine Learning algorithms to the large data sets. But, at high level all those different algorithms can be classified in two groups : supervised learning and unsupervised learning."
},
{
"code": null,
"e": 9096,
"s": 8998,
"text": "Without wasting much time, I would just give a brief overview about these two types of learnings."
},
{
"code": null,
"e": 9423,
"s": 9096,
"text": "Supervised learning : Supervised learning is a type of system in which both input and desired output data are provided. Input and output data are labelled for classification to provide a learning basis for future data processing. Supervised learning problems can be further grouped into Regression and Classification problems."
},
{
"code": null,
"e": 9533,
"s": 9423,
"text": "A regression problem is when the output variable is a real or continuous value, such as “salary” or “weight”."
},
{
"code": null,
"e": 9643,
"s": 9533,
"text": "A classification problem is when the output variable is a category like filtering emails “spam” or “not spam”"
},
{
"code": null,
"e": 9835,
"s": 9643,
"text": "Unsupervised Learning : Unsupervised learning is the algorithm using information that is neither classified nor labeled and allowing the algorithm to act on that information without guidance."
},
{
"code": null,
"e": 10034,
"s": 9835,
"text": "In our dataset we have the outcome variable or Dependent variable i.e Y having only two set of values, either M (Malign) or B(Benign). So we will use Classification algorithm of supervised learning."
},
{
"code": null,
"e": 10110,
"s": 10034,
"text": "We have different types of classification algorithms in Machine Learning :-"
},
{
"code": null,
"e": 10133,
"s": 10110,
"text": "1. Logistic Regression"
},
{
"code": null,
"e": 10153,
"s": 10133,
"text": "2. Nearest Neighbor"
},
{
"code": null,
"e": 10180,
"s": 10153,
"text": "3. Support Vector Machines"
},
{
"code": null,
"e": 10194,
"s": 10180,
"text": "4. Kernel SVM"
},
{
"code": null,
"e": 10210,
"s": 10194,
"text": "5. Naïve Bayes"
},
{
"code": null,
"e": 10237,
"s": 10210,
"text": "6. Decision Tree Algorithm"
},
{
"code": null,
"e": 10269,
"s": 10237,
"text": "7. Random Forest Classification"
},
{
"code": null,
"e": 10306,
"s": 10269,
"text": "Lets start applying the algorithms :"
},
{
"code": null,
"e": 10390,
"s": 10306,
"text": "We will use sklearn library to import all the methods of classification algorithms."
},
{
"code": null,
"e": 10485,
"s": 10390,
"text": "We will use LogisticRegression method of model selection to use Logistic Regression Algorithm,"
},
{
"code": null,
"e": 11953,
"s": 10485,
"text": "#Using Logistic Regression Algorithm to the Training Setfrom sklearn.linear_model import LogisticRegressionclassifier = LogisticRegression(random_state = 0)classifier.fit(X_train, Y_train)#Using KNeighborsClassifier Method of neighbors class to use Nearest Neighbor algorithmfrom sklearn.neighbors import KNeighborsClassifierclassifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)classifier.fit(X_train, Y_train)#Using SVC method of svm class to use Support Vector Machine Algorithmfrom sklearn.svm import SVCclassifier = SVC(kernel = 'linear', random_state = 0)classifier.fit(X_train, Y_train)#Using SVC method of svm class to use Kernel SVM Algorithmfrom sklearn.svm import SVCclassifier = SVC(kernel = 'rbf', random_state = 0)classifier.fit(X_train, Y_train)#Using GaussianNB method of naïve_bayes class to use Naïve Bayes Algorithmfrom sklearn.naive_bayes import GaussianNBclassifier = GaussianNB()classifier.fit(X_train, Y_train)#Using DecisionTreeClassifier of tree class to use Decision Tree Algorithmfrom sklearn.tree import DecisionTreeClassifierclassifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)classifier.fit(X_train, Y_train)#Using RandomForestClassifier method of ensemble class to use Random Forest Classification algorithmfrom sklearn.ensemble import RandomForestClassifierclassifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0)classifier.fit(X_train, Y_train)"
},
{
"code": null,
"e": 12041,
"s": 11953,
"text": "We will now predict the test set results and check the accuracy with each of our model:"
},
{
"code": null,
"e": 12077,
"s": 12041,
"text": "Y_pred = classifier.predict(X_test)"
},
{
"code": null,
"e": 12348,
"s": 12077,
"text": "To check the accuracy we need to import confusion_matrix method of metrics class. The confusion matrix is a way of tabulating the number of mis-classifications, i.e., the number of predicted classes which ended up in a wrong classification bin based on the true classes."
},
{
"code": null,
"e": 12430,
"s": 12348,
"text": "from sklearn.metrics import confusion_matrixcm = confusion_matrix(Y_test, Y_pred)"
},
{
"code": null,
"e": 12676,
"s": 12430,
"text": "We will use Classification Accuracy method to find the accuracy of our models. Classification Accuracy is what we usually mean, when we use the term accuracy. It is the ratio of number of correct predictions to the total number of input samples."
},
{
"code": null,
"e": 12881,
"s": 12676,
"text": "To check the correct prediction we have to check confusion matrix object and add the predicted results diagonally which will be number of correct prediction and then divide by total number of predictions."
},
{
"code": null,
"e": 12985,
"s": 12881,
"text": "After applying the different classification models, we have got below accuracies with different models:"
},
{
"code": null,
"e": 13016,
"s": 12985,
"text": "1. Logistic Regression — 95.8%"
},
{
"code": null,
"e": 13044,
"s": 13016,
"text": "2. Nearest Neighbor — 95.1%"
},
{
"code": null,
"e": 13079,
"s": 13044,
"text": "3. Support Vector Machines — 97.2%"
},
{
"code": null,
"e": 13101,
"s": 13079,
"text": "4. Kernel SVM — 96.5%"
},
{
"code": null,
"e": 13124,
"s": 13101,
"text": "5. Naive Bayes — 91.6%"
},
{
"code": null,
"e": 13159,
"s": 13124,
"text": "6. Decision Tree Algorithm — 95.8%"
},
{
"code": null,
"e": 13199,
"s": 13159,
"text": "7. Random Forest Classification — 98.6%"
},
{
"code": null,
"e": 13498,
"s": 13199,
"text": "So finally we have built our classification model and we can see that Random Forest Classification algorithm gives the best results for our dataset. Well its not always applicable to every dataset. To choose our model we always need to analyze our dataset and then apply our machine learning model."
},
{
"code": null,
"e": 13692,
"s": 13498,
"text": "This is a basic application of Machine Learning Model to any dataset. Feel free to ask questions if you have any doubts. Drop an email to: vishabh1010@gmail.com or contact me through linked-in."
},
{
"code": null,
"e": 13755,
"s": 13692,
"text": "You can find the code on github and try it on Ipython console."
},
{
"code": null,
"e": 13840,
"s": 13755,
"text": "Remember to always keep in mind the problem of overfitting and underfitting as well."
}
] |
How to position text to center on an image with CSS
|
To positioned text to center an image, use the transform property in CSS. You can try to run the following code for centered text over an image
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.container {
position: relative;
}
.topleft {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
font-size: 18px;
}
img {
width: 100%;
height: auto;
opacity: 0.3;
}
</style>
</head>
<body>
<h2>Image Text</h2>
<p>Add some text to an image in the center of an image:</p>
<div class = "container">
<img src = "trolltunga.jpg" alt = "Norway" width = "1000" height = "300">
<div class = "topleft">Center</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1206,
"s": 1062,
"text": "To positioned text to center an image, use the transform property in CSS. You can try to run the following code for centered text over an image"
},
{
"code": null,
"e": 1216,
"s": 1206,
"text": "Live Demo"
},
{
"code": null,
"e": 1934,
"s": 1216,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .container {\n position: relative;\n }\n .topleft {\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%);\n font-size: 18px;\n }\n img {\n width: 100%;\n height: auto;\n opacity: 0.3;\n }\n </style>\n </head>\n <body>\n <h2>Image Text</h2>\n <p>Add some text to an image in the center of an image:</p>\n <div class = \"container\">\n <img src = \"trolltunga.jpg\" alt = \"Norway\" width = \"1000\" height = \"300\">\n <div class = \"topleft\">Center</div>\n </div>\n </body>\n</html>"
}
] |
Can we use the result of a SUM() function in MySQL WHERE clause
|
We can use the HAVING clause rather than the WHERE in MySQL. Let us first create a table −
mysql> create table DemoTable
(
Name varchar(50),
Price int
);
Query OK, 0 rows affected (0.79 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Chris',30);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('David',40);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Chris',10);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Mike',44);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('David',5);
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+-------+
| Name | Price |
+-------+-------+
| Chris | 30 |
| David | 40 |
| Chris | 10 |
| Mike | 44 |
| David | 5 |
+-------+-------+
5 rows in set (0.00 sec)
Following is the query to use the result of SUM() function in HAVING clause −
mysql> select Name,SUM(Price) AS Total_Price from DemoTable group by Name having Total_Price > 40;
This will produce the following output −
+-------+-------------+
| Name | Total_Price |
+-------+-------------+
| David | 45 |
| Mike | 44 |
+-------+-------------+
2 rows in set (0.03 sec)
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "We can use the HAVING clause rather than the WHERE in MySQL. Let us first create a table −"
},
{
"code": null,
"e": 1259,
"s": 1153,
"text": "mysql> create table DemoTable\n(\n Name varchar(50),\n Price int\n);\nQuery OK, 0 rows affected (0.79 sec)"
},
{
"code": null,
"e": 1315,
"s": 1259,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1738,
"s": 1315,
"text": "mysql> insert into DemoTable values('Chris',30);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values('David',40);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values('Chris',10);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values('Mike',44);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('David',5);\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1798,
"s": 1738,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1829,
"s": 1798,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1870,
"s": 1829,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2057,
"s": 1870,
"text": "+-------+-------+\n| Name | Price |\n+-------+-------+\n| Chris | 30 |\n| David | 40 |\n| Chris | 10 |\n| Mike | 44 |\n| David | 5 |\n+-------+-------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2135,
"s": 2057,
"text": "Following is the query to use the result of SUM() function in HAVING clause −"
},
{
"code": null,
"e": 2234,
"s": 2135,
"text": "mysql> select Name,SUM(Price) AS Total_Price from DemoTable group by Name having Total_Price > 40;"
},
{
"code": null,
"e": 2275,
"s": 2234,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2444,
"s": 2275,
"text": "+-------+-------------+\n| Name | Total_Price |\n+-------+-------------+\n| David | 45 |\n| Mike | 44 |\n+-------+-------------+\n2 rows in set (0.03 sec)"
}
] |
Python - Set Exercises
|
Now you have learned a lot about sets, and how to use them in Python.
Are you ready for a test?
Try to insert the missing part to make the code work as expected:
Check if "apple" is present in the fruits set.
fruits = {"apple", "banana", "cherry"}
if "apple" fruits:
print("Yes, apple is a fruit!")
Go to the Exercise section and test all of our Python Set Exercises:
Python Set Exercises
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 70,
"s": 0,
"text": "Now you have learned a lot about sets, and how to use them in Python."
},
{
"code": null,
"e": 96,
"s": 70,
"text": "Are you ready for a test?"
},
{
"code": null,
"e": 162,
"s": 96,
"text": "Try to insert the missing part to make the code work as expected:"
},
{
"code": null,
"e": 209,
"s": 162,
"text": "Check if \"apple\" is present in the fruits set."
},
{
"code": null,
"e": 303,
"s": 209,
"text": "fruits = {\"apple\", \"banana\", \"cherry\"}\nif \"apple\" fruits:\n print(\"Yes, apple is a fruit!\")\n"
},
{
"code": null,
"e": 372,
"s": 303,
"text": "Go to the Exercise section and test all of our Python Set Exercises:"
},
{
"code": null,
"e": 395,
"s": 372,
"text": "\nPython Set Exercises\n"
},
{
"code": null,
"e": 428,
"s": 395,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 470,
"s": 428,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 577,
"s": 470,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 596,
"s": 577,
"text": "help@w3schools.com"
}
] |
20+ Must-Subscribe Data and AI Newsletters in 2021 | by Benedict Neo | Towards Data Science
|
There’s an ocean of noise on the internet for data science and AI that it can be overwhelming to focus on good quality news and content.
As Herbert A. Simon says:
“...a wealth of information creates a poverty of attention...”
The solution to information overload?
Newsletters.
If you’re someone who wants to keep up with the industry, and are looking for the best newsletters to do so, then you’re in luck.
Below are 20+ reputable and content-rich newsletters that range from the latest news and opinions to the best tools, resources, and tutorials.
Categories of these newsletters:- Data Science - Data Engineering- Machine Learning- Artificial Intelligence
I’ve also linked the archives for each newsletter, so feel free to check them out before subscribing to make sure they suit your needs. Enjoy!
A comprehensive monthly newsletter by bitgrit.net with their latest AI competitions, workshops, technical articles and tutorial, AI news, and Data Science learning resources.
Read the latest issues & subscribe here.
Curated weekly by Lon Reisberg, data elixir is one of the most popular data science newsletters that bring you insight, tutorials, projects & opinions, and resources.
Read past issues & subscribe here.
A free weekly newsletter featuring curated news, articles, and jobs related to Data Science.
Read past issues & subscribe here.
A collection of the best and latest articles, papers, courses, interviews, podcasts, videos, datasets, events, books, and jobs on ML, DL, Computer Vision, NLP, Data Science, Robotics, and other aspects of AI.
Read past issues & subscribe here.
KDnuggets, a leading site on Machine Learning, Data Science, AI, and more, compiles their featured stories, tutorials and overviews, opinions, top stories, and open jobs every week.
Read past issues & subscribe here.
A perfect blend of the most up to date information and sources on what’s hot in the data world
Read the sample issue & subscribe here.
A weekly email about data, data science, and analytics, curated by the team at Mode.
Read past issues & subscribe here
Stay up to date with AI & Data Science by reading top-notch articles delivered straight to your inbox each weekday
Read the latest issues & subscribe here
Curated by Christophe, a Data Engineering Lead and Coach, Data news is a weekly curation of news and tools related to data engineering.
Read past issues & subscribe here.
Curated by Ananth Packkildurai, this is a weekly data engineering newsletter that features the latest trend and news in the data engineering world.
Read past issues & subscribe here.
A newsletter that keeps you updated with articles on core data engineering concepts, in-demand software and tools, and tips for growing your data engineering career every one to two weeks.
Read all the articles & subscribe here.
Stay informed on the latest trending ML papers with code, research developments, libraries, methods, and datasets.
Read past issues & subscribe here.
Receive curated articles, tutorials, and blog posts from experienced Machine Learning professionals. Obtain insights on best practices, tools, and techniques in machine learning explainability, reproducibility, model evaluation, feature analysis, and beyond.
Read past issues & subscribe here.
Get articles on effective data science, ML in production, and career growth, three interesting things Eugene, Applied Scientist at Amazon, is reading and informal sharing & chats.
Read past issues & subscribe here.
Crafted by Daniel Bourke, ML monthly keeps you up to date with the Machine Learning industry. The fastest-growing monthly newsletter for Machine Learning Engineers.
Read past issues & subscribe here.
Get the latest breakthroughs in Machine Learning. They use AI to analyze 1000+ research papers and articles every week to provide you with the most popular summary in the industry.
Read past issues & subscribe here.
The popular blog with tons of helpful machine learning tutorials has a newsletter to get updates on the latest machine learning tutorials.
Subscribe here.
Curated by Nihit Desai and Rishabh Bhargava, this newsletter aims to explore what it means to develop software 2.0 and the new challenges that arise. They share their views on how to write better Software 2.0.
Read the latest issues & subscribe here.
Every week, the Batch presents the most important AI events and perspectives in a curated, easy-to-read report for engineers, enthusiasts, and business leaders, as well as a personal note from Andrew Ng.
Read past issues & subscribe here.
A weekly newsletter about artificial intelligence, read by more than ten thousand experts.
Read past issues & subscribe here.
A weekly collection of AI News and resources on Artificial Intelligence and Machine Learning. For free.
Read past issues & subscribe here.
Andriy Burkov, author of The Hundred-Page Machine Learning Book and the Machine Learning Engineering book, presents his newsletter with the most important artificial intelligence and machine learning news and articles.
Read the latest issue and subscribe here.
The summary of the last research papers, cool tech releases, and investments in AI to keep you up-to-date without hassle. It’s a bite-sized newsletter; in 5 minutes, you get enough to be smart about the currents of the AI world.
Read past issues and subscribe here.
Weekly summaries of AI news, straight to your inbox! Plus occasional articles, interviews, and more. Run by a couple of graduate students as a hobby, so don’t worry about marketing or the like.
Read past issues and subscribe here.
Monthly analysis of AI technology, geopolitics, research, and startups.
Read past issues & subscribe here.
A weekly newsletter by Louis Bouchard, creator of the channel What’s AI, who shares one paper per week, contain everything about the paper plus some bonus projects he is working on.
Read past issues & subscribe here.
That’s all the newsletters I have for you. Thank you for reading!
If you have any suggestions or additions, feel free to leave a comment below!
Connect with me on LinkedIn for daily resources on Data Science.
Follow the bitgrit Data Science Publication, where I write data science and ML tutorials.
|
[
{
"code": null,
"e": 308,
"s": 171,
"text": "There’s an ocean of noise on the internet for data science and AI that it can be overwhelming to focus on good quality news and content."
},
{
"code": null,
"e": 334,
"s": 308,
"text": "As Herbert A. Simon says:"
},
{
"code": null,
"e": 397,
"s": 334,
"text": "“...a wealth of information creates a poverty of attention...”"
},
{
"code": null,
"e": 435,
"s": 397,
"text": "The solution to information overload?"
},
{
"code": null,
"e": 448,
"s": 435,
"text": "Newsletters."
},
{
"code": null,
"e": 578,
"s": 448,
"text": "If you’re someone who wants to keep up with the industry, and are looking for the best newsletters to do so, then you’re in luck."
},
{
"code": null,
"e": 721,
"s": 578,
"text": "Below are 20+ reputable and content-rich newsletters that range from the latest news and opinions to the best tools, resources, and tutorials."
},
{
"code": null,
"e": 830,
"s": 721,
"text": "Categories of these newsletters:- Data Science - Data Engineering- Machine Learning- Artificial Intelligence"
},
{
"code": null,
"e": 973,
"s": 830,
"text": "I’ve also linked the archives for each newsletter, so feel free to check them out before subscribing to make sure they suit your needs. Enjoy!"
},
{
"code": null,
"e": 1148,
"s": 973,
"text": "A comprehensive monthly newsletter by bitgrit.net with their latest AI competitions, workshops, technical articles and tutorial, AI news, and Data Science learning resources."
},
{
"code": null,
"e": 1189,
"s": 1148,
"text": "Read the latest issues & subscribe here."
},
{
"code": null,
"e": 1356,
"s": 1189,
"text": "Curated weekly by Lon Reisberg, data elixir is one of the most popular data science newsletters that bring you insight, tutorials, projects & opinions, and resources."
},
{
"code": null,
"e": 1391,
"s": 1356,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 1484,
"s": 1391,
"text": "A free weekly newsletter featuring curated news, articles, and jobs related to Data Science."
},
{
"code": null,
"e": 1519,
"s": 1484,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 1728,
"s": 1519,
"text": "A collection of the best and latest articles, papers, courses, interviews, podcasts, videos, datasets, events, books, and jobs on ML, DL, Computer Vision, NLP, Data Science, Robotics, and other aspects of AI."
},
{
"code": null,
"e": 1763,
"s": 1728,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 1945,
"s": 1763,
"text": "KDnuggets, a leading site on Machine Learning, Data Science, AI, and more, compiles their featured stories, tutorials and overviews, opinions, top stories, and open jobs every week."
},
{
"code": null,
"e": 1980,
"s": 1945,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 2075,
"s": 1980,
"text": "A perfect blend of the most up to date information and sources on what’s hot in the data world"
},
{
"code": null,
"e": 2115,
"s": 2075,
"text": "Read the sample issue & subscribe here."
},
{
"code": null,
"e": 2200,
"s": 2115,
"text": "A weekly email about data, data science, and analytics, curated by the team at Mode."
},
{
"code": null,
"e": 2234,
"s": 2200,
"text": "Read past issues & subscribe here"
},
{
"code": null,
"e": 2349,
"s": 2234,
"text": "Stay up to date with AI & Data Science by reading top-notch articles delivered straight to your inbox each weekday"
},
{
"code": null,
"e": 2389,
"s": 2349,
"text": "Read the latest issues & subscribe here"
},
{
"code": null,
"e": 2525,
"s": 2389,
"text": "Curated by Christophe, a Data Engineering Lead and Coach, Data news is a weekly curation of news and tools related to data engineering."
},
{
"code": null,
"e": 2560,
"s": 2525,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 2708,
"s": 2560,
"text": "Curated by Ananth Packkildurai, this is a weekly data engineering newsletter that features the latest trend and news in the data engineering world."
},
{
"code": null,
"e": 2743,
"s": 2708,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 2932,
"s": 2743,
"text": "A newsletter that keeps you updated with articles on core data engineering concepts, in-demand software and tools, and tips for growing your data engineering career every one to two weeks."
},
{
"code": null,
"e": 2972,
"s": 2932,
"text": "Read all the articles & subscribe here."
},
{
"code": null,
"e": 3087,
"s": 2972,
"text": "Stay informed on the latest trending ML papers with code, research developments, libraries, methods, and datasets."
},
{
"code": null,
"e": 3122,
"s": 3087,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 3381,
"s": 3122,
"text": "Receive curated articles, tutorials, and blog posts from experienced Machine Learning professionals. Obtain insights on best practices, tools, and techniques in machine learning explainability, reproducibility, model evaluation, feature analysis, and beyond."
},
{
"code": null,
"e": 3416,
"s": 3381,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 3596,
"s": 3416,
"text": "Get articles on effective data science, ML in production, and career growth, three interesting things Eugene, Applied Scientist at Amazon, is reading and informal sharing & chats."
},
{
"code": null,
"e": 3631,
"s": 3596,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 3796,
"s": 3631,
"text": "Crafted by Daniel Bourke, ML monthly keeps you up to date with the Machine Learning industry. The fastest-growing monthly newsletter for Machine Learning Engineers."
},
{
"code": null,
"e": 3831,
"s": 3796,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 4012,
"s": 3831,
"text": "Get the latest breakthroughs in Machine Learning. They use AI to analyze 1000+ research papers and articles every week to provide you with the most popular summary in the industry."
},
{
"code": null,
"e": 4047,
"s": 4012,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 4186,
"s": 4047,
"text": "The popular blog with tons of helpful machine learning tutorials has a newsletter to get updates on the latest machine learning tutorials."
},
{
"code": null,
"e": 4202,
"s": 4186,
"text": "Subscribe here."
},
{
"code": null,
"e": 4412,
"s": 4202,
"text": "Curated by Nihit Desai and Rishabh Bhargava, this newsletter aims to explore what it means to develop software 2.0 and the new challenges that arise. They share their views on how to write better Software 2.0."
},
{
"code": null,
"e": 4453,
"s": 4412,
"text": "Read the latest issues & subscribe here."
},
{
"code": null,
"e": 4657,
"s": 4453,
"text": "Every week, the Batch presents the most important AI events and perspectives in a curated, easy-to-read report for engineers, enthusiasts, and business leaders, as well as a personal note from Andrew Ng."
},
{
"code": null,
"e": 4692,
"s": 4657,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 4783,
"s": 4692,
"text": "A weekly newsletter about artificial intelligence, read by more than ten thousand experts."
},
{
"code": null,
"e": 4818,
"s": 4783,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 4922,
"s": 4818,
"text": "A weekly collection of AI News and resources on Artificial Intelligence and Machine Learning. For free."
},
{
"code": null,
"e": 4957,
"s": 4922,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 5176,
"s": 4957,
"text": "Andriy Burkov, author of The Hundred-Page Machine Learning Book and the Machine Learning Engineering book, presents his newsletter with the most important artificial intelligence and machine learning news and articles."
},
{
"code": null,
"e": 5218,
"s": 5176,
"text": "Read the latest issue and subscribe here."
},
{
"code": null,
"e": 5447,
"s": 5218,
"text": "The summary of the last research papers, cool tech releases, and investments in AI to keep you up-to-date without hassle. It’s a bite-sized newsletter; in 5 minutes, you get enough to be smart about the currents of the AI world."
},
{
"code": null,
"e": 5484,
"s": 5447,
"text": "Read past issues and subscribe here."
},
{
"code": null,
"e": 5678,
"s": 5484,
"text": "Weekly summaries of AI news, straight to your inbox! Plus occasional articles, interviews, and more. Run by a couple of graduate students as a hobby, so don’t worry about marketing or the like."
},
{
"code": null,
"e": 5715,
"s": 5678,
"text": "Read past issues and subscribe here."
},
{
"code": null,
"e": 5787,
"s": 5715,
"text": "Monthly analysis of AI technology, geopolitics, research, and startups."
},
{
"code": null,
"e": 5822,
"s": 5787,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 6004,
"s": 5822,
"text": "A weekly newsletter by Louis Bouchard, creator of the channel What’s AI, who shares one paper per week, contain everything about the paper plus some bonus projects he is working on."
},
{
"code": null,
"e": 6039,
"s": 6004,
"text": "Read past issues & subscribe here."
},
{
"code": null,
"e": 6105,
"s": 6039,
"text": "That’s all the newsletters I have for you. Thank you for reading!"
},
{
"code": null,
"e": 6183,
"s": 6105,
"text": "If you have any suggestions or additions, feel free to leave a comment below!"
},
{
"code": null,
"e": 6248,
"s": 6183,
"text": "Connect with me on LinkedIn for daily resources on Data Science."
}
] |
forward_list::front() and forward_list::empty() in C++ STL - GeeksforGeeks
|
28 Sep, 2021
Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of location of only next element while list keeps track to both next and previous elements.
This function is used to reference the first element of the forward list container. This function can be used to fetch the first element of a forward list.
Syntax :
forwardlistname.front()
Parameters :
No value is needed to pass as the parameter.
Returns :
Direct reference to the first element of the container.
Examples:
Input : forward_list forwardlist{1, 2, 3, 4, 5};
forwardlist.front();
Output : 1
Input : forward_list forwardlist{0, 1, 2, 3, 4, 5};
forwardlist.front();
Output : 0
Errors and Exceptions1. If the forward list container is empty, it causes undefined behavior. 2. It has a no exception throw guarantee if the forward list is not empty.
C++
// CPP program to illustrate// Implementation of front() function#include <forward_list>#include <iostream>using namespace std; int main(){ forward_list<int> myforwardlist{ 1, 2, 3, 4, 5 }; cout << myforwardlist.front(); return 0;}
Output:
1
empty() function is used to check if the forward list container is empty or not.
Syntax :
forwardlistname.empty()
Parameters :
No parameters are passed.
Returns :
True, if list is empty
False, Otherwise
Examples:
Input : forward_list forwardlist{1, 2, 3, 4, 5};
forwardlist.empty();
Output : False
Input : forward_list forwardlist{};
forwardlist.empty();
Output : True
Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed.
C++
// CPP program to illustrate// Implementation of empty() function#include <forward_list>#include <iostream>using namespace std; int main(){ forward_list<int> myforwardlist{}; if (myforwardlist.empty()) { cout << "True"; } else { cout << "False"; } return 0;}
Output:
True
Application – front() and empty() : Given a list of integers, find the sum of the all the integers.
Input : 1, 5, 6, 3, 9, 2
Output : 26
Explanation - 1+5+6+3+9+2 = 26
Algorithm : 1. Check if the forward list is empty, if not add the front element to a variable initialized as 0, and pop the front element. 2. Repeat this step until the forward list is empty. 3. Print the final value of the variable.
C++
// CPP program to illustrate// Application of empty() function#include <forward_list>#include <iostream>using namespace std; int main(){ int sum = 0; forward_list<int> myforwardlist{ 1, 5, 6, 3, 9, 2 }; while (!myforwardlist.empty()) { sum = sum + myforwardlist.front(); myforwardlist.pop_front(); } cout << sum; return 0;}
Output
26
chhabradhanvi
cpp-containers-library
CPP-forward-list
CPP-Library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Virtual Function in C++
Bitwise Operators in C/C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
|
[
{
"code": null,
"e": 25945,
"s": 25917,
"text": "\n28 Sep, 2021"
},
{
"code": null,
"e": 26335,
"s": 25945,
"text": "Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of location of only next element while list keeps track to both next and previous elements."
},
{
"code": null,
"e": 26491,
"s": 26335,
"text": "This function is used to reference the first element of the forward list container. This function can be used to fetch the first element of a forward list."
},
{
"code": null,
"e": 26501,
"s": 26491,
"text": "Syntax : "
},
{
"code": null,
"e": 26649,
"s": 26501,
"text": "forwardlistname.front()\nParameters :\nNo value is needed to pass as the parameter.\nReturns :\nDirect reference to the first element of the container."
},
{
"code": null,
"e": 26660,
"s": 26649,
"text": "Examples: "
},
{
"code": null,
"e": 26846,
"s": 26660,
"text": "Input : forward_list forwardlist{1, 2, 3, 4, 5};\n forwardlist.front();\nOutput : 1\n\nInput : forward_list forwardlist{0, 1, 2, 3, 4, 5};\n forwardlist.front();\nOutput : 0"
},
{
"code": null,
"e": 27015,
"s": 26846,
"text": "Errors and Exceptions1. If the forward list container is empty, it causes undefined behavior. 2. It has a no exception throw guarantee if the forward list is not empty."
},
{
"code": null,
"e": 27019,
"s": 27015,
"text": "C++"
},
{
"code": "// CPP program to illustrate// Implementation of front() function#include <forward_list>#include <iostream>using namespace std; int main(){ forward_list<int> myforwardlist{ 1, 2, 3, 4, 5 }; cout << myforwardlist.front(); return 0;}",
"e": 27260,
"s": 27019,
"text": null
},
{
"code": null,
"e": 27269,
"s": 27260,
"text": "Output: "
},
{
"code": null,
"e": 27271,
"s": 27269,
"text": "1"
},
{
"code": null,
"e": 27352,
"s": 27271,
"text": "empty() function is used to check if the forward list container is empty or not."
},
{
"code": null,
"e": 27363,
"s": 27352,
"text": "Syntax : "
},
{
"code": null,
"e": 27476,
"s": 27363,
"text": "forwardlistname.empty()\nParameters :\nNo parameters are passed.\nReturns :\nTrue, if list is empty\nFalse, Otherwise"
},
{
"code": null,
"e": 27487,
"s": 27476,
"text": "Examples: "
},
{
"code": null,
"e": 27664,
"s": 27487,
"text": "Input : forward_list forwardlist{1, 2, 3, 4, 5};\n forwardlist.empty();\nOutput : False\n\nInput : forward_list forwardlist{};\n forwardlist.empty();\nOutput : True"
},
{
"code": null,
"e": 27770,
"s": 27664,
"text": "Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed."
},
{
"code": null,
"e": 27774,
"s": 27770,
"text": "C++"
},
{
"code": "// CPP program to illustrate// Implementation of empty() function#include <forward_list>#include <iostream>using namespace std; int main(){ forward_list<int> myforwardlist{}; if (myforwardlist.empty()) { cout << \"True\"; } else { cout << \"False\"; } return 0;}",
"e": 28065,
"s": 27774,
"text": null
},
{
"code": null,
"e": 28074,
"s": 28065,
"text": "Output: "
},
{
"code": null,
"e": 28079,
"s": 28074,
"text": "True"
},
{
"code": null,
"e": 28180,
"s": 28079,
"text": "Application – front() and empty() : Given a list of integers, find the sum of the all the integers. "
},
{
"code": null,
"e": 28250,
"s": 28180,
"text": "Input : 1, 5, 6, 3, 9, 2\nOutput : 26\nExplanation - 1+5+6+3+9+2 = 26"
},
{
"code": null,
"e": 28484,
"s": 28250,
"text": "Algorithm : 1. Check if the forward list is empty, if not add the front element to a variable initialized as 0, and pop the front element. 2. Repeat this step until the forward list is empty. 3. Print the final value of the variable."
},
{
"code": null,
"e": 28488,
"s": 28484,
"text": "C++"
},
{
"code": "// CPP program to illustrate// Application of empty() function#include <forward_list>#include <iostream>using namespace std; int main(){ int sum = 0; forward_list<int> myforwardlist{ 1, 5, 6, 3, 9, 2 }; while (!myforwardlist.empty()) { sum = sum + myforwardlist.front(); myforwardlist.pop_front(); } cout << sum; return 0;}",
"e": 28844,
"s": 28488,
"text": null
},
{
"code": null,
"e": 28852,
"s": 28844,
"text": "Output "
},
{
"code": null,
"e": 28855,
"s": 28852,
"text": "26"
},
{
"code": null,
"e": 28871,
"s": 28857,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 28894,
"s": 28871,
"text": "cpp-containers-library"
},
{
"code": null,
"e": 28911,
"s": 28894,
"text": "CPP-forward-list"
},
{
"code": null,
"e": 28923,
"s": 28911,
"text": "CPP-Library"
},
{
"code": null,
"e": 28927,
"s": 28923,
"text": "STL"
},
{
"code": null,
"e": 28931,
"s": 28927,
"text": "C++"
},
{
"code": null,
"e": 28935,
"s": 28931,
"text": "STL"
},
{
"code": null,
"e": 28939,
"s": 28935,
"text": "CPP"
},
{
"code": null,
"e": 29037,
"s": 28939,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29056,
"s": 29037,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29099,
"s": 29056,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29123,
"s": 29099,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 29147,
"s": 29123,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 29174,
"s": 29147,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 29205,
"s": 29174,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 29225,
"s": 29205,
"text": "Constructors in C++"
},
{
"code": null,
"e": 29253,
"s": 29225,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 29281,
"s": 29253,
"text": "Socket Programming in C/C++"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.