title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Video Streaming in Web Browsers with OpenCV & Flask | by Nakul Lakhotia | Towards Data Science | You took the trouble of installing a webcam or a surveillance camera at your home, or office or any place that you own. Obviously, you would want to be able to watch the live stream of the video anyplace and anytime you like.
Most of the people use IP cameras (Internet Protocol cameras) instead of CCTV (Closed-Circuit Television) for surveillance purposes as they have a much higher resolution and reduced cost for cabling. You can find the detailed differences between both these systems here. In this article we will be focusing on IP cameras.
IP camera, is a type of digital video camera that receives control data and sends image data via an IP network and require no local recording device. Most IP cameras are RTSP (Real Time Streaming Protocol) based and is therefore “not supported” natively in internet browsers.
In this article we will learn how to do that using Computer Vision.
Computer Vision is an interdisciplinary field that deals with how computers can be made to gain a high-level understanding from digital images or videos.
For implementing the computer vision part we will use the OpenCV module in Python and to display the live stream in the web browser we will use the Flask web framework. Before diving into the coding part let us first know about these modules briefly. If you are already familiar with these modules, you can directly jump to the next section.
According to the Wikipedia, Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.
According to GeeksForGeeks, OpenCV is the huge open-source library for the computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems.
You can use the ‘pip install flask’ and ‘pip install opencv-python’ command. I use the PyCharm IDE to develop flask applications. To easily install libraries in PyCharm follow these steps.
We will now import the necessary libraries and initialize our flask app.
#Import necessary librariesfrom flask import Flask, render_template, Responseimport cv2#Initialize the Flask appapp = Flask(__name__)
Create a VideoCapture() object to trigger the camera and read the first image/frame of the video. We can either provide the path of the video file or use numbers to specify the use of local webcam. To trigger the webcam we pass ‘0’ as the argument. To capture the live feed from an IP Camera we provide the RTSP link as the argument. To know the RTSP address for your IP Camera go through this — Finding RTSP addresses.
camera = cv2.VideoCapture(0)'''for ip camera use - rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp' for local webcam use cv2.VideoCapture(0)'''
The gen_frames() function enters a loop where it continuously returns frames from the camera as response chunks. The function asks the camera to provide a frame then it yields with this frame formatted as a response chunk with a content type of image/jpeg, as shown above. The code is shown below :
Routes refer to URL patterns of an app (such as myapp.com/home or myapp.com/about). @app.route("/") is a Python decorator that Flask provides to assign URLs in our app to functions easily.
@app.route('/')def index(): return render_template('index.html')
The decorator is telling our @app that whenever a user visits our app domain (localhost:5000 for local servers) at the given .route(), execute the index() function. Flask uses the Jinja template library to render templates. In our application, we will use templates to render HTML which will display in the browser.
@app.route('/video_feed')def video_feed(): return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
The ‘/video_feed’ route returns the streaming response. Because this stream returns the images that are to be displayed in the web page, the URL to this route is in the “src” attribute of the image tag (see ‘index.html’ below). The browser will automatically keep the image element updated by displaying the stream of JPEG images in it, since multipart responses are supported in most/all browsers
Let’s have a look at our index.html file :
<body><div class="container"> <div class="row"> <div class="col-lg-8 offset-lg-2"> <h3 class="mt-5">Live Streaming</h3> <img src="{{ url_for('video_feed') }}" width="100%"> </div> </div></div></body>
if __name__ == "__main__": app.run(debug=True)
app.run() is called and the web-application is hosted locally on [localhost:5000].
“debug=True” makes sure that we don’t require to run our app every time we makes changes, we can simply refresh our web page to see the changes while the server is still running.
The project is saved in a folder called “Camera Detection”. We run the ‘app.py’ file. On running this file, our application is hosted in the local server at port 5000.
You can simply type “localhost:5000” on your web browser to open your web-application after running ‘app.py’
app.py — This is the Flask application we created above
templates — This folder contains our ‘index.html’ file. This is mandatory in Flask while rendering templates. All HTML files are placed under this folder.
Let’s see what happens when we run ‘app.py’ :
On clicking on the provided URL, our web browser opens up with the live feed. Since I used VideoCapture(0) above, the webcam feed is displayed on the browser:
And that’s it !!
You have the live video stream from your IP camera/webcam on your web browser which can be used for security and surveillance purposes.
Refer to my GitHub Code.
Note: All the resources that you will require to get started have been mentioned and their links provided in this article as well. I hope you make good use of it :)
I hope this article will get you interested in trying out new things in the Computer Vision domain and help you add to your knowledge. If you have enjoyed reading this article do share it with your friends and family. Thank you for your time. | [
{
"code": null,
"e": 398,
"s": 172,
"text": "You took the trouble of installing a webcam or a surveillance camera at your home, or office or any place that you own. Obviously, you would want to be able to watch the live stream of the video anyplace and anytime you like."
},
{
"code": null,
"e": 720,
"s": 398,
"text": "Most of the people use IP cameras (Internet Protocol cameras) instead of CCTV (Closed-Circuit Television) for surveillance purposes as they have a much higher resolution and reduced cost for cabling. You can find the detailed differences between both these systems here. In this article we will be focusing on IP cameras."
},
{
"code": null,
"e": 996,
"s": 720,
"text": "IP camera, is a type of digital video camera that receives control data and sends image data via an IP network and require no local recording device. Most IP cameras are RTSP (Real Time Streaming Protocol) based and is therefore “not supported” natively in internet browsers."
},
{
"code": null,
"e": 1064,
"s": 996,
"text": "In this article we will learn how to do that using Computer Vision."
},
{
"code": null,
"e": 1218,
"s": 1064,
"text": "Computer Vision is an interdisciplinary field that deals with how computers can be made to gain a high-level understanding from digital images or videos."
},
{
"code": null,
"e": 1560,
"s": 1218,
"text": "For implementing the computer vision part we will use the OpenCV module in Python and to display the live stream in the web browser we will use the Flask web framework. Before diving into the coding part let us first know about these modules briefly. If you are already familiar with these modules, you can directly jump to the next section."
},
{
"code": null,
"e": 1880,
"s": 1560,
"text": "According to the Wikipedia, Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions."
},
{
"code": null,
"e": 2108,
"s": 1880,
"text": "According to GeeksForGeeks, OpenCV is the huge open-source library for the computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems."
},
{
"code": null,
"e": 2297,
"s": 2108,
"text": "You can use the ‘pip install flask’ and ‘pip install opencv-python’ command. I use the PyCharm IDE to develop flask applications. To easily install libraries in PyCharm follow these steps."
},
{
"code": null,
"e": 2370,
"s": 2297,
"text": "We will now import the necessary libraries and initialize our flask app."
},
{
"code": null,
"e": 2504,
"s": 2370,
"text": "#Import necessary librariesfrom flask import Flask, render_template, Responseimport cv2#Initialize the Flask appapp = Flask(__name__)"
},
{
"code": null,
"e": 2924,
"s": 2504,
"text": "Create a VideoCapture() object to trigger the camera and read the first image/frame of the video. We can either provide the path of the video file or use numbers to specify the use of local webcam. To trigger the webcam we pass ‘0’ as the argument. To capture the live feed from an IP Camera we provide the RTSP link as the argument. To know the RTSP address for your IP Camera go through this — Finding RTSP addresses."
},
{
"code": null,
"e": 3130,
"s": 2924,
"text": "camera = cv2.VideoCapture(0)'''for ip camera use - rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp' for local webcam use cv2.VideoCapture(0)'''"
},
{
"code": null,
"e": 3429,
"s": 3130,
"text": "The gen_frames() function enters a loop where it continuously returns frames from the camera as response chunks. The function asks the camera to provide a frame then it yields with this frame formatted as a response chunk with a content type of image/jpeg, as shown above. The code is shown below :"
},
{
"code": null,
"e": 3618,
"s": 3429,
"text": "Routes refer to URL patterns of an app (such as myapp.com/home or myapp.com/about). @app.route(\"/\") is a Python decorator that Flask provides to assign URLs in our app to functions easily."
},
{
"code": null,
"e": 3686,
"s": 3618,
"text": "@app.route('/')def index(): return render_template('index.html')"
},
{
"code": null,
"e": 4002,
"s": 3686,
"text": "The decorator is telling our @app that whenever a user visits our app domain (localhost:5000 for local servers) at the given .route(), execute the index() function. Flask uses the Jinja template library to render templates. In our application, we will use templates to render HTML which will display in the browser."
},
{
"code": null,
"e": 4132,
"s": 4002,
"text": "@app.route('/video_feed')def video_feed(): return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')"
},
{
"code": null,
"e": 4530,
"s": 4132,
"text": "The ‘/video_feed’ route returns the streaming response. Because this stream returns the images that are to be displayed in the web page, the URL to this route is in the “src” attribute of the image tag (see ‘index.html’ below). The browser will automatically keep the image element updated by displaying the stream of JPEG images in it, since multipart responses are supported in most/all browsers"
},
{
"code": null,
"e": 4573,
"s": 4530,
"text": "Let’s have a look at our index.html file :"
},
{
"code": null,
"e": 4816,
"s": 4573,
"text": "<body><div class=\"container\"> <div class=\"row\"> <div class=\"col-lg-8 offset-lg-2\"> <h3 class=\"mt-5\">Live Streaming</h3> <img src=\"{{ url_for('video_feed') }}\" width=\"100%\"> </div> </div></div></body>"
},
{
"code": null,
"e": 4866,
"s": 4816,
"text": "if __name__ == \"__main__\": app.run(debug=True)"
},
{
"code": null,
"e": 4949,
"s": 4866,
"text": "app.run() is called and the web-application is hosted locally on [localhost:5000]."
},
{
"code": null,
"e": 5128,
"s": 4949,
"text": "“debug=True” makes sure that we don’t require to run our app every time we makes changes, we can simply refresh our web page to see the changes while the server is still running."
},
{
"code": null,
"e": 5296,
"s": 5128,
"text": "The project is saved in a folder called “Camera Detection”. We run the ‘app.py’ file. On running this file, our application is hosted in the local server at port 5000."
},
{
"code": null,
"e": 5405,
"s": 5296,
"text": "You can simply type “localhost:5000” on your web browser to open your web-application after running ‘app.py’"
},
{
"code": null,
"e": 5461,
"s": 5405,
"text": "app.py — This is the Flask application we created above"
},
{
"code": null,
"e": 5616,
"s": 5461,
"text": "templates — This folder contains our ‘index.html’ file. This is mandatory in Flask while rendering templates. All HTML files are placed under this folder."
},
{
"code": null,
"e": 5662,
"s": 5616,
"text": "Let’s see what happens when we run ‘app.py’ :"
},
{
"code": null,
"e": 5821,
"s": 5662,
"text": "On clicking on the provided URL, our web browser opens up with the live feed. Since I used VideoCapture(0) above, the webcam feed is displayed on the browser:"
},
{
"code": null,
"e": 5838,
"s": 5821,
"text": "And that’s it !!"
},
{
"code": null,
"e": 5974,
"s": 5838,
"text": "You have the live video stream from your IP camera/webcam on your web browser which can be used for security and surveillance purposes."
},
{
"code": null,
"e": 5999,
"s": 5974,
"text": "Refer to my GitHub Code."
},
{
"code": null,
"e": 6164,
"s": 5999,
"text": "Note: All the resources that you will require to get started have been mentioned and their links provided in this article as well. I hope you make good use of it :)"
}
]
|
A hidden gem: df.select_dtypes(). A micro-post about a Pandas function... | by Patrick Coffey | Towards Data Science | How many times have you gone to feed a pandas DataFrame into a utility function form another library and it fails due to there being object columns. Maybe it was a graph from seaborn? (we’re looking at you sns.clustermaps()).
>>> sns.clustermap( df, method='ward', cmap="YlGnBu", standard_scale=1 )TypeError: unsupported operand type(s) for -: 'str' and 'str'
So, I build a list of all the data types of my columns and filter those non numeric columns out, and pass that resulting data frame into the function that only expected numeric columns.
>>> numeric_cols = [ col for col, dtype in df.dtypes.items() if dtype=='float64' ]>>> print(numeric_cols)['col1', 'col2']>>> sns.clustermap( df[numeric_cols], method='ward', cmap="YlGnBu", standard_scale=1 )
As I was investigating some data relating to gene expressions in yeasts yesterday, it got me thinking. There has to be a better way. This concept of filtering a DataFrame’s columns by datatype should be common enough to be a one-liner! Well, it turns out it is, and even though I thought I had crawled to documentation enough times to be across the pandas API, it turns out there’s always a new hidden gem!
Pandas DataFrames have a built in method called select_dtypes() which does exactly what I wanted. And rewriting the above code to use this new (to me) function looks like the following (notice select_dtypes() takes a list, you can filter for multiple data types!):
>>> sns.clustermap( df.select_dtypes(['number']), method='ward', cmap="YlGnBu", standard_scale=1 )
I’m sure most of you are already well across this since (I did a git blame on the pandas git repo to see when it was added: 2014 🤦). Anyway, I hope maybe someone will find this as helpful as I have. Happy coding! | [
{
"code": null,
"e": 398,
"s": 172,
"text": "How many times have you gone to feed a pandas DataFrame into a utility function form another library and it fails due to there being object columns. Maybe it was a graph from seaborn? (we’re looking at you sns.clustermaps())."
},
{
"code": null,
"e": 566,
"s": 398,
"text": ">>> sns.clustermap( df, method='ward', cmap=\"YlGnBu\", standard_scale=1 )TypeError: unsupported operand type(s) for -: 'str' and 'str'"
},
{
"code": null,
"e": 752,
"s": 566,
"text": "So, I build a list of all the data types of my columns and filter those non numeric columns out, and pass that resulting data frame into the function that only expected numeric columns."
},
{
"code": null,
"e": 1028,
"s": 752,
"text": ">>> numeric_cols = [ col for col, dtype in df.dtypes.items() if dtype=='float64' ]>>> print(numeric_cols)['col1', 'col2']>>> sns.clustermap( df[numeric_cols], method='ward', cmap=\"YlGnBu\", standard_scale=1 )"
},
{
"code": null,
"e": 1435,
"s": 1028,
"text": "As I was investigating some data relating to gene expressions in yeasts yesterday, it got me thinking. There has to be a better way. This concept of filtering a DataFrame’s columns by datatype should be common enough to be a one-liner! Well, it turns out it is, and even though I thought I had crawled to documentation enough times to be across the pandas API, it turns out there’s always a new hidden gem!"
},
{
"code": null,
"e": 1700,
"s": 1435,
"text": "Pandas DataFrames have a built in method called select_dtypes() which does exactly what I wanted. And rewriting the above code to use this new (to me) function looks like the following (notice select_dtypes() takes a list, you can filter for multiple data types!):"
},
{
"code": null,
"e": 1833,
"s": 1700,
"text": ">>> sns.clustermap( df.select_dtypes(['number']), method='ward', cmap=\"YlGnBu\", standard_scale=1 )"
}
]
|
Python - HTTP Response | The http or Hyper Text Transfer Protocol works on client server model. Usually the web browser is the client and the computer hosting the website is the
server. Upon receiving a request from client the server generates a response and sends it back to the client in certain format.
After receiving and interpreting a request message, a server responds with an HTTP response message:
A Status-line
Zero or more header (General|Response|Entity) fields followed by CRLF
An empty line (i.e., a line with nothing preceding the CRLF)
indicating the end of the header fields
Optionally a message-body
A Status-line
Zero or more header (General|Response|Entity) fields followed by CRLF
An empty line (i.e., a line with nothing preceding the CRLF)
indicating the end of the header fields
Optionally a message-body
The following sections explain each of the entities used in an HTTP response message.
A Status-Line consists of the protocol version followed by a numeric status code and its associated textual phrase. The elements are separated by space SP characters.
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
A server supporting HTTP version 1.1 will return the following version information:
HTTP-Version = HTTP/1.1
The Status-Code element is a 3-digit integer where first digit of the Status-Code defines the class of response and the last two digits do not have any categorization role. There are 5 values for the first digit:
It means the request was received and the process is continuing.
It means the action was successfully received, understood, and accepted.
It means further action must be taken in order to complete the request.
It means the request contains incorrect syntax or cannot be fulfilled.
It means the server failed to fulfill an apparently valid request.
HTTP status codes are extensible and HTTP applications are not required to understand the meaning of all registered status codes.
In the below python program we use the urllib3 module to make a http GET request and receive the response containing the data. It also provides the
response code which is also managed by the functions in the module. The PoolManager object handles all of the details of connection pooling and also handles the thread safety.
import urllib3
http = urllib3.PoolManager()
resp = http.request('GET', 'http://tutorialspoint.com/robots.txt')
print resp.data
# get the status of the response
print resp.status
When we run the above program, we get the following output −
User-agent: *
Disallow: /tmp
Disallow: /logs
Disallow: /rate/*
Disallow: /cgi-bin/*
Disallow: /videotutorials/video_course_view.php?*
Disallow: /videotutorials/course_view.php?*
Disallow: /videos/*
Disallow: /*/*_question_bank/*
Disallow: //*/*/*/*/src/*
200
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2608,
"s": 2326,
"text": "The http or Hyper Text Transfer Protocol works on client server model. Usually the web browser is the client and the computer hosting the website is the \nserver. Upon receiving a request from client the server generates a response and sends it back to the client in certain format."
},
{
"code": null,
"e": 2709,
"s": 2608,
"text": "After receiving and interpreting a request message, a server responds with an HTTP response message:"
},
{
"code": null,
"e": 2923,
"s": 2709,
"text": "\nA Status-line\nZero or more header (General|Response|Entity) fields followed by CRLF\nAn empty line (i.e., a line with nothing preceding the CRLF) \nindicating the end of the header fields\nOptionally a message-body\n"
},
{
"code": null,
"e": 2937,
"s": 2923,
"text": "A Status-line"
},
{
"code": null,
"e": 3007,
"s": 2937,
"text": "Zero or more header (General|Response|Entity) fields followed by CRLF"
},
{
"code": null,
"e": 3109,
"s": 3007,
"text": "An empty line (i.e., a line with nothing preceding the CRLF) \nindicating the end of the header fields"
},
{
"code": null,
"e": 3135,
"s": 3109,
"text": "Optionally a message-body"
},
{
"code": null,
"e": 3221,
"s": 3135,
"text": "The following sections explain each of the entities used in an HTTP response message."
},
{
"code": null,
"e": 3388,
"s": 3221,
"text": "A Status-Line consists of the protocol version followed by a numeric status code and its associated textual phrase. The elements are separated by space SP characters."
},
{
"code": null,
"e": 3453,
"s": 3388,
"text": "Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF\n"
},
{
"code": null,
"e": 3537,
"s": 3453,
"text": "A server supporting HTTP version 1.1 will return the following version information:"
},
{
"code": null,
"e": 3562,
"s": 3537,
"text": "HTTP-Version = HTTP/1.1\n"
},
{
"code": null,
"e": 3775,
"s": 3562,
"text": "The Status-Code element is a 3-digit integer where first digit of the Status-Code defines the class of response and the last two digits do not have any categorization role. There are 5 values for the first digit:"
},
{
"code": null,
"e": 3841,
"s": 3775,
"text": " It means the request was received and the process is continuing."
},
{
"code": null,
"e": 3916,
"s": 3841,
"text": " It means the action was successfully received, understood, and accepted."
},
{
"code": null,
"e": 3989,
"s": 3916,
"text": " It means further action must be taken in order to complete the request."
},
{
"code": null,
"e": 4061,
"s": 3989,
"text": " It means the request contains incorrect syntax or cannot be fulfilled."
},
{
"code": null,
"e": 4129,
"s": 4061,
"text": " It means the server failed to fulfill an apparently valid request."
},
{
"code": null,
"e": 4259,
"s": 4129,
"text": "HTTP status codes are extensible and HTTP applications are not required to understand the meaning of all registered status codes."
},
{
"code": null,
"e": 4583,
"s": 4259,
"text": "In the below python program we use the urllib3 module to make a http GET request and receive the response containing the data. It also provides the\nresponse code which is also managed by the functions in the module. The PoolManager object handles all of the details of connection pooling and also handles the thread safety."
},
{
"code": null,
"e": 4763,
"s": 4583,
"text": "import urllib3\nhttp = urllib3.PoolManager()\n\nresp = http.request('GET', 'http://tutorialspoint.com/robots.txt')\nprint resp.data\n\n# get the status of the response\nprint resp.status"
},
{
"code": null,
"e": 4824,
"s": 4763,
"text": "When we run the above program, we get the following output −"
},
{
"code": null,
"e": 5085,
"s": 4824,
"text": "User-agent: *\nDisallow: /tmp\nDisallow: /logs\nDisallow: /rate/*\nDisallow: /cgi-bin/*\nDisallow: /videotutorials/video_course_view.php?*\nDisallow: /videotutorials/course_view.php?*\nDisallow: /videos/*\nDisallow: /*/*_question_bank/*\nDisallow: //*/*/*/*/src/*\n\n200\n"
},
{
"code": null,
"e": 5122,
"s": 5085,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5138,
"s": 5122,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5171,
"s": 5138,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5190,
"s": 5171,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5225,
"s": 5190,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 5247,
"s": 5225,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5281,
"s": 5247,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5309,
"s": 5281,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5344,
"s": 5309,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5358,
"s": 5344,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5391,
"s": 5358,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5408,
"s": 5391,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5415,
"s": 5408,
"text": " Print"
},
{
"code": null,
"e": 5426,
"s": 5415,
"text": " Add Notes"
}
]
|
Node.js console.timeStamp() Method - GeeksforGeeks | 06 Sep, 2020
The console module provides a simple debugging console that is provided by web browsers which export two specific components:
A Console class that can be used to write to any Node.js stream. Example: console.log(), console.error(), etc.
A global console that can be used without importing console. Example: process.stdout, process.stderr, etc.
The console.timeStamp() (Added in v8.0.0) method is an inbuilt application programming interface of the ‘console‘ module which does not display anything unless used in the inspector. This method adds an event with the label ‘label‘ to the Timeline panel of the inspector.
Note: The global console methods are neither consistently synchronous nor consistently asynchronous.
Syntax:
console.timeStamp([label])
Parameters: This function accepts a single parameter as mentioned above and described below:
label <string>: It accepts the label name that is further to be used in the inspector.
Return Value: It doesn’t print anything in console instead, prints timestamp at the call in Inspector.
The Below examples illustrate the use of console.timeStamp() method in Node.js.
Example 1: Filename: index.js
// Node.js program to demonstrate the // console.timeStamp() Method // Starting newProfile() console profileconsole.profile("Hello()"); // Printing timestampconsole.timeStamp("Hello()"); // Finishing profileconsole.profileEnd("Hello()");
Run index.js file using the following command:
node index.js
Output in Console:
*Doesn’t print anything in Console...
Output in Inspector(edge):
Example 2: Filename: index.js
// Node.js program to demonstrate the // console.timeStamp() Method // Starting Hello() console profileconsole.profile("Hello()"); // Printing timeStampconsole.timeStamp("Hello()"); // Performing some actionfor(var i=0; i<1; i++) { console.log("doing some task...");} // Finishing profileconsole.profileEnd("Hello()"); // Printing timeStamp againconsole.timeStamp("Hello()");
Run index.js file using the following command:
node index.js
Output in Console:
Doing some task...
Output in Inspector (edge):
Reference: https://nodejs.org/api/console.html#console_console_timestamp_label
Node.js-console-module
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
JWT Authentication with Node.js
Node.js Event Loop
Mongoose Populate() Method
Mongoose find() Function
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24842,
"s": 24814,
"text": "\n06 Sep, 2020"
},
{
"code": null,
"e": 24968,
"s": 24842,
"text": "The console module provides a simple debugging console that is provided by web browsers which export two specific components:"
},
{
"code": null,
"e": 25079,
"s": 24968,
"text": "A Console class that can be used to write to any Node.js stream. Example: console.log(), console.error(), etc."
},
{
"code": null,
"e": 25186,
"s": 25079,
"text": "A global console that can be used without importing console. Example: process.stdout, process.stderr, etc."
},
{
"code": null,
"e": 25458,
"s": 25186,
"text": "The console.timeStamp() (Added in v8.0.0) method is an inbuilt application programming interface of the ‘console‘ module which does not display anything unless used in the inspector. This method adds an event with the label ‘label‘ to the Timeline panel of the inspector."
},
{
"code": null,
"e": 25559,
"s": 25458,
"text": "Note: The global console methods are neither consistently synchronous nor consistently asynchronous."
},
{
"code": null,
"e": 25567,
"s": 25559,
"text": "Syntax:"
},
{
"code": null,
"e": 25594,
"s": 25567,
"text": "console.timeStamp([label])"
},
{
"code": null,
"e": 25687,
"s": 25594,
"text": "Parameters: This function accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 25774,
"s": 25687,
"text": "label <string>: It accepts the label name that is further to be used in the inspector."
},
{
"code": null,
"e": 25877,
"s": 25774,
"text": "Return Value: It doesn’t print anything in console instead, prints timestamp at the call in Inspector."
},
{
"code": null,
"e": 25957,
"s": 25877,
"text": "The Below examples illustrate the use of console.timeStamp() method in Node.js."
},
{
"code": null,
"e": 25989,
"s": 25957,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the // console.timeStamp() Method // Starting newProfile() console profileconsole.profile(\"Hello()\"); // Printing timestampconsole.timeStamp(\"Hello()\"); // Finishing profileconsole.profileEnd(\"Hello()\");",
"e": 26230,
"s": 25989,
"text": null
},
{
"code": null,
"e": 26277,
"s": 26230,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 26291,
"s": 26277,
"text": "node index.js"
},
{
"code": null,
"e": 26310,
"s": 26291,
"text": "Output in Console:"
},
{
"code": null,
"e": 26348,
"s": 26310,
"text": "*Doesn’t print anything in Console..."
},
{
"code": null,
"e": 26375,
"s": 26348,
"text": "Output in Inspector(edge):"
},
{
"code": null,
"e": 26407,
"s": 26375,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the // console.timeStamp() Method // Starting Hello() console profileconsole.profile(\"Hello()\"); // Printing timeStampconsole.timeStamp(\"Hello()\"); // Performing some actionfor(var i=0; i<1; i++) { console.log(\"doing some task...\");} // Finishing profileconsole.profileEnd(\"Hello()\"); // Printing timeStamp againconsole.timeStamp(\"Hello()\");",
"e": 26789,
"s": 26407,
"text": null
},
{
"code": null,
"e": 26836,
"s": 26789,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 26850,
"s": 26836,
"text": "node index.js"
},
{
"code": null,
"e": 26869,
"s": 26850,
"text": "Output in Console:"
},
{
"code": null,
"e": 26888,
"s": 26869,
"text": "Doing some task..."
},
{
"code": null,
"e": 26916,
"s": 26888,
"text": "Output in Inspector (edge):"
},
{
"code": null,
"e": 26995,
"s": 26916,
"text": "Reference: https://nodejs.org/api/console.html#console_console_timestamp_label"
},
{
"code": null,
"e": 27018,
"s": 26995,
"text": "Node.js-console-module"
},
{
"code": null,
"e": 27034,
"s": 27018,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 27042,
"s": 27034,
"text": "Node.js"
},
{
"code": null,
"e": 27059,
"s": 27042,
"text": "Web Technologies"
},
{
"code": null,
"e": 27157,
"s": 27059,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27166,
"s": 27157,
"text": "Comments"
},
{
"code": null,
"e": 27179,
"s": 27166,
"text": "Old Comments"
},
{
"code": null,
"e": 27216,
"s": 27179,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 27248,
"s": 27216,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 27267,
"s": 27248,
"text": "Node.js Event Loop"
},
{
"code": null,
"e": 27294,
"s": 27267,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 27319,
"s": 27294,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 27361,
"s": 27319,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27404,
"s": 27361,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27466,
"s": 27404,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27516,
"s": 27466,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
MySQL increment a database field by 1? | You can increment a database using update command. The syntax is as follows −
UPDATE yourTableName
set yourColumnName=yourColumnName+1
where condition;
To understand the above syntax, let us first create a table. The query to create a table is as follows −
mysql> create table IncrementBy1
-> (
-> Id int,
-> Name varchar(100),
-> CounterLogin int
-> );
Query OK, 0 rows affected (0.63 sec)
Insert some records using insert command. The query to insert records in the table is as follows −
mysql> insert into IncrementBy1 values(100,'John',30);
Query OK, 1 row affected (0.17 sec)
mysql> insert into IncrementBy1 values(101,'Carol',50);
Query OK, 1 row affected (0.15 sec)
mysql> insert into IncrementBy1 values(102,'Bob',89);
Query OK, 1 row affected (0.25 sec)
mysql> insert into IncrementBy1 values(103,'Mike',99);
Query OK, 1 row affected (0.18 sec)
mysql> insert into IncrementBy1 values(104,'Sam',199);
Query OK, 1 row affected (0.36 sec)
mysql> insert into IncrementBy1 values(105,'Tom',999);
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from IncrementBy1;
+------+-------+--------------+
| Id | Name | CounterLogin |
+------+-------+--------------+
| 100 | John | 30 |
| 101 | Carol | 50 |
| 102 | Bob | 89 |
| 103 | Mike | 99 |
| 104 | Sam | 199 |
| 105 | Tom | 999 |
+------+-------+--------------+
6 rows in set (0.00 sec)
Here is the query that increments the database field by 1 −
mysql> update IncrementBy1
-> set CounterLogin=CounterLogin+1
-> where Id=105;
Query OK, 1 row affected (0.45 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Now you can check the particular record is incremented or not. The value 999 has been incremented with 1 since we are incrementing the value where Id=105 as shown above.
The following is the query to check the record −
mysql> select *from IncrementBy1 where Id=105;
+------+------+--------------+
| Id | Name | CounterLogin |
+------+------+--------------+
| 105 | Tom | 1 000 |
+------+------+--------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1140,
"s": 1062,
"text": "You can increment a database using update command. The syntax is as follows −"
},
{
"code": null,
"e": 1214,
"s": 1140,
"text": "UPDATE yourTableName\nset yourColumnName=yourColumnName+1\nwhere condition;"
},
{
"code": null,
"e": 1319,
"s": 1214,
"text": "To understand the above syntax, let us first create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1468,
"s": 1319,
"text": "mysql> create table IncrementBy1\n -> (\n -> Id int,\n -> Name varchar(100),\n -> CounterLogin int\n -> );\nQuery OK, 0 rows affected (0.63 sec)"
},
{
"code": null,
"e": 1567,
"s": 1468,
"text": "Insert some records using insert command. The query to insert records in the table is as follows −"
},
{
"code": null,
"e": 2118,
"s": 1567,
"text": "mysql> insert into IncrementBy1 values(100,'John',30);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into IncrementBy1 values(101,'Carol',50);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into IncrementBy1 values(102,'Bob',89);\nQuery OK, 1 row affected (0.25 sec)\n\nmysql> insert into IncrementBy1 values(103,'Mike',99);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into IncrementBy1 values(104,'Sam',199);\nQuery OK, 1 row affected (0.36 sec)\n\nmysql> insert into IncrementBy1 values(105,'Tom',999);\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 2203,
"s": 2118,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2237,
"s": 2203,
"text": "mysql> select *from IncrementBy1;"
},
{
"code": null,
"e": 2582,
"s": 2237,
"text": "+------+-------+--------------+\n| Id | Name | CounterLogin |\n+------+-------+--------------+\n| 100 | John | 30 |\n| 101 | Carol | 50 |\n| 102 | Bob | 89 |\n| 103 | Mike | 99 |\n| 104 | Sam | 199 |\n| 105 | Tom | 999 |\n+------+-------+--------------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2642,
"s": 2582,
"text": "Here is the query that increments the database field by 1 −"
},
{
"code": null,
"e": 2802,
"s": 2642,
"text": "mysql> update IncrementBy1\n -> set CounterLogin=CounterLogin+1\n -> where Id=105;\nQuery OK, 1 row affected (0.45 sec)\nRows matched: 1 Changed: 1 Warnings: 0"
},
{
"code": null,
"e": 2972,
"s": 2802,
"text": "Now you can check the particular record is incremented or not. The value 999 has been incremented with 1 since we are incrementing the value where Id=105 as shown above."
},
{
"code": null,
"e": 3021,
"s": 2972,
"text": "The following is the query to check the record −"
},
{
"code": null,
"e": 3068,
"s": 3021,
"text": "mysql> select *from IncrementBy1 where Id=105;"
},
{
"code": null,
"e": 3247,
"s": 3068,
"text": "+------+------+--------------+\n| Id | Name | CounterLogin |\n+------+------+--------------+\n| 105 | Tom | 1 000 |\n+------+------+--------------+\n1 row in set (0.00 sec)"
}
]
|
From Pandas to PySpark with Koalas | by Maria Karanasou | Towards Data Science | For those who are familiar with pandas DataFrames, switching to PySpark can be quite confusing. The API is not the same, and when switching to a distributed nature, some things are being done quite differently because of the restrictions imposed by that nature.
I recently stumbled upon Koalas from a very interesting Databricks presentation about Apache Spark 3.0, Delta Lake and Koalas, and thought that it would be nice to explore it.
The Koalas project makes data scientists more productive when interacting with big data, by implementing the pandas DataFrame API on top of Apache Spark.
pandas is the de facto standard (single-node) DataFrame implementation in Python, while Spark is the de facto standard for big data processing. With this package, you can:
- Be immediately productive with Spark, with no learning curve, if you are already familiar with pandas.
- Have a single codebase that works both with pandas (tests, smaller datasets) and with Spark (distributed datasets).
source: https://koalas.readthedocs.io/en/latest/index.html
Koalas supports ≥ Python 3.5 and from what I can see from the docs, PySpark 2.4.x. Dependencies include pandas ≥ 0.23.0, pyarrow ≥ 0.10 for using columnar in-memory format for better vector manipulation performance and matplotlib ≥ 3.0.0 for plotting.
The different ways to install Koalas are listed here:
koalas.readthedocs.io
But let’s start simple with:
pip install koalas and pip install pyspark
Keep in mind the dependencies mentioned above.
Given the following data:
import pandas as pdfrom databricks import koalas as ksfrom pyspark.sql import SparkSessiondata = {'a': [1, 2, 3, 4, 5, 6], 'b': [100, 200, 300, 400, 500, 600], 'c': ["one", "two", "three", "four", "five", "six"]}index = [10, 20, 30, 40, 50, 60]
You can either start from a pandas DataFrame:
pdf = pd.DataFrame(data, index=index)# from a pandas dataframekdf = ks.from_pandas(pdf)
From a Koalas Dataframe:
# start from raw datakdf = ks.DataFrame(data, index=index)
Or from a spark Dataframe (one way):
# creating a spark dataframe from a pandas dataframesdf2 = spark_session.createDataFrame(pdf)# and then converting the spark dataframe to a koalas dataframekdf = sdf.to_koalas('index')
A full simple example with output:
The API between Pandas and Koalas is more or less the same. More examples in the official documentation:
koalas.readthedocs.io
Some notes on the Koalas project:
If you are starting from scratch with no previous knowledge of Pandas, then diving in straight to PySpark would probably be a better way to learn.
Some functions may be missing — the missing functions are documented here
Some behavior may be different (e.g. Null vs NaN, where NaN is used with Koalas and is more coherent with Pandas and Null with Spark)
Remember that since it is using Spark under the hood, some operations are lazy, meaning they are not really evaluated and executed before there is a Spark action, like printing out the top 20 rows.
I do have some concerns regarding the efficiency of some of the operations, e.g. .to_koalas() gives a No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation. warning, which seems to be because of the indexing operation and can be quite problematic depending on the amount of data you have. Note that when you specify the index column name in .to_koalas('index') the warning does not exist, which is reasonable since spark/koalas knows which column to use as index and does not need to bring all the data into one partition in order to calculate a global rank/ index. See more details about this here: https://towardsdatascience.com/adding-sequential-ids-to-a-spark-dataframe-fa0df5566ff6
Disclaimer: I haven’t really used it much, since, when I started learning Spark this wasn’t available, but I really think it is good to know about the available tools and it could be helpful for those coming from the Pandas’ environment — I can still remember the confusion I had from switching from pandas DataFrames to spark Dataframes.
I hope this was helpful and that knowing about Koalas will save you some time and trouble. Any thoughts, questions, corrections and suggestions are very welcome :)
If you want to know more about how Spark works, take a look at:
towardsdatascience.com
About adding indexes in Spark: | [
{
"code": null,
"e": 434,
"s": 172,
"text": "For those who are familiar with pandas DataFrames, switching to PySpark can be quite confusing. The API is not the same, and when switching to a distributed nature, some things are being done quite differently because of the restrictions imposed by that nature."
},
{
"code": null,
"e": 610,
"s": 434,
"text": "I recently stumbled upon Koalas from a very interesting Databricks presentation about Apache Spark 3.0, Delta Lake and Koalas, and thought that it would be nice to explore it."
},
{
"code": null,
"e": 764,
"s": 610,
"text": "The Koalas project makes data scientists more productive when interacting with big data, by implementing the pandas DataFrame API on top of Apache Spark."
},
{
"code": null,
"e": 936,
"s": 764,
"text": "pandas is the de facto standard (single-node) DataFrame implementation in Python, while Spark is the de facto standard for big data processing. With this package, you can:"
},
{
"code": null,
"e": 1041,
"s": 936,
"text": "- Be immediately productive with Spark, with no learning curve, if you are already familiar with pandas."
},
{
"code": null,
"e": 1159,
"s": 1041,
"text": "- Have a single codebase that works both with pandas (tests, smaller datasets) and with Spark (distributed datasets)."
},
{
"code": null,
"e": 1218,
"s": 1159,
"text": "source: https://koalas.readthedocs.io/en/latest/index.html"
},
{
"code": null,
"e": 1470,
"s": 1218,
"text": "Koalas supports ≥ Python 3.5 and from what I can see from the docs, PySpark 2.4.x. Dependencies include pandas ≥ 0.23.0, pyarrow ≥ 0.10 for using columnar in-memory format for better vector manipulation performance and matplotlib ≥ 3.0.0 for plotting."
},
{
"code": null,
"e": 1524,
"s": 1470,
"text": "The different ways to install Koalas are listed here:"
},
{
"code": null,
"e": 1546,
"s": 1524,
"text": "koalas.readthedocs.io"
},
{
"code": null,
"e": 1575,
"s": 1546,
"text": "But let’s start simple with:"
},
{
"code": null,
"e": 1618,
"s": 1575,
"text": "pip install koalas and pip install pyspark"
},
{
"code": null,
"e": 1665,
"s": 1618,
"text": "Keep in mind the dependencies mentioned above."
},
{
"code": null,
"e": 1691,
"s": 1665,
"text": "Given the following data:"
},
{
"code": null,
"e": 1950,
"s": 1691,
"text": "import pandas as pdfrom databricks import koalas as ksfrom pyspark.sql import SparkSessiondata = {'a': [1, 2, 3, 4, 5, 6], 'b': [100, 200, 300, 400, 500, 600], 'c': [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\"]}index = [10, 20, 30, 40, 50, 60]"
},
{
"code": null,
"e": 1996,
"s": 1950,
"text": "You can either start from a pandas DataFrame:"
},
{
"code": null,
"e": 2084,
"s": 1996,
"text": "pdf = pd.DataFrame(data, index=index)# from a pandas dataframekdf = ks.from_pandas(pdf)"
},
{
"code": null,
"e": 2109,
"s": 2084,
"text": "From a Koalas Dataframe:"
},
{
"code": null,
"e": 2168,
"s": 2109,
"text": "# start from raw datakdf = ks.DataFrame(data, index=index)"
},
{
"code": null,
"e": 2205,
"s": 2168,
"text": "Or from a spark Dataframe (one way):"
},
{
"code": null,
"e": 2390,
"s": 2205,
"text": "# creating a spark dataframe from a pandas dataframesdf2 = spark_session.createDataFrame(pdf)# and then converting the spark dataframe to a koalas dataframekdf = sdf.to_koalas('index')"
},
{
"code": null,
"e": 2425,
"s": 2390,
"text": "A full simple example with output:"
},
{
"code": null,
"e": 2530,
"s": 2425,
"text": "The API between Pandas and Koalas is more or less the same. More examples in the official documentation:"
},
{
"code": null,
"e": 2552,
"s": 2530,
"text": "koalas.readthedocs.io"
},
{
"code": null,
"e": 2586,
"s": 2552,
"text": "Some notes on the Koalas project:"
},
{
"code": null,
"e": 2733,
"s": 2586,
"text": "If you are starting from scratch with no previous knowledge of Pandas, then diving in straight to PySpark would probably be a better way to learn."
},
{
"code": null,
"e": 2807,
"s": 2733,
"text": "Some functions may be missing — the missing functions are documented here"
},
{
"code": null,
"e": 2941,
"s": 2807,
"text": "Some behavior may be different (e.g. Null vs NaN, where NaN is used with Koalas and is more coherent with Pandas and Null with Spark)"
},
{
"code": null,
"e": 3139,
"s": 2941,
"text": "Remember that since it is using Spark under the hood, some operations are lazy, meaning they are not really evaluated and executed before there is a Spark action, like printing out the top 20 rows."
},
{
"code": null,
"e": 3901,
"s": 3139,
"text": "I do have some concerns regarding the efficiency of some of the operations, e.g. .to_koalas() gives a No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation. warning, which seems to be because of the indexing operation and can be quite problematic depending on the amount of data you have. Note that when you specify the index column name in .to_koalas('index') the warning does not exist, which is reasonable since spark/koalas knows which column to use as index and does not need to bring all the data into one partition in order to calculate a global rank/ index. See more details about this here: https://towardsdatascience.com/adding-sequential-ids-to-a-spark-dataframe-fa0df5566ff6"
},
{
"code": null,
"e": 4240,
"s": 3901,
"text": "Disclaimer: I haven’t really used it much, since, when I started learning Spark this wasn’t available, but I really think it is good to know about the available tools and it could be helpful for those coming from the Pandas’ environment — I can still remember the confusion I had from switching from pandas DataFrames to spark Dataframes."
},
{
"code": null,
"e": 4404,
"s": 4240,
"text": "I hope this was helpful and that knowing about Koalas will save you some time and trouble. Any thoughts, questions, corrections and suggestions are very welcome :)"
},
{
"code": null,
"e": 4468,
"s": 4404,
"text": "If you want to know more about how Spark works, take a look at:"
},
{
"code": null,
"e": 4491,
"s": 4468,
"text": "towardsdatascience.com"
}
]
|
Logistic Regression In Python. An explanation of the Logistic... | by Cory Maklin | Towards Data Science | Despite the word Regression in Logistic Regression, Logistic Regression is a supervised machine learning algorithm used in binary classification. I say binary because one of the limitations of Logistic Regression is the fact that it can only categorize data with two distinct classes. At a high level, Logistic Regression fits a line to a dataset and then returns the probability that a new sample belongs to one of the two classes according to its location with respect to the line.
Before diving into the nitty gritty of Logistic Regression, it’s important that we understand the difference between probability and odds. Odds are calculated by taking the number of events where something happened and dividing by the number events where that same something didn’t happen. For example, if the odds of winning a game are 5 to 2, we calculate the ratio as 5/2=2.5. On the other hand, probability is calculated by taking the number of events where something happened and dividing by the total number events (including events when that same something did and didn’t happen). For example, the probability of winning a game with the same odds is 5/(5+2)=0.714.
One important distinction between odds and probabilities, which will come into play when we go to train the model, is the fact that probabilities range from 0 and 1 whereas the log of the odds can range from negative to positive infinity. We take the log of the odds because otherwise, when we calculate the odds of some event occurring (i.e. winning a game), if the denominator is larger than the numerator, the odds will range from 0 to 1. However, when the numerator is larger than the denominator, then the odds will range from 1 to infinity. For example, suppose that we compared the odds of winning a game for two different teams. Team A is composed of all-stars therefore their odds of winning a game are 5 to 1.
On the other hand, the odds of Team B winning a game are 1 to 5.
In taking the log of the odds, the distance from the origin (0) is the same for both teams.
We can go from probability to odds by dividing the probability that an event occurs by the probability that it doesn’t occur.
We write the general formula of the latter as follows:
As we’re about to see, we need to go back and forth between probabilities and odds when determining the optimal fit for our model.
Suppose we wanted to build a Logistic Regression model to predict whether a student would pass or fail given certain variables such as the number of hours studied. To be exact, we want a model that outputs the probability (a number between 0 and 1) that a student passes. A value of 1 implies that the student is guaranteed to pass whereas a value of 0 implies that the student will fail.
In mathematics, we call the following equation a Sigmoid function.
Where y is the equation for a line.
No matter what value we have for y, a Sigmoid function ranges from 0 to 1. For instance, when y tends towards negative infinity, the probability approaches zero.
When y tends towards positive infinity, the probability approaches one.
In Logistic Regression, we use the Sigmoid function to describe the probability that a sample belongs to one of the two classes. The shape of the Sigmoid function determines the probabilities predicted by our model. When we train our model, we are in fact attempting to select the Sigmoid function whose shape best fits our data. The actual way we go about choosing the optimal line involves lots of math. As we saw in Linear Regression, we can use Gradient Descent or some other technique to converge towards a solution. However, the derivative of the Sigmoid function is rather complicated.
What if we could optimize the equation of a line instead?
As we mentioned previously, we can go from probabilities (a function that ranges from 0 to 1) to log(odds) (a function that ranges from negative to positive infinity).
For example, suppose that the probability that a student passes is 0.8 or 80%. We can find the corresponding position on the y-axis of the new graph by dividing the probability that they pass by the probability that they fail and then taking the log of the result.
We would then repeat the process for each data point.
Once we’ve plotted every data point on the new y-axis, just like Linear Regression, we can use an optimizer to determine the y-intercept and slope of the best fitting line.
In this example, we’ll cover how to optimize the function using maximum likelihood.
First, we generate a candidate line, and then project the original data points on to it.
We look at the y value of each data point along the line and convert it from the log of the odds to a probability.
After repeating the process for each data point, we end up with the following function.
The likelihood that a student passes is the value on the y-axis at that point along the line. The likelihood of observing students with the current distribution given the shape of the Sigmoid is the product of observing each student pass individually.
Next, we include the likelihoods for the students who did not pass to the equation for the overall likelihood. Since the Sigmoid function represents the probability that a student passes, the likelihood that a student fails is 1 (the total probability) minus the y value at that point along the line.
You’ll typically see the log of the likelihood being used instead. The product of two numbers inside of a log is equivalent to the addition of their logs.
We end up with the following likelihood.
We then repeat the entire process for a different line and compare the likelihoods. We choose the line with the maximum likelihood (highest positive number).
Let’s take a look at how we could go about implementing Logistic Regression in Python. To begin, import the following libraries.
from sklearn.datasets import make_classificationfrom matplotlib import pyplot as pltfrom sklearn.linear_model import LogisticRegressionimport seaborn as snssns.set()from sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matriximport pandas as pd
Next, we’ll take advantage of the make_classification function from the scikit-learn library to generate data. As we mentioned previously, Logistic Regression is only applicable to binary classification problems. Thus, the data points are composed of two classes.
x, y = make_classification( n_samples=100, n_features=1, n_classes=2, n_clusters_per_class=1, flip_y=0.03, n_informative=1, n_redundant=0, n_repeated=0)
We plot the relationship between the feature and classes.
plt.scatter(x, y, c=y, cmap='rainbow')
Prior to training our model, we’ll set aside a portion of our data in order to evaluate its performance.
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1)
We instantiate an instance of the LogisticRegression class and call the fit function with the features and the labels (since Logistic Regression is a supervised machine learning algorithm) as arguments.
lr = LogisticRegression()lr.fit(x_train, y_train)
We can access the following properties to actually view the coefficient for the slope and y-intercept of the best fitting line.
print(lr.coef_)print(lr.intercept_)
Let’s see how the model performs against data that it hasn’t been trained on.
y_pred = lr.predict(x_test)
Given that this consists of a classification problem, we use a confusion matrix to measure the accuracy of our model.
confusion_matrix(y_test, y_pred)
From our confusion matrix we conclude that:
True positive: 7 (We predicted a positive result and it was positive)
True negative: 12 (We predicted a negative result and it was negative)
False positive: 4 (We predicted a positive result and it was negative)
False negative: 2 (We predicted a negative result and it was positive)
If for whatever reason we’d like to check the actual probability that a data point belongs to a given class, we can use the predict_proba function.
lr.predict_proba(x_test)
The first column corresponds to the probability that the sample belongs to the first class and the second column corresponds to the probability that the sample belongs to the second class.
Before attempting to plot the Sigmoid function, we create and sort a DataFrame containing our test data.
df = pd.DataFrame({'x': x_test[:,0], 'y': y_test})df = df.sort_values(by='x')from scipy.special import expitsigmoid_function = expit(df['x'] * lr.coef_[0][0] + lr.intercept_[0]).ravel()plt.plot(df['x'], sigmoid_function)plt.scatter(df['x'], df['y'], c=df['y'], cmap='rainbow', edgecolors='b') | [
{
"code": null,
"e": 655,
"s": 171,
"text": "Despite the word Regression in Logistic Regression, Logistic Regression is a supervised machine learning algorithm used in binary classification. I say binary because one of the limitations of Logistic Regression is the fact that it can only categorize data with two distinct classes. At a high level, Logistic Regression fits a line to a dataset and then returns the probability that a new sample belongs to one of the two classes according to its location with respect to the line."
},
{
"code": null,
"e": 1327,
"s": 655,
"text": "Before diving into the nitty gritty of Logistic Regression, it’s important that we understand the difference between probability and odds. Odds are calculated by taking the number of events where something happened and dividing by the number events where that same something didn’t happen. For example, if the odds of winning a game are 5 to 2, we calculate the ratio as 5/2=2.5. On the other hand, probability is calculated by taking the number of events where something happened and dividing by the total number events (including events when that same something did and didn’t happen). For example, the probability of winning a game with the same odds is 5/(5+2)=0.714."
},
{
"code": null,
"e": 2047,
"s": 1327,
"text": "One important distinction between odds and probabilities, which will come into play when we go to train the model, is the fact that probabilities range from 0 and 1 whereas the log of the odds can range from negative to positive infinity. We take the log of the odds because otherwise, when we calculate the odds of some event occurring (i.e. winning a game), if the denominator is larger than the numerator, the odds will range from 0 to 1. However, when the numerator is larger than the denominator, then the odds will range from 1 to infinity. For example, suppose that we compared the odds of winning a game for two different teams. Team A is composed of all-stars therefore their odds of winning a game are 5 to 1."
},
{
"code": null,
"e": 2112,
"s": 2047,
"text": "On the other hand, the odds of Team B winning a game are 1 to 5."
},
{
"code": null,
"e": 2204,
"s": 2112,
"text": "In taking the log of the odds, the distance from the origin (0) is the same for both teams."
},
{
"code": null,
"e": 2330,
"s": 2204,
"text": "We can go from probability to odds by dividing the probability that an event occurs by the probability that it doesn’t occur."
},
{
"code": null,
"e": 2385,
"s": 2330,
"text": "We write the general formula of the latter as follows:"
},
{
"code": null,
"e": 2516,
"s": 2385,
"text": "As we’re about to see, we need to go back and forth between probabilities and odds when determining the optimal fit for our model."
},
{
"code": null,
"e": 2905,
"s": 2516,
"text": "Suppose we wanted to build a Logistic Regression model to predict whether a student would pass or fail given certain variables such as the number of hours studied. To be exact, we want a model that outputs the probability (a number between 0 and 1) that a student passes. A value of 1 implies that the student is guaranteed to pass whereas a value of 0 implies that the student will fail."
},
{
"code": null,
"e": 2972,
"s": 2905,
"text": "In mathematics, we call the following equation a Sigmoid function."
},
{
"code": null,
"e": 3008,
"s": 2972,
"text": "Where y is the equation for a line."
},
{
"code": null,
"e": 3170,
"s": 3008,
"text": "No matter what value we have for y, a Sigmoid function ranges from 0 to 1. For instance, when y tends towards negative infinity, the probability approaches zero."
},
{
"code": null,
"e": 3242,
"s": 3170,
"text": "When y tends towards positive infinity, the probability approaches one."
},
{
"code": null,
"e": 3835,
"s": 3242,
"text": "In Logistic Regression, we use the Sigmoid function to describe the probability that a sample belongs to one of the two classes. The shape of the Sigmoid function determines the probabilities predicted by our model. When we train our model, we are in fact attempting to select the Sigmoid function whose shape best fits our data. The actual way we go about choosing the optimal line involves lots of math. As we saw in Linear Regression, we can use Gradient Descent or some other technique to converge towards a solution. However, the derivative of the Sigmoid function is rather complicated."
},
{
"code": null,
"e": 3893,
"s": 3835,
"text": "What if we could optimize the equation of a line instead?"
},
{
"code": null,
"e": 4061,
"s": 3893,
"text": "As we mentioned previously, we can go from probabilities (a function that ranges from 0 to 1) to log(odds) (a function that ranges from negative to positive infinity)."
},
{
"code": null,
"e": 4326,
"s": 4061,
"text": "For example, suppose that the probability that a student passes is 0.8 or 80%. We can find the corresponding position on the y-axis of the new graph by dividing the probability that they pass by the probability that they fail and then taking the log of the result."
},
{
"code": null,
"e": 4380,
"s": 4326,
"text": "We would then repeat the process for each data point."
},
{
"code": null,
"e": 4553,
"s": 4380,
"text": "Once we’ve plotted every data point on the new y-axis, just like Linear Regression, we can use an optimizer to determine the y-intercept and slope of the best fitting line."
},
{
"code": null,
"e": 4637,
"s": 4553,
"text": "In this example, we’ll cover how to optimize the function using maximum likelihood."
},
{
"code": null,
"e": 4726,
"s": 4637,
"text": "First, we generate a candidate line, and then project the original data points on to it."
},
{
"code": null,
"e": 4841,
"s": 4726,
"text": "We look at the y value of each data point along the line and convert it from the log of the odds to a probability."
},
{
"code": null,
"e": 4929,
"s": 4841,
"text": "After repeating the process for each data point, we end up with the following function."
},
{
"code": null,
"e": 5181,
"s": 4929,
"text": "The likelihood that a student passes is the value on the y-axis at that point along the line. The likelihood of observing students with the current distribution given the shape of the Sigmoid is the product of observing each student pass individually."
},
{
"code": null,
"e": 5482,
"s": 5181,
"text": "Next, we include the likelihoods for the students who did not pass to the equation for the overall likelihood. Since the Sigmoid function represents the probability that a student passes, the likelihood that a student fails is 1 (the total probability) minus the y value at that point along the line."
},
{
"code": null,
"e": 5637,
"s": 5482,
"text": "You’ll typically see the log of the likelihood being used instead. The product of two numbers inside of a log is equivalent to the addition of their logs."
},
{
"code": null,
"e": 5678,
"s": 5637,
"text": "We end up with the following likelihood."
},
{
"code": null,
"e": 5836,
"s": 5678,
"text": "We then repeat the entire process for a different line and compare the likelihoods. We choose the line with the maximum likelihood (highest positive number)."
},
{
"code": null,
"e": 5965,
"s": 5836,
"text": "Let’s take a look at how we could go about implementing Logistic Regression in Python. To begin, import the following libraries."
},
{
"code": null,
"e": 6246,
"s": 5965,
"text": "from sklearn.datasets import make_classificationfrom matplotlib import pyplot as pltfrom sklearn.linear_model import LogisticRegressionimport seaborn as snssns.set()from sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matriximport pandas as pd"
},
{
"code": null,
"e": 6510,
"s": 6246,
"text": "Next, we’ll take advantage of the make_classification function from the scikit-learn library to generate data. As we mentioned previously, Logistic Regression is only applicable to binary classification problems. Thus, the data points are composed of two classes."
},
{
"code": null,
"e": 6687,
"s": 6510,
"text": "x, y = make_classification( n_samples=100, n_features=1, n_classes=2, n_clusters_per_class=1, flip_y=0.03, n_informative=1, n_redundant=0, n_repeated=0)"
},
{
"code": null,
"e": 6745,
"s": 6687,
"text": "We plot the relationship between the feature and classes."
},
{
"code": null,
"e": 6784,
"s": 6745,
"text": "plt.scatter(x, y, c=y, cmap='rainbow')"
},
{
"code": null,
"e": 6889,
"s": 6784,
"text": "Prior to training our model, we’ll set aside a portion of our data in order to evaluate its performance."
},
{
"code": null,
"e": 6963,
"s": 6889,
"text": "x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1)"
},
{
"code": null,
"e": 7166,
"s": 6963,
"text": "We instantiate an instance of the LogisticRegression class and call the fit function with the features and the labels (since Logistic Regression is a supervised machine learning algorithm) as arguments."
},
{
"code": null,
"e": 7216,
"s": 7166,
"text": "lr = LogisticRegression()lr.fit(x_train, y_train)"
},
{
"code": null,
"e": 7344,
"s": 7216,
"text": "We can access the following properties to actually view the coefficient for the slope and y-intercept of the best fitting line."
},
{
"code": null,
"e": 7380,
"s": 7344,
"text": "print(lr.coef_)print(lr.intercept_)"
},
{
"code": null,
"e": 7458,
"s": 7380,
"text": "Let’s see how the model performs against data that it hasn’t been trained on."
},
{
"code": null,
"e": 7486,
"s": 7458,
"text": "y_pred = lr.predict(x_test)"
},
{
"code": null,
"e": 7604,
"s": 7486,
"text": "Given that this consists of a classification problem, we use a confusion matrix to measure the accuracy of our model."
},
{
"code": null,
"e": 7637,
"s": 7604,
"text": "confusion_matrix(y_test, y_pred)"
},
{
"code": null,
"e": 7681,
"s": 7637,
"text": "From our confusion matrix we conclude that:"
},
{
"code": null,
"e": 7751,
"s": 7681,
"text": "True positive: 7 (We predicted a positive result and it was positive)"
},
{
"code": null,
"e": 7822,
"s": 7751,
"text": "True negative: 12 (We predicted a negative result and it was negative)"
},
{
"code": null,
"e": 7893,
"s": 7822,
"text": "False positive: 4 (We predicted a positive result and it was negative)"
},
{
"code": null,
"e": 7964,
"s": 7893,
"text": "False negative: 2 (We predicted a negative result and it was positive)"
},
{
"code": null,
"e": 8112,
"s": 7964,
"text": "If for whatever reason we’d like to check the actual probability that a data point belongs to a given class, we can use the predict_proba function."
},
{
"code": null,
"e": 8137,
"s": 8112,
"text": "lr.predict_proba(x_test)"
},
{
"code": null,
"e": 8326,
"s": 8137,
"text": "The first column corresponds to the probability that the sample belongs to the first class and the second column corresponds to the probability that the sample belongs to the second class."
},
{
"code": null,
"e": 8431,
"s": 8326,
"text": "Before attempting to plot the Sigmoid function, we create and sort a DataFrame containing our test data."
}
]
|
Step by Step: Build Your Custom Real-Time Object Detector | by Alaa Sinjab | Towards Data Science | Police response time is very critical when an incident occurs. In the United States, the police average response time is around 18 minutes.1In my last project, I was trying to minimize the police response time by detecting weapons in a live CCTV camera as an approach to alert them as soon as a gun is being detected. The main motivation for this project is due to the increasing number of school mass shootings in the U.S.
In this tutorial, we will:
Perform object detection on custom images using Tensorflow Object Detection API
Use Google Colab free GPU for training and Google Drive to keep everything synced.
Detailed steps to tune, train, monitor, and use the model for inference using your local webcam.
I have created this Colab Notebook if you would like to start exploring. It has some steps and notes that were not mentioned here. I suggest looking at it after reading this tutorial.
Let’s get started, shall we?
1. Gathering Images and Labels.2. Setting up the environment.3. Importing and Installing Required Packages.4. Preprocessing Images and Labels.5. Downloading Tensorflow model.6. Generating TFRecords.7. Selecting and Downloading a Pre-trained model.8. Configuring the Training Pipeline.9. Tensorboard.10. Training.11. Export the trained model.12. Webcam Inference.
I will be using pictures of pistols. The original dataset was collected and labeled by the University of Granada in Spain. The dataset contains 3,000 pictures of guns in various positions, rotations, backgrounds, etc. The guns are already labeled as well (not the best). You may use your own images or use the dataset I am using here!
If you have your images already collected, great! If not, depending on your problem, you can take pictures from your phone or scrape Google for images.
Remember: Garbage In = Garbage Out. Choosing the images is the most important part!Here are some tips that might help when collecting your images:
At least 50 images for each class. The more, the better! Get even more if you are detecting only one class.Images with random objects in the background.Various background conditions; dark, light, in/outdoor, etc.
At least 50 images for each class. The more, the better! Get even more if you are detecting only one class.
Images with random objects in the background.
Various background conditions; dark, light, in/outdoor, etc.
One of the easiest ways to collect images is by using google-images-download. You may also download the images using this tutorial, it provides multiple ways to collect images from Google.
Save your images in a folder called images
Note: Make sure all the images are .jpg, you might get errors when training if the images are in different extensions.
Once you have your images gathered, it’s time to label them. There are many tools that can help you with labeling your images. Perhaps, LabelImg is the most popular and easiest to use. Using the instructions from the github repo, download and install it on your local machine.
Using LabelImg is easy, just remember to:
Create a new directory for the labels, I will name it annotationsIn LabelImg, Click on Change Save Dir and select the annotations folder. This is where the labels/annotations will be saved.Click on Open Dir and select the images folder.Use the shortcuts to make this faster.
Create a new directory for the labels, I will name it annotations
In LabelImg, Click on Change Save Dir and select the annotations folder. This is where the labels/annotations will be saved.
Click on Open Dir and select the images folder.
Use the shortcuts to make this faster.
Shortcuts for MacOS:_____| CMD + s | Save the label_| w | Create a box_| d | Next image| a | Previous image_| CMD + + | Zoom in| CMD + - | Zoom out_____
By default, The labels will be in PascalVOC format. Each image will have one .xml file that has its labels. If there is more than one class or one label in an image, that .xml file will include them all.
Create a new Notebook.From the top left menu: Go to Runtime > Change runtime type > select GPU from hardware accelerator. Some pretrained models support TPU. The pretrained model we are choosing in this project only supports GPU.(Highly Recommended) Mount Google Drive to the Colab notebook:
Create a new Notebook.
From the top left menu: Go to Runtime > Change runtime type > select GPU from hardware accelerator. Some pretrained models support TPU. The pretrained model we are choosing in this project only supports GPU.
(Highly Recommended) Mount Google Drive to the Colab notebook:
When training starts, checkpoints, logs and many other important files will be created. When the kernel disconnects, these files, along with everything else, will be deleted if they don’t get saved on your Google Drive or somewhere else.The kernel disconnects shortly after your computer sleeps or after using the Colab GPU for 12 hours. Training will need to be restarted from zero if the trained model did not get saved.2I also highly recommend downloading Google Backup and Sync app so it’s easier to move and edit files as well as to keep everything synchronized.
Head to your Google Drive and create a folder named object_detection
Open Google Backup and Sync app on your local machine and select that object_detection folder ←
Note: This method will greatly depend on the speed of your internet connection.
.
On the Colab Notebook, Mount gdrive and navigate to the project’s folder, you will be asked for the authorization code:
from google.colab import drive drive.mount('/gdrive')# the project's folder%cd /gdrive/'My Drive'/object_detection
Inside object_detectionfolder, create a folder data that will have the images and labels. Choose one of the methods below to upload your data.
Using Google Backup and Sync app:
Using Google Backup and Sync app:
Uploading the images and annotations folders is easy; just move them to the data/object_detection folder from your computer.
.
.
2. Uploading directly from the notebook:
Note: This method is the slowest.
Use the following to upload directly to the notebook. You will have to either zip the images folder or upload them separately (uploading a folder to Google Colab is not supported). Organizing and having the same files structure is important.
from google.colab import filesuploaded = files.upload()
3. Uploading directly from source:
You could also download directly from source using curl or wget
The working directory so far:
object_detection └── data ├── images │ ├── image_1.jpg │ ├── image_2.jpg │ └── ... │ └── annotations ├── image_1.xml ├── image_2.xml └── ...
Tip: You can view the full working directory on Google Colab Notebook by: Open the left panel by clicking on the top left arrow. Or use ⌘/Ctrl+Alt+PThen Click on Files from the top left menu.
Depending on how large your dataset is, you might want to split your data manually. If you have a lot of pictures, you might want to use something like this to split your data randomly.
Note: The images inside images don’t need to be split, only the .xml files.
The working directory at this point:
object_detection └── data ├── images │ ├── image_1.jpg │ └── ... │ ├── annotations │ ├── image_1.xml │ └── ... │ ├── train_labels //contains the labels only │ ├── image_1.xml │ └── ... │ └── test_labels //contains the labels only ├── image_50.xml └── ...
Google Colab has most of the packages pre installed already; Python, Tensorflow, pandas, etc.
These are the packages we will need and they don’t get pre installed by default. Install them by running:
!apt-get install -qq protobuf-compiler python-pil python-lxml python-tk!pip install -qq Cython contextlib2 pillow lxml matplotlib pycocotools
Other Imports will be done when needed later.
We need Tensorflow version 1.15.0. Check Tensorflow version by running:
print(tf.__version__)
We need to create two csv files for the .xml files in each train_labels/ and test_labels/
These 2 csv files will contain each image’s file name, the label /box position, etc. Also, more than one row is created for the same picture if there is more than one class or label for it.
Other than the CSVs, we will need to create a pbtxt file that will contain the label map for each class. This file will tell the model what each object is by defining a mapping of class names to class ID numbers.
You don’t have to do any of these manually, the following will convert the xml files to two csvs and will create the .pbtxt file. Just make sure that:
The same folders’ name where the xmls are located is matched:train_labels/ and test_labels/ (or change them for the code below)
Current directory is object_detection/data/
The images are in .jpg format
The working directory at this point:
object_detection/ └── data/ ├── images/ │ └── ... ├── annotations/ │ └── ... ├── train_labels/ │ └── ... ├── test_labels/ │ └── ... │ ├── label_map.pbtxt │ ├── test_labels.csv │ └── train_labels.csv
Tensorflow model contains the object detection API we are interested in. We will get it from the official repo.
Navigate to object_detection/ dir, then:
# downloads the models!git clone --q https://github.com/tensorflow/models.git
Next, we need to compile the proto buffers — Not important to understand for this project but you can learn more about them here. Also, the PATH var should have the following directories added: models/research/ and models/research/slim/
Navigate to object_detection/models/research/ dir, then:
# compils the proto buffers!protoc object_detection/protos/*.proto --python_out=.# exports PYTHONPATH environment var with research and slim pathsos.environ['PYTHONPATH'] += ':./:./slim/'
Finally, run a quick test to confirm that the model builder is working properly:
# testing the model builder!python3 object_detection/builders/model_builder_test.py
If you see an OK at the end of the test, then everything is going great!
Tensorflow accepts the data as TFRecords data.record. TFRecord is a binary file that runs fast with low memory usage. It contains all the images and labels in one file. Read more about it here.
In our case, we will have two TFRecords; one for testing and another for training. To make this work, we need to make sure that:
The CSVs file names is matched:train_labels.csv and test_labels.csv (or change them in the code below)
Current directory is object_detection/models/research
Add your custom object text in the function class_text_to_int below by changing the row_label variable (This is the text that will appear on the detected object). Add more labels if you have more than one object.
Check if the path to data/ directory is the same asdata_base_url below.
A pre-trained model simply means that it has been trained on another dataset. That model has seen thousands or millions of images and objects.COCO (Common Objects in Context) is a dataset of 330,000 images that contains 1.5 million objects for 80 different classes. Such as, dogs, cats, cars, bananas, ... Check all the classes here.
Training a model from scratch is extremely time consuming; it may take days or weeks to finish training. A pre-trained model has already seen tons of objects and knows how to classify each one of them. So, why not just use it!
Because our interest is to interfere on a real time video, we will be choosing a model that has a low ms inference speed with a relatively high mAP on COCO.
The model used for this project is ssd_mobilenet_v2_coco. Check the other models from here. You could use any pre-trained model you prefer, but I would suggest experimenting with SSD ‘Single Shot Detector’ models first as they perform faster than any type of RCNN on a real-time video4.
Explaining the difference between object detection techniques is out of the scope of this tutorial. You can read more about them from this blog post, or learn about how their speed and accuracy compare from here.
Let’s start with selecting a pretrained model:
We will download the selected model. I have created these two models configurations to make it easier. the ssd_mobilenet_v2 is selected here, try using faster_rcnn_inception_v2 later if you would like. Just change selected_model above.
Navigate to models/research/
DEST_DIR is where the model will be downloaded. Change it if you have a different working directory.
While training, the model will get autosaved every 600 seconds by default. The logs and graphs, such as, the mAP, loss and AR, will also get saved constantly. Lets create a folder for all of them to be saved in during training:
Create a folder called training inside object_detection/model/research/
The working directory at this point:
object_detection/ ├── data/ │ ├── images/ │ │ └── ... │ ├── annotations/ │ │ └── ... │ ├── train_labels/ │ │ └── ... │ ├── test_labels/ │ │ └── ... │ ├── label_map.pbtxt │ ├── test_labels.csv │ ├── train_labels.csv │ ├── test_labels.records │ └── train_labels.records │ └── models/ ├── research/ │ ├── training/ │ │ └── ... │ ├── pretrained_model/ │ ├── frozen_inference_graph.pb │ └── ... └── ...
This is the last step before starting to train the model, finally! Perhaps, it will be the step where you might spend some time to tune the model.
Tensorflow Object Detection API model we downloaded comes with many sample config files. For each model, there is a config file that is ‘almost’ ready to be used.
The config files are located here:
object_detection/models/research/object_detection/samples/configs/
ssd_mobilenet_v2_coco.config is the config file for the pretrained model we are using. If you chose another model, you need to use & edit the correspondent config file.
Because we will probably have to tune the config constantly, I suggest doing the following:
view the content of the sample config file by running:
Copy the content of the config file
Edit it by using
Or, you can open and edit the config file directly from your local machine if you have everything synced by using any text editor.
Here are the required edits that need to be changed in the sample config file, also some suggested edits to improve your model performance.
➊. Required edits to the config file:
model {} > ssd {}: change num_classes to the number of classes you have.
model {} > ssd {}: change num_classes to the number of classes you have.
2. train_config {}: change fine_tune_checkpoint to the checkpoint file path.
Note: The exact file name model.ckpt doesn't exist. This is where the model will be saved during training. This is its relative path:
/object_detection/models/research/pretrained_model/model.ckpt
3. train_input_reader {}: set the path to the train_labels.record and the label map pbtxt file.
4. eval_input_reader {}: set the path to the test_labels.record and the label map pbtxt file.
That’s it! You can skip the optional edits and head to training!
➋. Suggested edits to the config file:
First, you might want to start training the model and see how well it does. If you are overfitting, then you might want to do some more image augmentation.
In the sample config file: random_horizontal_flip & ssd_random_crop are added by default. You could try adding these as well:
from train_config {}:
Note: Each image augmentation will increase the training time drastically.
There are many data augmentation options that you can add. Check the full list from the official code here.
In model {} > ssd {} > box_predictor {}: set use_dropout to true This will be helpful to counter overfitting.
In eval_config : {} set the number of testing images you have in num_examples and remove max_eval to evaluate indefinitely
Note: The notebook provided explains many more things in regard to tuning the config file. Check it out!
The full working directory: (Including some files/folders that will be created and used later)
object_detection/ ├── data/ │ ├── images/ │ │ └── ... │ ├── annotations/ │ │ └── ... │ ├── train_labels/ │ │ └── ... │ ├── test_labels/ │ │ └── ... │ ├── label_map.pbtxt │ ├── test_labels.csv │ ├── train_labels.csv │ ├── test_labels.records │ └── train_labels.records │ └── models/ ├─ research/ │ ├── fine_tuned_model/ │ │ ├── frozen_inference_graph.pb │ │ └── ... │ │ │ ├── pretrained_model/ │ │ ├── frozen_inference_graph.pb │ │ └── ... │ │ │ ├── object_detection/ │ │ ├── utils/ │ │ ├── samples/ │ │ │ ├── configs/ │ │ │ │ ├── ssd_mobilenet_v2_coco.config │ │ │ │ ├── rfcn_resnet101_pets.config │ │ │ │ └── ... │ │ │ └── ... │ │ ├── export_inference_graph.py │ │ ├── model_main.py │ │ └── ... │ │ │ ├── training/ │ │ ├── events.out.tfevents.xxxxx │ │ └── ... │ └── ... └── ...
Tensorboard is the place where we can visualize everything that’s happening during training. You can monitor the loss, mAP, AR and many more.
You could also monitor the pictures and the annotations during training. At each evaluation step, you could see how good your model was at detecting the object ←.Note: Remember when we set num_visualizations: 20 above? Tensorboard will display that much pictures of the testing images here.
To use Tensorboard on Colab, we need to use it through ngrok. Get it by running:
Next, we specify where the log files are stored and we configure a link to view Tensorboard:
When you run the code above, at the end of the output there will be a url where you can access Tensorboard through.
Notes:
You might not get a url when running the above code, but an error instead. Just run the above cell again. No need to reinstall ngrok.Tensorboard will not log any files until the training starts.A max of 20 connection per minute is allowed when using ngrok, you will not be able to access tensorboard while the model is logging to it. (happens very frequently)
You might not get a url when running the above code, but an error instead. Just run the above cell again. No need to reinstall ngrok.
Tensorboard will not log any files until the training starts.
A max of 20 connection per minute is allowed when using ngrok, you will not be able to access tensorboard while the model is logging to it. (happens very frequently)
If you have the project synced to your local machine, you will be able to view the Tensorboard without any limitation.
Go to terminal on your local machine and run:
$ pip install tensorboard
Run it and specify where the logging dir is:
# in my case, the path to the training folder is:tensorboard --logdir=/Users/alaasenjab/Google\ Drive/object_detection/models/research/training
Training the model is as easy as running the following code. We just need to give it:
model_main.py which runs the training process
pipeline_config_path=Path/to/config/file/model.config
model_dir= Path/to/training/
Notes:
If the kernel dies, the training will resume from the last checkpoint. Unless you didn’t save the training/ directory somewhere, ex: GDrive.If you are changing the below paths, make sure there is no space between the equal sign = and the path.
If the kernel dies, the training will resume from the last checkpoint. Unless you didn’t save the training/ directory somewhere, ex: GDrive.
If you are changing the below paths, make sure there is no space between the equal sign = and the path.
Now set back and watch your model train on Tensorboard.
By default, the model will save a checkpoint every 600 seconds while training up to 5 checkpoints. Then, as new files are created, older files are deleted.
We can find the last model trained by running this code:
Then by executing export_inference_graph.py to convert the model to a frozen model frozen_inference_graph.pb that we can use for inference. This frozen model can’t be used to resume training. However, saved_model.pb gets exported as well which can be used to resume training as it has all the weights.
pipeline_config_path=Path/to/config/file/model.config
output_directory= where the model will be saved at
trained_checkpoint_prefix=Path/to/a/checkpoint
You can access all exported files from this directory:
/gdrive/My Drive/object_detection/models/research/pretrained_model/
Or, you can download the frozen graph needed for inference directly from Google Colab:
#downloads the frozen model that is needed for inference# output_directory = 'fine_tuned_model' dir specified above.files.download(output_directory + '/frozen_inference_graph.pb')
We also need the label map .pbtxt file:
#downlaod the label map# we specified 'data_base_url' above. It directs to# 'object_detection/data/' folder.files.download(data_base_url + '/label_map.pbtxt')
To use your webcam in your local machine to inference the model, you need to have the following installed:
Tensorflow = 1.15.0cv2 = 4.1.2
You also need Tensorflow model downloaded on your local machine (Step 5 above) or you can skip that and navigate to the model if you have GDrive on your local machine synced.
Go to terminal on your local machine and navigate to models/research/object_detection
In my case, I am navigating to the folder in GDrive.
$ cd /Users/alaasenjab/Google\ Drive/object_detection/models/research/object_detection
You can run the following from a jupyter notebook or by creating a .py file. However, change PATH_TO_FROZEN_GRAPH , PATH_TO_LABEL_MAP and NUM_CLASSES
Run the code and smile :)
Detecting objects from images and videos is a bit easier than in real-time. When we have a video or an image that we want to detect an object from, we don’t care much about the inference time the model might take to detect the object. In real-time object detection, we might want to sacrifice some precision over a faster inference time. In the case of detecting guns to notify the police, we don’t care much about detecting exactly where the gun is located. Instead, we probably would optimize for both:False Negative: Not detecting a gun when there is one.True Negative: Detecting a gun when there isn’t one.
I hope you found this tutorial on how to detect custom objects using Tensorflow easy and useful. Don’t forget to check the Colab Notebook for more details.
Please let me know if you have any question down below, I will try my best to help!
⋆ Tensorflow object detection API. By: Tensorflow. ⋆ Inspired from: Train Object Detection for free. By: Chengwei. ⋆ Raccoon detector dataset. By: Dat Tran. ⋆ Train Yolov3 using Colab. By: David Ibáñez. | [
{
"code": null,
"e": 596,
"s": 172,
"text": "Police response time is very critical when an incident occurs. In the United States, the police average response time is around 18 minutes.1In my last project, I was trying to minimize the police response time by detecting weapons in a live CCTV camera as an approach to alert them as soon as a gun is being detected. The main motivation for this project is due to the increasing number of school mass shootings in the U.S."
},
{
"code": null,
"e": 623,
"s": 596,
"text": "In this tutorial, we will:"
},
{
"code": null,
"e": 703,
"s": 623,
"text": "Perform object detection on custom images using Tensorflow Object Detection API"
},
{
"code": null,
"e": 786,
"s": 703,
"text": "Use Google Colab free GPU for training and Google Drive to keep everything synced."
},
{
"code": null,
"e": 883,
"s": 786,
"text": "Detailed steps to tune, train, monitor, and use the model for inference using your local webcam."
},
{
"code": null,
"e": 1067,
"s": 883,
"text": "I have created this Colab Notebook if you would like to start exploring. It has some steps and notes that were not mentioned here. I suggest looking at it after reading this tutorial."
},
{
"code": null,
"e": 1096,
"s": 1067,
"text": "Let’s get started, shall we?"
},
{
"code": null,
"e": 1459,
"s": 1096,
"text": "1. Gathering Images and Labels.2. Setting up the environment.3. Importing and Installing Required Packages.4. Preprocessing Images and Labels.5. Downloading Tensorflow model.6. Generating TFRecords.7. Selecting and Downloading a Pre-trained model.8. Configuring the Training Pipeline.9. Tensorboard.10. Training.11. Export the trained model.12. Webcam Inference."
},
{
"code": null,
"e": 1794,
"s": 1459,
"text": "I will be using pictures of pistols. The original dataset was collected and labeled by the University of Granada in Spain. The dataset contains 3,000 pictures of guns in various positions, rotations, backgrounds, etc. The guns are already labeled as well (not the best). You may use your own images or use the dataset I am using here!"
},
{
"code": null,
"e": 1946,
"s": 1794,
"text": "If you have your images already collected, great! If not, depending on your problem, you can take pictures from your phone or scrape Google for images."
},
{
"code": null,
"e": 2093,
"s": 1946,
"text": "Remember: Garbage In = Garbage Out. Choosing the images is the most important part!Here are some tips that might help when collecting your images:"
},
{
"code": null,
"e": 2306,
"s": 2093,
"text": "At least 50 images for each class. The more, the better! Get even more if you are detecting only one class.Images with random objects in the background.Various background conditions; dark, light, in/outdoor, etc."
},
{
"code": null,
"e": 2414,
"s": 2306,
"text": "At least 50 images for each class. The more, the better! Get even more if you are detecting only one class."
},
{
"code": null,
"e": 2460,
"s": 2414,
"text": "Images with random objects in the background."
},
{
"code": null,
"e": 2521,
"s": 2460,
"text": "Various background conditions; dark, light, in/outdoor, etc."
},
{
"code": null,
"e": 2710,
"s": 2521,
"text": "One of the easiest ways to collect images is by using google-images-download. You may also download the images using this tutorial, it provides multiple ways to collect images from Google."
},
{
"code": null,
"e": 2753,
"s": 2710,
"text": "Save your images in a folder called images"
},
{
"code": null,
"e": 2872,
"s": 2753,
"text": "Note: Make sure all the images are .jpg, you might get errors when training if the images are in different extensions."
},
{
"code": null,
"e": 3149,
"s": 2872,
"text": "Once you have your images gathered, it’s time to label them. There are many tools that can help you with labeling your images. Perhaps, LabelImg is the most popular and easiest to use. Using the instructions from the github repo, download and install it on your local machine."
},
{
"code": null,
"e": 3191,
"s": 3149,
"text": "Using LabelImg is easy, just remember to:"
},
{
"code": null,
"e": 3466,
"s": 3191,
"text": "Create a new directory for the labels, I will name it annotationsIn LabelImg, Click on Change Save Dir and select the annotations folder. This is where the labels/annotations will be saved.Click on Open Dir and select the images folder.Use the shortcuts to make this faster."
},
{
"code": null,
"e": 3532,
"s": 3466,
"text": "Create a new directory for the labels, I will name it annotations"
},
{
"code": null,
"e": 3657,
"s": 3532,
"text": "In LabelImg, Click on Change Save Dir and select the annotations folder. This is where the labels/annotations will be saved."
},
{
"code": null,
"e": 3705,
"s": 3657,
"text": "Click on Open Dir and select the images folder."
},
{
"code": null,
"e": 3744,
"s": 3705,
"text": "Use the shortcuts to make this faster."
},
{
"code": null,
"e": 3915,
"s": 3744,
"text": "Shortcuts for MacOS:_____| CMD + s | Save the label_| w | Create a box_| d | Next image| a | Previous image_| CMD + + | Zoom in| CMD + - | Zoom out_____"
},
{
"code": null,
"e": 4119,
"s": 3915,
"text": "By default, The labels will be in PascalVOC format. Each image will have one .xml file that has its labels. If there is more than one class or one label in an image, that .xml file will include them all."
},
{
"code": null,
"e": 4411,
"s": 4119,
"text": "Create a new Notebook.From the top left menu: Go to Runtime > Change runtime type > select GPU from hardware accelerator. Some pretrained models support TPU. The pretrained model we are choosing in this project only supports GPU.(Highly Recommended) Mount Google Drive to the Colab notebook:"
},
{
"code": null,
"e": 4434,
"s": 4411,
"text": "Create a new Notebook."
},
{
"code": null,
"e": 4642,
"s": 4434,
"text": "From the top left menu: Go to Runtime > Change runtime type > select GPU from hardware accelerator. Some pretrained models support TPU. The pretrained model we are choosing in this project only supports GPU."
},
{
"code": null,
"e": 4705,
"s": 4642,
"text": "(Highly Recommended) Mount Google Drive to the Colab notebook:"
},
{
"code": null,
"e": 5273,
"s": 4705,
"text": "When training starts, checkpoints, logs and many other important files will be created. When the kernel disconnects, these files, along with everything else, will be deleted if they don’t get saved on your Google Drive or somewhere else.The kernel disconnects shortly after your computer sleeps or after using the Colab GPU for 12 hours. Training will need to be restarted from zero if the trained model did not get saved.2I also highly recommend downloading Google Backup and Sync app so it’s easier to move and edit files as well as to keep everything synchronized."
},
{
"code": null,
"e": 5342,
"s": 5273,
"text": "Head to your Google Drive and create a folder named object_detection"
},
{
"code": null,
"e": 5438,
"s": 5342,
"text": "Open Google Backup and Sync app on your local machine and select that object_detection folder ←"
},
{
"code": null,
"e": 5518,
"s": 5438,
"text": "Note: This method will greatly depend on the speed of your internet connection."
},
{
"code": null,
"e": 5520,
"s": 5518,
"text": "."
},
{
"code": null,
"e": 5640,
"s": 5520,
"text": "On the Colab Notebook, Mount gdrive and navigate to the project’s folder, you will be asked for the authorization code:"
},
{
"code": null,
"e": 5755,
"s": 5640,
"text": "from google.colab import drive drive.mount('/gdrive')# the project's folder%cd /gdrive/'My Drive'/object_detection"
},
{
"code": null,
"e": 5898,
"s": 5755,
"text": "Inside object_detectionfolder, create a folder data that will have the images and labels. Choose one of the methods below to upload your data."
},
{
"code": null,
"e": 5932,
"s": 5898,
"text": "Using Google Backup and Sync app:"
},
{
"code": null,
"e": 5966,
"s": 5932,
"text": "Using Google Backup and Sync app:"
},
{
"code": null,
"e": 6091,
"s": 5966,
"text": "Uploading the images and annotations folders is easy; just move them to the data/object_detection folder from your computer."
},
{
"code": null,
"e": 6093,
"s": 6091,
"text": "."
},
{
"code": null,
"e": 6095,
"s": 6093,
"text": "."
},
{
"code": null,
"e": 6136,
"s": 6095,
"text": "2. Uploading directly from the notebook:"
},
{
"code": null,
"e": 6170,
"s": 6136,
"text": "Note: This method is the slowest."
},
{
"code": null,
"e": 6412,
"s": 6170,
"text": "Use the following to upload directly to the notebook. You will have to either zip the images folder or upload them separately (uploading a folder to Google Colab is not supported). Organizing and having the same files structure is important."
},
{
"code": null,
"e": 6468,
"s": 6412,
"text": "from google.colab import filesuploaded = files.upload()"
},
{
"code": null,
"e": 6503,
"s": 6468,
"text": "3. Uploading directly from source:"
},
{
"code": null,
"e": 6567,
"s": 6503,
"text": "You could also download directly from source using curl or wget"
},
{
"code": null,
"e": 6597,
"s": 6567,
"text": "The working directory so far:"
},
{
"code": null,
"e": 6948,
"s": 6597,
"text": "object_detection └── data ├── images │ ├── image_1.jpg │ ├── image_2.jpg │ └── ... │ └── annotations ├── image_1.xml ├── image_2.xml └── ..."
},
{
"code": null,
"e": 7140,
"s": 6948,
"text": "Tip: You can view the full working directory on Google Colab Notebook by: Open the left panel by clicking on the top left arrow. Or use ⌘/Ctrl+Alt+PThen Click on Files from the top left menu."
},
{
"code": null,
"e": 7326,
"s": 7140,
"text": "Depending on how large your dataset is, you might want to split your data manually. If you have a lot of pictures, you might want to use something like this to split your data randomly."
},
{
"code": null,
"e": 7402,
"s": 7326,
"text": "Note: The images inside images don’t need to be split, only the .xml files."
},
{
"code": null,
"e": 7439,
"s": 7402,
"text": "The working directory at this point:"
},
{
"code": null,
"e": 8021,
"s": 7439,
"text": "object_detection └── data ├── images │ ├── image_1.jpg │ └── ... │ ├── annotations │ ├── image_1.xml │ └── ... │ ├── train_labels //contains the labels only │ ├── image_1.xml │ └── ... │ └── test_labels //contains the labels only ├── image_50.xml └── ..."
},
{
"code": null,
"e": 8115,
"s": 8021,
"text": "Google Colab has most of the packages pre installed already; Python, Tensorflow, pandas, etc."
},
{
"code": null,
"e": 8221,
"s": 8115,
"text": "These are the packages we will need and they don’t get pre installed by default. Install them by running:"
},
{
"code": null,
"e": 8363,
"s": 8221,
"text": "!apt-get install -qq protobuf-compiler python-pil python-lxml python-tk!pip install -qq Cython contextlib2 pillow lxml matplotlib pycocotools"
},
{
"code": null,
"e": 8409,
"s": 8363,
"text": "Other Imports will be done when needed later."
},
{
"code": null,
"e": 8481,
"s": 8409,
"text": "We need Tensorflow version 1.15.0. Check Tensorflow version by running:"
},
{
"code": null,
"e": 8503,
"s": 8481,
"text": "print(tf.__version__)"
},
{
"code": null,
"e": 8593,
"s": 8503,
"text": "We need to create two csv files for the .xml files in each train_labels/ and test_labels/"
},
{
"code": null,
"e": 8783,
"s": 8593,
"text": "These 2 csv files will contain each image’s file name, the label /box position, etc. Also, more than one row is created for the same picture if there is more than one class or label for it."
},
{
"code": null,
"e": 8996,
"s": 8783,
"text": "Other than the CSVs, we will need to create a pbtxt file that will contain the label map for each class. This file will tell the model what each object is by defining a mapping of class names to class ID numbers."
},
{
"code": null,
"e": 9147,
"s": 8996,
"text": "You don’t have to do any of these manually, the following will convert the xml files to two csvs and will create the .pbtxt file. Just make sure that:"
},
{
"code": null,
"e": 9275,
"s": 9147,
"text": "The same folders’ name where the xmls are located is matched:train_labels/ and test_labels/ (or change them for the code below)"
},
{
"code": null,
"e": 9319,
"s": 9275,
"text": "Current directory is object_detection/data/"
},
{
"code": null,
"e": 9349,
"s": 9319,
"text": "The images are in .jpg format"
},
{
"code": null,
"e": 9386,
"s": 9349,
"text": "The working directory at this point:"
},
{
"code": null,
"e": 9867,
"s": 9386,
"text": "object_detection/ └── data/ ├── images/ │ └── ... ├── annotations/ │ └── ... ├── train_labels/ │ └── ... ├── test_labels/ │ └── ... │ ├── label_map.pbtxt │ ├── test_labels.csv │ └── train_labels.csv"
},
{
"code": null,
"e": 9979,
"s": 9867,
"text": "Tensorflow model contains the object detection API we are interested in. We will get it from the official repo."
},
{
"code": null,
"e": 10020,
"s": 9979,
"text": "Navigate to object_detection/ dir, then:"
},
{
"code": null,
"e": 10098,
"s": 10020,
"text": "# downloads the models!git clone --q https://github.com/tensorflow/models.git"
},
{
"code": null,
"e": 10335,
"s": 10098,
"text": "Next, we need to compile the proto buffers — Not important to understand for this project but you can learn more about them here. Also, the PATH var should have the following directories added: models/research/ and models/research/slim/"
},
{
"code": null,
"e": 10392,
"s": 10335,
"text": "Navigate to object_detection/models/research/ dir, then:"
},
{
"code": null,
"e": 10580,
"s": 10392,
"text": "# compils the proto buffers!protoc object_detection/protos/*.proto --python_out=.# exports PYTHONPATH environment var with research and slim pathsos.environ['PYTHONPATH'] += ':./:./slim/'"
},
{
"code": null,
"e": 10661,
"s": 10580,
"text": "Finally, run a quick test to confirm that the model builder is working properly:"
},
{
"code": null,
"e": 10745,
"s": 10661,
"text": "# testing the model builder!python3 object_detection/builders/model_builder_test.py"
},
{
"code": null,
"e": 10818,
"s": 10745,
"text": "If you see an OK at the end of the test, then everything is going great!"
},
{
"code": null,
"e": 11012,
"s": 10818,
"text": "Tensorflow accepts the data as TFRecords data.record. TFRecord is a binary file that runs fast with low memory usage. It contains all the images and labels in one file. Read more about it here."
},
{
"code": null,
"e": 11141,
"s": 11012,
"text": "In our case, we will have two TFRecords; one for testing and another for training. To make this work, we need to make sure that:"
},
{
"code": null,
"e": 11244,
"s": 11141,
"text": "The CSVs file names is matched:train_labels.csv and test_labels.csv (or change them in the code below)"
},
{
"code": null,
"e": 11298,
"s": 11244,
"text": "Current directory is object_detection/models/research"
},
{
"code": null,
"e": 11511,
"s": 11298,
"text": "Add your custom object text in the function class_text_to_int below by changing the row_label variable (This is the text that will appear on the detected object). Add more labels if you have more than one object."
},
{
"code": null,
"e": 11583,
"s": 11511,
"text": "Check if the path to data/ directory is the same asdata_base_url below."
},
{
"code": null,
"e": 11917,
"s": 11583,
"text": "A pre-trained model simply means that it has been trained on another dataset. That model has seen thousands or millions of images and objects.COCO (Common Objects in Context) is a dataset of 330,000 images that contains 1.5 million objects for 80 different classes. Such as, dogs, cats, cars, bananas, ... Check all the classes here."
},
{
"code": null,
"e": 12144,
"s": 11917,
"text": "Training a model from scratch is extremely time consuming; it may take days or weeks to finish training. A pre-trained model has already seen tons of objects and knows how to classify each one of them. So, why not just use it!"
},
{
"code": null,
"e": 12301,
"s": 12144,
"text": "Because our interest is to interfere on a real time video, we will be choosing a model that has a low ms inference speed with a relatively high mAP on COCO."
},
{
"code": null,
"e": 12588,
"s": 12301,
"text": "The model used for this project is ssd_mobilenet_v2_coco. Check the other models from here. You could use any pre-trained model you prefer, but I would suggest experimenting with SSD ‘Single Shot Detector’ models first as they perform faster than any type of RCNN on a real-time video4."
},
{
"code": null,
"e": 12801,
"s": 12588,
"text": "Explaining the difference between object detection techniques is out of the scope of this tutorial. You can read more about them from this blog post, or learn about how their speed and accuracy compare from here."
},
{
"code": null,
"e": 12848,
"s": 12801,
"text": "Let’s start with selecting a pretrained model:"
},
{
"code": null,
"e": 13084,
"s": 12848,
"text": "We will download the selected model. I have created these two models configurations to make it easier. the ssd_mobilenet_v2 is selected here, try using faster_rcnn_inception_v2 later if you would like. Just change selected_model above."
},
{
"code": null,
"e": 13113,
"s": 13084,
"text": "Navigate to models/research/"
},
{
"code": null,
"e": 13214,
"s": 13113,
"text": "DEST_DIR is where the model will be downloaded. Change it if you have a different working directory."
},
{
"code": null,
"e": 13442,
"s": 13214,
"text": "While training, the model will get autosaved every 600 seconds by default. The logs and graphs, such as, the mAP, loss and AR, will also get saved constantly. Lets create a folder for all of them to be saved in during training:"
},
{
"code": null,
"e": 13514,
"s": 13442,
"text": "Create a folder called training inside object_detection/model/research/"
},
{
"code": null,
"e": 13551,
"s": 13514,
"text": "The working directory at this point:"
},
{
"code": null,
"e": 14330,
"s": 13551,
"text": "object_detection/ ├── data/ │ ├── images/ │ │ └── ... │ ├── annotations/ │ │ └── ... │ ├── train_labels/ │ │ └── ... │ ├── test_labels/ │ │ └── ... │ ├── label_map.pbtxt │ ├── test_labels.csv │ ├── train_labels.csv │ ├── test_labels.records │ └── train_labels.records │ └── models/ ├── research/ │ ├── training/ │ │ └── ... │ ├── pretrained_model/ │ ├── frozen_inference_graph.pb │ └── ... └── ..."
},
{
"code": null,
"e": 14477,
"s": 14330,
"text": "This is the last step before starting to train the model, finally! Perhaps, it will be the step where you might spend some time to tune the model."
},
{
"code": null,
"e": 14640,
"s": 14477,
"text": "Tensorflow Object Detection API model we downloaded comes with many sample config files. For each model, there is a config file that is ‘almost’ ready to be used."
},
{
"code": null,
"e": 14675,
"s": 14640,
"text": "The config files are located here:"
},
{
"code": null,
"e": 14742,
"s": 14675,
"text": "object_detection/models/research/object_detection/samples/configs/"
},
{
"code": null,
"e": 14911,
"s": 14742,
"text": "ssd_mobilenet_v2_coco.config is the config file for the pretrained model we are using. If you chose another model, you need to use & edit the correspondent config file."
},
{
"code": null,
"e": 15003,
"s": 14911,
"text": "Because we will probably have to tune the config constantly, I suggest doing the following:"
},
{
"code": null,
"e": 15058,
"s": 15003,
"text": "view the content of the sample config file by running:"
},
{
"code": null,
"e": 15094,
"s": 15058,
"text": "Copy the content of the config file"
},
{
"code": null,
"e": 15111,
"s": 15094,
"text": "Edit it by using"
},
{
"code": null,
"e": 15242,
"s": 15111,
"text": "Or, you can open and edit the config file directly from your local machine if you have everything synced by using any text editor."
},
{
"code": null,
"e": 15382,
"s": 15242,
"text": "Here are the required edits that need to be changed in the sample config file, also some suggested edits to improve your model performance."
},
{
"code": null,
"e": 15420,
"s": 15382,
"text": "➊. Required edits to the config file:"
},
{
"code": null,
"e": 15493,
"s": 15420,
"text": "model {} > ssd {}: change num_classes to the number of classes you have."
},
{
"code": null,
"e": 15566,
"s": 15493,
"text": "model {} > ssd {}: change num_classes to the number of classes you have."
},
{
"code": null,
"e": 15643,
"s": 15566,
"text": "2. train_config {}: change fine_tune_checkpoint to the checkpoint file path."
},
{
"code": null,
"e": 15777,
"s": 15643,
"text": "Note: The exact file name model.ckpt doesn't exist. This is where the model will be saved during training. This is its relative path:"
},
{
"code": null,
"e": 15839,
"s": 15777,
"text": "/object_detection/models/research/pretrained_model/model.ckpt"
},
{
"code": null,
"e": 15935,
"s": 15839,
"text": "3. train_input_reader {}: set the path to the train_labels.record and the label map pbtxt file."
},
{
"code": null,
"e": 16029,
"s": 15935,
"text": "4. eval_input_reader {}: set the path to the test_labels.record and the label map pbtxt file."
},
{
"code": null,
"e": 16094,
"s": 16029,
"text": "That’s it! You can skip the optional edits and head to training!"
},
{
"code": null,
"e": 16133,
"s": 16094,
"text": "➋. Suggested edits to the config file:"
},
{
"code": null,
"e": 16289,
"s": 16133,
"text": "First, you might want to start training the model and see how well it does. If you are overfitting, then you might want to do some more image augmentation."
},
{
"code": null,
"e": 16415,
"s": 16289,
"text": "In the sample config file: random_horizontal_flip & ssd_random_crop are added by default. You could try adding these as well:"
},
{
"code": null,
"e": 16437,
"s": 16415,
"text": "from train_config {}:"
},
{
"code": null,
"e": 16512,
"s": 16437,
"text": "Note: Each image augmentation will increase the training time drastically."
},
{
"code": null,
"e": 16620,
"s": 16512,
"text": "There are many data augmentation options that you can add. Check the full list from the official code here."
},
{
"code": null,
"e": 16730,
"s": 16620,
"text": "In model {} > ssd {} > box_predictor {}: set use_dropout to true This will be helpful to counter overfitting."
},
{
"code": null,
"e": 16853,
"s": 16730,
"text": "In eval_config : {} set the number of testing images you have in num_examples and remove max_eval to evaluate indefinitely"
},
{
"code": null,
"e": 16958,
"s": 16853,
"text": "Note: The notebook provided explains many more things in regard to tuning the config file. Check it out!"
},
{
"code": null,
"e": 17053,
"s": 16958,
"text": "The full working directory: (Including some files/folders that will be created and used later)"
},
{
"code": null,
"e": 18515,
"s": 17053,
"text": "object_detection/ ├── data/ │ ├── images/ │ │ └── ... │ ├── annotations/ │ │ └── ... │ ├── train_labels/ │ │ └── ... │ ├── test_labels/ │ │ └── ... │ ├── label_map.pbtxt │ ├── test_labels.csv │ ├── train_labels.csv │ ├── test_labels.records │ └── train_labels.records │ └── models/ ├─ research/ │ ├── fine_tuned_model/ │ │ ├── frozen_inference_graph.pb │ │ └── ... │ │ │ ├── pretrained_model/ │ │ ├── frozen_inference_graph.pb │ │ └── ... │ │ │ ├── object_detection/ │ │ ├── utils/ │ │ ├── samples/ │ │ │ ├── configs/ │ │ │ │ ├── ssd_mobilenet_v2_coco.config │ │ │ │ ├── rfcn_resnet101_pets.config │ │ │ │ └── ... │ │ │ └── ... │ │ ├── export_inference_graph.py │ │ ├── model_main.py │ │ └── ... │ │ │ ├── training/ │ │ ├── events.out.tfevents.xxxxx │ │ └── ... │ └── ... └── ..."
},
{
"code": null,
"e": 18657,
"s": 18515,
"text": "Tensorboard is the place where we can visualize everything that’s happening during training. You can monitor the loss, mAP, AR and many more."
},
{
"code": null,
"e": 18948,
"s": 18657,
"text": "You could also monitor the pictures and the annotations during training. At each evaluation step, you could see how good your model was at detecting the object ←.Note: Remember when we set num_visualizations: 20 above? Tensorboard will display that much pictures of the testing images here."
},
{
"code": null,
"e": 19029,
"s": 18948,
"text": "To use Tensorboard on Colab, we need to use it through ngrok. Get it by running:"
},
{
"code": null,
"e": 19122,
"s": 19029,
"text": "Next, we specify where the log files are stored and we configure a link to view Tensorboard:"
},
{
"code": null,
"e": 19238,
"s": 19122,
"text": "When you run the code above, at the end of the output there will be a url where you can access Tensorboard through."
},
{
"code": null,
"e": 19245,
"s": 19238,
"text": "Notes:"
},
{
"code": null,
"e": 19605,
"s": 19245,
"text": "You might not get a url when running the above code, but an error instead. Just run the above cell again. No need to reinstall ngrok.Tensorboard will not log any files until the training starts.A max of 20 connection per minute is allowed when using ngrok, you will not be able to access tensorboard while the model is logging to it. (happens very frequently)"
},
{
"code": null,
"e": 19739,
"s": 19605,
"text": "You might not get a url when running the above code, but an error instead. Just run the above cell again. No need to reinstall ngrok."
},
{
"code": null,
"e": 19801,
"s": 19739,
"text": "Tensorboard will not log any files until the training starts."
},
{
"code": null,
"e": 19967,
"s": 19801,
"text": "A max of 20 connection per minute is allowed when using ngrok, you will not be able to access tensorboard while the model is logging to it. (happens very frequently)"
},
{
"code": null,
"e": 20086,
"s": 19967,
"text": "If you have the project synced to your local machine, you will be able to view the Tensorboard without any limitation."
},
{
"code": null,
"e": 20132,
"s": 20086,
"text": "Go to terminal on your local machine and run:"
},
{
"code": null,
"e": 20158,
"s": 20132,
"text": "$ pip install tensorboard"
},
{
"code": null,
"e": 20203,
"s": 20158,
"text": "Run it and specify where the logging dir is:"
},
{
"code": null,
"e": 20347,
"s": 20203,
"text": "# in my case, the path to the training folder is:tensorboard --logdir=/Users/alaasenjab/Google\\ Drive/object_detection/models/research/training"
},
{
"code": null,
"e": 20433,
"s": 20347,
"text": "Training the model is as easy as running the following code. We just need to give it:"
},
{
"code": null,
"e": 20479,
"s": 20433,
"text": "model_main.py which runs the training process"
},
{
"code": null,
"e": 20533,
"s": 20479,
"text": "pipeline_config_path=Path/to/config/file/model.config"
},
{
"code": null,
"e": 20562,
"s": 20533,
"text": "model_dir= Path/to/training/"
},
{
"code": null,
"e": 20569,
"s": 20562,
"text": "Notes:"
},
{
"code": null,
"e": 20813,
"s": 20569,
"text": "If the kernel dies, the training will resume from the last checkpoint. Unless you didn’t save the training/ directory somewhere, ex: GDrive.If you are changing the below paths, make sure there is no space between the equal sign = and the path."
},
{
"code": null,
"e": 20954,
"s": 20813,
"text": "If the kernel dies, the training will resume from the last checkpoint. Unless you didn’t save the training/ directory somewhere, ex: GDrive."
},
{
"code": null,
"e": 21058,
"s": 20954,
"text": "If you are changing the below paths, make sure there is no space between the equal sign = and the path."
},
{
"code": null,
"e": 21114,
"s": 21058,
"text": "Now set back and watch your model train on Tensorboard."
},
{
"code": null,
"e": 21270,
"s": 21114,
"text": "By default, the model will save a checkpoint every 600 seconds while training up to 5 checkpoints. Then, as new files are created, older files are deleted."
},
{
"code": null,
"e": 21327,
"s": 21270,
"text": "We can find the last model trained by running this code:"
},
{
"code": null,
"e": 21629,
"s": 21327,
"text": "Then by executing export_inference_graph.py to convert the model to a frozen model frozen_inference_graph.pb that we can use for inference. This frozen model can’t be used to resume training. However, saved_model.pb gets exported as well which can be used to resume training as it has all the weights."
},
{
"code": null,
"e": 21683,
"s": 21629,
"text": "pipeline_config_path=Path/to/config/file/model.config"
},
{
"code": null,
"e": 21734,
"s": 21683,
"text": "output_directory= where the model will be saved at"
},
{
"code": null,
"e": 21781,
"s": 21734,
"text": "trained_checkpoint_prefix=Path/to/a/checkpoint"
},
{
"code": null,
"e": 21836,
"s": 21781,
"text": "You can access all exported files from this directory:"
},
{
"code": null,
"e": 21904,
"s": 21836,
"text": "/gdrive/My Drive/object_detection/models/research/pretrained_model/"
},
{
"code": null,
"e": 21991,
"s": 21904,
"text": "Or, you can download the frozen graph needed for inference directly from Google Colab:"
},
{
"code": null,
"e": 22171,
"s": 21991,
"text": "#downloads the frozen model that is needed for inference# output_directory = 'fine_tuned_model' dir specified above.files.download(output_directory + '/frozen_inference_graph.pb')"
},
{
"code": null,
"e": 22211,
"s": 22171,
"text": "We also need the label map .pbtxt file:"
},
{
"code": null,
"e": 22370,
"s": 22211,
"text": "#downlaod the label map# we specified 'data_base_url' above. It directs to# 'object_detection/data/' folder.files.download(data_base_url + '/label_map.pbtxt')"
},
{
"code": null,
"e": 22477,
"s": 22370,
"text": "To use your webcam in your local machine to inference the model, you need to have the following installed:"
},
{
"code": null,
"e": 22508,
"s": 22477,
"text": "Tensorflow = 1.15.0cv2 = 4.1.2"
},
{
"code": null,
"e": 22683,
"s": 22508,
"text": "You also need Tensorflow model downloaded on your local machine (Step 5 above) or you can skip that and navigate to the model if you have GDrive on your local machine synced."
},
{
"code": null,
"e": 22769,
"s": 22683,
"text": "Go to terminal on your local machine and navigate to models/research/object_detection"
},
{
"code": null,
"e": 22822,
"s": 22769,
"text": "In my case, I am navigating to the folder in GDrive."
},
{
"code": null,
"e": 22909,
"s": 22822,
"text": "$ cd /Users/alaasenjab/Google\\ Drive/object_detection/models/research/object_detection"
},
{
"code": null,
"e": 23059,
"s": 22909,
"text": "You can run the following from a jupyter notebook or by creating a .py file. However, change PATH_TO_FROZEN_GRAPH , PATH_TO_LABEL_MAP and NUM_CLASSES"
},
{
"code": null,
"e": 23085,
"s": 23059,
"text": "Run the code and smile :)"
},
{
"code": null,
"e": 23696,
"s": 23085,
"text": "Detecting objects from images and videos is a bit easier than in real-time. When we have a video or an image that we want to detect an object from, we don’t care much about the inference time the model might take to detect the object. In real-time object detection, we might want to sacrifice some precision over a faster inference time. In the case of detecting guns to notify the police, we don’t care much about detecting exactly where the gun is located. Instead, we probably would optimize for both:False Negative: Not detecting a gun when there is one.True Negative: Detecting a gun when there isn’t one."
},
{
"code": null,
"e": 23852,
"s": 23696,
"text": "I hope you found this tutorial on how to detect custom objects using Tensorflow easy and useful. Don’t forget to check the Colab Notebook for more details."
},
{
"code": null,
"e": 23936,
"s": 23852,
"text": "Please let me know if you have any question down below, I will try my best to help!"
}
]
|
3 Ways to Drastically Improve Your Programming Skills On Your Own | by Kurtis Pykes | Towards Data Science | I’ve always thought of myself to be a decent programmer, but, I’ve never had anything to measure it against. Well, that’s until I saw what a really good programmer looks like — now I’m obsessed with developing my skills.
Instead of explaining what happened, I’ll show you. The task was to refactor code that analyzes a wine quality dataset from the UCI Machine Learning Repository.
I recommend all readers attempt the challenge in the Google Colab I’ve created before proceeding with the rest of the article.
Disclaimer: This task is taken from the Machine Learning Engineer Nanodegree on Udacity.
Before I reveal the solution that enlightened me of my ignorance, let me show you the solution the course developers asked us to improve on ...
# Course providers solutionlabels = list(df.columns)labels[0] = labels[0].replace(' ', '_')labels[1] = labels[1].replace(' ', '_')labels[2] = labels[2].replace(' ', '_')labels[3] = labels[3].replace(' ', '_')labels[5] = labels[5].replace(' ', '_')labels[6] = labels[6].replace(' ', '_')df.columns = labelsdf.head()
It seemed like a pretty simple task. Here’s my solution...
# My improvement of the solutiondef remove_spaces(df): cols = list(df.columns) for i in range(len(cols)): cols[i] = cols[i].replace(" ", "_") df.columns = cols return dfdf = remove_spaces(df)df.head()
One could argue that my solution is an improvement to their solution since it eradicates the repetitive nature of the code — therefore abiding by the Don’t Repeat Yourself (DRY) best practice from software engineering. However, it’s not the optimal solution and can be improved.
Here’s how the course providers optimized their solution...
df.columns = [label.replace(' ', '_') for label in df.columns]df.head()
Simple and elegant.
What annoys me most about their solution is that I understand it. I know the logic well. I can write list comprehensions just like they’ve done. But, I couldn't come up with that solution. Not once did it cross my mind to do a list comprehension which is crazy to think of it now because I used a for loop.
This blooper activated my latest mission. A day does not pass where I am not actively attempting to better my programming skills.
Below, I’ve listed 3 methods I employ daily to improve my programming skills.
It goes without saying... If you want to be a better writer, you’ve got to become a better reader — this means reading more books, as well as a wider range of books.
In the same way, if you want to become a better programmer, which effectively is a different form of writing, you should seek to read a lot more code, especially code from very good programmers.
Some Github repositories with really good code are:
Scikit-Learn
Findings from Stackoverflow by JJruner
Bootstrap
It doesn't stop at reading code.
There are plenty of books out there to help you become a better programmer — A popular book to get you started is The Pragmatic Programmer by David Thomas & Andrew Hunt — but reading, in general, is really useful as it expands your mind.
Note: By clicking on the book link above, you would be directed to Amazon via my affiliates link. I’ve also integrated geo-linking so if you are not in the UK, you would automatically be directed to your local Amazon store.
I’ll be honest, initially, I adopted the mindset of “if it works, then it’s good”. Refactoring code always gets put off. In hindsight, it’s actually quite daft. I would never publish an article without iterating over it once or twice to ensure I am conveying the messaging I wish to.
Of course, code refactoring serves a different purpose. The purpose of refactoring code is to either make the code more efficient, more maintainable or both.
To become a better programmer, you must set aside time to refactor. To improve your refactoring skills, you must learn about refactoring — this will give you an idea of what to look for. Lastly, ensure you devote a lot of time refactoring code. You can revisit past projects or others people's projects and modify their code to make it more efficient, maintainable, or both.
If you want to become a better writer, you have to write more. If you want to become a better cook, you have to cook more. If you want to become a better programmer, you have to write more programs.
A little hack you could steal to write more programs is to start by writing lots of small programs. This will allow you to crank up the amount of code you’re writing each day which would allow you to create a lot more programs.
However, a large number of small programs would not cover the scope of programming skills required to be considered a good programmer. At some point, it’s important to make the transition from writing lots of small programs to writing larger programs as this would reveal a new set challenges that would force you to become a better programmer.
While these methods are great if you’re working in isolation to improve your programming skills, in the real world, it’s likely you’re going to be collaborating with other people. From my little experience, true growth comes when you step out of isolation and begin to work with others, especially those that are much smarter than you since you can adopt their methodologies to become a better programmer.
If you think I’ve left some ideas out leave a comment so we can continue to develop in unison.
Thanks for Reading!
If you enjoyed this article, connect with me by subscribing to my FREE weekly newsletter. Never miss a post I make about Artificial Intelligence, Data Science, and Freelancing. | [
{
"code": null,
"e": 393,
"s": 172,
"text": "I’ve always thought of myself to be a decent programmer, but, I’ve never had anything to measure it against. Well, that’s until I saw what a really good programmer looks like — now I’m obsessed with developing my skills."
},
{
"code": null,
"e": 554,
"s": 393,
"text": "Instead of explaining what happened, I’ll show you. The task was to refactor code that analyzes a wine quality dataset from the UCI Machine Learning Repository."
},
{
"code": null,
"e": 681,
"s": 554,
"text": "I recommend all readers attempt the challenge in the Google Colab I’ve created before proceeding with the rest of the article."
},
{
"code": null,
"e": 770,
"s": 681,
"text": "Disclaimer: This task is taken from the Machine Learning Engineer Nanodegree on Udacity."
},
{
"code": null,
"e": 914,
"s": 770,
"text": "Before I reveal the solution that enlightened me of my ignorance, let me show you the solution the course developers asked us to improve on ..."
},
{
"code": null,
"e": 1229,
"s": 914,
"text": "# Course providers solutionlabels = list(df.columns)labels[0] = labels[0].replace(' ', '_')labels[1] = labels[1].replace(' ', '_')labels[2] = labels[2].replace(' ', '_')labels[3] = labels[3].replace(' ', '_')labels[5] = labels[5].replace(' ', '_')labels[6] = labels[6].replace(' ', '_')df.columns = labelsdf.head()"
},
{
"code": null,
"e": 1288,
"s": 1229,
"text": "It seemed like a pretty simple task. Here’s my solution..."
},
{
"code": null,
"e": 1508,
"s": 1288,
"text": "# My improvement of the solutiondef remove_spaces(df): cols = list(df.columns) for i in range(len(cols)): cols[i] = cols[i].replace(\" \", \"_\") df.columns = cols return dfdf = remove_spaces(df)df.head()"
},
{
"code": null,
"e": 1787,
"s": 1508,
"text": "One could argue that my solution is an improvement to their solution since it eradicates the repetitive nature of the code — therefore abiding by the Don’t Repeat Yourself (DRY) best practice from software engineering. However, it’s not the optimal solution and can be improved."
},
{
"code": null,
"e": 1847,
"s": 1787,
"text": "Here’s how the course providers optimized their solution..."
},
{
"code": null,
"e": 1919,
"s": 1847,
"text": "df.columns = [label.replace(' ', '_') for label in df.columns]df.head()"
},
{
"code": null,
"e": 1939,
"s": 1919,
"text": "Simple and elegant."
},
{
"code": null,
"e": 2246,
"s": 1939,
"text": "What annoys me most about their solution is that I understand it. I know the logic well. I can write list comprehensions just like they’ve done. But, I couldn't come up with that solution. Not once did it cross my mind to do a list comprehension which is crazy to think of it now because I used a for loop."
},
{
"code": null,
"e": 2376,
"s": 2246,
"text": "This blooper activated my latest mission. A day does not pass where I am not actively attempting to better my programming skills."
},
{
"code": null,
"e": 2454,
"s": 2376,
"text": "Below, I’ve listed 3 methods I employ daily to improve my programming skills."
},
{
"code": null,
"e": 2620,
"s": 2454,
"text": "It goes without saying... If you want to be a better writer, you’ve got to become a better reader — this means reading more books, as well as a wider range of books."
},
{
"code": null,
"e": 2815,
"s": 2620,
"text": "In the same way, if you want to become a better programmer, which effectively is a different form of writing, you should seek to read a lot more code, especially code from very good programmers."
},
{
"code": null,
"e": 2867,
"s": 2815,
"text": "Some Github repositories with really good code are:"
},
{
"code": null,
"e": 2880,
"s": 2867,
"text": "Scikit-Learn"
},
{
"code": null,
"e": 2919,
"s": 2880,
"text": "Findings from Stackoverflow by JJruner"
},
{
"code": null,
"e": 2929,
"s": 2919,
"text": "Bootstrap"
},
{
"code": null,
"e": 2962,
"s": 2929,
"text": "It doesn't stop at reading code."
},
{
"code": null,
"e": 3200,
"s": 2962,
"text": "There are plenty of books out there to help you become a better programmer — A popular book to get you started is The Pragmatic Programmer by David Thomas & Andrew Hunt — but reading, in general, is really useful as it expands your mind."
},
{
"code": null,
"e": 3424,
"s": 3200,
"text": "Note: By clicking on the book link above, you would be directed to Amazon via my affiliates link. I’ve also integrated geo-linking so if you are not in the UK, you would automatically be directed to your local Amazon store."
},
{
"code": null,
"e": 3708,
"s": 3424,
"text": "I’ll be honest, initially, I adopted the mindset of “if it works, then it’s good”. Refactoring code always gets put off. In hindsight, it’s actually quite daft. I would never publish an article without iterating over it once or twice to ensure I am conveying the messaging I wish to."
},
{
"code": null,
"e": 3866,
"s": 3708,
"text": "Of course, code refactoring serves a different purpose. The purpose of refactoring code is to either make the code more efficient, more maintainable or both."
},
{
"code": null,
"e": 4241,
"s": 3866,
"text": "To become a better programmer, you must set aside time to refactor. To improve your refactoring skills, you must learn about refactoring — this will give you an idea of what to look for. Lastly, ensure you devote a lot of time refactoring code. You can revisit past projects or others people's projects and modify their code to make it more efficient, maintainable, or both."
},
{
"code": null,
"e": 4440,
"s": 4241,
"text": "If you want to become a better writer, you have to write more. If you want to become a better cook, you have to cook more. If you want to become a better programmer, you have to write more programs."
},
{
"code": null,
"e": 4668,
"s": 4440,
"text": "A little hack you could steal to write more programs is to start by writing lots of small programs. This will allow you to crank up the amount of code you’re writing each day which would allow you to create a lot more programs."
},
{
"code": null,
"e": 5013,
"s": 4668,
"text": "However, a large number of small programs would not cover the scope of programming skills required to be considered a good programmer. At some point, it’s important to make the transition from writing lots of small programs to writing larger programs as this would reveal a new set challenges that would force you to become a better programmer."
},
{
"code": null,
"e": 5419,
"s": 5013,
"text": "While these methods are great if you’re working in isolation to improve your programming skills, in the real world, it’s likely you’re going to be collaborating with other people. From my little experience, true growth comes when you step out of isolation and begin to work with others, especially those that are much smarter than you since you can adopt their methodologies to become a better programmer."
},
{
"code": null,
"e": 5514,
"s": 5419,
"text": "If you think I’ve left some ideas out leave a comment so we can continue to develop in unison."
},
{
"code": null,
"e": 5534,
"s": 5514,
"text": "Thanks for Reading!"
}
]
|
VBA - While Wend Loops | In a While...Wend loop, if the condition is True, all the statements are executed until the Wend keyword is encountered.
If the condition is false, the loop is exited and the control jumps to the very next statement after the Wend keyword.
Following is the syntax of a While..Wend loop in VBA.
While condition(s)
[statements 1]
[statements 2]
...
[statements n]
Wend
Private Sub Constant_demo_Click()
Dim Counter : Counter = 10
While Counter < 15 ' Test value of Counter.
Counter = Counter + 1 ' Increment Counter.
msgbox "The Current Value of the Counter is : " & Counter
Wend ' While loop exits if Counter Value becomes 15.
End Sub
When the above code is executed, it prints the following in a message box.
The Current Value of the Counter is : 11
The Current Value of the Counter is : 12
The Current Value of the Counter is : 13
The Current Value of the Counter is : 14
The Current Value of the Counter is : 15
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": 2056,
"s": 1935,
"text": "In a While...Wend loop, if the condition is True, all the statements are executed until the Wend keyword is encountered."
},
{
"code": null,
"e": 2175,
"s": 2056,
"text": "If the condition is false, the loop is exited and the control jumps to the very next statement after the Wend keyword."
},
{
"code": null,
"e": 2229,
"s": 2175,
"text": "Following is the syntax of a While..Wend loop in VBA."
},
{
"code": null,
"e": 2315,
"s": 2229,
"text": "While condition(s)\n [statements 1]\n [statements 2]\n ...\n [statements n]\nWend\n"
},
{
"code": null,
"e": 2622,
"s": 2315,
"text": "Private Sub Constant_demo_Click()\n Dim Counter : Counter = 10 \n \n While Counter < 15 ' Test value of Counter.\n Counter = Counter + 1 ' Increment Counter.\n msgbox \"The Current Value of the Counter is : \" & Counter\n Wend ' While loop exits if Counter Value becomes 15.\nEnd Sub "
},
{
"code": null,
"e": 2697,
"s": 2622,
"text": "When the above code is executed, it prints the following in a message box."
},
{
"code": null,
"e": 2911,
"s": 2697,
"text": "The Current Value of the Counter is : 11 \n\nThe Current Value of the Counter is : 12 \n\nThe Current Value of the Counter is : 13 \n\nThe Current Value of the Counter is : 14 \n\nThe Current Value of the Counter is : 15\n"
},
{
"code": null,
"e": 2945,
"s": 2911,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2960,
"s": 2945,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 2993,
"s": 2960,
"text": "\n 41 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3008,
"s": 2993,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3043,
"s": 3008,
"text": "\n 80 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3061,
"s": 3043,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 3094,
"s": 3061,
"text": "\n 25 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3112,
"s": 3094,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 3145,
"s": 3112,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3160,
"s": 3145,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3196,
"s": 3160,
"text": "\n 92 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 3224,
"s": 3196,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 3231,
"s": 3224,
"text": " Print"
},
{
"code": null,
"e": 3242,
"s": 3231,
"text": " Add Notes"
}
]
|
Handling overfitting in deep learning models | by Bert Carremans | Towards Data Science | Overfitting occurs when you achieve a good fit of your model on the training data, while it does not generalize well on new, unseen data. In other words, the model learned patterns specific to the training data, which are irrelevant in other data.
We can identify overfitting by looking at validation metrics, like loss or accuracy. Usually, the validation metric stops improving after a certain number of epochs and begins to decrease afterward. The training metric continues to improve because the model seeks to find the best fit for the training data.
There are several manners in which we can reduce overfitting in deep learning models. The best option is to get more training data. Unfortunately, in real-world situations, you often do not have this possibility due to time, budget or technical constraints.
Another way to reduce overfitting is to lower the capacity of the model to memorize the training data. As such, the model will need to focus on the relevant patterns in the training data, which results in better generalization. In this post, we’ll discuss three options to achieve this.
We start by importing the necessary packages and configuring some parameters. We will use Keras to fit the deep learning models. The training data is the Twitter US Airline Sentiment data set from Kaggle.
# Basic packagesimport pandas as pd import numpy as npimport reimport collectionsimport matplotlib.pyplot as pltfrom pathlib import Path# Packages for data preparationfrom sklearn.model_selection import train_test_splitfrom nltk.corpus import stopwordsfrom keras.preprocessing.text import Tokenizerfrom keras.utils.np_utils import to_categoricalfrom sklearn.preprocessing import LabelEncoder# Packages for modelingfrom keras import modelsfrom keras import layersfrom keras import regularizersNB_WORDS = 10000 # Parameter indicating the number of words we'll put in the dictionaryNB_START_EPOCHS = 20 # Number of epochs we usually start to train withBATCH_SIZE = 512 # Size of the batches used in the mini-batch gradient descentMAX_LEN = 20 # Maximum number of words in a sequenceroot = Path('../')input_path = root / 'input/' ouput_path = root / 'output/'source_path = root / 'source/'
We will use some helper functions throughout this article.
def deep_model(model, X_train, y_train, X_valid, y_valid): ''' Function to train a multi-class model. The number of epochs and batch_size are set by the constants at the top of the notebook. Parameters: model : model with the chosen architecture X_train : training features y_train : training target X_valid : validation features Y_valid : validation target Output: model training history ''' model.compile(optimizer='rmsprop' , loss='categorical_crossentropy' , metrics=['accuracy']) history = model.fit(X_train , y_train , epochs=NB_START_EPOCHS , batch_size=BATCH_SIZE , validation_data=(X_valid, y_valid) , verbose=0) return historydef eval_metric(model, history, metric_name): ''' Function to evaluate a trained model on a chosen metric. Training and validation metric are plotted in a line chart for each epoch. Parameters: history : model training history metric_name : loss or accuracy Output: line chart with epochs of x-axis and metric on y-axis ''' metric = history.history[metric_name] val_metric = history.history['val_' + metric_name] e = range(1, NB_START_EPOCHS + 1) plt.plot(e, metric, 'bo', label='Train ' + metric_name) plt.plot(e, val_metric, 'b', label='Validation ' + metric_name) plt.xlabel('Epoch number') plt.ylabel(metric_name) plt.title('Comparing training and validation ' + metric_name + ' for ' + model.name) plt.legend() plt.show()def test_model(model, X_train, y_train, X_test, y_test, epoch_stop): ''' Function to test the model on new data after training it on the full training data with the optimal number of epochs. Parameters: model : trained model X_train : training features y_train : training target X_test : test features y_test : test target epochs : optimal number of epochs Output: test accuracy and test loss ''' model.fit(X_train , y_train , epochs=epoch_stop , batch_size=BATCH_SIZE , verbose=0) results = model.evaluate(X_test, y_test) print() print('Test accuracy: {0:.2f}%'.format(results[1]*100)) return results def remove_stopwords(input_text): ''' Function to remove English stopwords from a Pandas Series. Parameters: input_text : text to clean Output: cleaned Pandas Series ''' stopwords_list = stopwords.words('english') # Some words which might indicate a certain sentiment are kept via a whitelist whitelist = ["n't", "not", "no"] words = input_text.split() clean_words = [word for word in words if (word not in stopwords_list or word in whitelist) and len(word) > 1] return " ".join(clean_words) def remove_mentions(input_text): ''' Function to remove mentions, preceded by @, in a Pandas Series Parameters: input_text : text to clean Output: cleaned Pandas Series ''' return re.sub(r'@\w+', '', input_text)def compare_models_by_metric(model_1, model_2, model_hist_1, model_hist_2, metric): ''' Function to compare a metric between two models Parameters: model_hist_1 : training history of model 1 model_hist_2 : training history of model 2 metrix : metric to compare, loss, acc, val_loss or val_acc Output: plot of metrics of both models ''' metric_model_1 = model_hist_1.history[metric] metric_model_2 = model_hist_2.history[metric] e = range(1, NB_START_EPOCHS + 1) metrics_dict = { 'acc' : 'Training Accuracy', 'loss' : 'Training Loss', 'val_acc' : 'Validation accuracy', 'val_loss' : 'Validation loss' } metric_label = metrics_dict[metric] plt.plot(e, metric_model_1, 'bo', label=model_1.name) plt.plot(e, metric_model_2, 'b', label=model_2.name) plt.xlabel('Epoch number') plt.ylabel(metric_label) plt.title('Comparing ' + metric_label + ' between models') plt.legend() plt.show() def optimal_epoch(model_hist): ''' Function to return the epoch number where the validation loss is at its minimum Parameters: model_hist : training history of model Output: epoch number with minimum validation loss ''' min_epoch = np.argmin(model_hist.history['val_loss']) + 1 print("Minimum validation loss reached in epoch {}".format(min_epoch)) return min_epoch
We load the CSV with the tweets and perform a random shuffle. It’s a good practice to shuffle the data before splitting between a train and test set. That way the sentiment classes are equally distributed over the train and test sets. We’ll only keep the text column as input and the airline_sentiment column as the target.
The next thing we’ll do is removing stopwords. Stopwords do not have any value for predicting the sentiment. Furthermore, as we want to build a model that can be used for other airline companies as well, we remove the mentions.
df = pd.read_csv(input_path / 'Tweets.csv')df = df.reindex(np.random.permutation(df.index)) df = df[['text', 'airline_sentiment']]df.text = df.text.apply(remove_stopwords).apply(remove_mentions)
The evaluation of the model performance needs to be done on a separate test set. As such, we can estimate how well the model generalizes. This is done with the train_test_split method of scikit-learn.
X_train, X_test, y_train, y_test = train_test_split(df.text, df.airline_sentiment, test_size=0.1, random_state=37)
To use the text as input for a model, we first need to convert the words into tokens, which simply means converting the words to integers that refer to an index in a dictionary. Here we will only keep the most frequent words in the training set.
We clean up the text by applying filters and putting the words to lowercase. Words are separated by spaces.
tk = Tokenizer(num_words=NB_WORDS, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{"}~\t\n', lower=True, char_level=False, split=' ')tk.fit_on_texts(X_train)
After having created the dictionary we can convert the text of a tweet to a vector with NB_WORDS values. With mode=binary, it contains an indicator whether the word appeared in the tweet or not. This is done with the texts_to_matrix method of the Tokenizer.
X_train_oh = tk.texts_to_matrix(X_train, mode='binary')X_test_oh = tk.texts_to_matrix(X_test, mode='binary')
We need to convert the target classes to numbers as well, which in turn are one-hot-encoded with the to_categorical method in Keras
le = LabelEncoder()y_train_le = le.fit_transform(y_train)y_test_le = le.transform(y_test)y_train_oh = to_categorical(y_train_le)y_test_oh = to_categorical(y_test_le)
Now that our data is ready, we split off a validation set. This validation set will be used to evaluate the model performance when we tune the parameters of the model.
X_train_rest, X_valid, y_train_rest, y_valid = train_test_split(X_train_oh, y_train_oh, test_size=0.1, random_state=37)
We start with a model that overfits. It has 2 densely connected layers of 64 elements. The input_shape for the first layer is equal to the number of words we kept in the dictionary and for which we created one-hot-encoded features.
As we need to predict 3 different sentiment classes, the last layer has 3 elements. The softmax activation function makes sure the three probabilities sum up to 1.
The number of parameters to train is computed as (nb inputs x nb elements in hidden layer) + nb bias terms. The number of inputs for the first layer equals the number of words in our corpus. The subsequent layers have the number of outputs of the previous layer as inputs. So the number of parameters per layer are:
First layer : (10000 x 64) + 64 = 640064
Second layer : (64 x 64) + 64 = 4160
Last layer : (64 x 3) + 3 = 195
base_model = models.Sequential()base_model.add(layers.Dense(64, activation='relu', input_shape=(NB_WORDS,)))base_model.add(layers.Dense(64, activation='relu'))base_model.add(layers.Dense(3, activation='softmax'))base_model.name = 'Baseline model'
Because this project is a multi-class, single-label prediction, we use categorical_crossentropy as the loss function and softmax as the final activation function. We fit the model on the train data and validate on the validation set. We run for a predetermined number of epochs and will see when the model starts to overfit.
base_history = deep_model(base_model, X_train_rest, y_train_rest, X_valid, y_valid)base_min = optimal_epoch(base_history)eval_metric(base_model, base_history, 'loss')
In the beginning, the validation loss goes down. But at epoch 3 this stops and the validation loss starts increasing rapidly. This is when the models begin to overfit.
The training loss continues to go down and almost reaches zero at epoch 20. This is normal as the model is trained to fit the train data as good as possible.
Now, we can try to do something about the overfitting. There are different options to do that.
Reduce the network’s capacity by removing layers or reducing the number of elements in the hidden layers
Apply regularization, which comes down to adding a cost to the loss function for large weights
Use Dropout layers, which will randomly remove certain features by setting them to zero
Our first model has a large number of trainable parameters. The higher this number, the easier the model can memorize the target class for each training sample. Obviously, this is not ideal for generalizing on new data.
By lowering the capacity of the network, you force it to learn the patterns that matter or that minimize the loss. On the other hand, reducing the network’s capacity too much will lead to underfitting. The model will not be able to learn the relevant patterns in the train data.
We reduce the network’s capacity by removing one hidden layer and lowering the number of elements in the remaining layer to 16.
reduced_model = models.Sequential()reduced_model.add(layers.Dense(16, activation='relu', input_shape=(NB_WORDS,)))reduced_model.add(layers.Dense(3, activation='softmax'))reduced_model.name = 'Reduced model'reduced_history = deep_model(reduced_model, X_train_rest, y_train_rest, X_valid, y_valid)reduced_min = optimal_epoch(reduced_history)eval_metric(reduced_model, reduced_history, 'loss')
We can see that it takes more epochs before the reduced model starts overfitting. The validation loss also goes up slower than our first model.
compare_models_by_metric(base_model, reduced_model, base_history, reduced_history, 'val_loss')
When we compare the validation loss of the baseline model, it is clear that the reduced model starts overfitting at a later epoch. The validation loss stays lower much longer than the baseline model.
To address overfitting, we can apply weight regularization to the model. This will add a cost to the loss function of the network for large weights (or parameter values). As a result, you get a simpler model that will be forced to learn only the relevant patterns in the train data.
There are L1 regularization and L2 regularization.
L1 regularization will add a cost with regards to the absolute value of the parameters. It will result in some of the weights to be equal to zero.
L2 regularization will add a cost with regards to the squared value of the parameters. This results in smaller weights.
Let’s try with L2 regularization.
reg_model = models.Sequential()reg_model.add(layers.Dense(64, kernel_regularizer=regularizers.l2(0.001), activation='relu', input_shape=(NB_WORDS,)))reg_model.add(layers.Dense(64, kernel_regularizer=regularizers.l2(0.001), activation='relu'))reg_model.add(layers.Dense(3, activation='softmax'))reg_model.name = 'L2 Regularization model'reg_history = deep_model(reg_model, X_train_rest, y_train_rest, X_valid, y_valid)reg_min = optimal_epoch(reg_history)
For the regularized model we notice that it starts overfitting in the same epoch as the baseline model. However, the loss increases much slower afterward.
eval_metric(reg_model, reg_history, 'loss')
compare_models_by_metric(base_model, reg_model, base_history, reg_history, 'val_loss')
The last option we’ll try is to add Dropout layers. A Dropout layer will randomly set output features of a layer to zero.
drop_model = models.Sequential()drop_model.add(layers.Dense(64, activation='relu', input_shape=(NB_WORDS,)))drop_model.add(layers.Dropout(0.5))drop_model.add(layers.Dense(64, activation='relu'))drop_model.add(layers.Dropout(0.5))drop_model.add(layers.Dense(3, activation='softmax'))drop_model.name = 'Dropout layers model'drop_history = deep_model(drop_model, X_train_rest, y_train_rest, X_valid, y_valid)drop_min = optimal_epoch(drop_history)eval_metric(drop_model, drop_history, 'loss')
The model with dropout layers starts overfitting later than the baseline model. The loss also increases slower than the baseline model.
compare_models_by_metric(base_model, drop_model, base_history, drop_history, 'val_loss')
The model with the Dropout layers starts overfitting later. Compared to the baseline model the loss also remains much lower.
At first sight, the reduced model seems to be the best model for generalization. But let’s check that on the test set.
base_results = test_model(base_model, X_train_oh, y_train_oh, X_test_oh, y_test_oh, base_min)reduced_results = test_model(reduced_model, X_train_oh, y_train_oh, X_test_oh, y_test_oh, reduced_min)reg_results = test_model(reg_model, X_train_oh, y_train_oh, X_test_oh, y_test_oh, reg_min)drop_results = test_model(drop_model, X_train_oh, y_train_oh, X_test_oh, y_test_oh, drop_min)
As shown above, all three options help to reduce overfitting. We manage to increase the accuracy on the test data substantially. Among these three options, the model with the Dropout layers performs the best on the test data.
You can find the notebook on GitHub. Have fun with it! Any feedback is welcome. | [
{
"code": null,
"e": 420,
"s": 172,
"text": "Overfitting occurs when you achieve a good fit of your model on the training data, while it does not generalize well on new, unseen data. In other words, the model learned patterns specific to the training data, which are irrelevant in other data."
},
{
"code": null,
"e": 728,
"s": 420,
"text": "We can identify overfitting by looking at validation metrics, like loss or accuracy. Usually, the validation metric stops improving after a certain number of epochs and begins to decrease afterward. The training metric continues to improve because the model seeks to find the best fit for the training data."
},
{
"code": null,
"e": 986,
"s": 728,
"text": "There are several manners in which we can reduce overfitting in deep learning models. The best option is to get more training data. Unfortunately, in real-world situations, you often do not have this possibility due to time, budget or technical constraints."
},
{
"code": null,
"e": 1273,
"s": 986,
"text": "Another way to reduce overfitting is to lower the capacity of the model to memorize the training data. As such, the model will need to focus on the relevant patterns in the training data, which results in better generalization. In this post, we’ll discuss three options to achieve this."
},
{
"code": null,
"e": 1478,
"s": 1273,
"text": "We start by importing the necessary packages and configuring some parameters. We will use Keras to fit the deep learning models. The training data is the Twitter US Airline Sentiment data set from Kaggle."
},
{
"code": null,
"e": 2368,
"s": 1478,
"text": "# Basic packagesimport pandas as pd import numpy as npimport reimport collectionsimport matplotlib.pyplot as pltfrom pathlib import Path# Packages for data preparationfrom sklearn.model_selection import train_test_splitfrom nltk.corpus import stopwordsfrom keras.preprocessing.text import Tokenizerfrom keras.utils.np_utils import to_categoricalfrom sklearn.preprocessing import LabelEncoder# Packages for modelingfrom keras import modelsfrom keras import layersfrom keras import regularizersNB_WORDS = 10000 # Parameter indicating the number of words we'll put in the dictionaryNB_START_EPOCHS = 20 # Number of epochs we usually start to train withBATCH_SIZE = 512 # Size of the batches used in the mini-batch gradient descentMAX_LEN = 20 # Maximum number of words in a sequenceroot = Path('../')input_path = root / 'input/' ouput_path = root / 'output/'source_path = root / 'source/'"
},
{
"code": null,
"e": 2427,
"s": 2368,
"text": "We will use some helper functions throughout this article."
},
{
"code": null,
"e": 7065,
"s": 2427,
"text": "def deep_model(model, X_train, y_train, X_valid, y_valid): ''' Function to train a multi-class model. The number of epochs and batch_size are set by the constants at the top of the notebook. Parameters: model : model with the chosen architecture X_train : training features y_train : training target X_valid : validation features Y_valid : validation target Output: model training history ''' model.compile(optimizer='rmsprop' , loss='categorical_crossentropy' , metrics=['accuracy']) history = model.fit(X_train , y_train , epochs=NB_START_EPOCHS , batch_size=BATCH_SIZE , validation_data=(X_valid, y_valid) , verbose=0) return historydef eval_metric(model, history, metric_name): ''' Function to evaluate a trained model on a chosen metric. Training and validation metric are plotted in a line chart for each epoch. Parameters: history : model training history metric_name : loss or accuracy Output: line chart with epochs of x-axis and metric on y-axis ''' metric = history.history[metric_name] val_metric = history.history['val_' + metric_name] e = range(1, NB_START_EPOCHS + 1) plt.plot(e, metric, 'bo', label='Train ' + metric_name) plt.plot(e, val_metric, 'b', label='Validation ' + metric_name) plt.xlabel('Epoch number') plt.ylabel(metric_name) plt.title('Comparing training and validation ' + metric_name + ' for ' + model.name) plt.legend() plt.show()def test_model(model, X_train, y_train, X_test, y_test, epoch_stop): ''' Function to test the model on new data after training it on the full training data with the optimal number of epochs. Parameters: model : trained model X_train : training features y_train : training target X_test : test features y_test : test target epochs : optimal number of epochs Output: test accuracy and test loss ''' model.fit(X_train , y_train , epochs=epoch_stop , batch_size=BATCH_SIZE , verbose=0) results = model.evaluate(X_test, y_test) print() print('Test accuracy: {0:.2f}%'.format(results[1]*100)) return results def remove_stopwords(input_text): ''' Function to remove English stopwords from a Pandas Series. Parameters: input_text : text to clean Output: cleaned Pandas Series ''' stopwords_list = stopwords.words('english') # Some words which might indicate a certain sentiment are kept via a whitelist whitelist = [\"n't\", \"not\", \"no\"] words = input_text.split() clean_words = [word for word in words if (word not in stopwords_list or word in whitelist) and len(word) > 1] return \" \".join(clean_words) def remove_mentions(input_text): ''' Function to remove mentions, preceded by @, in a Pandas Series Parameters: input_text : text to clean Output: cleaned Pandas Series ''' return re.sub(r'@\\w+', '', input_text)def compare_models_by_metric(model_1, model_2, model_hist_1, model_hist_2, metric): ''' Function to compare a metric between two models Parameters: model_hist_1 : training history of model 1 model_hist_2 : training history of model 2 metrix : metric to compare, loss, acc, val_loss or val_acc Output: plot of metrics of both models ''' metric_model_1 = model_hist_1.history[metric] metric_model_2 = model_hist_2.history[metric] e = range(1, NB_START_EPOCHS + 1) metrics_dict = { 'acc' : 'Training Accuracy', 'loss' : 'Training Loss', 'val_acc' : 'Validation accuracy', 'val_loss' : 'Validation loss' } metric_label = metrics_dict[metric] plt.plot(e, metric_model_1, 'bo', label=model_1.name) plt.plot(e, metric_model_2, 'b', label=model_2.name) plt.xlabel('Epoch number') plt.ylabel(metric_label) plt.title('Comparing ' + metric_label + ' between models') plt.legend() plt.show() def optimal_epoch(model_hist): ''' Function to return the epoch number where the validation loss is at its minimum Parameters: model_hist : training history of model Output: epoch number with minimum validation loss ''' min_epoch = np.argmin(model_hist.history['val_loss']) + 1 print(\"Minimum validation loss reached in epoch {}\".format(min_epoch)) return min_epoch"
},
{
"code": null,
"e": 7389,
"s": 7065,
"text": "We load the CSV with the tweets and perform a random shuffle. It’s a good practice to shuffle the data before splitting between a train and test set. That way the sentiment classes are equally distributed over the train and test sets. We’ll only keep the text column as input and the airline_sentiment column as the target."
},
{
"code": null,
"e": 7617,
"s": 7389,
"text": "The next thing we’ll do is removing stopwords. Stopwords do not have any value for predicting the sentiment. Furthermore, as we want to build a model that can be used for other airline companies as well, we remove the mentions."
},
{
"code": null,
"e": 7813,
"s": 7617,
"text": "df = pd.read_csv(input_path / 'Tweets.csv')df = df.reindex(np.random.permutation(df.index)) df = df[['text', 'airline_sentiment']]df.text = df.text.apply(remove_stopwords).apply(remove_mentions)"
},
{
"code": null,
"e": 8014,
"s": 7813,
"text": "The evaluation of the model performance needs to be done on a separate test set. As such, we can estimate how well the model generalizes. This is done with the train_test_split method of scikit-learn."
},
{
"code": null,
"e": 8129,
"s": 8014,
"text": "X_train, X_test, y_train, y_test = train_test_split(df.text, df.airline_sentiment, test_size=0.1, random_state=37)"
},
{
"code": null,
"e": 8375,
"s": 8129,
"text": "To use the text as input for a model, we first need to convert the words into tokens, which simply means converting the words to integers that refer to an index in a dictionary. Here we will only keep the most frequent words in the training set."
},
{
"code": null,
"e": 8483,
"s": 8375,
"text": "We clean up the text by applying filters and putting the words to lowercase. Words are separated by spaces."
},
{
"code": null,
"e": 8687,
"s": 8483,
"text": "tk = Tokenizer(num_words=NB_WORDS, filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{\"}~\\t\\n', lower=True, char_level=False, split=' ')tk.fit_on_texts(X_train)"
},
{
"code": null,
"e": 8945,
"s": 8687,
"text": "After having created the dictionary we can convert the text of a tweet to a vector with NB_WORDS values. With mode=binary, it contains an indicator whether the word appeared in the tweet or not. This is done with the texts_to_matrix method of the Tokenizer."
},
{
"code": null,
"e": 9054,
"s": 8945,
"text": "X_train_oh = tk.texts_to_matrix(X_train, mode='binary')X_test_oh = tk.texts_to_matrix(X_test, mode='binary')"
},
{
"code": null,
"e": 9186,
"s": 9054,
"text": "We need to convert the target classes to numbers as well, which in turn are one-hot-encoded with the to_categorical method in Keras"
},
{
"code": null,
"e": 9352,
"s": 9186,
"text": "le = LabelEncoder()y_train_le = le.fit_transform(y_train)y_test_le = le.transform(y_test)y_train_oh = to_categorical(y_train_le)y_test_oh = to_categorical(y_test_le)"
},
{
"code": null,
"e": 9520,
"s": 9352,
"text": "Now that our data is ready, we split off a validation set. This validation set will be used to evaluate the model performance when we tune the parameters of the model."
},
{
"code": null,
"e": 9640,
"s": 9520,
"text": "X_train_rest, X_valid, y_train_rest, y_valid = train_test_split(X_train_oh, y_train_oh, test_size=0.1, random_state=37)"
},
{
"code": null,
"e": 9872,
"s": 9640,
"text": "We start with a model that overfits. It has 2 densely connected layers of 64 elements. The input_shape for the first layer is equal to the number of words we kept in the dictionary and for which we created one-hot-encoded features."
},
{
"code": null,
"e": 10036,
"s": 9872,
"text": "As we need to predict 3 different sentiment classes, the last layer has 3 elements. The softmax activation function makes sure the three probabilities sum up to 1."
},
{
"code": null,
"e": 10352,
"s": 10036,
"text": "The number of parameters to train is computed as (nb inputs x nb elements in hidden layer) + nb bias terms. The number of inputs for the first layer equals the number of words in our corpus. The subsequent layers have the number of outputs of the previous layer as inputs. So the number of parameters per layer are:"
},
{
"code": null,
"e": 10393,
"s": 10352,
"text": "First layer : (10000 x 64) + 64 = 640064"
},
{
"code": null,
"e": 10430,
"s": 10393,
"text": "Second layer : (64 x 64) + 64 = 4160"
},
{
"code": null,
"e": 10462,
"s": 10430,
"text": "Last layer : (64 x 3) + 3 = 195"
},
{
"code": null,
"e": 10709,
"s": 10462,
"text": "base_model = models.Sequential()base_model.add(layers.Dense(64, activation='relu', input_shape=(NB_WORDS,)))base_model.add(layers.Dense(64, activation='relu'))base_model.add(layers.Dense(3, activation='softmax'))base_model.name = 'Baseline model'"
},
{
"code": null,
"e": 11034,
"s": 10709,
"text": "Because this project is a multi-class, single-label prediction, we use categorical_crossentropy as the loss function and softmax as the final activation function. We fit the model on the train data and validate on the validation set. We run for a predetermined number of epochs and will see when the model starts to overfit."
},
{
"code": null,
"e": 11201,
"s": 11034,
"text": "base_history = deep_model(base_model, X_train_rest, y_train_rest, X_valid, y_valid)base_min = optimal_epoch(base_history)eval_metric(base_model, base_history, 'loss')"
},
{
"code": null,
"e": 11369,
"s": 11201,
"text": "In the beginning, the validation loss goes down. But at epoch 3 this stops and the validation loss starts increasing rapidly. This is when the models begin to overfit."
},
{
"code": null,
"e": 11527,
"s": 11369,
"text": "The training loss continues to go down and almost reaches zero at epoch 20. This is normal as the model is trained to fit the train data as good as possible."
},
{
"code": null,
"e": 11622,
"s": 11527,
"text": "Now, we can try to do something about the overfitting. There are different options to do that."
},
{
"code": null,
"e": 11727,
"s": 11622,
"text": "Reduce the network’s capacity by removing layers or reducing the number of elements in the hidden layers"
},
{
"code": null,
"e": 11822,
"s": 11727,
"text": "Apply regularization, which comes down to adding a cost to the loss function for large weights"
},
{
"code": null,
"e": 11910,
"s": 11822,
"text": "Use Dropout layers, which will randomly remove certain features by setting them to zero"
},
{
"code": null,
"e": 12130,
"s": 11910,
"text": "Our first model has a large number of trainable parameters. The higher this number, the easier the model can memorize the target class for each training sample. Obviously, this is not ideal for generalizing on new data."
},
{
"code": null,
"e": 12409,
"s": 12130,
"text": "By lowering the capacity of the network, you force it to learn the patterns that matter or that minimize the loss. On the other hand, reducing the network’s capacity too much will lead to underfitting. The model will not be able to learn the relevant patterns in the train data."
},
{
"code": null,
"e": 12537,
"s": 12409,
"text": "We reduce the network’s capacity by removing one hidden layer and lowering the number of elements in the remaining layer to 16."
},
{
"code": null,
"e": 12928,
"s": 12537,
"text": "reduced_model = models.Sequential()reduced_model.add(layers.Dense(16, activation='relu', input_shape=(NB_WORDS,)))reduced_model.add(layers.Dense(3, activation='softmax'))reduced_model.name = 'Reduced model'reduced_history = deep_model(reduced_model, X_train_rest, y_train_rest, X_valid, y_valid)reduced_min = optimal_epoch(reduced_history)eval_metric(reduced_model, reduced_history, 'loss')"
},
{
"code": null,
"e": 13072,
"s": 12928,
"text": "We can see that it takes more epochs before the reduced model starts overfitting. The validation loss also goes up slower than our first model."
},
{
"code": null,
"e": 13167,
"s": 13072,
"text": "compare_models_by_metric(base_model, reduced_model, base_history, reduced_history, 'val_loss')"
},
{
"code": null,
"e": 13367,
"s": 13167,
"text": "When we compare the validation loss of the baseline model, it is clear that the reduced model starts overfitting at a later epoch. The validation loss stays lower much longer than the baseline model."
},
{
"code": null,
"e": 13650,
"s": 13367,
"text": "To address overfitting, we can apply weight regularization to the model. This will add a cost to the loss function of the network for large weights (or parameter values). As a result, you get a simpler model that will be forced to learn only the relevant patterns in the train data."
},
{
"code": null,
"e": 13701,
"s": 13650,
"text": "There are L1 regularization and L2 regularization."
},
{
"code": null,
"e": 13848,
"s": 13701,
"text": "L1 regularization will add a cost with regards to the absolute value of the parameters. It will result in some of the weights to be equal to zero."
},
{
"code": null,
"e": 13968,
"s": 13848,
"text": "L2 regularization will add a cost with regards to the squared value of the parameters. This results in smaller weights."
},
{
"code": null,
"e": 14002,
"s": 13968,
"text": "Let’s try with L2 regularization."
},
{
"code": null,
"e": 14456,
"s": 14002,
"text": "reg_model = models.Sequential()reg_model.add(layers.Dense(64, kernel_regularizer=regularizers.l2(0.001), activation='relu', input_shape=(NB_WORDS,)))reg_model.add(layers.Dense(64, kernel_regularizer=regularizers.l2(0.001), activation='relu'))reg_model.add(layers.Dense(3, activation='softmax'))reg_model.name = 'L2 Regularization model'reg_history = deep_model(reg_model, X_train_rest, y_train_rest, X_valid, y_valid)reg_min = optimal_epoch(reg_history)"
},
{
"code": null,
"e": 14611,
"s": 14456,
"text": "For the regularized model we notice that it starts overfitting in the same epoch as the baseline model. However, the loss increases much slower afterward."
},
{
"code": null,
"e": 14655,
"s": 14611,
"text": "eval_metric(reg_model, reg_history, 'loss')"
},
{
"code": null,
"e": 14742,
"s": 14655,
"text": "compare_models_by_metric(base_model, reg_model, base_history, reg_history, 'val_loss')"
},
{
"code": null,
"e": 14864,
"s": 14742,
"text": "The last option we’ll try is to add Dropout layers. A Dropout layer will randomly set output features of a layer to zero."
},
{
"code": null,
"e": 15353,
"s": 14864,
"text": "drop_model = models.Sequential()drop_model.add(layers.Dense(64, activation='relu', input_shape=(NB_WORDS,)))drop_model.add(layers.Dropout(0.5))drop_model.add(layers.Dense(64, activation='relu'))drop_model.add(layers.Dropout(0.5))drop_model.add(layers.Dense(3, activation='softmax'))drop_model.name = 'Dropout layers model'drop_history = deep_model(drop_model, X_train_rest, y_train_rest, X_valid, y_valid)drop_min = optimal_epoch(drop_history)eval_metric(drop_model, drop_history, 'loss')"
},
{
"code": null,
"e": 15489,
"s": 15353,
"text": "The model with dropout layers starts overfitting later than the baseline model. The loss also increases slower than the baseline model."
},
{
"code": null,
"e": 15578,
"s": 15489,
"text": "compare_models_by_metric(base_model, drop_model, base_history, drop_history, 'val_loss')"
},
{
"code": null,
"e": 15703,
"s": 15578,
"text": "The model with the Dropout layers starts overfitting later. Compared to the baseline model the loss also remains much lower."
},
{
"code": null,
"e": 15822,
"s": 15703,
"text": "At first sight, the reduced model seems to be the best model for generalization. But let’s check that on the test set."
},
{
"code": null,
"e": 16201,
"s": 15822,
"text": "base_results = test_model(base_model, X_train_oh, y_train_oh, X_test_oh, y_test_oh, base_min)reduced_results = test_model(reduced_model, X_train_oh, y_train_oh, X_test_oh, y_test_oh, reduced_min)reg_results = test_model(reg_model, X_train_oh, y_train_oh, X_test_oh, y_test_oh, reg_min)drop_results = test_model(drop_model, X_train_oh, y_train_oh, X_test_oh, y_test_oh, drop_min)"
},
{
"code": null,
"e": 16427,
"s": 16201,
"text": "As shown above, all three options help to reduce overfitting. We manage to increase the accuracy on the test data substantially. Among these three options, the model with the Dropout layers performs the best on the test data."
}
]
|
Extracting tabular data from PDFs made easy with Camelot. | by Parul Pandey | Towards Data Science | Extracting tabular data from PDFs is hard. But what is even a bigger problem is that a lot of open data is available as PDF files. This open data is crucial for analysis and getting vital insights. However, accessing such data becomes a challenge. For instance, let’s look at an important report released by the National Agricultural Statistics Service (NASS), which deals with the principal crops planted in the U.S:
For any analysis, the starting point would be to get the table with details and convert it to a format that can be ingested by most of the available tools. As you can see above, a mere copy-paste, in this case, doesn’t work. Most of the time, the headers are not in the correct place, some of the numbers are lost. This makes PDFs somewhat tricky to handle, and apparently, there is a reason for that. We’ll go over that, but let’s first try and understand the concept of a PDF file.
This article is part of a complete series on finding suitable datasets. Here are all the articles included in the series:
Part 1: Getting Datasets for Data Analysis tasks — Advanced Google Search
Part 2: Useful sites for finding datasets for Data Analysis tasks
Part 3: Creating custom image datasets for Deep Learning projects
Part 4: Import HTML tables into Google Sheets effortlessly
Part 5: Extracting tabular data from PDFs made easy with Camelot.
Part 6: Extracting information from XML files into a Pandas dataframe
Part 7: 5 Real-World datasets for honing your Exploratory Data Analysis skills
PDF stands for Portable Document Format. It is a file format that was created in the early nineties by Adobe. It is based on the PostScript language and is commonly used to present and share documents. The idea behind the development of PDF was to have a format that makes it possible to view, display, and print documents on any modern printer.
Each PDF file encapsulates a complete description of a fixed-layout flat document, including the text, fonts, vector graphics, raster images, and other information needed to display[Wikipedia].
A basic PDF file contains the following elements.
If you look at the PDF layout above, you will notice no concept of tables in it. A PDF contains instructions to place a character at an x,y coordinate on a 2-D plane, retaining no knowledge of words, sentences, or tables.
So how does a PDF differentiate between words and sentences? Words are simulated by placing characters together, while sentences are simulated by placing words relatively farther. The following diagram will cement this concept more concretely:
M denotes the distance between two characters in the above figure, while W refers to the space between two words. Any text chunk with space < M is grouped into one. Tables are simulated by putting words as they appear in a spreadsheet without any information on what a row or a column is. Hence, this makes it challenging to extract data from PDFs for analysis purposes. However, a lot of open data in the form of government reports, documentation, etc., is released in the form of PDFs. A tool that can extract information without compromising on its quality is the need of the hour. This point brings us to a versatile library called Camelot, which has been created to extract tabular information from PDFs.
Camelot, which derives its name from the famous Camelot Project, is an open-source Python library that can help you extract tables from PDFs easily. It has been built on top of pdfminer, another text extraction tool for PDF documents.
It comes packaged with a lot of useful features like:
Configurability — works well for most of the cases but can also be configured
Visual Debugging using the Matplotlib library
Output is available in multiple formats, including CSV, JSON, Excel, HTML, and even Pandas dataframe.
Opensource- MIT licensed
Detailed documentation
You can install Camelot via conda, pip, or directly from the source. If you go for pip, do not forget to install the following dependencies: Tkinter and Ghostscript.
#conda (easiest way)$ conda install -c conda-forge camelot-py#pip after installing the tk and ghostscript dependencies$ pip install "camelot-py[cv]"
Before we get into working, it is a good idea to understand what goes under the hood. Typically, two parsing methods are used by Camelot to extract tables:
Stream: looks for whitespaces between words to identify a table.
Lattice: Looks for lines on a page to identify a table. Lattice is used by default.
You can read more about Camelot’s working in the documentation.
Let’s now get to the exciting part- extracting tables from PDFs. Here I am using a PDF containing information about the number of beneficiaries under the Adult Education Programme 2015–16 in India. The PDF looks like this:
We’ll start by importing the library and reading in the PDF file as follows:
import camelottables = camelot.read_pdf('schools.pdf')
We get a TableList object, which is a list of Table objects.
tables--------------<TableList n=2>
We can see that two tables have been detected, which can be easily accessed through its index. Let’s access the second table, i.e., the table comprising of more information, and look at its shape:
tables[1] #indexing starts from 0<Table shape=(28, 4)>
Next, let’s print the parsing report, which is an indication of the extraction quality of the table:
tables[1].parsing_report{'accuracy': 100.0, 'whitespace': 44.64, 'order': 2, 'page': 1}
It shows a whopping 100% accuracy, which means the extraction is perfect. We can also access the table’s dataframe as follows:
tables[1].df.head()
The entire table could also be extracted as a CSV file as follows:
tables.export('table.csv')
Additionally, you can also plot elements found on the PDF page based on the kind specified, like the ‘text’, ‘grid’, ‘contour’, ‘line’, ‘joint’ , etc. These are useful for debugging and playing with different parameters to get the best output.
camelot.plot(tables[1],kind=<specify the kind>)
Camelot comes with a command-line interface too. It also comes equipped with a bunch of advanced features like:
Reading encrypted PDFs
Reading rotated PDFs
Tweaking parameters when the default result is not perfect. Specify exact table boundaries, Specify column separators, and much more. You can read more about these features here.
Camelot only works with text-based PDFs and not scanned documents. So if you have scanned documents, you’ll have to look at some other alternatives.
Another interesting feature of Camelot is that it also has a web interface called Excalibur for people who do not want to code but still want to use the library's features. Let’s quickly see how to use it.
After installing Ghostscript, use pip to install Excalibur:
$ pip install excalibur-py
And then start the web server using:
$ excalibur webserver
You can then navigate to the localhost to access the interface. The whole process has been demonstrated in the video below:
In the above article, we looked at Camelot — an open-source python library that appears to be pretty helpful for extracting tabular data from PDFs. The fact that it has many parameters that can be adjusted makes it pretty scalable and applicable in a lot of situations. The Web interface offers an excellent alternative to people looking for a code-free environment. Overall, it seems to be a useful tool that could help in reducing the time that is generally taken for data extraction.
This article is inspired by a talk given by Vinayak Mehta-the creator and maintainer of the project Camelot at PyCon India 2019. Some of the resources have been taken from the slide deck shared publicly after the event. It is highly recommended also to watch the presentation for more clarity. | [
{
"code": null,
"e": 590,
"s": 172,
"text": "Extracting tabular data from PDFs is hard. But what is even a bigger problem is that a lot of open data is available as PDF files. This open data is crucial for analysis and getting vital insights. However, accessing such data becomes a challenge. For instance, let’s look at an important report released by the National Agricultural Statistics Service (NASS), which deals with the principal crops planted in the U.S:"
},
{
"code": null,
"e": 1074,
"s": 590,
"text": "For any analysis, the starting point would be to get the table with details and convert it to a format that can be ingested by most of the available tools. As you can see above, a mere copy-paste, in this case, doesn’t work. Most of the time, the headers are not in the correct place, some of the numbers are lost. This makes PDFs somewhat tricky to handle, and apparently, there is a reason for that. We’ll go over that, but let’s first try and understand the concept of a PDF file."
},
{
"code": null,
"e": 1196,
"s": 1074,
"text": "This article is part of a complete series on finding suitable datasets. Here are all the articles included in the series:"
},
{
"code": null,
"e": 1270,
"s": 1196,
"text": "Part 1: Getting Datasets for Data Analysis tasks — Advanced Google Search"
},
{
"code": null,
"e": 1336,
"s": 1270,
"text": "Part 2: Useful sites for finding datasets for Data Analysis tasks"
},
{
"code": null,
"e": 1402,
"s": 1336,
"text": "Part 3: Creating custom image datasets for Deep Learning projects"
},
{
"code": null,
"e": 1461,
"s": 1402,
"text": "Part 4: Import HTML tables into Google Sheets effortlessly"
},
{
"code": null,
"e": 1527,
"s": 1461,
"text": "Part 5: Extracting tabular data from PDFs made easy with Camelot."
},
{
"code": null,
"e": 1597,
"s": 1527,
"text": "Part 6: Extracting information from XML files into a Pandas dataframe"
},
{
"code": null,
"e": 1676,
"s": 1597,
"text": "Part 7: 5 Real-World datasets for honing your Exploratory Data Analysis skills"
},
{
"code": null,
"e": 2022,
"s": 1676,
"text": "PDF stands for Portable Document Format. It is a file format that was created in the early nineties by Adobe. It is based on the PostScript language and is commonly used to present and share documents. The idea behind the development of PDF was to have a format that makes it possible to view, display, and print documents on any modern printer."
},
{
"code": null,
"e": 2216,
"s": 2022,
"text": "Each PDF file encapsulates a complete description of a fixed-layout flat document, including the text, fonts, vector graphics, raster images, and other information needed to display[Wikipedia]."
},
{
"code": null,
"e": 2266,
"s": 2216,
"text": "A basic PDF file contains the following elements."
},
{
"code": null,
"e": 2488,
"s": 2266,
"text": "If you look at the PDF layout above, you will notice no concept of tables in it. A PDF contains instructions to place a character at an x,y coordinate on a 2-D plane, retaining no knowledge of words, sentences, or tables."
},
{
"code": null,
"e": 2732,
"s": 2488,
"text": "So how does a PDF differentiate between words and sentences? Words are simulated by placing characters together, while sentences are simulated by placing words relatively farther. The following diagram will cement this concept more concretely:"
},
{
"code": null,
"e": 3442,
"s": 2732,
"text": "M denotes the distance between two characters in the above figure, while W refers to the space between two words. Any text chunk with space < M is grouped into one. Tables are simulated by putting words as they appear in a spreadsheet without any information on what a row or a column is. Hence, this makes it challenging to extract data from PDFs for analysis purposes. However, a lot of open data in the form of government reports, documentation, etc., is released in the form of PDFs. A tool that can extract information without compromising on its quality is the need of the hour. This point brings us to a versatile library called Camelot, which has been created to extract tabular information from PDFs."
},
{
"code": null,
"e": 3677,
"s": 3442,
"text": "Camelot, which derives its name from the famous Camelot Project, is an open-source Python library that can help you extract tables from PDFs easily. It has been built on top of pdfminer, another text extraction tool for PDF documents."
},
{
"code": null,
"e": 3731,
"s": 3677,
"text": "It comes packaged with a lot of useful features like:"
},
{
"code": null,
"e": 3809,
"s": 3731,
"text": "Configurability — works well for most of the cases but can also be configured"
},
{
"code": null,
"e": 3855,
"s": 3809,
"text": "Visual Debugging using the Matplotlib library"
},
{
"code": null,
"e": 3957,
"s": 3855,
"text": "Output is available in multiple formats, including CSV, JSON, Excel, HTML, and even Pandas dataframe."
},
{
"code": null,
"e": 3982,
"s": 3957,
"text": "Opensource- MIT licensed"
},
{
"code": null,
"e": 4005,
"s": 3982,
"text": "Detailed documentation"
},
{
"code": null,
"e": 4171,
"s": 4005,
"text": "You can install Camelot via conda, pip, or directly from the source. If you go for pip, do not forget to install the following dependencies: Tkinter and Ghostscript."
},
{
"code": null,
"e": 4320,
"s": 4171,
"text": "#conda (easiest way)$ conda install -c conda-forge camelot-py#pip after installing the tk and ghostscript dependencies$ pip install \"camelot-py[cv]\""
},
{
"code": null,
"e": 4476,
"s": 4320,
"text": "Before we get into working, it is a good idea to understand what goes under the hood. Typically, two parsing methods are used by Camelot to extract tables:"
},
{
"code": null,
"e": 4541,
"s": 4476,
"text": "Stream: looks for whitespaces between words to identify a table."
},
{
"code": null,
"e": 4625,
"s": 4541,
"text": "Lattice: Looks for lines on a page to identify a table. Lattice is used by default."
},
{
"code": null,
"e": 4689,
"s": 4625,
"text": "You can read more about Camelot’s working in the documentation."
},
{
"code": null,
"e": 4912,
"s": 4689,
"text": "Let’s now get to the exciting part- extracting tables from PDFs. Here I am using a PDF containing information about the number of beneficiaries under the Adult Education Programme 2015–16 in India. The PDF looks like this:"
},
{
"code": null,
"e": 4989,
"s": 4912,
"text": "We’ll start by importing the library and reading in the PDF file as follows:"
},
{
"code": null,
"e": 5044,
"s": 4989,
"text": "import camelottables = camelot.read_pdf('schools.pdf')"
},
{
"code": null,
"e": 5105,
"s": 5044,
"text": "We get a TableList object, which is a list of Table objects."
},
{
"code": null,
"e": 5141,
"s": 5105,
"text": "tables--------------<TableList n=2>"
},
{
"code": null,
"e": 5338,
"s": 5141,
"text": "We can see that two tables have been detected, which can be easily accessed through its index. Let’s access the second table, i.e., the table comprising of more information, and look at its shape:"
},
{
"code": null,
"e": 5393,
"s": 5338,
"text": "tables[1] #indexing starts from 0<Table shape=(28, 4)>"
},
{
"code": null,
"e": 5494,
"s": 5393,
"text": "Next, let’s print the parsing report, which is an indication of the extraction quality of the table:"
},
{
"code": null,
"e": 5582,
"s": 5494,
"text": "tables[1].parsing_report{'accuracy': 100.0, 'whitespace': 44.64, 'order': 2, 'page': 1}"
},
{
"code": null,
"e": 5709,
"s": 5582,
"text": "It shows a whopping 100% accuracy, which means the extraction is perfect. We can also access the table’s dataframe as follows:"
},
{
"code": null,
"e": 5729,
"s": 5709,
"text": "tables[1].df.head()"
},
{
"code": null,
"e": 5796,
"s": 5729,
"text": "The entire table could also be extracted as a CSV file as follows:"
},
{
"code": null,
"e": 5823,
"s": 5796,
"text": "tables.export('table.csv')"
},
{
"code": null,
"e": 6067,
"s": 5823,
"text": "Additionally, you can also plot elements found on the PDF page based on the kind specified, like the ‘text’, ‘grid’, ‘contour’, ‘line’, ‘joint’ , etc. These are useful for debugging and playing with different parameters to get the best output."
},
{
"code": null,
"e": 6115,
"s": 6067,
"text": "camelot.plot(tables[1],kind=<specify the kind>)"
},
{
"code": null,
"e": 6227,
"s": 6115,
"text": "Camelot comes with a command-line interface too. It also comes equipped with a bunch of advanced features like:"
},
{
"code": null,
"e": 6250,
"s": 6227,
"text": "Reading encrypted PDFs"
},
{
"code": null,
"e": 6271,
"s": 6250,
"text": "Reading rotated PDFs"
},
{
"code": null,
"e": 6450,
"s": 6271,
"text": "Tweaking parameters when the default result is not perfect. Specify exact table boundaries, Specify column separators, and much more. You can read more about these features here."
},
{
"code": null,
"e": 6599,
"s": 6450,
"text": "Camelot only works with text-based PDFs and not scanned documents. So if you have scanned documents, you’ll have to look at some other alternatives."
},
{
"code": null,
"e": 6805,
"s": 6599,
"text": "Another interesting feature of Camelot is that it also has a web interface called Excalibur for people who do not want to code but still want to use the library's features. Let’s quickly see how to use it."
},
{
"code": null,
"e": 6865,
"s": 6805,
"text": "After installing Ghostscript, use pip to install Excalibur:"
},
{
"code": null,
"e": 6893,
"s": 6865,
"text": "$ pip install excalibur-py "
},
{
"code": null,
"e": 6930,
"s": 6893,
"text": "And then start the web server using:"
},
{
"code": null,
"e": 6952,
"s": 6930,
"text": "$ excalibur webserver"
},
{
"code": null,
"e": 7076,
"s": 6952,
"text": "You can then navigate to the localhost to access the interface. The whole process has been demonstrated in the video below:"
},
{
"code": null,
"e": 7563,
"s": 7076,
"text": "In the above article, we looked at Camelot — an open-source python library that appears to be pretty helpful for extracting tabular data from PDFs. The fact that it has many parameters that can be adjusted makes it pretty scalable and applicable in a lot of situations. The Web interface offers an excellent alternative to people looking for a code-free environment. Overall, it seems to be a useful tool that could help in reducing the time that is generally taken for data extraction."
}
]
|
Check if a file exists in Java
| The java.io.File class provides useful methods on file. This example shows how to check a file existence by using the file.exists() method of File class.
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/java.txt");
System.out.println(file.exists());
}
}
The above code sample will produce the following result (if the file "java.txt" exists in 'C' drive).
true
The following is another simple example of the file exist or not in java.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintpWriter;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class fileexist {
public static void main(String[] args) throws IOException {
File f = new File(System.getProperty("user.dir")+"/folder/file.txt");
System.out.println(f.exists());
if(!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
if(!f.exists()) {
try {
f.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
File dir = new File(f.getParentFile(), f.getName());
PrintpWriter pWriter = new PrintpWriter(dir);
pWriter.print("writing anything...");
pWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
The above code sample will produce the following result (if the file "java.txt" exists in 'C' drive).
true | [
{
"code": null,
"e": 1216,
"s": 1062,
"text": "The java.io.File class provides useful methods on file. This example shows how to check a file existence by using the file.exists() method of File class."
},
{
"code": null,
"e": 1393,
"s": 1216,
"text": "import java.io.File;\n\npublic class Main {\n public static void main(String[] args) {\n File file = new File(\"C:/java.txt\");\n System.out.println(file.exists());\n }\n}"
},
{
"code": null,
"e": 1495,
"s": 1393,
"text": "The above code sample will produce the following result (if the file \"java.txt\" exists in 'C' drive)."
},
{
"code": null,
"e": 1500,
"s": 1495,
"text": "true"
},
{
"code": null,
"e": 1574,
"s": 1500,
"text": "The following is another simple example of the file exist or not in java."
},
{
"code": null,
"e": 2579,
"s": 1574,
"text": "import java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.PrintpWriter;\n\nimport java.nio.file.FileAlreadyExistsException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\n\npublic class fileexist {\n public static void main(String[] args) throws IOException {\n File f = new File(System.getProperty(\"user.dir\")+\"/folder/file.txt\");\n System.out.println(f.exists());\n\n if(!f.getParentFile().exists()) {\n f.getParentFile().mkdirs();\n } \n\n if(!f.exists()) {\n try {\n f.createNewFile();\n } catch (Exception e) {\n e.printStackTrace();\n } \n }\n\n try {\n File dir = new File(f.getParentFile(), f.getName());\n PrintpWriter pWriter = new PrintpWriter(dir);\n pWriter.print(\"writing anything...\");\n pWriter.close();\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 2681,
"s": 2579,
"text": "The above code sample will produce the following result (if the file \"java.txt\" exists in 'C' drive)."
},
{
"code": null,
"e": 2686,
"s": 2681,
"text": "true"
}
]
|
Finding the length of string in R programming - nchar() method - GeeksforGeeks | 25 Oct, 2021
nchar() method in R Programming Language is used to get the length of a character in a string object.
Syntax: nchar(string)
Where: String is object.
Return: Returns the length of a string.
In this example, we are going to see how to get the length of a string object using nchar() method.
R
# R program to calculate length of string # Given Stringgfg < - "Geeks For Geeks" # Using nchar() methodanswer < - nchar(gfg) print(answer)
Output:
[1] 15
In this example, we will get the length of the vector using nchar() method.
R
# R program to get length of Character Vectors # by default numeric values# are converted into charactersv1 <- c('geeks', '2', 'hello', 57) # Displaying type of vectortypeof(v1) nchar(v1)
Output:
'character'
5 1 5 2
The nchar() function provides an optional argument called keepNA, it can help when dealing with NA values.
R
# R program to create Character Vectors # by default numeric values# are converted into charactersv1 <- c(NULL, '2', 'hello', NA) nchar(v1, keepNA = FALSE)
Output:
1 5 2
In the above example, the first element is NULL then it returns nothing and the last element NA returns 2 because we keep keepNA = FALSE. If we pass keepNA = TRUE, then see the following output:
R
# R program to create Character Vectors # by default numeric values# are converted into charactersv1 <- c('', NULL, 'hello', NA) nchar(v1, keepNA = TRUE)
Output:
0 5 <NA>
kumar_satyam
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R | [
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 24953,
"s": 24851,
"text": "nchar() method in R Programming Language is used to get the length of a character in a string object."
},
{
"code": null,
"e": 24975,
"s": 24953,
"text": "Syntax: nchar(string)"
},
{
"code": null,
"e": 25000,
"s": 24975,
"text": "Where: String is object."
},
{
"code": null,
"e": 25041,
"s": 25000,
"text": "Return: Returns the length of a string. "
},
{
"code": null,
"e": 25141,
"s": 25041,
"text": "In this example, we are going to see how to get the length of a string object using nchar() method."
},
{
"code": null,
"e": 25143,
"s": 25141,
"text": "R"
},
{
"code": "# R program to calculate length of string # Given Stringgfg < - \"Geeks For Geeks\" # Using nchar() methodanswer < - nchar(gfg) print(answer)",
"e": 25283,
"s": 25143,
"text": null
},
{
"code": null,
"e": 25291,
"s": 25283,
"text": "Output:"
},
{
"code": null,
"e": 25298,
"s": 25291,
"text": "[1] 15"
},
{
"code": null,
"e": 25374,
"s": 25298,
"text": "In this example, we will get the length of the vector using nchar() method."
},
{
"code": null,
"e": 25376,
"s": 25374,
"text": "R"
},
{
"code": "# R program to get length of Character Vectors # by default numeric values# are converted into charactersv1 <- c('geeks', '2', 'hello', 57) # Displaying type of vectortypeof(v1) nchar(v1)",
"e": 25564,
"s": 25376,
"text": null
},
{
"code": null,
"e": 25572,
"s": 25564,
"text": "Output:"
},
{
"code": null,
"e": 25592,
"s": 25572,
"text": "'character'\n5 1 5 2"
},
{
"code": null,
"e": 25699,
"s": 25592,
"text": "The nchar() function provides an optional argument called keepNA, it can help when dealing with NA values."
},
{
"code": null,
"e": 25701,
"s": 25699,
"text": "R"
},
{
"code": "# R program to create Character Vectors # by default numeric values# are converted into charactersv1 <- c(NULL, '2', 'hello', NA) nchar(v1, keepNA = FALSE)",
"e": 25857,
"s": 25701,
"text": null
},
{
"code": null,
"e": 25865,
"s": 25857,
"text": "Output:"
},
{
"code": null,
"e": 25871,
"s": 25865,
"text": "1 5 2"
},
{
"code": null,
"e": 26066,
"s": 25871,
"text": "In the above example, the first element is NULL then it returns nothing and the last element NA returns 2 because we keep keepNA = FALSE. If we pass keepNA = TRUE, then see the following output:"
},
{
"code": null,
"e": 26068,
"s": 26066,
"text": "R"
},
{
"code": "# R program to create Character Vectors # by default numeric values# are converted into charactersv1 <- c('', NULL, 'hello', NA) nchar(v1, keepNA = TRUE)",
"e": 26222,
"s": 26068,
"text": null
},
{
"code": null,
"e": 26230,
"s": 26222,
"text": "Output:"
},
{
"code": null,
"e": 26239,
"s": 26230,
"text": "0 5 <NA>"
},
{
"code": null,
"e": 26252,
"s": 26239,
"text": "kumar_satyam"
},
{
"code": null,
"e": 26263,
"s": 26252,
"text": "R Language"
},
{
"code": null,
"e": 26361,
"s": 26263,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26370,
"s": 26361,
"text": "Comments"
},
{
"code": null,
"e": 26383,
"s": 26370,
"text": "Old Comments"
},
{
"code": null,
"e": 26435,
"s": 26383,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26473,
"s": 26435,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26508,
"s": 26473,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26566,
"s": 26508,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 26615,
"s": 26566,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 26658,
"s": 26615,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 26708,
"s": 26658,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 26725,
"s": 26708,
"text": "R - if statement"
},
{
"code": null,
"e": 26762,
"s": 26725,
"text": "How to import an Excel File into R ?"
}
]
|
What are reference data types in C#? | The reference data type in C# does not have the actual data stored in a variable, but they contain a reference to the variables.
In C#, the following are the built-in reference types −
The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types.
object ob;
ob = 250; // boxing
Store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time.
dynamic d = 100;
The String Type allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type.
String val = "Welcome!"; | [
{
"code": null,
"e": 1191,
"s": 1062,
"text": "The reference data type in C# does not have the actual data stored in a variable, but they contain a reference to the variables."
},
{
"code": null,
"e": 1247,
"s": 1191,
"text": "In C#, the following are the built-in reference types −"
},
{
"code": null,
"e": 1465,
"s": 1247,
"text": "The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types."
},
{
"code": null,
"e": 1496,
"s": 1465,
"text": "object ob;\nob = 250; // boxing"
},
{
"code": null,
"e": 1623,
"s": 1496,
"text": "Store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time."
},
{
"code": null,
"e": 1641,
"s": 1623,
"text": "dynamic d = 100;\n"
},
{
"code": null,
"e": 1800,
"s": 1641,
"text": "The String Type allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type."
},
{
"code": null,
"e": 1825,
"s": 1800,
"text": "String val = \"Welcome!\";"
}
]
|
Teaching Cars To See — Advanced Lane Detection Using Computer Vision | by Eddie Forson | Towards Data Science | This is project 4 of Term 1 of the Udacity Self-Driving Car Engineer Nanodegree. You can find all code related to this project on github. You can also read my posts on previous projects:
project 1: Detecting Lane Lines Using Computer Vision
project 2: Traffic Sign Classification Using Deep Learning
project 3: Steering Angle Prediction Using Deep Learning
Identifying lanes on the road is a common task performed by all human drivers to ensure their vehicles are within lane constraints when driving, so as to make sure traffic is smooth and minimise chances of collisions with other cars in nearby lanes. Similarly, it is a critical task for an autonomous vehicle to perform. It turns out that recognising lane markings on roads is possible using well known computer vision techniques. We will cover how to use various techniques to identify and draw the inside of a lane, compute lane curvature, and even estimate the vehicle’s position relative to the center of the lane.
To detect and draw a polygon that takes the shape of the lane the car is currently in, we build a pipeline consisting of the following steps:
Computation of camera calibration matrix and distortion coefficients from a set of chessboard images
Distortion removal on images
Application of color and gradient thresholds to focus on lane lines
Production of a bird’s eye view image via perspective transform
Use of sliding windows to find hot lane line pixels
Fitting of second degree polynomials to identify left and right lines composing the lane
Computation of lane curvature and deviation from lane center
Warping and drawing of lane boundaries on image as well as lane curvature information
I believe a diagram is worth a thousand words so here it is:
The first step we will take is to find the calibration matrix, along with distortion coefficients for the camera that was used to take pictures of the road. This is necessary because the convex shape of camera lenses curves light rays as they enter the pinhole, thus causing distortions to the real image. Therefore lines that are straight in the real world may not be anymore on our photos.
To compute the camera the transformation matrix and distortion coefficients, we use multiple pictures of a chessboard on a flat surface taken by the same camera. OpenCV has a convenient method called findChessboardCorners that will identify the points where black and white squares intersect and reverse engineer the distorsion matrix this way. The image below shows the identified chessboard corners traced on a sample image:
We can see that corners are very well identified. Next we run our chessboard finding algorithm over multiple chessboard images taken from different angles to identify image and object points to calibrate the camera. The former refers to coordinates in our 2D mapping while the latter represents the real-world coordinates of those image points in 3D space (with z axis, or depth = 0 for our chessboard images). Those mappings enable us to find out how to properly remove distortion on images taken from the same camera. You can witness its effectiveness on the image below:
We are now in a position to reverse the distortion on all images, as shown below on a sample of them:
We apply color and edge thresholding in this section to better detect the lines, and make it easier to find the polynomial that best describes our left and right lanes later.
We start with first exploring which color spaces we should adopt to increase our chances of detecting the lanes and facilitating the task of the gradient thresholding step.
We experiment with different color spaces to see which color space and channel(s) we should use for the most effective separation of lane lines:
On the RGB components, we see that the blue channel is worst at identifying yellow lines, while the red channel seems to give best results.
For HLS and HSV, the hue channel produces an extremely noisy output, while the saturation channel of HLS seems to give the strong results; better than HSV’s saturation channel. conversely, HSV’s value channel is giving a very clear grayscale-ish image, especially on the yellow line, much better than HLS’ lightness channel.
Lastly, LAB’s A channel is not doing a great job, while it’s B channel is strong at identifying the yellow line. But it is the lightness channel that shines (no pun intended) at identifying both yellow and white lines.
At this stage, we are faced with various choices that have pros and cons. Our goal here is to find the right thresholds on a given color channel to highlight yellow and white lines of the lane. There are actually many ways we could achieve this result, but we choose to use HLS because we already know how to set thresholds for yellow and white lane lines from Project 1: Simple Lane Detection .
The code below shows how we threshold for white and yellow (our lane colors) on HLS and produce a binary image:
def compute_hls_white_yellow_binary(rgb_img): """ Returns a binary thresholded image produced retaining only white and yellow elements on the picture The provided image should be in RGB format """ hls_img = to_hls(rgb_img) # Compute a binary thresholded image where yellow is isolated from HLS components img_hls_yellow_bin = np.zeros_like(hls_img[:,:,0]) img_hls_yellow_bin[((hls_img[:,:,0] >= 15) & (hls_img[:,:,0] <= 35)) & ((hls_img[:,:,1] >= 30) & (hls_img[:,:,1] <= 204)) & ((hls_img[:,:,2] >= 115) & (hls_img[:,:,2] <= 255)) ] = 1 # Compute a binary thresholded image where white is isolated from HLS components img_hls_white_bin = np.zeros_like(hls_img[:,:,0]) img_hls_white_bin[((hls_img[:,:,0] >= 0) & (hls_img[:,:,0] <= 255)) & ((hls_img[:,:,1] >= 200) & (hls_img[:,:,1] <= 255)) & ((hls_img[:,:,2] >= 0) & (hls_img[:,:,2] <= 255)) ] = 1 # Now combine both img_hls_white_yellow_bin = np.zeros_like(hls_img[:,:,0]) img_hls_white_yellow_bin[(img_hls_yellow_bin == 1) | (img_hls_white_bin == 1)] = 1 return img_hls_white_yellow_bin
The result can be seen just below:
As you can see above, our HLS color thresholding achieves great results on the image. The thresholding somewhat struggles a little with the shadow of the tree on the yellow line further up ahead. We believe gradient thresholding can help in this case.
We use the Sobel operator to identify gradients, that is change in color intensity in the image. Higher values would denote strong gradients, and therefore sharp changes in color.
We have decided to use LAB’s L channel as our single-channel image to serve as input to the sobel functions below.
We experimented with many parameters and across different Sobel operations (all available for you to see on this Jupyter notebook), and came up with this final result:
We pick the second image from the bottom as our best result. Notice that on our chosen image we applied a kernel of 15x15 pixels, thus effectively smoothing out the pixels and producing a cleaner binary image.
We naturally combine both color and Sobel thresholded binary images, and arrive at the following results:
On the left image, all green pixels were retained by our Sobel thresholding, while the blue pixels were identified by our HLS color thresholding. The results are very encouraging and it seems we have found the right parameters to detect lanes in a robust manner. We turn next to applying a perspective transform to our image and produce a bird’s eye view of the lane.
We now need to define a trapezoidal region in the 2D image that will go through a perspective transform to convert into a bird’s eye view, like in the below:
We then define 4 extra points which form a rectangle that will map to the pixels in our source trapezoid:
dst_pts = np.array([[200, bottom_px], [200, 0], [1000, 0], [1000, bottom_px]], np.float32)
The perspective transform produces the following type of images:
We can see that our perspective transform keeps straight lines straight, which is a required sanity check. The curved lines however are not perfect on the example above, but they should not cause unsurmountable problems for our algorithm either.
We can now apply our thresholding to our bird’s eye view images:
We then compute a histogram of our binary thresholded images in the y direction, on the bottom half of the image, to identify the x positions where the pixel intensities are highest:
Since we now know the starting x position of pixels (from the bottom of the image) most likely to yield a lane line, we run a sliding windows search in an attempt to “capture” the pixel coordinates of our lane lines.
From then, we simply compute a second degree polynomial, via numpy’s polyfit, to find the coefficients of the curves that best fit the left and right lane lines.
One way we improve the algorithm is by saving the previously computed coefficients for frame t-1 and attempt to find our lane pixels from those coefficients. However, when we do not find enough lane line pixels (less than 85% of total non zero pixels), we revert to sliding windows search to help improve our chances of fitting better curves around our lane.
We also compute the lane curvature by calculating the radius of the smallest circle that could be a tangent to our lane lines — on a straight lane the radius would be quite big. We have to convert from pixel space to meters (aka real world units) by defining the appropriate pixel height to lane length and pixel width to lane width ratios:
# Height ratio: 32 meters / 720 pxself.ym_per_px = self.real_world_lane_size_meters[0] / self.img_dimensions[0]# Width ratio: 3.7 meters / 800 pxself.xm_per_px = self.real_world_lane_size_meters[1] / self.lane_width_px
I tried to manually estimate the length of the road on my bird’s eye view images by referring to data from this resource: every time a car has travelled it has passed 40 feet (around 12.2 meters). On my sample image it seems the bird’s eye view covers around 32 meters. The width remains 3.7 meters, in line with US highway standards. You can find more information on the mathematical underpinnings of radius of curvature via the following link.
We also compute the car’s distance from the center of the lane by offsetting the average of the starting (i.e. bottom) coordinates for the left and right lines of the lane, subtract the middle point as an offset and multiply by the lane’s pixel to real world width ratio.
Finally, we draw the inside the of the lane in green and unwarp the image, thus moving from bird’s eye view to the original undistorted image. Additionally, we overlay this big image with small images of our lane detection algorithm to give a better feel of what is going on frame by frame. We also add textual information about lane curvature and vehicle’s center position:
The following gif shows we have built a strong lane detection pipeline for the project video:
Additionally, I have uploaded a video on Youtube where I draw the lanes on the project video, and add extra information such as lane curvature approximations. The background music is The Son Of Flynn (from Tron:Legacy, obviously 😎). Enjoy!
This was an exciting, but hard project, which felt very different from our previous 2 deep learning projects. We’ve covered how to perform camera calibration, color and gradient thresholds, as well as perspective transform and sliding windows to identify lane lines! The sliding windows code was particularly hard to understand initially but after long time debugging it and making comments (all available on my notebook) I finally understood every line!
We believe there are many improvements that could be made to this project, such as:
experiment with LAB and YUV color spaces to determine whether we can produce better color thresholding
use convolutions instead of sliding windows to identify hot pixels
produce an exponential moving average of the line coefficients of previous frames and use it when our pixel detection fails
better detect anomalies in pixels “captured” (e.g. some non-zero pixels that are completely off the line) and reject them
apply other relevant computer vision techniques not covered by this project
Moreover, we need to build a much more robust pipeline to succeed on the two challenge videos that are part of this project.
As usual, I’d like to thank my mentor Dylan for his advice and support as well as my peers at Udacity, previous and present cohorts, for putting together great writeups and inspiring me.
Thanks for reading this post. I hope you found it useful. I’m now building a new startup called EnVsion! At EnVsion, we’re creating the central repository for UX researchers and product teams to unlock the insights from their user interview videos. And of course we use AI for this ;).
If you’re a UX researcher or product manager feeling overwhelmed with all your video calls with users and customers, then EnVsion is for you!
You also can follow me on Twitter. | [
{
"code": null,
"e": 358,
"s": 171,
"text": "This is project 4 of Term 1 of the Udacity Self-Driving Car Engineer Nanodegree. You can find all code related to this project on github. You can also read my posts on previous projects:"
},
{
"code": null,
"e": 412,
"s": 358,
"text": "project 1: Detecting Lane Lines Using Computer Vision"
},
{
"code": null,
"e": 471,
"s": 412,
"text": "project 2: Traffic Sign Classification Using Deep Learning"
},
{
"code": null,
"e": 528,
"s": 471,
"text": "project 3: Steering Angle Prediction Using Deep Learning"
},
{
"code": null,
"e": 1147,
"s": 528,
"text": "Identifying lanes on the road is a common task performed by all human drivers to ensure their vehicles are within lane constraints when driving, so as to make sure traffic is smooth and minimise chances of collisions with other cars in nearby lanes. Similarly, it is a critical task for an autonomous vehicle to perform. It turns out that recognising lane markings on roads is possible using well known computer vision techniques. We will cover how to use various techniques to identify and draw the inside of a lane, compute lane curvature, and even estimate the vehicle’s position relative to the center of the lane."
},
{
"code": null,
"e": 1289,
"s": 1147,
"text": "To detect and draw a polygon that takes the shape of the lane the car is currently in, we build a pipeline consisting of the following steps:"
},
{
"code": null,
"e": 1390,
"s": 1289,
"text": "Computation of camera calibration matrix and distortion coefficients from a set of chessboard images"
},
{
"code": null,
"e": 1419,
"s": 1390,
"text": "Distortion removal on images"
},
{
"code": null,
"e": 1487,
"s": 1419,
"text": "Application of color and gradient thresholds to focus on lane lines"
},
{
"code": null,
"e": 1551,
"s": 1487,
"text": "Production of a bird’s eye view image via perspective transform"
},
{
"code": null,
"e": 1603,
"s": 1551,
"text": "Use of sliding windows to find hot lane line pixels"
},
{
"code": null,
"e": 1692,
"s": 1603,
"text": "Fitting of second degree polynomials to identify left and right lines composing the lane"
},
{
"code": null,
"e": 1753,
"s": 1692,
"text": "Computation of lane curvature and deviation from lane center"
},
{
"code": null,
"e": 1839,
"s": 1753,
"text": "Warping and drawing of lane boundaries on image as well as lane curvature information"
},
{
"code": null,
"e": 1900,
"s": 1839,
"text": "I believe a diagram is worth a thousand words so here it is:"
},
{
"code": null,
"e": 2292,
"s": 1900,
"text": "The first step we will take is to find the calibration matrix, along with distortion coefficients for the camera that was used to take pictures of the road. This is necessary because the convex shape of camera lenses curves light rays as they enter the pinhole, thus causing distortions to the real image. Therefore lines that are straight in the real world may not be anymore on our photos."
},
{
"code": null,
"e": 2719,
"s": 2292,
"text": "To compute the camera the transformation matrix and distortion coefficients, we use multiple pictures of a chessboard on a flat surface taken by the same camera. OpenCV has a convenient method called findChessboardCorners that will identify the points where black and white squares intersect and reverse engineer the distorsion matrix this way. The image below shows the identified chessboard corners traced on a sample image:"
},
{
"code": null,
"e": 3293,
"s": 2719,
"text": "We can see that corners are very well identified. Next we run our chessboard finding algorithm over multiple chessboard images taken from different angles to identify image and object points to calibrate the camera. The former refers to coordinates in our 2D mapping while the latter represents the real-world coordinates of those image points in 3D space (with z axis, or depth = 0 for our chessboard images). Those mappings enable us to find out how to properly remove distortion on images taken from the same camera. You can witness its effectiveness on the image below:"
},
{
"code": null,
"e": 3395,
"s": 3293,
"text": "We are now in a position to reverse the distortion on all images, as shown below on a sample of them:"
},
{
"code": null,
"e": 3570,
"s": 3395,
"text": "We apply color and edge thresholding in this section to better detect the lines, and make it easier to find the polynomial that best describes our left and right lanes later."
},
{
"code": null,
"e": 3743,
"s": 3570,
"text": "We start with first exploring which color spaces we should adopt to increase our chances of detecting the lanes and facilitating the task of the gradient thresholding step."
},
{
"code": null,
"e": 3888,
"s": 3743,
"text": "We experiment with different color spaces to see which color space and channel(s) we should use for the most effective separation of lane lines:"
},
{
"code": null,
"e": 4028,
"s": 3888,
"text": "On the RGB components, we see that the blue channel is worst at identifying yellow lines, while the red channel seems to give best results."
},
{
"code": null,
"e": 4353,
"s": 4028,
"text": "For HLS and HSV, the hue channel produces an extremely noisy output, while the saturation channel of HLS seems to give the strong results; better than HSV’s saturation channel. conversely, HSV’s value channel is giving a very clear grayscale-ish image, especially on the yellow line, much better than HLS’ lightness channel."
},
{
"code": null,
"e": 4572,
"s": 4353,
"text": "Lastly, LAB’s A channel is not doing a great job, while it’s B channel is strong at identifying the yellow line. But it is the lightness channel that shines (no pun intended) at identifying both yellow and white lines."
},
{
"code": null,
"e": 4968,
"s": 4572,
"text": "At this stage, we are faced with various choices that have pros and cons. Our goal here is to find the right thresholds on a given color channel to highlight yellow and white lines of the lane. There are actually many ways we could achieve this result, but we choose to use HLS because we already know how to set thresholds for yellow and white lane lines from Project 1: Simple Lane Detection ."
},
{
"code": null,
"e": 5080,
"s": 4968,
"text": "The code below shows how we threshold for white and yellow (our lane colors) on HLS and produce a binary image:"
},
{
"code": null,
"e": 6303,
"s": 5080,
"text": "def compute_hls_white_yellow_binary(rgb_img): \"\"\" Returns a binary thresholded image produced retaining only white and yellow elements on the picture The provided image should be in RGB format \"\"\" hls_img = to_hls(rgb_img) # Compute a binary thresholded image where yellow is isolated from HLS components img_hls_yellow_bin = np.zeros_like(hls_img[:,:,0]) img_hls_yellow_bin[((hls_img[:,:,0] >= 15) & (hls_img[:,:,0] <= 35)) & ((hls_img[:,:,1] >= 30) & (hls_img[:,:,1] <= 204)) & ((hls_img[:,:,2] >= 115) & (hls_img[:,:,2] <= 255)) ] = 1 # Compute a binary thresholded image where white is isolated from HLS components img_hls_white_bin = np.zeros_like(hls_img[:,:,0]) img_hls_white_bin[((hls_img[:,:,0] >= 0) & (hls_img[:,:,0] <= 255)) & ((hls_img[:,:,1] >= 200) & (hls_img[:,:,1] <= 255)) & ((hls_img[:,:,2] >= 0) & (hls_img[:,:,2] <= 255)) ] = 1 # Now combine both img_hls_white_yellow_bin = np.zeros_like(hls_img[:,:,0]) img_hls_white_yellow_bin[(img_hls_yellow_bin == 1) | (img_hls_white_bin == 1)] = 1 return img_hls_white_yellow_bin"
},
{
"code": null,
"e": 6338,
"s": 6303,
"text": "The result can be seen just below:"
},
{
"code": null,
"e": 6590,
"s": 6338,
"text": "As you can see above, our HLS color thresholding achieves great results on the image. The thresholding somewhat struggles a little with the shadow of the tree on the yellow line further up ahead. We believe gradient thresholding can help in this case."
},
{
"code": null,
"e": 6770,
"s": 6590,
"text": "We use the Sobel operator to identify gradients, that is change in color intensity in the image. Higher values would denote strong gradients, and therefore sharp changes in color."
},
{
"code": null,
"e": 6885,
"s": 6770,
"text": "We have decided to use LAB’s L channel as our single-channel image to serve as input to the sobel functions below."
},
{
"code": null,
"e": 7053,
"s": 6885,
"text": "We experimented with many parameters and across different Sobel operations (all available for you to see on this Jupyter notebook), and came up with this final result:"
},
{
"code": null,
"e": 7263,
"s": 7053,
"text": "We pick the second image from the bottom as our best result. Notice that on our chosen image we applied a kernel of 15x15 pixels, thus effectively smoothing out the pixels and producing a cleaner binary image."
},
{
"code": null,
"e": 7369,
"s": 7263,
"text": "We naturally combine both color and Sobel thresholded binary images, and arrive at the following results:"
},
{
"code": null,
"e": 7737,
"s": 7369,
"text": "On the left image, all green pixels were retained by our Sobel thresholding, while the blue pixels were identified by our HLS color thresholding. The results are very encouraging and it seems we have found the right parameters to detect lanes in a robust manner. We turn next to applying a perspective transform to our image and produce a bird’s eye view of the lane."
},
{
"code": null,
"e": 7895,
"s": 7737,
"text": "We now need to define a trapezoidal region in the 2D image that will go through a perspective transform to convert into a bird’s eye view, like in the below:"
},
{
"code": null,
"e": 8001,
"s": 7895,
"text": "We then define 4 extra points which form a rectangle that will map to the pixels in our source trapezoid:"
},
{
"code": null,
"e": 8092,
"s": 8001,
"text": "dst_pts = np.array([[200, bottom_px], [200, 0], [1000, 0], [1000, bottom_px]], np.float32)"
},
{
"code": null,
"e": 8157,
"s": 8092,
"text": "The perspective transform produces the following type of images:"
},
{
"code": null,
"e": 8403,
"s": 8157,
"text": "We can see that our perspective transform keeps straight lines straight, which is a required sanity check. The curved lines however are not perfect on the example above, but they should not cause unsurmountable problems for our algorithm either."
},
{
"code": null,
"e": 8468,
"s": 8403,
"text": "We can now apply our thresholding to our bird’s eye view images:"
},
{
"code": null,
"e": 8651,
"s": 8468,
"text": "We then compute a histogram of our binary thresholded images in the y direction, on the bottom half of the image, to identify the x positions where the pixel intensities are highest:"
},
{
"code": null,
"e": 8868,
"s": 8651,
"text": "Since we now know the starting x position of pixels (from the bottom of the image) most likely to yield a lane line, we run a sliding windows search in an attempt to “capture” the pixel coordinates of our lane lines."
},
{
"code": null,
"e": 9030,
"s": 8868,
"text": "From then, we simply compute a second degree polynomial, via numpy’s polyfit, to find the coefficients of the curves that best fit the left and right lane lines."
},
{
"code": null,
"e": 9389,
"s": 9030,
"text": "One way we improve the algorithm is by saving the previously computed coefficients for frame t-1 and attempt to find our lane pixels from those coefficients. However, when we do not find enough lane line pixels (less than 85% of total non zero pixels), we revert to sliding windows search to help improve our chances of fitting better curves around our lane."
},
{
"code": null,
"e": 9730,
"s": 9389,
"text": "We also compute the lane curvature by calculating the radius of the smallest circle that could be a tangent to our lane lines — on a straight lane the radius would be quite big. We have to convert from pixel space to meters (aka real world units) by defining the appropriate pixel height to lane length and pixel width to lane width ratios:"
},
{
"code": null,
"e": 9949,
"s": 9730,
"text": "# Height ratio: 32 meters / 720 pxself.ym_per_px = self.real_world_lane_size_meters[0] / self.img_dimensions[0]# Width ratio: 3.7 meters / 800 pxself.xm_per_px = self.real_world_lane_size_meters[1] / self.lane_width_px"
},
{
"code": null,
"e": 10395,
"s": 9949,
"text": "I tried to manually estimate the length of the road on my bird’s eye view images by referring to data from this resource: every time a car has travelled it has passed 40 feet (around 12.2 meters). On my sample image it seems the bird’s eye view covers around 32 meters. The width remains 3.7 meters, in line with US highway standards. You can find more information on the mathematical underpinnings of radius of curvature via the following link."
},
{
"code": null,
"e": 10667,
"s": 10395,
"text": "We also compute the car’s distance from the center of the lane by offsetting the average of the starting (i.e. bottom) coordinates for the left and right lines of the lane, subtract the middle point as an offset and multiply by the lane’s pixel to real world width ratio."
},
{
"code": null,
"e": 11042,
"s": 10667,
"text": "Finally, we draw the inside the of the lane in green and unwarp the image, thus moving from bird’s eye view to the original undistorted image. Additionally, we overlay this big image with small images of our lane detection algorithm to give a better feel of what is going on frame by frame. We also add textual information about lane curvature and vehicle’s center position:"
},
{
"code": null,
"e": 11136,
"s": 11042,
"text": "The following gif shows we have built a strong lane detection pipeline for the project video:"
},
{
"code": null,
"e": 11376,
"s": 11136,
"text": "Additionally, I have uploaded a video on Youtube where I draw the lanes on the project video, and add extra information such as lane curvature approximations. The background music is The Son Of Flynn (from Tron:Legacy, obviously 😎). Enjoy!"
},
{
"code": null,
"e": 11831,
"s": 11376,
"text": "This was an exciting, but hard project, which felt very different from our previous 2 deep learning projects. We’ve covered how to perform camera calibration, color and gradient thresholds, as well as perspective transform and sliding windows to identify lane lines! The sliding windows code was particularly hard to understand initially but after long time debugging it and making comments (all available on my notebook) I finally understood every line!"
},
{
"code": null,
"e": 11915,
"s": 11831,
"text": "We believe there are many improvements that could be made to this project, such as:"
},
{
"code": null,
"e": 12018,
"s": 11915,
"text": "experiment with LAB and YUV color spaces to determine whether we can produce better color thresholding"
},
{
"code": null,
"e": 12085,
"s": 12018,
"text": "use convolutions instead of sliding windows to identify hot pixels"
},
{
"code": null,
"e": 12209,
"s": 12085,
"text": "produce an exponential moving average of the line coefficients of previous frames and use it when our pixel detection fails"
},
{
"code": null,
"e": 12331,
"s": 12209,
"text": "better detect anomalies in pixels “captured” (e.g. some non-zero pixels that are completely off the line) and reject them"
},
{
"code": null,
"e": 12407,
"s": 12331,
"text": "apply other relevant computer vision techniques not covered by this project"
},
{
"code": null,
"e": 12532,
"s": 12407,
"text": "Moreover, we need to build a much more robust pipeline to succeed on the two challenge videos that are part of this project."
},
{
"code": null,
"e": 12719,
"s": 12532,
"text": "As usual, I’d like to thank my mentor Dylan for his advice and support as well as my peers at Udacity, previous and present cohorts, for putting together great writeups and inspiring me."
},
{
"code": null,
"e": 13005,
"s": 12719,
"text": "Thanks for reading this post. I hope you found it useful. I’m now building a new startup called EnVsion! At EnVsion, we’re creating the central repository for UX researchers and product teams to unlock the insights from their user interview videos. And of course we use AI for this ;)."
},
{
"code": null,
"e": 13147,
"s": 13005,
"text": "If you’re a UX researcher or product manager feeling overwhelmed with all your video calls with users and customers, then EnVsion is for you!"
}
]
|
How will you print numbers from 1 to 100 without using loop? - GeeksforGeeks | 12 Jan, 2022
If we take a look at this problem carefully, we can see that the idea of “loop” is to track some counter value e.g. “i=0” till “i <= 100”. So if we aren’t allowed to use loop, how else can be track something in C language! Well, one possibility is the use of ‘recursion’ provided we use the terminating condition carefully. Here is a solution that prints numbers using recursion.
Method-1:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to How will you print// numbers from 1 to 100 without using loop?#include <iostream>using namespace std; class gfg{ // Prints numbers from 1 to npublic:void printNos(unsigned int n){ if(n > 0) { printNos(n - 1); cout << n << " "; } return;}}; // Driver codeint main(){ gfg g; g.printNos(100); return 0;} // This code is contributed by SoM15242
#include <stdio.h> // Prints numbers from 1 to nvoid printNos(unsigned int n){ if(n > 0) { printNos(n - 1); printf("%d ", n); } return;} // Driver codeint main(){ printNos(100); getchar(); return 0;}
import java.io.*;import java.util.*;import java.text.*;import java.math.*;import java.util.regex.*; class GFG{ // Prints numbers from 1 to n static void printNos(int n) { if(n > 0) { printNos(n - 1); System.out.print(n + " "); } return; } // Driver Code public static void main(String[] args) { printNos(100); }} // This code is contributed by Manish_100
# Python3 program to Print# numbers from 1 to n def printNos(n): if n > 0: printNos(n - 1) print(n, end = ' ') # Driver codeprintNos(100) # This code is contributed by Smitha Dinesh Semwal
// C# code for print numbers from// 1 to 100 without using loopusing System; class GFG{ // Prints numbers from 1 to n static void printNos(int n) { if(n > 0) { printNos(n - 1); Console.Write(n + " "); } return; } // Driver Codepublic static void Main(){ printNos(100);}} // This code is contributed by Ajit
<?php// PHP program print numbers// from 1 to 100 without// using loop // Prints numbers from 1 to nfunction printNos($n){ if($n > 0) { printNos($n - 1); echo $n, " "; } return;} // Driver codeprintNos(100); // This code is contributed by vt_m?>
<script> // Javascript code for print numbers from // 1 to 100 without using loop // Prints numbers from 1 to n function printNos(n) { if(n > 0) { printNos(n - 1); document.write(n + " "); } return; } printNos(100); // This code is contributed by rameshtravel07.</script>
Output :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49 50 51
52 53 54 55 56 57 58 59 60 61 62 63
64 65 66 67 68 69 70 71 72 73 74 75
76 77 78 79 80 81 82 83 84 85 86 87
88 89 90 91 92 93 94 95 96 97 98 99
100
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2:
C++
Java
Python3
C#
Javascript
// C++ program#include <bits/stdc++.h>using namespace std; void printNos(int initial, int last){ if (initial <= last) { cout << initial << " "; printNos(initial + 1, last); }} int main(){ printNos(1, 100); return 0;} // This code is contributed by ukasp.
/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main(String[] args) { printNos(1, 100); } public static void printNos(int initial, int last) { if (initial <= last) { System.out.print(initial + " "); printNos(initial + 1, last); } }}
def printNos(initial, last): if(initial<=last): print(initial) printNos(initial+1,last)printNos(1,10)
/*package whatever //do not write package name here */ using System;public class GFG { public static void Main(String[] args) { printNos(1, 100); } public static void printNos(int initial, int last) { if (initial <= last) { Console.Write(initial + " "); printNos(initial + 1, last); } }} // This code contributed by gauravrajput1
/*package whatever //do not write package name here */ printNos(1, 100); function printNos(initial, last) { if (initial <= last) { document.write(initial + " "); printNos(initial + 1, last); } } // This code is contributed by shivanisinghss2110
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
Time Complexity : O(n)
Auxiliary Space: O(n)Now try writing a program that does the same but without any “if” construct. Hint — use some operator which can be used instead of “if”. Please note that recursion technique is good but every call to the function creates one “stack-frame” in program stack. So if there’s constraint to the limited memory and we need to print large set of numbers, “recursion” might not be a good idea. So what could be the other alternative?Another alternative is “goto” statement. Though use of “goto” is not suggestible as a general programming practice as “goto” statement changes the normal program execution sequence yet in some cases, use of “goto” is the best working solution. So please give a try printing numbers from 1 to 100 with “goto” statement. You can use GfG IDE! Print 1 to 100 in C++, without loop and recursion
Manish_100
vt_m
jit_t
SoumikMondal
rameshtravel07
saivinaygondrala
GauravRajput1
ukasp
simmytarika5
rishavmahato348
shivanisinghss2110
subham348
1612
cpp-puzzle
C Language
C++
Recursion
Recursion
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
fork() in C
Left Shift and Right Shift Operators in C/C++
Command line arguments 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": 25254,
"s": 25226,
"text": "\n12 Jan, 2022"
},
{
"code": null,
"e": 25636,
"s": 25254,
"text": "If we take a look at this problem carefully, we can see that the idea of “loop” is to track some counter value e.g. “i=0” till “i <= 100”. So if we aren’t allowed to use loop, how else can be track something in C language! Well, one possibility is the use of ‘recursion’ provided we use the terminating condition carefully. Here is a solution that prints numbers using recursion. "
},
{
"code": null,
"e": 25646,
"s": 25636,
"text": "Method-1:"
},
{
"code": null,
"e": 25650,
"s": 25646,
"text": "C++"
},
{
"code": null,
"e": 25652,
"s": 25650,
"text": "C"
},
{
"code": null,
"e": 25657,
"s": 25652,
"text": "Java"
},
{
"code": null,
"e": 25665,
"s": 25657,
"text": "Python3"
},
{
"code": null,
"e": 25668,
"s": 25665,
"text": "C#"
},
{
"code": null,
"e": 25672,
"s": 25668,
"text": "PHP"
},
{
"code": null,
"e": 25683,
"s": 25672,
"text": "Javascript"
},
{
"code": "// C++ program to How will you print// numbers from 1 to 100 without using loop?#include <iostream>using namespace std; class gfg{ // Prints numbers from 1 to npublic:void printNos(unsigned int n){ if(n > 0) { printNos(n - 1); cout << n << \" \"; } return;}}; // Driver codeint main(){ gfg g; g.printNos(100); return 0;} // This code is contributed by SoM15242",
"e": 26083,
"s": 25683,
"text": null
},
{
"code": "#include <stdio.h> // Prints numbers from 1 to nvoid printNos(unsigned int n){ if(n > 0) { printNos(n - 1); printf(\"%d \", n); } return;} // Driver codeint main(){ printNos(100); getchar(); return 0;}",
"e": 26318,
"s": 26083,
"text": null
},
{
"code": "import java.io.*;import java.util.*;import java.text.*;import java.math.*;import java.util.regex.*; class GFG{ // Prints numbers from 1 to n static void printNos(int n) { if(n > 0) { printNos(n - 1); System.out.print(n + \" \"); } return; } // Driver Code public static void main(String[] args) { printNos(100); }} // This code is contributed by Manish_100",
"e": 26755,
"s": 26318,
"text": null
},
{
"code": "# Python3 program to Print# numbers from 1 to n def printNos(n): if n > 0: printNos(n - 1) print(n, end = ' ') # Driver codeprintNos(100) # This code is contributed by Smitha Dinesh Semwal",
"e": 26961,
"s": 26755,
"text": null
},
{
"code": "// C# code for print numbers from// 1 to 100 without using loopusing System; class GFG{ // Prints numbers from 1 to n static void printNos(int n) { if(n > 0) { printNos(n - 1); Console.Write(n + \" \"); } return; } // Driver Codepublic static void Main(){ printNos(100);}} // This code is contributed by Ajit",
"e": 27342,
"s": 26961,
"text": null
},
{
"code": "<?php// PHP program print numbers// from 1 to 100 without// using loop // Prints numbers from 1 to nfunction printNos($n){ if($n > 0) { printNos($n - 1); echo $n, \" \"; } return;} // Driver codeprintNos(100); // This code is contributed by vt_m?>",
"e": 27617,
"s": 27342,
"text": null
},
{
"code": "<script> // Javascript code for print numbers from // 1 to 100 without using loop // Prints numbers from 1 to n function printNos(n) { if(n > 0) { printNos(n - 1); document.write(n + \" \"); } return; } printNos(100); // This code is contributed by rameshtravel07.</script>",
"e": 27970,
"s": 27617,
"text": null
},
{
"code": null,
"e": 27981,
"s": 27970,
"text": "Output : "
},
{
"code": null,
"e": 28277,
"s": 27981,
"text": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 \n16 17 18 19 20 21 22 23 24 25 26 27 \n28 29 30 31 32 33 34 35 36 37 38 39\n40 41 42 43 44 45 46 47 48 49 50 51\n52 53 54 55 56 57 58 59 60 61 62 63\n64 65 66 67 68 69 70 71 72 73 74 75\n76 77 78 79 80 81 82 83 84 85 86 87\n88 89 90 91 92 93 94 95 96 97 98 99 \n100 "
},
{
"code": null,
"e": 28299,
"s": 28277,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 28321,
"s": 28299,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 28331,
"s": 28321,
"text": "Method 2:"
},
{
"code": null,
"e": 28335,
"s": 28331,
"text": "C++"
},
{
"code": null,
"e": 28340,
"s": 28335,
"text": "Java"
},
{
"code": null,
"e": 28348,
"s": 28340,
"text": "Python3"
},
{
"code": null,
"e": 28351,
"s": 28348,
"text": "C#"
},
{
"code": null,
"e": 28362,
"s": 28351,
"text": "Javascript"
},
{
"code": "// C++ program#include <bits/stdc++.h>using namespace std; void printNos(int initial, int last){ if (initial <= last) { cout << initial << \" \"; printNos(initial + 1, last); }} int main(){ printNos(1, 100); return 0;} // This code is contributed by ukasp.",
"e": 28643,
"s": 28362,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main(String[] args) { printNos(1, 100); } public static void printNos(int initial, int last) { if (initial <= last) { System.out.print(initial + \" \"); printNos(initial + 1, last); } }}",
"e": 28993,
"s": 28643,
"text": null
},
{
"code": "def printNos(initial, last): if(initial<=last): print(initial) printNos(initial+1,last)printNos(1,10)",
"e": 29112,
"s": 28993,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ using System;public class GFG { public static void Main(String[] args) { printNos(1, 100); } public static void printNos(int initial, int last) { if (initial <= last) { Console.Write(initial + \" \"); printNos(initial + 1, last); } }} // This code contributed by gauravrajput1",
"e": 29505,
"s": 29112,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ printNos(1, 100); function printNos(initial, last) { if (initial <= last) { document.write(initial + \" \"); printNos(initial + 1, last); } } // This code is contributed by shivanisinghss2110",
"e": 29804,
"s": 29505,
"text": null
},
{
"code": null,
"e": 30097,
"s": 29804,
"text": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 "
},
{
"code": null,
"e": 30120,
"s": 30097,
"text": "Time Complexity : O(n)"
},
{
"code": null,
"e": 30956,
"s": 30120,
"text": "Auxiliary Space: O(n)Now try writing a program that does the same but without any “if” construct. Hint — use some operator which can be used instead of “if”. Please note that recursion technique is good but every call to the function creates one “stack-frame” in program stack. So if there’s constraint to the limited memory and we need to print large set of numbers, “recursion” might not be a good idea. So what could be the other alternative?Another alternative is “goto” statement. Though use of “goto” is not suggestible as a general programming practice as “goto” statement changes the normal program execution sequence yet in some cases, use of “goto” is the best working solution. So please give a try printing numbers from 1 to 100 with “goto” statement. You can use GfG IDE! Print 1 to 100 in C++, without loop and recursion "
},
{
"code": null,
"e": 30967,
"s": 30956,
"text": "Manish_100"
},
{
"code": null,
"e": 30972,
"s": 30967,
"text": "vt_m"
},
{
"code": null,
"e": 30978,
"s": 30972,
"text": "jit_t"
},
{
"code": null,
"e": 30991,
"s": 30978,
"text": "SoumikMondal"
},
{
"code": null,
"e": 31006,
"s": 30991,
"text": "rameshtravel07"
},
{
"code": null,
"e": 31023,
"s": 31006,
"text": "saivinaygondrala"
},
{
"code": null,
"e": 31037,
"s": 31023,
"text": "GauravRajput1"
},
{
"code": null,
"e": 31043,
"s": 31037,
"text": "ukasp"
},
{
"code": null,
"e": 31056,
"s": 31043,
"text": "simmytarika5"
},
{
"code": null,
"e": 31072,
"s": 31056,
"text": "rishavmahato348"
},
{
"code": null,
"e": 31091,
"s": 31072,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 31101,
"s": 31091,
"text": "subham348"
},
{
"code": null,
"e": 31106,
"s": 31101,
"text": "1612"
},
{
"code": null,
"e": 31117,
"s": 31106,
"text": "cpp-puzzle"
},
{
"code": null,
"e": 31128,
"s": 31117,
"text": "C Language"
},
{
"code": null,
"e": 31132,
"s": 31128,
"text": "C++"
},
{
"code": null,
"e": 31142,
"s": 31132,
"text": "Recursion"
},
{
"code": null,
"e": 31152,
"s": 31142,
"text": "Recursion"
},
{
"code": null,
"e": 31156,
"s": 31152,
"text": "CPP"
},
{
"code": null,
"e": 31254,
"s": 31156,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31263,
"s": 31254,
"text": "Comments"
},
{
"code": null,
"e": 31276,
"s": 31263,
"text": "Old Comments"
},
{
"code": null,
"e": 31311,
"s": 31276,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 31339,
"s": 31311,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 31351,
"s": 31339,
"text": "fork() in C"
},
{
"code": null,
"e": 31397,
"s": 31351,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 31429,
"s": 31397,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 31447,
"s": 31429,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 31466,
"s": 31447,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 31512,
"s": 31466,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 31555,
"s": 31512,
"text": "Map in C++ Standard Template Library (STL)"
}
]
|
Using the Gini coefficient to evaluate the performance of credit score models | by Idan Schatz | Towards Data Science | When a new credit score model is born, usually the first question that comes up is: “what is its Gini?”. To an outsider, it must sound like an odd referral to Disney’s film Aladdin. But, Gini or the Gini coefficient is one of the most popular metrics used by the financial industry for evaluating the performance of credit score models.
The Gini coefficient is a metric that indicates the model’s discriminatory power, namely, the effectiveness of the model in differentiating between “bad” borrowers, who will default in the future, and “good” borrowers, who won’t default in the future. This metric is often used to compare the quality of different models and evaluate their prediction power.
Despite its commonality, some practitioners are not genuinely familiar with the mechanism beyond this Gini coefficient and mistakenly confuse it with a different metric with the same name. While many practitioners mistakenly associate the Gini coefficient with the summary of the Lorenz curve, Corrado Gini’s measure of inequality[1], the Gini coefficient they are using is most of the time Somers’ D, which is the summary of the CAP (Cumulative Accuracy Profile) curve.
Somers’ D is named after Robert H. Somers, who proposed it in 1962[2]. It is a measure of the ordinal relationship between two variables. In the context of credit score models, it measures the ordinal relationship between the models’ predictions, in terms of PD (Probability of Default) or score, and the actual outcome — default or not default. If the model is useful, low scores (high PD) should be more associated with defaults than high scores (low PD).
Somers’ D takes on a value between (-1) and 1. (-1) being a perfect negative ordinal relationship and 1 a perfect ordinal relationship. In practice, a credit score model with Somers’ D of 0.4 is deemed to be good. (Henceforth, I will be addressing Somers’ D as the Gini coefficient)
For the sake of minimalism, I won’t describe the math involved in calculating the Gini coefficient. Instead, I will show three different ways to derive it.
To demonstrate each of these methods, I will be using a sample credit score model which developed using logistic regression and data of 10,000 borrowers from Lending-club.
model <- glm(default ~ fico + loan_amnt + annual_inc + home_ownership, family = "binomial", data = data_set)
Based on the models’ predictions — estimated Probability of Default (PD), I scored each of the borrows from 1 to 1000; 1 represents the lowest PD and 1000 the highest PD.
Extract the Gini coefficient from the CAP curve
The CAP curve, in our context, is designed to capture the ordinal relation between score (PD) and default rate. If our model does a good job of discriminating between good and bad borrowers, we would expect to find more defaults at low scored borrowers than at high scored borrowers. The CAP curve captures this notion by aggregating the cumulative default rate when sampling borrowers from the lowest score to the highest score.
To construct the CAP curve, all the model’s population needs to be ordered by the predicted likelihood of default. Namely, the observation with the lowest score is first, and the observation with the highest score is last. Then, we sample the population from first to last, and after each sampling, we calculate the cumulative default rate. The x-axis of the CAP curve represents the portion of the population sampled, and the y-axis represents the corresponding cumulative default rate.
If our model has perfect discriminatory power, we would expect to reach 100% of the cumulative default rate after sampling a portion of observations, which is equal to the default rate in our data (the green line in the chart below). E.g., if the default rate in our data is 16%, after sampling 16% of the observations, we would capture all the defaults in our data. On the contrary, if we use a random model, i.e., a model which randomly assigns scores in equal distribution, the cumulative default rate will always equal to the portion of observations sampled (the red line in the chart below).
The Gini coefficient is defined as the ratio between the area within the model curve and the random model line (A) and the area between the perfect model curve and the random model line (A+B). Put it differently, the Gini coefficient is a ratio that represents how close our model to be a “perfect model” and how far it is from being a “random model.” Thus, a “perfect model” would get a Gini coefficient of 1, and a “random model” would get a Gini coefficient of 0.
My model gained a low Gini coefficient of 0.26:
Construct the Lorenz curve, extract Corrado Gini’s measure, then derive the Gini coefficient
The Lorenz curve is the inverse of the CAP curve; it is constructed using the same mechanism of sampling observations and aggregating the cumulative default rate, but the sampling is done in reverse order (from highest to lowest score). The Lorenz also has a diagonal line, which is equivalent to the ‘CAP random model’ line and is called “the Line of Equality” (the red line in the chart below).
Another difference between the two curves is the “perfect model” line. Since the Lorenz curve was designed to capture the distribution of wealth, the most discriminative outcome is a case where all the wealth of the population is concentrated in one observation. Namely, the line which is equivalent to the “CAP perfect model” line in the Lorenz curve is constructed from the two perpendicular lines, which are the x-axis and a vertical line, which evolved from the end of the x-axis at the value of 100% (the green line in the chart below). This line represents the case in which all the cumulative outcome is in the last sampled observation. The value of Corrado Gini’s measure is defined as the ratio of the area between the model’s curve and the “Line of Equality” to the area between the “Line of Equality” and the x-axis.
However, when using the Lorenz curve to evaluate the discrimination power of a credit score model and assigning its y-axis to be the cumulative default rate, a problem emerges. Since the y-axis describes the aggregation of a binary outcome (1 or 0), a case where all the cumulative default rate concentrates in one observation doesn’t exist. Put it differently, when evaluating a credit score model using the Lorenz curve, it is impossible to reach the “Perfect model” line. Consequently, an appropriate “perfect model” line for this kind of evaluation should be adjusted to the default rate in the population, as in the CAP curve.
Hence, to adjust Corrado Gini’s measure for credit score model evaluation, we need to deduct the unreachable area from its denominator.
Finally, to derive the Gini coefficient from Corrado Gini’s measure, we can use the following formula:
My model gained Corrado Gini’s measure of 0.22:
The default rate in my sample is 16%, so the Gini coefficient of my model can be calculated as follows:
Construct the ROC curve, extract the AUC, then derive the Gini coefficient
The third method of calculating the Gini coefficient is through another popular curve: the ROC curve. The area under the ROC curve, which is usually called the AUC, is also a popular metric for evaluating and comparing the performance of credit score models. The ROC curve summarizes two ratios from the confusion matrix: the True Positive Ratio (TPR or Recall) and the False Positive Ratio (FPR).
The confusion matrix summarizes, for a given threshold, the number of cases in which:
The model predicted a default and the borrower defaulted — True Positive.
The model predicted a default and the borrower didn’t default — False Positive.
The model predicted no default and the borrower didn’t default — True Negative.
The model predicted no default and the borrower defaulted — False Negative
For example, let’s use the score of 850 as our threshold, i.e., borrows with a score below 850, are predicted to default, and borrowers with a score above 850 are predicted not to default.
The True Positive Ratio (TPR) is defined as the number of defaulted borrowers in which our model caught over the total number of defaulted borrowers in our data. The False Positive Ratio (FPR) is calculated as the number of cases in which the model incorrectly predicted a default over the total number of non-default instances.
The ROC curve is constructed by using confusion matrices that originated from thresholds between 1 to 1000 and driving their TPR and FPR. The y-axis of the ROC curve represents the TPR values, and the x-axis represents the FPR values. The AUC is the area between the curve and the x-axis.
Surprisingly, as shown by Schechtman & Schechtman, 2016[3] there is a linear relationship between the AUC and the Gini coefficient. So, to derive the Gini coefficient from the AUC all you need to do is to use the following formula:
Practitioners tend to disclose the AUC in addition to the Gini coefficient in their model validation report. However, since these metrics have a linear relation, the disclosure of these metrics together doesn’t add any value to the evaluation of the model’s quality.
The AUC of my model is 0.63, hence the Gini coefficient is calculated like this:
Drawbacks and pitfalls of the Gini coefficient
Despite its commonality, the Gini coefficient has some drawbacks and pitfalls you should consider when using it to evaluate and compare credit score models. For the sake of minimalism, in this section, I’ll describe a common pitfall when trying to derive the Gini coefficient and its main drawback.
To illustrate these concepts I’ll use a toy example: 15 borrowers, 2 ”bad” and 13 ”good”, and scores that go from 1 (highest PD) to 10 (lowest PD).
A common pitfall when trying to derive the Gini coefficient is identical scores. In most cases (especially when using large datasets), the credit score model will estimate the same score for different observations. This score duplication raises an issue when trying to derive the Gini coefficient using the CAP curve method. As mentioned above, the first step to derive the CAP curve is to sort the observations by their score, as in the following two examples:
These two examples use the same borrowers with the same scores. The only difference between these two tables is the secondary level of ordering. In Example 1 when there is a case of identical scores (in score 5), the observations which defaulted come first. Example 2 is the other way around. This minor change can have a major effect on the value of the Gini coefficient, e.g. in this case, Example 1 has a Gini coefficient of 0.67, and Example 2 has a Gini coefficient of 0.38.
To avoid this pitfall, I recommend doing a secondary sorting like in Example 1 or simply to derive the Gini coefficient using the AUC method mentioned above.
The major disadvantage of the Gini coefficient comes from the fact that it is an ordinal metric, i.e., it captures the order of values while ignoring the distance between them. This characteristic of the Gini coefficient can sometimes mask poor model performances.
When ordering the borrowers based on the score predicted by both of the models, we get the same “Default” column. This indicates that these two models have the same Gini coefficient (0.85).
When comparing the distributions of scores predicted by these two models we get the following charts:
Both models have the same Gini coefficient. But, Model B was only able to separate the borrowers into three types: 1, 2 and 3, while Model A was able to capture all 10 levels of risk. This suggests that Model A is more sensitive than Model B to the different characteristics of the borrowers, and can differentiate better between different risk levels.
To understand the importance of the feature above, assume that the owner of Model A and the owner of Model B decide to set a score which will be the threshold for their loan approval. I.e., the loan requests of borrowers with a score below or equal to the threshold, will be denied and the loan requests of borrowers with a score above the threshold, will be approved. Both model owners examined their model outcomes on the test sample and decide to use the score which captured 100% of the cumulative default rate as their threshold. Consequently, the owner of Model A sets the threshold to be 6 and the owner of Model B sets her threshold to be 2. By choosing these scores, the model owners got very different results:
The owner of Model A rejected 8 “good” borrowers and approved 5 while the owner of Model B rejected 12 “good” borrowers and approved only 1. The threshold set by the owner of Model A yields FPR of 62%, and the threshold set by the owner of Model B yields FPR of 92%.
Hence, the Gini coefficient inability to capture the model’s effectiveness in differentiating between different levels of risk is a major drawback.
In order to overcome this drawback, I recommend eyeball testing the distribution of the model predictions, as in Gambacorta, Huang, Qiu, & Wang, 2019[4], and using the Precision-Recall curve to evaluate the model’s trade-off between capturing “bad’” borrowers and mistakenly predict default of ‘“good” borrowers.
Summary
The Gini coefficient which is used in the financial industry to evaluate the quality of a credit score model is actually Somers’ D and not Corrado Gini’s measure of inequality.
There are three common methods to derive the Gini coefficient:
Extract the Gini coefficient from the CAP curve.Construct the Lorenz curve, extract Corrado Gini’s measure, then derive the Gini coefficient.Construct the ROC curve to extract the AUC then derive the Gini coefficient.
Extract the Gini coefficient from the CAP curve.
Construct the Lorenz curve, extract Corrado Gini’s measure, then derive the Gini coefficient.
Construct the ROC curve to extract the AUC then derive the Gini coefficient.
A common pitfall when deriving the Gini coefficient is identical scores.
The major drawback of the Gini coefficient is that it doesn’t capture the model’s sensitivity to different risk levels.
References
[1] Gini, C. (1914). Reprinted: On the measurement of concentration and variability of characters (2005). Metron, LXIII(1), 338.
[2] Somers, R. (1962). A New Asymmetric Measure of Association for Ordinal Variables. American Sociological Review, 27(6), 799–811. Retrieved from www.jstor.org/stable/2090408
[3] Schechtman, E., & Schechtman, G. (2016). The Relationship between Gini Methodology and the ROC curve (SSRN Scholarly Paper No. ID 2739245). Rochester, NY: Social Science Research Network.
[4] Gambacorta, L., Huang, Y., Qiu, H., & Wang, J. (2019). How do machine learning and non-traditional data affect credit scoring? New evidence from a Chinese fintech firm. Retrieved from https://www.bis.org/publ/work834.htm | [
{
"code": null,
"e": 508,
"s": 171,
"text": "When a new credit score model is born, usually the first question that comes up is: “what is its Gini?”. To an outsider, it must sound like an odd referral to Disney’s film Aladdin. But, Gini or the Gini coefficient is one of the most popular metrics used by the financial industry for evaluating the performance of credit score models."
},
{
"code": null,
"e": 866,
"s": 508,
"text": "The Gini coefficient is a metric that indicates the model’s discriminatory power, namely, the effectiveness of the model in differentiating between “bad” borrowers, who will default in the future, and “good” borrowers, who won’t default in the future. This metric is often used to compare the quality of different models and evaluate their prediction power."
},
{
"code": null,
"e": 1337,
"s": 866,
"text": "Despite its commonality, some practitioners are not genuinely familiar with the mechanism beyond this Gini coefficient and mistakenly confuse it with a different metric with the same name. While many practitioners mistakenly associate the Gini coefficient with the summary of the Lorenz curve, Corrado Gini’s measure of inequality[1], the Gini coefficient they are using is most of the time Somers’ D, which is the summary of the CAP (Cumulative Accuracy Profile) curve."
},
{
"code": null,
"e": 1795,
"s": 1337,
"text": "Somers’ D is named after Robert H. Somers, who proposed it in 1962[2]. It is a measure of the ordinal relationship between two variables. In the context of credit score models, it measures the ordinal relationship between the models’ predictions, in terms of PD (Probability of Default) or score, and the actual outcome — default or not default. If the model is useful, low scores (high PD) should be more associated with defaults than high scores (low PD)."
},
{
"code": null,
"e": 2078,
"s": 1795,
"text": "Somers’ D takes on a value between (-1) and 1. (-1) being a perfect negative ordinal relationship and 1 a perfect ordinal relationship. In practice, a credit score model with Somers’ D of 0.4 is deemed to be good. (Henceforth, I will be addressing Somers’ D as the Gini coefficient)"
},
{
"code": null,
"e": 2234,
"s": 2078,
"text": "For the sake of minimalism, I won’t describe the math involved in calculating the Gini coefficient. Instead, I will show three different ways to derive it."
},
{
"code": null,
"e": 2406,
"s": 2234,
"text": "To demonstrate each of these methods, I will be using a sample credit score model which developed using logistic regression and data of 10,000 borrowers from Lending-club."
},
{
"code": null,
"e": 2515,
"s": 2406,
"text": "model <- glm(default ~ fico + loan_amnt + annual_inc + home_ownership, family = \"binomial\", data = data_set)"
},
{
"code": null,
"e": 2686,
"s": 2515,
"text": "Based on the models’ predictions — estimated Probability of Default (PD), I scored each of the borrows from 1 to 1000; 1 represents the lowest PD and 1000 the highest PD."
},
{
"code": null,
"e": 2734,
"s": 2686,
"text": "Extract the Gini coefficient from the CAP curve"
},
{
"code": null,
"e": 3164,
"s": 2734,
"text": "The CAP curve, in our context, is designed to capture the ordinal relation between score (PD) and default rate. If our model does a good job of discriminating between good and bad borrowers, we would expect to find more defaults at low scored borrowers than at high scored borrowers. The CAP curve captures this notion by aggregating the cumulative default rate when sampling borrowers from the lowest score to the highest score."
},
{
"code": null,
"e": 3652,
"s": 3164,
"text": "To construct the CAP curve, all the model’s population needs to be ordered by the predicted likelihood of default. Namely, the observation with the lowest score is first, and the observation with the highest score is last. Then, we sample the population from first to last, and after each sampling, we calculate the cumulative default rate. The x-axis of the CAP curve represents the portion of the population sampled, and the y-axis represents the corresponding cumulative default rate."
},
{
"code": null,
"e": 4249,
"s": 3652,
"text": "If our model has perfect discriminatory power, we would expect to reach 100% of the cumulative default rate after sampling a portion of observations, which is equal to the default rate in our data (the green line in the chart below). E.g., if the default rate in our data is 16%, after sampling 16% of the observations, we would capture all the defaults in our data. On the contrary, if we use a random model, i.e., a model which randomly assigns scores in equal distribution, the cumulative default rate will always equal to the portion of observations sampled (the red line in the chart below)."
},
{
"code": null,
"e": 4716,
"s": 4249,
"text": "The Gini coefficient is defined as the ratio between the area within the model curve and the random model line (A) and the area between the perfect model curve and the random model line (A+B). Put it differently, the Gini coefficient is a ratio that represents how close our model to be a “perfect model” and how far it is from being a “random model.” Thus, a “perfect model” would get a Gini coefficient of 1, and a “random model” would get a Gini coefficient of 0."
},
{
"code": null,
"e": 4764,
"s": 4716,
"text": "My model gained a low Gini coefficient of 0.26:"
},
{
"code": null,
"e": 4857,
"s": 4764,
"text": "Construct the Lorenz curve, extract Corrado Gini’s measure, then derive the Gini coefficient"
},
{
"code": null,
"e": 5254,
"s": 4857,
"text": "The Lorenz curve is the inverse of the CAP curve; it is constructed using the same mechanism of sampling observations and aggregating the cumulative default rate, but the sampling is done in reverse order (from highest to lowest score). The Lorenz also has a diagonal line, which is equivalent to the ‘CAP random model’ line and is called “the Line of Equality” (the red line in the chart below)."
},
{
"code": null,
"e": 6082,
"s": 5254,
"text": "Another difference between the two curves is the “perfect model” line. Since the Lorenz curve was designed to capture the distribution of wealth, the most discriminative outcome is a case where all the wealth of the population is concentrated in one observation. Namely, the line which is equivalent to the “CAP perfect model” line in the Lorenz curve is constructed from the two perpendicular lines, which are the x-axis and a vertical line, which evolved from the end of the x-axis at the value of 100% (the green line in the chart below). This line represents the case in which all the cumulative outcome is in the last sampled observation. The value of Corrado Gini’s measure is defined as the ratio of the area between the model’s curve and the “Line of Equality” to the area between the “Line of Equality” and the x-axis."
},
{
"code": null,
"e": 6714,
"s": 6082,
"text": "However, when using the Lorenz curve to evaluate the discrimination power of a credit score model and assigning its y-axis to be the cumulative default rate, a problem emerges. Since the y-axis describes the aggregation of a binary outcome (1 or 0), a case where all the cumulative default rate concentrates in one observation doesn’t exist. Put it differently, when evaluating a credit score model using the Lorenz curve, it is impossible to reach the “Perfect model” line. Consequently, an appropriate “perfect model” line for this kind of evaluation should be adjusted to the default rate in the population, as in the CAP curve."
},
{
"code": null,
"e": 6850,
"s": 6714,
"text": "Hence, to adjust Corrado Gini’s measure for credit score model evaluation, we need to deduct the unreachable area from its denominator."
},
{
"code": null,
"e": 6953,
"s": 6850,
"text": "Finally, to derive the Gini coefficient from Corrado Gini’s measure, we can use the following formula:"
},
{
"code": null,
"e": 7001,
"s": 6953,
"text": "My model gained Corrado Gini’s measure of 0.22:"
},
{
"code": null,
"e": 7105,
"s": 7001,
"text": "The default rate in my sample is 16%, so the Gini coefficient of my model can be calculated as follows:"
},
{
"code": null,
"e": 7180,
"s": 7105,
"text": "Construct the ROC curve, extract the AUC, then derive the Gini coefficient"
},
{
"code": null,
"e": 7578,
"s": 7180,
"text": "The third method of calculating the Gini coefficient is through another popular curve: the ROC curve. The area under the ROC curve, which is usually called the AUC, is also a popular metric for evaluating and comparing the performance of credit score models. The ROC curve summarizes two ratios from the confusion matrix: the True Positive Ratio (TPR or Recall) and the False Positive Ratio (FPR)."
},
{
"code": null,
"e": 7664,
"s": 7578,
"text": "The confusion matrix summarizes, for a given threshold, the number of cases in which:"
},
{
"code": null,
"e": 7738,
"s": 7664,
"text": "The model predicted a default and the borrower defaulted — True Positive."
},
{
"code": null,
"e": 7818,
"s": 7738,
"text": "The model predicted a default and the borrower didn’t default — False Positive."
},
{
"code": null,
"e": 7898,
"s": 7818,
"text": "The model predicted no default and the borrower didn’t default — True Negative."
},
{
"code": null,
"e": 7973,
"s": 7898,
"text": "The model predicted no default and the borrower defaulted — False Negative"
},
{
"code": null,
"e": 8162,
"s": 7973,
"text": "For example, let’s use the score of 850 as our threshold, i.e., borrows with a score below 850, are predicted to default, and borrowers with a score above 850 are predicted not to default."
},
{
"code": null,
"e": 8491,
"s": 8162,
"text": "The True Positive Ratio (TPR) is defined as the number of defaulted borrowers in which our model caught over the total number of defaulted borrowers in our data. The False Positive Ratio (FPR) is calculated as the number of cases in which the model incorrectly predicted a default over the total number of non-default instances."
},
{
"code": null,
"e": 8780,
"s": 8491,
"text": "The ROC curve is constructed by using confusion matrices that originated from thresholds between 1 to 1000 and driving their TPR and FPR. The y-axis of the ROC curve represents the TPR values, and the x-axis represents the FPR values. The AUC is the area between the curve and the x-axis."
},
{
"code": null,
"e": 9012,
"s": 8780,
"text": "Surprisingly, as shown by Schechtman & Schechtman, 2016[3] there is a linear relationship between the AUC and the Gini coefficient. So, to derive the Gini coefficient from the AUC all you need to do is to use the following formula:"
},
{
"code": null,
"e": 9279,
"s": 9012,
"text": "Practitioners tend to disclose the AUC in addition to the Gini coefficient in their model validation report. However, since these metrics have a linear relation, the disclosure of these metrics together doesn’t add any value to the evaluation of the model’s quality."
},
{
"code": null,
"e": 9360,
"s": 9279,
"text": "The AUC of my model is 0.63, hence the Gini coefficient is calculated like this:"
},
{
"code": null,
"e": 9407,
"s": 9360,
"text": "Drawbacks and pitfalls of the Gini coefficient"
},
{
"code": null,
"e": 9706,
"s": 9407,
"text": "Despite its commonality, the Gini coefficient has some drawbacks and pitfalls you should consider when using it to evaluate and compare credit score models. For the sake of minimalism, in this section, I’ll describe a common pitfall when trying to derive the Gini coefficient and its main drawback."
},
{
"code": null,
"e": 9854,
"s": 9706,
"text": "To illustrate these concepts I’ll use a toy example: 15 borrowers, 2 ”bad” and 13 ”good”, and scores that go from 1 (highest PD) to 10 (lowest PD)."
},
{
"code": null,
"e": 10316,
"s": 9854,
"text": "A common pitfall when trying to derive the Gini coefficient is identical scores. In most cases (especially when using large datasets), the credit score model will estimate the same score for different observations. This score duplication raises an issue when trying to derive the Gini coefficient using the CAP curve method. As mentioned above, the first step to derive the CAP curve is to sort the observations by their score, as in the following two examples:"
},
{
"code": null,
"e": 10796,
"s": 10316,
"text": "These two examples use the same borrowers with the same scores. The only difference between these two tables is the secondary level of ordering. In Example 1 when there is a case of identical scores (in score 5), the observations which defaulted come first. Example 2 is the other way around. This minor change can have a major effect on the value of the Gini coefficient, e.g. in this case, Example 1 has a Gini coefficient of 0.67, and Example 2 has a Gini coefficient of 0.38."
},
{
"code": null,
"e": 10954,
"s": 10796,
"text": "To avoid this pitfall, I recommend doing a secondary sorting like in Example 1 or simply to derive the Gini coefficient using the AUC method mentioned above."
},
{
"code": null,
"e": 11219,
"s": 10954,
"text": "The major disadvantage of the Gini coefficient comes from the fact that it is an ordinal metric, i.e., it captures the order of values while ignoring the distance between them. This characteristic of the Gini coefficient can sometimes mask poor model performances."
},
{
"code": null,
"e": 11409,
"s": 11219,
"text": "When ordering the borrowers based on the score predicted by both of the models, we get the same “Default” column. This indicates that these two models have the same Gini coefficient (0.85)."
},
{
"code": null,
"e": 11511,
"s": 11409,
"text": "When comparing the distributions of scores predicted by these two models we get the following charts:"
},
{
"code": null,
"e": 11864,
"s": 11511,
"text": "Both models have the same Gini coefficient. But, Model B was only able to separate the borrowers into three types: 1, 2 and 3, while Model A was able to capture all 10 levels of risk. This suggests that Model A is more sensitive than Model B to the different characteristics of the borrowers, and can differentiate better between different risk levels."
},
{
"code": null,
"e": 12585,
"s": 11864,
"text": "To understand the importance of the feature above, assume that the owner of Model A and the owner of Model B decide to set a score which will be the threshold for their loan approval. I.e., the loan requests of borrowers with a score below or equal to the threshold, will be denied and the loan requests of borrowers with a score above the threshold, will be approved. Both model owners examined their model outcomes on the test sample and decide to use the score which captured 100% of the cumulative default rate as their threshold. Consequently, the owner of Model A sets the threshold to be 6 and the owner of Model B sets her threshold to be 2. By choosing these scores, the model owners got very different results:"
},
{
"code": null,
"e": 12852,
"s": 12585,
"text": "The owner of Model A rejected 8 “good” borrowers and approved 5 while the owner of Model B rejected 12 “good” borrowers and approved only 1. The threshold set by the owner of Model A yields FPR of 62%, and the threshold set by the owner of Model B yields FPR of 92%."
},
{
"code": null,
"e": 13000,
"s": 12852,
"text": "Hence, the Gini coefficient inability to capture the model’s effectiveness in differentiating between different levels of risk is a major drawback."
},
{
"code": null,
"e": 13313,
"s": 13000,
"text": "In order to overcome this drawback, I recommend eyeball testing the distribution of the model predictions, as in Gambacorta, Huang, Qiu, & Wang, 2019[4], and using the Precision-Recall curve to evaluate the model’s trade-off between capturing “bad’” borrowers and mistakenly predict default of ‘“good” borrowers."
},
{
"code": null,
"e": 13321,
"s": 13313,
"text": "Summary"
},
{
"code": null,
"e": 13498,
"s": 13321,
"text": "The Gini coefficient which is used in the financial industry to evaluate the quality of a credit score model is actually Somers’ D and not Corrado Gini’s measure of inequality."
},
{
"code": null,
"e": 13561,
"s": 13498,
"text": "There are three common methods to derive the Gini coefficient:"
},
{
"code": null,
"e": 13779,
"s": 13561,
"text": "Extract the Gini coefficient from the CAP curve.Construct the Lorenz curve, extract Corrado Gini’s measure, then derive the Gini coefficient.Construct the ROC curve to extract the AUC then derive the Gini coefficient."
},
{
"code": null,
"e": 13828,
"s": 13779,
"text": "Extract the Gini coefficient from the CAP curve."
},
{
"code": null,
"e": 13922,
"s": 13828,
"text": "Construct the Lorenz curve, extract Corrado Gini’s measure, then derive the Gini coefficient."
},
{
"code": null,
"e": 13999,
"s": 13922,
"text": "Construct the ROC curve to extract the AUC then derive the Gini coefficient."
},
{
"code": null,
"e": 14072,
"s": 13999,
"text": "A common pitfall when deriving the Gini coefficient is identical scores."
},
{
"code": null,
"e": 14192,
"s": 14072,
"text": "The major drawback of the Gini coefficient is that it doesn’t capture the model’s sensitivity to different risk levels."
},
{
"code": null,
"e": 14203,
"s": 14192,
"text": "References"
},
{
"code": null,
"e": 14332,
"s": 14203,
"text": "[1] Gini, C. (1914). Reprinted: On the measurement of concentration and variability of characters (2005). Metron, LXIII(1), 338."
},
{
"code": null,
"e": 14508,
"s": 14332,
"text": "[2] Somers, R. (1962). A New Asymmetric Measure of Association for Ordinal Variables. American Sociological Review, 27(6), 799–811. Retrieved from www.jstor.org/stable/2090408"
},
{
"code": null,
"e": 14700,
"s": 14508,
"text": "[3] Schechtman, E., & Schechtman, G. (2016). The Relationship between Gini Methodology and the ROC curve (SSRN Scholarly Paper No. ID 2739245). Rochester, NY: Social Science Research Network."
}
]
|
Add and Remove vertex in Adjacency List representation of Graph - GeeksforGeeks | 07 Feb, 2020
Prerequisites: Linked List, Graph Data Structure
In this article, adding and removing a vertex is discussed in a given adjacency list representation.
Let the Directed Graph be:
The graph can be represented in the Adjacency List representation as:
It is a Linked List representation where the head of the linked list is a vertex in the graph and all the connected nodes are the vertices to which the first vertex is connected. For example, from the graph, it is clear that vertex 0 is connected to vertex 4, 3 and 1. The same is representated in the adjacency list(or Linked List) representation.
Approach:
Adding a Vertex in the Graph: To add a vertex in the graph, the adjacency list can be iterated to the place where the insertion is required and the new node can be created using linked list implementation. For example, if 5 needs to be added between vertex 2 and vertex 3 such that vertex 3 points to vertex 5 and vertex 5 points to vertex 2, then a new edge is created between vertex 5 and vertex 3 and a new edge is created from vertex 5 and vertex 2. After adding the vertex, the adjacency list changes to:
Removing a Vertex in the Graph: To delete a vertex in the graph, iterate through the list of each vertex if an edge is present or not. If the edge is present, then delete the vertex in the same way as delete is performed in a linked list. For example, the adjacency list translates to the below list if vertex 4 is deleted from the list:Below is the implementation of the above approach:# Python implementation of the above approach# Implementing Linked List representationclass AdjNode(object): def __init__(self, data): self.vertex = data self.next = None # Adjacency List representationclass AdjList(object): def __init__(self, vertices): self.v = vertices self.graph =[None]*self.v # Function to add an edge from a source vertex # to a destination vertex def addedge(self, source, destination): node = AdjNode(destination) node.next = self.graph self.graph= node # Function to call the above function. def addvertex(self, vk, source, destination): graph.addedge(source, vk) graph.addedge(vk, destination) # Function to print the graph def print_graph(self): for i in range(self.v): print(i, end ="") temp = self.graph[i] while temp: print("->", temp.vertex, end ="") temp = temp.next print("\n") # Function to delete a vertex def delvertex(self, k): # Iterating through all the vertices of the graph for i in range(self.v): temp = self.graph[i] if i == k: while temp: self.graph[i]= temp.next temp = self.graph[i] # Delete the vertex # using linked list concept if temp: if temp.vertex == k: self.graph[i]= temp.next temp = None while temp: if temp.vertex == k: break prev = temp temp = temp.next if temp == None: continue prev.next = temp.next temp = None # Driver codeif __name__ == "__main__": V = 6 graph = AdjList(V) graph.addedge(0, 1) graph.addedge(0, 3) graph.addedge(0, 4) graph.addedge(1, 2) graph.addedge(3, 2) graph.addedge(4, 3) print("Initial adjacency list")graph.print_graph() # Add vertexgraph.addvertex(5, 3, 2)print("Adjacency list after adding vertex")graph.print_graph() # Delete vertexgraph.delvertex(4)print("Adjacency list after deleting vertex")graph.print_graph()Output:Initial adjacency list
0-> 4-> 3-> 1
1-> 2
2
3-> 2
4-> 3
5
Adjacency list after adding vertex
0-> 4-> 3-> 1
1-> 2
2
3-> 5-> 2
4-> 3
5-> 2
Adjacency list after deleting vertex
0-> 3-> 1
1-> 2
2
3-> 5-> 2
4
5-> 2
My Personal Notes
arrow_drop_upSave
Below is the implementation of the above approach:
# Python implementation of the above approach# Implementing Linked List representationclass AdjNode(object): def __init__(self, data): self.vertex = data self.next = None # Adjacency List representationclass AdjList(object): def __init__(self, vertices): self.v = vertices self.graph =[None]*self.v # Function to add an edge from a source vertex # to a destination vertex def addedge(self, source, destination): node = AdjNode(destination) node.next = self.graph self.graph= node # Function to call the above function. def addvertex(self, vk, source, destination): graph.addedge(source, vk) graph.addedge(vk, destination) # Function to print the graph def print_graph(self): for i in range(self.v): print(i, end ="") temp = self.graph[i] while temp: print("->", temp.vertex, end ="") temp = temp.next print("\n") # Function to delete a vertex def delvertex(self, k): # Iterating through all the vertices of the graph for i in range(self.v): temp = self.graph[i] if i == k: while temp: self.graph[i]= temp.next temp = self.graph[i] # Delete the vertex # using linked list concept if temp: if temp.vertex == k: self.graph[i]= temp.next temp = None while temp: if temp.vertex == k: break prev = temp temp = temp.next if temp == None: continue prev.next = temp.next temp = None # Driver codeif __name__ == "__main__": V = 6 graph = AdjList(V) graph.addedge(0, 1) graph.addedge(0, 3) graph.addedge(0, 4) graph.addedge(1, 2) graph.addedge(3, 2) graph.addedge(4, 3) print("Initial adjacency list")graph.print_graph() # Add vertexgraph.addvertex(5, 3, 2)print("Adjacency list after adding vertex")graph.print_graph() # Delete vertexgraph.delvertex(4)print("Adjacency list after deleting vertex")graph.print_graph()
Initial adjacency list
0-> 4-> 3-> 1
1-> 2
2
3-> 2
4-> 3
5
Adjacency list after adding vertex
0-> 4-> 3-> 1
1-> 2
2
3-> 5-> 2
4-> 3
5-> 2
Adjacency list after deleting vertex
0-> 3-> 1
1-> 2
2
3-> 5-> 2
4
5-> 2
Picked
Technical Scripter 2019
Graph
Technical Scripter
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Detect Cycle in a Directed Graph
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Detect cycle in an undirected graph
Ford-Fulkerson Algorithm for Maximum Flow Problem
Traveling Salesman Problem (TSP) Implementation | [
{
"code": null,
"e": 24903,
"s": 24875,
"text": "\n07 Feb, 2020"
},
{
"code": null,
"e": 24952,
"s": 24903,
"text": "Prerequisites: Linked List, Graph Data Structure"
},
{
"code": null,
"e": 25053,
"s": 24952,
"text": "In this article, adding and removing a vertex is discussed in a given adjacency list representation."
},
{
"code": null,
"e": 25080,
"s": 25053,
"text": "Let the Directed Graph be:"
},
{
"code": null,
"e": 25150,
"s": 25080,
"text": "The graph can be represented in the Adjacency List representation as:"
},
{
"code": null,
"e": 25499,
"s": 25150,
"text": "It is a Linked List representation where the head of the linked list is a vertex in the graph and all the connected nodes are the vertices to which the first vertex is connected. For example, from the graph, it is clear that vertex 0 is connected to vertex 4, 3 and 1. The same is representated in the adjacency list(or Linked List) representation."
},
{
"code": null,
"e": 25509,
"s": 25499,
"text": "Approach:"
},
{
"code": null,
"e": 26019,
"s": 25509,
"text": "Adding a Vertex in the Graph: To add a vertex in the graph, the adjacency list can be iterated to the place where the insertion is required and the new node can be created using linked list implementation. For example, if 5 needs to be added between vertex 2 and vertex 3 such that vertex 3 points to vertex 5 and vertex 5 points to vertex 2, then a new edge is created between vertex 5 and vertex 3 and a new edge is created from vertex 5 and vertex 2. After adding the vertex, the adjacency list changes to:"
},
{
"code": null,
"e": 28917,
"s": 26019,
"text": "Removing a Vertex in the Graph: To delete a vertex in the graph, iterate through the list of each vertex if an edge is present or not. If the edge is present, then delete the vertex in the same way as delete is performed in a linked list. For example, the adjacency list translates to the below list if vertex 4 is deleted from the list:Below is the implementation of the above approach:# Python implementation of the above approach# Implementing Linked List representationclass AdjNode(object): def __init__(self, data): self.vertex = data self.next = None # Adjacency List representationclass AdjList(object): def __init__(self, vertices): self.v = vertices self.graph =[None]*self.v # Function to add an edge from a source vertex # to a destination vertex def addedge(self, source, destination): node = AdjNode(destination) node.next = self.graph self.graph= node # Function to call the above function. def addvertex(self, vk, source, destination): graph.addedge(source, vk) graph.addedge(vk, destination) # Function to print the graph def print_graph(self): for i in range(self.v): print(i, end =\"\") temp = self.graph[i] while temp: print(\"->\", temp.vertex, end =\"\") temp = temp.next print(\"\\n\") # Function to delete a vertex def delvertex(self, k): # Iterating through all the vertices of the graph for i in range(self.v): temp = self.graph[i] if i == k: while temp: self.graph[i]= temp.next temp = self.graph[i] # Delete the vertex # using linked list concept if temp: if temp.vertex == k: self.graph[i]= temp.next temp = None while temp: if temp.vertex == k: break prev = temp temp = temp.next if temp == None: continue prev.next = temp.next temp = None # Driver codeif __name__ == \"__main__\": V = 6 graph = AdjList(V) graph.addedge(0, 1) graph.addedge(0, 3) graph.addedge(0, 4) graph.addedge(1, 2) graph.addedge(3, 2) graph.addedge(4, 3) print(\"Initial adjacency list\")graph.print_graph() # Add vertexgraph.addvertex(5, 3, 2)print(\"Adjacency list after adding vertex\")graph.print_graph() # Delete vertexgraph.delvertex(4)print(\"Adjacency list after deleting vertex\")graph.print_graph()Output:Initial adjacency list\n0-> 4-> 3-> 1\n\n1-> 2\n\n2\n\n3-> 2\n\n4-> 3\n\n5\n\nAdjacency list after adding vertex\n0-> 4-> 3-> 1\n\n1-> 2\n\n2\n\n3-> 5-> 2\n\n4-> 3\n\n5-> 2\n\nAdjacency list after deleting vertex\n0-> 3-> 1\n\n1-> 2\n\n2\n\n3-> 5-> 2\n\n4\n\n5-> 2\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 28968,
"s": 28917,
"text": "Below is the implementation of the above approach:"
},
{
"code": "# Python implementation of the above approach# Implementing Linked List representationclass AdjNode(object): def __init__(self, data): self.vertex = data self.next = None # Adjacency List representationclass AdjList(object): def __init__(self, vertices): self.v = vertices self.graph =[None]*self.v # Function to add an edge from a source vertex # to a destination vertex def addedge(self, source, destination): node = AdjNode(destination) node.next = self.graph self.graph= node # Function to call the above function. def addvertex(self, vk, source, destination): graph.addedge(source, vk) graph.addedge(vk, destination) # Function to print the graph def print_graph(self): for i in range(self.v): print(i, end =\"\") temp = self.graph[i] while temp: print(\"->\", temp.vertex, end =\"\") temp = temp.next print(\"\\n\") # Function to delete a vertex def delvertex(self, k): # Iterating through all the vertices of the graph for i in range(self.v): temp = self.graph[i] if i == k: while temp: self.graph[i]= temp.next temp = self.graph[i] # Delete the vertex # using linked list concept if temp: if temp.vertex == k: self.graph[i]= temp.next temp = None while temp: if temp.vertex == k: break prev = temp temp = temp.next if temp == None: continue prev.next = temp.next temp = None # Driver codeif __name__ == \"__main__\": V = 6 graph = AdjList(V) graph.addedge(0, 1) graph.addedge(0, 3) graph.addedge(0, 4) graph.addedge(1, 2) graph.addedge(3, 2) graph.addedge(4, 3) print(\"Initial adjacency list\")graph.print_graph() # Add vertexgraph.addvertex(5, 3, 2)print(\"Adjacency list after adding vertex\")graph.print_graph() # Delete vertexgraph.delvertex(4)print(\"Adjacency list after deleting vertex\")graph.print_graph()",
"e": 31209,
"s": 28968,
"text": null
},
{
"code": null,
"e": 31438,
"s": 31209,
"text": "Initial adjacency list\n0-> 4-> 3-> 1\n\n1-> 2\n\n2\n\n3-> 2\n\n4-> 3\n\n5\n\nAdjacency list after adding vertex\n0-> 4-> 3-> 1\n\n1-> 2\n\n2\n\n3-> 5-> 2\n\n4-> 3\n\n5-> 2\n\nAdjacency list after deleting vertex\n0-> 3-> 1\n\n1-> 2\n\n2\n\n3-> 5-> 2\n\n4\n\n5-> 2\n"
},
{
"code": null,
"e": 31445,
"s": 31438,
"text": "Picked"
},
{
"code": null,
"e": 31469,
"s": 31445,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 31475,
"s": 31469,
"text": "Graph"
},
{
"code": null,
"e": 31494,
"s": 31475,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31500,
"s": 31494,
"text": "Graph"
},
{
"code": null,
"e": 31598,
"s": 31500,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31607,
"s": 31598,
"text": "Comments"
},
{
"code": null,
"e": 31620,
"s": 31607,
"text": "Old Comments"
},
{
"code": null,
"e": 31678,
"s": 31620,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 31698,
"s": 31678,
"text": "Topological Sorting"
},
{
"code": null,
"e": 31731,
"s": 31698,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 31762,
"s": 31731,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 31795,
"s": 31762,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 31863,
"s": 31795,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 31938,
"s": 31863,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 31974,
"s": 31938,
"text": "Detect cycle in an undirected graph"
},
{
"code": null,
"e": 32024,
"s": 31974,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
}
]
|
Good or Bad string | Practice | GeeksforGeeks | In this problem, a String S is composed of lowercase alphabets and wildcard characters i.e. '?'. Here, '?' can be replaced by any of the lowercase alphabets. Now you have to classify the given String on the basis of following rules:
If there are more than 3 consonants together or more than 5 vowels together, the String is considered to be "BAD". A String is considered "GOOD" only if it is not “BAD”.
NOTE: String is considered as "BAD" if the above condition is satisfied even once. Else it is "GOOD" and the task is to make the string "BAD".
Example 1:
Input:
S = aeioup??
Output:
1
Explanation: The String doesn't contain more
than 3 consonants or more than 5 vowels together.
So, it's a GOOD string.
Example 2:
Input:
S = bcdaeiou??
Output:
0
Explanation: The String contains the
Substring "aeiou??" which counts as 7
vowels together. So, it's a BAD string.
Your Task:
You don't need to read input or print anything. Your task is to complete the function isGoodorBad() which takes the String S as input and returns 0 or 1.
Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(1)
Constraints:
1 <= |S| <= 100000
0
roy99mustang2 days ago
Easy Python solution:
#User function Template for python3
class Solution:
def isGoodorBad(self, S):
v = "aeiou"
def isV(p):
return all([(x in v or x is "?") for x in p])
def isC(p):
return all([(x not in v or x is "?") for x in p])
j = 0
n = len(S)
while j < n:
# check for a bad substring
if (j + 5 < n and isV(S[j:j+6])) or (j + 3 < n and isC(S[j:j+4])):
return 0
else:
j += 1
return 1
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t = int (input ())
for _ in range (t):
S=input()
ob = Solution()
print(ob.isGoodorBad(S))
# } Driver Code Ends
The question marks, “?”, have to be treated as vowels or consonants strategically; so as to force a bad substring.
0
ashmeetsingh78013 days ago
int isGoodorBad(string S) { int v=0,c=0; for(int i=0;i<S.size();i++) { if(S[i]=='a' ||S[i]=='e' ||S[i]=='i' ||S[i]=='o' ||S[i]=='u' ) { v++; c=0; } else { c++; v=0; } if(c>3 || v>5) return 0; } return 1; }
0
codewithshoaib191 week ago
// Simple easy to understand java solution
static int isGoodorBad(String S) { // finding index of ? int x=S.indexOf("?"); // if character before ? is consonant then change all ? with any consonants if(x!=-1 && x-1>0 && !(isVowel(S.charAt(x-1)))){ S=S.replaceAll("[^a-zA-Z]","g"); } // if character before ? is vowels then change all ? with any vowel if(x!=-1 && x-1>0 && (isVowel(S.charAt(x-1)))){ S=S.replaceAll("[^a-zA-Z]","e"); } // iterating over the string for(int i=0;i<S.length();i++){ char ch=S.charAt(i); // check wheter a char is vowel is vowel or consonant // if vowel then point j on it and increment it till it reaches more than 5 if(isVowel(ch)){ int j=i; int k=0; while(j<S.length() && isVowel(S.charAt(j))){ j++; k++; // if it becomes greater than 5 then break and return false if(k>5){ // System.out.println(k); return 0; } } } // if consonant then point j on it and increment it till it reaches more than 3 else if(!isVowel(ch)){ int j=i; int k=0; while(j<S.length() && !isVowel(S.charAt(j))){ j++; k++; // if it becomes greater than 3 then break and return false if(k>3){ // System.out.println(k); return 0; } } } } return 1; } public static boolean isVowel(char ch){ if(ch=='a' || ch=='e' || ch=='o' || ch=='i' || ch=='u'){ return true; } return false; }
0
user_4na01 month ago
class Solution { public: int isGoodorBad(string S) { int con = 0,vow = 0; int cnt = 0; for(int i = 0;i<S.length();i++) { if(S[i] == 'a' || S[i] == 'e' || S[i] == 'o' || S[i] == 'i' || S[i] == 'u') { if(vow>5) { cnt++; vow = 0; } con = 0; vow++; } else { if(con == 3) { cnt++; con = 0; } vow = 0; con++; } } return (cnt>0)?0:1; }};
0
hitentandon2 months ago
Java Sol:
int vc = 0, cc= 0;
for(char c: S.toCharArray())
if(vc>5||cc>3)
return 0;
else if(c=='?')
{
vc++;
cc++;
}
else if("AEIOUaeiou".indexOf(c)>-1)
{
vc++;
cc=0;
}
else
{
cc++;
vc=0;
}
return 1;
0
mayank20213 months ago
C++
int isGoodorBad(string S) {
int countc=0, countv=0; for(int i=0; i<S.size(); i++) { if(S[i]=='a' || S[i]=='e' || S[i]=='i' || S[i]=='o' || S[i]=='u' ) { countv++; countc=0; if(countv>5) return 0; } else if (S[i]=='?') { countv++; countc++; if(countv>5 || countc >3) return 0; } else { countc++; countv=0; if(countc>3) return 0; } } return 1;
}
0
himanshujain457
This comment was deleted.
0
anmol1neema4 months ago
int k=0,j=0; String s = S.replaceAll(" ",""); for(int i=0;i<s.length();i++){ if(s.charAt(i)=='a'||s.charAt(i)=='e'|| s.charAt(i)=='i'||s.charAt(i)=='o'||s.charAt(i)=='u' || s.charAt(i)=='?'){ if(k>3){ break; } k=0; j++; }else{ if(j>5){ break; } j=0; k++; } } if(j>5 || k>3){ return 1; }else{ return 0; } }
+3
aditichoudharyit194 months ago
class Solution {
public:
int isGoodorBad(string S) {
int vowel = 0 ;
int cons = 0 ;
for( int i = 0 ; i < S.length() ; i++ )
{
if( vowel > 5 || cons > 3 )
{
return 0;
}
if( S[i] == 'a' || S[i] == 'e' || S[i] == 'i' || S[i] == 'o' || S[i] == 'u' )
{
vowel++ ;
cons = 0 ;
}
else if( S[i] == '?')
{
cons++;
vowel++;
}
else
{
vowel = 0;
cons++;
}
}
return 1;
}
};
+1
badgujarsachin837 months ago
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": 459,
"s": 226,
"text": "In this problem, a String S is composed of lowercase alphabets and wildcard characters i.e. '?'. Here, '?' can be replaced by any of the lowercase alphabets. Now you have to classify the given String on the basis of following rules:"
},
{
"code": null,
"e": 629,
"s": 459,
"text": "If there are more than 3 consonants together or more than 5 vowels together, the String is considered to be \"BAD\". A String is considered \"GOOD\" only if it is not “BAD”."
},
{
"code": null,
"e": 774,
"s": 629,
"text": "NOTE: String is considered as \"BAD\" if the above condition is satisfied even once. Else it is \"GOOD\" and the task is to make the string \"BAD\".\n "
},
{
"code": null,
"e": 785,
"s": 774,
"text": "Example 1:"
},
{
"code": null,
"e": 935,
"s": 785,
"text": "Input:\nS = aeioup??\nOutput:\n1\nExplanation: The String doesn't contain more\nthan 3 consonants or more than 5 vowels together.\nSo, it's a GOOD string.\n"
},
{
"code": null,
"e": 946,
"s": 935,
"text": "Example 2:"
},
{
"code": null,
"e": 1094,
"s": 946,
"text": "Input:\nS = bcdaeiou??\nOutput:\n0\nExplanation: The String contains the\nSubstring \"aeiou??\" which counts as 7\nvowels together. So, it's a BAD string.\n"
},
{
"code": null,
"e": 1263,
"s": 1094,
"text": "\n\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isGoodorBad() which takes the String S as input and returns 0 or 1.\n "
},
{
"code": null,
"e": 1329,
"s": 1263,
"text": "Expected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(1)\n "
},
{
"code": null,
"e": 1361,
"s": 1329,
"text": "Constraints:\n1 <= |S| <= 100000"
},
{
"code": null,
"e": 1363,
"s": 1361,
"text": "0"
},
{
"code": null,
"e": 1386,
"s": 1363,
"text": "roy99mustang2 days ago"
},
{
"code": null,
"e": 1409,
"s": 1386,
"text": "Easy Python solution: "
},
{
"code": null,
"e": 2210,
"s": 1409,
"text": "#User function Template for python3\n\nclass Solution:\n def isGoodorBad(self, S):\n v = \"aeiou\"\n \n def isV(p):\n return all([(x in v or x is \"?\") for x in p])\n \n def isC(p):\n return all([(x not in v or x is \"?\") for x in p])\n \n j = 0\n n = len(S)\n while j < n:\n # check for a bad substring\n if (j + 5 < n and isV(S[j:j+6])) or (j + 3 < n and isC(S[j:j+4])):\n return 0\n else:\n j += 1\n return 1\n \n#{ \n# Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__': \n t = int (input ())\n for _ in range (t):\n S=input()\n \n ob = Solution()\n print(ob.isGoodorBad(S))\n# } Driver Code Ends"
},
{
"code": null,
"e": 2325,
"s": 2210,
"text": "The question marks, “?”, have to be treated as vowels or consonants strategically; so as to force a bad substring."
},
{
"code": null,
"e": 2327,
"s": 2325,
"text": "0"
},
{
"code": null,
"e": 2354,
"s": 2327,
"text": "ashmeetsingh78013 days ago"
},
{
"code": null,
"e": 2721,
"s": 2354,
"text": "int isGoodorBad(string S) { int v=0,c=0; for(int i=0;i<S.size();i++) { if(S[i]=='a' ||S[i]=='e' ||S[i]=='i' ||S[i]=='o' ||S[i]=='u' ) { v++; c=0; } else { c++; v=0; } if(c>3 || v>5) return 0; } return 1; }"
},
{
"code": null,
"e": 2723,
"s": 2721,
"text": "0"
},
{
"code": null,
"e": 2750,
"s": 2723,
"text": "codewithshoaib191 week ago"
},
{
"code": null,
"e": 2793,
"s": 2750,
"text": "// Simple easy to understand java solution"
},
{
"code": null,
"e": 4690,
"s": 2793,
"text": "static int isGoodorBad(String S) { // finding index of ? int x=S.indexOf(\"?\"); // if character before ? is consonant then change all ? with any consonants if(x!=-1 && x-1>0 && !(isVowel(S.charAt(x-1)))){ S=S.replaceAll(\"[^a-zA-Z]\",\"g\"); } // if character before ? is vowels then change all ? with any vowel if(x!=-1 && x-1>0 && (isVowel(S.charAt(x-1)))){ S=S.replaceAll(\"[^a-zA-Z]\",\"e\"); } // iterating over the string for(int i=0;i<S.length();i++){ char ch=S.charAt(i); // check wheter a char is vowel is vowel or consonant // if vowel then point j on it and increment it till it reaches more than 5 if(isVowel(ch)){ int j=i; int k=0; while(j<S.length() && isVowel(S.charAt(j))){ j++; k++; // if it becomes greater than 5 then break and return false if(k>5){ // System.out.println(k); return 0; } } } // if consonant then point j on it and increment it till it reaches more than 3 else if(!isVowel(ch)){ int j=i; int k=0; while(j<S.length() && !isVowel(S.charAt(j))){ j++; k++; // if it becomes greater than 3 then break and return false if(k>3){ // System.out.println(k); return 0; } } } } return 1; } public static boolean isVowel(char ch){ if(ch=='a' || ch=='e' || ch=='o' || ch=='i' || ch=='u'){ return true; } return false; }"
},
{
"code": null,
"e": 4692,
"s": 4690,
"text": "0"
},
{
"code": null,
"e": 4713,
"s": 4692,
"text": "user_4na01 month ago"
},
{
"code": null,
"e": 5356,
"s": 4713,
"text": "class Solution { public: int isGoodorBad(string S) { int con = 0,vow = 0; int cnt = 0; for(int i = 0;i<S.length();i++) { if(S[i] == 'a' || S[i] == 'e' || S[i] == 'o' || S[i] == 'i' || S[i] == 'u') { if(vow>5) { cnt++; vow = 0; } con = 0; vow++; } else { if(con == 3) { cnt++; con = 0; } vow = 0; con++; } } return (cnt>0)?0:1; }};"
},
{
"code": null,
"e": 5358,
"s": 5356,
"text": "0"
},
{
"code": null,
"e": 5382,
"s": 5358,
"text": "hitentandon2 months ago"
},
{
"code": null,
"e": 5392,
"s": 5382,
"text": "Java Sol:"
},
{
"code": null,
"e": 5832,
"s": 5392,
"text": "\tint vc = 0, cc= 0;\n for(char c: S.toCharArray())\n if(vc>5||cc>3)\n return 0;\n else if(c=='?')\n {\n vc++;\n cc++;\n }\n else if(\"AEIOUaeiou\".indexOf(c)>-1)\n {\n vc++;\n cc=0;\n } \n else\n {\n cc++;\n vc=0;\n }\n return 1;"
},
{
"code": null,
"e": 5834,
"s": 5832,
"text": "0"
},
{
"code": null,
"e": 5857,
"s": 5834,
"text": "mayank20213 months ago"
},
{
"code": null,
"e": 5861,
"s": 5857,
"text": "C++"
},
{
"code": null,
"e": 5891,
"s": 5863,
"text": "int isGoodorBad(string S) {"
},
{
"code": null,
"e": 6450,
"s": 5891,
"text": " int countc=0, countv=0; for(int i=0; i<S.size(); i++) { if(S[i]=='a' || S[i]=='e' || S[i]=='i' || S[i]=='o' || S[i]=='u' ) { countv++; countc=0; if(countv>5) return 0; } else if (S[i]=='?') { countv++; countc++; if(countv>5 || countc >3) return 0; } else { countc++; countv=0; if(countc>3) return 0; } } return 1;"
},
{
"code": null,
"e": 6455,
"s": 6450,
"text": " }"
},
{
"code": null,
"e": 6457,
"s": 6455,
"text": "0"
},
{
"code": null,
"e": 6473,
"s": 6457,
"text": "himanshujain457"
},
{
"code": null,
"e": 6499,
"s": 6473,
"text": "This comment was deleted."
},
{
"code": null,
"e": 6501,
"s": 6499,
"text": "0"
},
{
"code": null,
"e": 6525,
"s": 6501,
"text": "anmol1neema4 months ago"
},
{
"code": null,
"e": 7077,
"s": 6525,
"text": "int k=0,j=0; String s = S.replaceAll(\" \",\"\"); for(int i=0;i<s.length();i++){ if(s.charAt(i)=='a'||s.charAt(i)=='e'|| s.charAt(i)=='i'||s.charAt(i)=='o'||s.charAt(i)=='u' || s.charAt(i)=='?'){ if(k>3){ break; } k=0; j++; }else{ if(j>5){ break; } j=0; k++; } } if(j>5 || k>3){ return 1; }else{ return 0; } }"
},
{
"code": null,
"e": 7080,
"s": 7077,
"text": "+3"
},
{
"code": null,
"e": 7111,
"s": 7080,
"text": "aditichoudharyit194 months ago"
},
{
"code": null,
"e": 7772,
"s": 7111,
"text": "class Solution {\n public:\n int isGoodorBad(string S) {\n int vowel = 0 ;\n int cons = 0 ;\n for( int i = 0 ; i < S.length() ; i++ )\n {\n if( vowel > 5 || cons > 3 )\n {\n return 0;\n }\n if( S[i] == 'a' || S[i] == 'e' || S[i] == 'i' || S[i] == 'o' || S[i] == 'u' )\n {\n vowel++ ;\n cons = 0 ;\n }\n else if( S[i] == '?') \n {\n cons++;\n vowel++;\n }\n else \n {\n vowel = 0;\n cons++;\n }\n \n }\n \n return 1;\n }\n};"
},
{
"code": null,
"e": 7775,
"s": 7772,
"text": "+1"
},
{
"code": null,
"e": 7804,
"s": 7775,
"text": "badgujarsachin837 months ago"
},
{
"code": null,
"e": 7950,
"s": 7804,
"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": 7986,
"s": 7950,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7996,
"s": 7986,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8006,
"s": 7996,
"text": "\nContest\n"
},
{
"code": null,
"e": 8069,
"s": 8006,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8217,
"s": 8069,
"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": 8425,
"s": 8217,
"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": 8531,
"s": 8425,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Spring BeanFactory Container | This is the simplest container providing the basic support for DI and defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purpose of backward compatibility with a large number of third-party frameworks that integrate with Spring.
There are a number of implementations of the BeanFactory interface that are come straight out-of-the-box with Spring. The most commonly used BeanFactory implementation is the XmlBeanFactory class. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application.
The BeanFactory is usually preferred where the resources are limited like mobile devices or applet-based applications. Thus, use an ApplicationContext unless you have a good reason for not doing so.
Let us take a look at a working Eclipse IDE in place and take the following steps to create a Spring application −
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.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class MainApp {
public static void main(String[] args) {
XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("Beans.xml"));
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");
obj.getMessage();
}
}
Following two important points should be noted about the main program −
The first step is to create a factory object where we used the framework APIXmlBeanFactory() to create the factory bean andClassPathResource() API to load the bean configuration file available in CLASSPATH. The XmlBeanFactory() API takes care of creating and initializing all the objects, i.e. beans mentioned in the configuration file.
The first step is to create a factory object where we used the framework APIXmlBeanFactory() to create the factory bean andClassPathResource() API to load the bean configuration file available in CLASSPATH. The XmlBeanFactory() API takes care of creating and initializing all the objects, i.e. beans mentioned in the configuration file.
The second step is used to get the required bean using getBean() method of the created bean factory object. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have the object, you can use this object to call any class method.
The second step is used to get the required bean using getBean() method of the created bean factory object. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have the object, you can use this object to call any class method.
Following is the content of the bean configuration file Beans.xml
<?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>
Once you are done with creating the source and the bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −
Your Message : Hello World!
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": 2678,
"s": 2292,
"text": "This is the simplest container providing the basic support for DI and defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purpose of backward compatibility with a large number of third-party frameworks that integrate with Spring."
},
{
"code": null,
"e": 3004,
"s": 2678,
"text": "There are a number of implementations of the BeanFactory interface that are come straight out-of-the-box with Spring. The most commonly used BeanFactory implementation is the XmlBeanFactory class. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application."
},
{
"code": null,
"e": 3203,
"s": 3004,
"text": "The BeanFactory is usually preferred where the resources are limited like mobile devices or applet-based applications. Thus, use an ApplicationContext unless you have a good reason for not doing so."
},
{
"code": null,
"e": 3318,
"s": 3203,
"text": "Let us take a look at a working Eclipse IDE in place and take the following steps to create a Spring application −"
},
{
"code": null,
"e": 3364,
"s": 3318,
"text": "Here is the content of HelloWorld.java file −"
},
{
"code": null,
"e": 3632,
"s": 3364,
"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": 3689,
"s": 3632,
"text": "Following is the content of the second file MainApp.java"
},
{
"code": null,
"e": 4166,
"s": 3689,
"text": "package com.tutorialspoint; \n\nimport org.springframework.beans.factory.InitializingBean; \nimport org.springframework.beans.factory.xml.XmlBeanFactory; \nimport org.springframework.core.io.ClassPathResource; \n\npublic class MainApp { \n public static void main(String[] args) { \n XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource(\"Beans.xml\")); \n HelloWorld obj = (HelloWorld) factory.getBean(\"helloWorld\"); \n obj.getMessage(); \n }\n} "
},
{
"code": null,
"e": 4238,
"s": 4166,
"text": "Following two important points should be noted about the main program −"
},
{
"code": null,
"e": 4575,
"s": 4238,
"text": "The first step is to create a factory object where we used the framework APIXmlBeanFactory() to create the factory bean andClassPathResource() API to load the bean configuration file available in CLASSPATH. The XmlBeanFactory() API takes care of creating and initializing all the objects, i.e. beans mentioned in the configuration file."
},
{
"code": null,
"e": 4912,
"s": 4575,
"text": "The first step is to create a factory object where we used the framework APIXmlBeanFactory() to create the factory bean andClassPathResource() API to load the bean configuration file available in CLASSPATH. The XmlBeanFactory() API takes care of creating and initializing all the objects, i.e. beans mentioned in the configuration file."
},
{
"code": null,
"e": 5199,
"s": 4912,
"text": "The second step is used to get the required bean using getBean() method of the created bean factory object. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have the object, you can use this object to call any class method."
},
{
"code": null,
"e": 5486,
"s": 5199,
"text": "The second step is used to get the required bean using getBean() method of the created bean factory object. This method uses bean ID to return a generic object, which finally can be casted to the actual object. Once you have the object, you can use this object to call any class method."
},
{
"code": null,
"e": 5552,
"s": 5486,
"text": "Following is the content of the bean configuration file Beans.xml"
},
{
"code": null,
"e": 6003,
"s": 5552,
"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": 6191,
"s": 6003,
"text": "Once you are done with creating the source and the bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −"
},
{
"code": null,
"e": 6220,
"s": 6191,
"text": "Your Message : Hello World!\n"
},
{
"code": null,
"e": 6254,
"s": 6220,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6268,
"s": 6254,
"text": " Karthikeya T"
},
{
"code": null,
"e": 6301,
"s": 6268,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6316,
"s": 6301,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 6351,
"s": 6316,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6363,
"s": 6351,
"text": " Senol Atac"
},
{
"code": null,
"e": 6398,
"s": 6363,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6410,
"s": 6398,
"text": " Senol Atac"
},
{
"code": null,
"e": 6445,
"s": 6410,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6457,
"s": 6445,
"text": " Senol Atac"
},
{
"code": null,
"e": 6490,
"s": 6457,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6502,
"s": 6490,
"text": " Senol Atac"
},
{
"code": null,
"e": 6509,
"s": 6502,
"text": " Print"
},
{
"code": null,
"e": 6520,
"s": 6509,
"text": " Add Notes"
}
]
|
What is header() function in PHP? | The header() function is an predefined PHP native function.With header() HTTP functions we can control data sent to the client or browser by the Web server before some other output has been sent.
The header function sets the headers for an HTTP Response given by the server. We can do all sorts of things using the header function in PHP like Change page location, set timezone, set caching control, etc...
Some of the important uses of the header() in PHP are listed below:
It is used to redirect a from one web page to another web page in PHP.
header('Location:give your url here');
PHP defaults to sending Content-Type:text/html.If we want to change the Content-Type, we can achieve that with the header() function.
Generated PDF file :header('Content-Type: application/pdf');
Return response in json format:header('Content-Type: application/pdf');.
header("HTTP/1.0 404 Not Found");
The below example helps to prevent caching by sending header information which overrides browser setting to not-cache.
header("Cache-Control: no-cache, must-revalidate"); | [
{
"code": null,
"e": 1258,
"s": 1062,
"text": "The header() function is an predefined PHP native function.With header() HTTP functions we can control data sent to the client or browser by the Web server before some other output has been sent."
},
{
"code": null,
"e": 1469,
"s": 1258,
"text": "The header function sets the headers for an HTTP Response given by the server. We can do all sorts of things using the header function in PHP like Change page location, set timezone, set caching control, etc..."
},
{
"code": null,
"e": 1537,
"s": 1469,
"text": "Some of the important uses of the header() in PHP are listed below:"
},
{
"code": null,
"e": 1608,
"s": 1537,
"text": "It is used to redirect a from one web page to another web page in PHP."
},
{
"code": null,
"e": 1647,
"s": 1608,
"text": "header('Location:give your url here');"
},
{
"code": null,
"e": 1781,
"s": 1647,
"text": "PHP defaults to sending Content-Type:text/html.If we want to change the Content-Type, we can achieve that with the header() function."
},
{
"code": null,
"e": 1915,
"s": 1781,
"text": "Generated PDF file :header('Content-Type: application/pdf');\nReturn response in json format:header('Content-Type: application/pdf');."
},
{
"code": null,
"e": 1949,
"s": 1915,
"text": "header(\"HTTP/1.0 404 Not Found\");"
},
{
"code": null,
"e": 2068,
"s": 1949,
"text": "The below example helps to prevent caching by sending header information which overrides browser setting to not-cache."
},
{
"code": null,
"e": 2120,
"s": 2068,
"text": "header(\"Cache-Control: no-cache, must-revalidate\");"
}
]
|
How to ignore the null and empty fields using the Jackson library in Java?
| The Jackson is a library for Java and it has very powerful data binding capabilities and provides a framework to serialize custom java objects to JSON and deserialize JSON back to Java object. The Jackson library provides @JsonInclude annotation that controls the serialization of a class as a whole or its individual fields based on their values during serialization.
The @JsonInclude annotation contains below two values
Include.NON_NULL: Indicates that only properties with not null values will be included in JSON.
Include.NON_EMPTY: Indicates that only properties that are not empty will be included in JSON
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
public class IgnoreNullAndEmptyFieldTest {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Employee employee = new Employee(115, null, ""); // passing null and empty fields
String result = mapper.writeValueAsString(employee);
System.out.println(result);
}
}
// Employee class
class Employee {
private int id;
@JsonInclude(Include.NON_NULL)
private String firstName;
@JsonInclude(Include.NON_EMPTY)
private String lastName;
public Employee(int id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
{
"id" : 115
} | [
{
"code": null,
"e": 1431,
"s": 1062,
"text": "The Jackson is a library for Java and it has very powerful data binding capabilities and provides a framework to serialize custom java objects to JSON and deserialize JSON back to Java object. The Jackson library provides @JsonInclude annotation that controls the serialization of a class as a whole or its individual fields based on their values during serialization."
},
{
"code": null,
"e": 1485,
"s": 1431,
"text": "The @JsonInclude annotation contains below two values"
},
{
"code": null,
"e": 1581,
"s": 1485,
"text": "Include.NON_NULL: Indicates that only properties with not null values will be included in JSON."
},
{
"code": null,
"e": 1675,
"s": 1581,
"text": "Include.NON_EMPTY: Indicates that only properties that are not empty will be included in JSON"
},
{
"code": null,
"e": 3013,
"s": 1675,
"text": "import com.fasterxml.jackson.annotation.*;\nimport com.fasterxml.jackson.annotation.JsonInclude.Include;\nimport com.fasterxml.jackson.core.*;\nimport com.fasterxml.jackson.databind.*;\npublic class IgnoreNullAndEmptyFieldTest {\n public static void main(String[] args) throws JsonProcessingException {\n ObjectMapper mapper = new ObjectMapper();\n mapper.enable(SerializationFeature.INDENT_OUTPUT);\n Employee employee = new Employee(115, null, \"\"); // passing null and empty fields\n String result = mapper.writeValueAsString(employee);\n System.out.println(result);\n }\n}\n// Employee class\nclass Employee {\n private int id;\n @JsonInclude(Include.NON_NULL)\n private String firstName;\n @JsonInclude(Include.NON_EMPTY)\n private String lastName;\n public Employee(int id, String firstName, String lastName) {\n super();\n this.id = id;\n this.firstName = firstName;\n this.lastName = lastName;\n }\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getFirstName() {\n return firstName;\n }\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n public String getLastName() {\n return lastName;\n }\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n}"
},
{
"code": null,
"e": 3029,
"s": 3013,
"text": "{\n \"id\" : 115\n}"
}
]
|
Add the slug field inside Django Model | In this tutorial, we are going to learn about the SlugField in Django.
SlugField is a way to generate a URL using the data which we already have. You can generate URL using your title of the post or page. Let's see one detailed example.
Let's say we have an article with name This is from Tutorialspoint with id = 5. Then we can have URL as www.tutorialspoint.com/posts/5/. It's difficult for the content writers to recognize the article with the previous URL. But, if you have a URL like www.tutorialspoint.com/this-isfrom-tutorialspoint, then it's easy for us to identify the piece. So, SlugField is used to generate those types of URLs'.
Let's see the code of our post model. Compare your model with the following model.
CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
class Article(models.Model):
title = models.CharField(max_length = 250)
slug = models.SlugField(max_length = 250, null = True, blank = True)
text = models.TextField()
published_on = models.DateTimeField(auto_now_add = True)
updated_time = models.DateTimeField(auto_now = True)
status = models.CharField(max_length = 10, choices = CHOICES, default ='draft')
class Meta:
ordering = ('_Published_At', )
def __str__(self):
return self.title
Now, we will add SlugField to our project. So, it automatically generates the URLs according the title.
Create a file called util.py in the project level directory. We have to generate URL every time invoke the Post model. To achieve that, we need signals.
import string
from django.utils.text import slugify
def get_random_string(size = 10, chars = string.ascii_lowercase + string.digits
return ''.join(random.choice(chars) for _ in range(size))
def get_slug(instance, slug = None):
if slug is not None:
slug_two = slug
else:
slug_two = slugify(instance.title)
Klass = instance.__class__
is_exists = Klass.objects.filter(slug_two = slug_two).exists()
if is_exists:
slug_two = "{slug_two}-{random_string}".format(slug_two = slug_two, ran
string = get_random_string(size = 5))
return get_slug(instance, slug = slug)
return slug_two
Add the following code at the end of the file models.py.
def pre_save_receiver(sender, instance, *args, **kwargs):
if not instance.slug_two:
instance.slug_two = get_slug(instance)
pre_save.connect(pre_save_receiver, sender = Article)
In the urls.py edit the path like path('posts/', post). Edit the views.py according to the code.
def article(request, slug):
obj = Article.objects.filter(slug__iexact = slug)
if obj.exists():
obj = obj.first()
else:
return HttpResponse('Article Not Found')
context = {
'article': obj
}
return render(request, 'posts/post.html', context) | [
{
"code": null,
"e": 1133,
"s": 1062,
"text": "In this tutorial, we are going to learn about the SlugField in Django."
},
{
"code": null,
"e": 1299,
"s": 1133,
"text": "SlugField is a way to generate a URL using the data which we already have. You can generate URL using your title of the post or page. Let's see one detailed example."
},
{
"code": null,
"e": 1703,
"s": 1299,
"text": "Let's say we have an article with name This is from Tutorialspoint with id = 5. Then we can have URL as www.tutorialspoint.com/posts/5/. It's difficult for the content writers to recognize the article with the previous URL. But, if you have a URL like www.tutorialspoint.com/this-isfrom-tutorialspoint, then it's easy for us to identify the piece. So, SlugField is used to generate those types of URLs'."
},
{
"code": null,
"e": 1786,
"s": 1703,
"text": "Let's see the code of our post model. Compare your model with the following model."
},
{
"code": null,
"e": 2315,
"s": 1786,
"text": "CHOICES = (\n ('draft', 'Draft'),\n ('published', 'Published'),\n)\nclass Article(models.Model):\n title = models.CharField(max_length = 250)\n slug = models.SlugField(max_length = 250, null = True, blank = True)\n text = models.TextField()\n published_on = models.DateTimeField(auto_now_add = True)\n updated_time = models.DateTimeField(auto_now = True)\n status = models.CharField(max_length = 10, choices = CHOICES, default ='draft')\nclass Meta:\n ordering = ('_Published_At', )\n def __str__(self):\nreturn self.title"
},
{
"code": null,
"e": 2419,
"s": 2315,
"text": "Now, we will add SlugField to our project. So, it automatically generates the URLs according the title."
},
{
"code": null,
"e": 2572,
"s": 2419,
"text": "Create a file called util.py in the project level directory. We have to generate URL every time invoke the Post model. To achieve that, we need signals."
},
{
"code": null,
"e": 3197,
"s": 2572,
"text": "import string\n from django.utils.text import slugify\n def get_random_string(size = 10, chars = string.ascii_lowercase + string.digits\n return ''.join(random.choice(chars) for _ in range(size))\ndef get_slug(instance, slug = None):\n if slug is not None:\n slug_two = slug\n else:\n slug_two = slugify(instance.title)\n Klass = instance.__class__\n is_exists = Klass.objects.filter(slug_two = slug_two).exists()\n if is_exists:\n slug_two = \"{slug_two}-{random_string}\".format(slug_two = slug_two, ran\n string = get_random_string(size = 5))\n return get_slug(instance, slug = slug)\nreturn slug_two"
},
{
"code": null,
"e": 3254,
"s": 3197,
"text": "Add the following code at the end of the file models.py."
},
{
"code": null,
"e": 3431,
"s": 3254,
"text": "def pre_save_receiver(sender, instance, *args, **kwargs):\nif not instance.slug_two:\ninstance.slug_two = get_slug(instance)\npre_save.connect(pre_save_receiver, sender = Article)"
},
{
"code": null,
"e": 3528,
"s": 3431,
"text": "In the urls.py edit the path like path('posts/', post). Edit the views.py according to the code."
},
{
"code": null,
"e": 3789,
"s": 3528,
"text": "def article(request, slug):\nobj = Article.objects.filter(slug__iexact = slug)\n if obj.exists():\n obj = obj.first()\n else:\n return HttpResponse('Article Not Found')\ncontext = {\n 'article': obj\n}\nreturn render(request, 'posts/post.html', context)"
}
]
|
Matrix creation of n*n in Python | When it is required to create a matrix of dimension n * n, a list comprehension is used.
Below is a demonstration of the same −
Live Demo
N = 4
print("The value of N is ")
print(N)
my_result = [list(range(1 + N * i, 1 + N * (i + 1)))
for i in range(N)]
print("The matrix of dimension N * 0 is :")
print(my_result)
The value of N is
4
The matrix of dimension N * 0 is :
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
The value of N is predefined.
The value of N is predefined.
It is displayed on the console.
It is displayed on the console.
It tells about the dimensions of the matrix.
It tells about the dimensions of the matrix.
The number is iterated over, and is converted into a list.
The number is iterated over, and is converted into a list.
This is assigned to a variable.
This is assigned to a variable.
It is displayed on the console.
It is displayed on the console. | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "When it is required to create a matrix of dimension n * n, a list comprehension is used."
},
{
"code": null,
"e": 1190,
"s": 1151,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1201,
"s": 1190,
"text": " Live Demo"
},
{
"code": null,
"e": 1382,
"s": 1201,
"text": "N = 4\nprint(\"The value of N is \")\nprint(N)\n\nmy_result = [list(range(1 + N * i, 1 + N * (i + 1)))\n for i in range(N)]\n\nprint(\"The matrix of dimension N * 0 is :\")\nprint(my_result)"
},
{
"code": null,
"e": 1501,
"s": 1382,
"text": "The value of N is\n4\nThe matrix of dimension N * 0 is :\n[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]"
},
{
"code": null,
"e": 1531,
"s": 1501,
"text": "The value of N is predefined."
},
{
"code": null,
"e": 1561,
"s": 1531,
"text": "The value of N is predefined."
},
{
"code": null,
"e": 1593,
"s": 1561,
"text": "It is displayed on the console."
},
{
"code": null,
"e": 1625,
"s": 1593,
"text": "It is displayed on the console."
},
{
"code": null,
"e": 1670,
"s": 1625,
"text": "It tells about the dimensions of the matrix."
},
{
"code": null,
"e": 1715,
"s": 1670,
"text": "It tells about the dimensions of the matrix."
},
{
"code": null,
"e": 1774,
"s": 1715,
"text": "The number is iterated over, and is converted into a list."
},
{
"code": null,
"e": 1833,
"s": 1774,
"text": "The number is iterated over, and is converted into a list."
},
{
"code": null,
"e": 1865,
"s": 1833,
"text": "This is assigned to a variable."
},
{
"code": null,
"e": 1897,
"s": 1865,
"text": "This is assigned to a variable."
},
{
"code": null,
"e": 1929,
"s": 1897,
"text": "It is displayed on the console."
},
{
"code": null,
"e": 1961,
"s": 1929,
"text": "It is displayed on the console."
}
]
|
Beginners Guide to Dynamic Programming | Towards Data Science | Dynamic programming is an art, the more problems you solve easier it gets.
Sometimes when you write code it might take some time to execute or it may never run even if your logic is fine. The same problem occurred to me while solving Google Foobar challenge questions and I realized that the solution was not optimized and was using all available RAM (for large values).
An entirely different approach is required to solve such kinds of problems i.e. “optimization of code” by following the concept of dynamic programming.
Dynamic programming is a terrific approach that can be applied to a class of problems for obtaining an efficient and optimal solution.
In simple words, the concept behind dynamic programming is to break the problems into sub-problems and save the result for the future so that we will not have to compute that same problem again. Further optimization of sub-problems which optimizes the overall solution is known as optimal substructure property.
Two ways in which dynamic programming can be applied:
In this method, the problem is broken down and if the problem is solved already then saved value is returned, otherwise, the value of the function is memoized i.e. it will be calculated for the first time; for every other time, the stored value will be called back. Memoization is a great way for computationally expensive programs. Don’t confuse memoization with memorize.
Memoize != memorize
This is an effective way of avoiding recursion by decreasing the time complexity that recursion builds up (i.e. memory cost because of recalculation of the same values). Here, the solutions to small problems are calculated which builds up the solution to the overall problem. (You will have more clarity on this with the examples explained later in the article).
As mentioned above, if you notice that the problem can be broken down into sub-problems and these can be broken into much smaller ones and some of these have overlap (i.e. requires the computation of previously calculated values). The main goal is to optimize the code by reducing the repetition of values by storing the results of sub-problems.
Dynamic Programming can be applied to any such problem that requires the re-calculation of certain values to reach the final solution.
Remember, dynamic programming should not be confused with recursion.
Recursion is a way of finding the solution by expressing the value of a function in terms of other values of that function directly or indirectly and such function is called a recursive function. It follows a top-down approach.
Dynamic programming is nothing but recursion with memoization i.e. calculating and storing values that can be later accessed to solve subproblems that occur again, hence making your code faster and reducing the time complexity (computing CPU cycles are reduced).
Here, the basic idea is to save time by efficient use of space. Recursion takes time but no space while dynamic programming uses space to store solutions to subproblems for future reference thus saving time.
Let’s start with a basic example of the Fibonacci series.
Fibonacci series is a sequence of numbers in such a way that each number is the sum of the two preceding ones, starting from 0 and 1.
F(n) = F(n-1) + F(n-2)
Recursive method:
def r_fibo(n): if n <= 1: return n else: return(r_fibo(n-1) + r_fibo(n-2))
Here, the program will call itself, again and again, to calculate further values. The calculation of the time complexity of the recursion based approach is around O(2^N). The space complexity of this approach is O(N) as recursion can go max to N.
For example-
F(4) = F(3) + F(2) = ((F(2) + F(1)) + F(2) = ((F(1) + F(0)) + F(1)) + (F(1) + F(0))
In this method values like F(2) are computed twice and calls for F(1) and F(0) are made multiple times. Imagine the number of repetitions if you have to calculate it F(100). This method is ineffective for large values.
Top-Down Method
def fibo(n, memo): if memo[n] != null: return memo[n] if n <= 1: return n else: res = fibo(n-1) + fibo(n+1) memo[n] = res return res
Here, the computation time is reduced significantly as the outputs produced after each recursion are stored in a list which can be reused later. This method is much more efficient than the previous one.
Bottom down
def fib(n): if n<=1: return n list_ = [0]*(n+1) list_[0] = 0 list_[1] = 1 for i in range(2, n+1): list_[i] = list_[i-1] + list[i-2] return list_[n]
This code doesn’t use recursion at all. Here, we create an empty list of length (n+1) and set the base case of F(0) and F(1) at index positions 0 and 1. This list is created to store the corresponding calculated values using a for loop for index values 2 up to n.
Unlike in the recursive method, the time complexity of this code is linear and takes much less time to compute the solution, as the loop runs from 2 to n, i.e., it runs in O(n). This approach is the most efficient way to write a program.
Time complexity: O(n) <<< O(2^N)
Now, let’s see another example (this is an intermediate level problem):
Problem statement: You have to build a staircase in such a way that, each type of staircase should consist of 2 or more steps. No two steps are allowed to be at the same height — each step must be lower than the previous one. All steps must contain at least one brick. A step’s height is classified as the total amount of bricks that make up that step.For example, when N = 3, you have only 1 choice of how to build the staircase, with the first step having a height of 2, and the second step having a height of 1 i.e.(2,1). But when N = 5, there are two ways you can build a staircase from the given bricks. The two staircases can have heights (4, 1) or (3, 2).
Write a function called solution(n) that takes a positive integer n and returns the number of different staircases that can be built from exactly n bricks. n will always be at least 3 (so you can have a staircase at all), but no more than 200.
This is a problem I had to solve at level 3 of Google Foobar Challenge. I would suggest you try this question on your own before reading the solution, it will help you understand the concept better.
An intuitive approach to this problem:
My first intuitive approach was to create a list l of integers till n.
Then append all the possible combinations of integers of list l into a new list sol.
And, at the final step, I used a for loop to check the sum of every element of the list solthat if it is equal to the required value. If the condition is true that element is appended to another new list final. And the length offinal is returned as a final solution to the problem.
from itertools import combinationsdef solution(n): l = [] for i in range(1,n): l.append(i) sol = [] for k in range(2,len(l)+1): for m in combinations(l,k): sol.append(m) final = [] for z in (sol): if sum(z) == n : final.append(z) steps = len(final) return (steps)solution(100)
This code turned out to be very ineffective and didn’t work for large values because of the same reason i.e. hight time complexity and repeated calculations of certain values. Running this code for large values(like 100) will use all available RAM and code will eventually crash.
Bottom-up approach for the same problem:
def solution(n): a = [1]+[0]* n for i in range(1, n+1): for k in reversed(range(i, n+1)): a[k] = a[k-i] + a[k] return a[n] - 1
At the first step, an empty list ‘a’ is initiated to store all the values from the further loops.
After each iteration of the outer loop, a[j] is the number of staircases you can make with height at most i where j is the number of bricks used.
List a is initiated to [1,0,0,...] because there can be only one stair with 0 blocks and 0 height.
In each iteration of the inner loop, list a is transformed from representing max-height i-1 to representing max-height i, by incorporating the possibility of adding a step of height i to any shorter staircase that leaves you with at least i blocks.
In the final step, the number of different staircases that can be built from exactly nbricks is returned by the function (1 is subtracted at the end to exclude the case of single stair of height n).
This method is effective for large values as well since the time complexity is traded for space here.
This kind of approach can be applied to other problems as well, you just need to identify them and apply the basics of dynamic programming and you will be able to solve the problems efficiently.
Dynamic programming is a very effective technique for the optimization of code. This technique is really simple and easy to learn however it requires some practice to master.
“Those who cannot remember the past are condemned to repeat it.”
-George Santayana
Check this out: https://www.fiverr.com/share/LDDp34 | [
{
"code": null,
"e": 246,
"s": 171,
"text": "Dynamic programming is an art, the more problems you solve easier it gets."
},
{
"code": null,
"e": 542,
"s": 246,
"text": "Sometimes when you write code it might take some time to execute or it may never run even if your logic is fine. The same problem occurred to me while solving Google Foobar challenge questions and I realized that the solution was not optimized and was using all available RAM (for large values)."
},
{
"code": null,
"e": 694,
"s": 542,
"text": "An entirely different approach is required to solve such kinds of problems i.e. “optimization of code” by following the concept of dynamic programming."
},
{
"code": null,
"e": 829,
"s": 694,
"text": "Dynamic programming is a terrific approach that can be applied to a class of problems for obtaining an efficient and optimal solution."
},
{
"code": null,
"e": 1141,
"s": 829,
"text": "In simple words, the concept behind dynamic programming is to break the problems into sub-problems and save the result for the future so that we will not have to compute that same problem again. Further optimization of sub-problems which optimizes the overall solution is known as optimal substructure property."
},
{
"code": null,
"e": 1195,
"s": 1141,
"text": "Two ways in which dynamic programming can be applied:"
},
{
"code": null,
"e": 1569,
"s": 1195,
"text": "In this method, the problem is broken down and if the problem is solved already then saved value is returned, otherwise, the value of the function is memoized i.e. it will be calculated for the first time; for every other time, the stored value will be called back. Memoization is a great way for computationally expensive programs. Don’t confuse memoization with memorize."
},
{
"code": null,
"e": 1589,
"s": 1569,
"text": "Memoize != memorize"
},
{
"code": null,
"e": 1952,
"s": 1589,
"text": "This is an effective way of avoiding recursion by decreasing the time complexity that recursion builds up (i.e. memory cost because of recalculation of the same values). Here, the solutions to small problems are calculated which builds up the solution to the overall problem. (You will have more clarity on this with the examples explained later in the article)."
},
{
"code": null,
"e": 2298,
"s": 1952,
"text": "As mentioned above, if you notice that the problem can be broken down into sub-problems and these can be broken into much smaller ones and some of these have overlap (i.e. requires the computation of previously calculated values). The main goal is to optimize the code by reducing the repetition of values by storing the results of sub-problems."
},
{
"code": null,
"e": 2433,
"s": 2298,
"text": "Dynamic Programming can be applied to any such problem that requires the re-calculation of certain values to reach the final solution."
},
{
"code": null,
"e": 2502,
"s": 2433,
"text": "Remember, dynamic programming should not be confused with recursion."
},
{
"code": null,
"e": 2730,
"s": 2502,
"text": "Recursion is a way of finding the solution by expressing the value of a function in terms of other values of that function directly or indirectly and such function is called a recursive function. It follows a top-down approach."
},
{
"code": null,
"e": 2993,
"s": 2730,
"text": "Dynamic programming is nothing but recursion with memoization i.e. calculating and storing values that can be later accessed to solve subproblems that occur again, hence making your code faster and reducing the time complexity (computing CPU cycles are reduced)."
},
{
"code": null,
"e": 3201,
"s": 2993,
"text": "Here, the basic idea is to save time by efficient use of space. Recursion takes time but no space while dynamic programming uses space to store solutions to subproblems for future reference thus saving time."
},
{
"code": null,
"e": 3259,
"s": 3201,
"text": "Let’s start with a basic example of the Fibonacci series."
},
{
"code": null,
"e": 3393,
"s": 3259,
"text": "Fibonacci series is a sequence of numbers in such a way that each number is the sum of the two preceding ones, starting from 0 and 1."
},
{
"code": null,
"e": 3416,
"s": 3393,
"text": "F(n) = F(n-1) + F(n-2)"
},
{
"code": null,
"e": 3434,
"s": 3416,
"text": "Recursive method:"
},
{
"code": null,
"e": 3525,
"s": 3434,
"text": "def r_fibo(n): if n <= 1: return n else: return(r_fibo(n-1) + r_fibo(n-2))"
},
{
"code": null,
"e": 3773,
"s": 3525,
"text": "Here, the program will call itself, again and again, to calculate further values. The calculation of the time complexity of the recursion based approach is around O(2^N). The space complexity of this approach is O(N) as recursion can go max to N."
},
{
"code": null,
"e": 3786,
"s": 3773,
"text": "For example-"
},
{
"code": null,
"e": 3870,
"s": 3786,
"text": "F(4) = F(3) + F(2) = ((F(2) + F(1)) + F(2) = ((F(1) + F(0)) + F(1)) + (F(1) + F(0))"
},
{
"code": null,
"e": 4089,
"s": 3870,
"text": "In this method values like F(2) are computed twice and calls for F(1) and F(0) are made multiple times. Imagine the number of repetitions if you have to calculate it F(100). This method is ineffective for large values."
},
{
"code": null,
"e": 4105,
"s": 4089,
"text": "Top-Down Method"
},
{
"code": null,
"e": 4256,
"s": 4105,
"text": "def fibo(n, memo): if memo[n] != null: return memo[n] if n <= 1: return n else: res = fibo(n-1) + fibo(n+1) memo[n] = res return res"
},
{
"code": null,
"e": 4459,
"s": 4256,
"text": "Here, the computation time is reduced significantly as the outputs produced after each recursion are stored in a list which can be reused later. This method is much more efficient than the previous one."
},
{
"code": null,
"e": 4471,
"s": 4459,
"text": "Bottom down"
},
{
"code": null,
"e": 4632,
"s": 4471,
"text": "def fib(n): if n<=1: return n list_ = [0]*(n+1) list_[0] = 0 list_[1] = 1 for i in range(2, n+1): list_[i] = list_[i-1] + list[i-2] return list_[n]"
},
{
"code": null,
"e": 4896,
"s": 4632,
"text": "This code doesn’t use recursion at all. Here, we create an empty list of length (n+1) and set the base case of F(0) and F(1) at index positions 0 and 1. This list is created to store the corresponding calculated values using a for loop for index values 2 up to n."
},
{
"code": null,
"e": 5134,
"s": 4896,
"text": "Unlike in the recursive method, the time complexity of this code is linear and takes much less time to compute the solution, as the loop runs from 2 to n, i.e., it runs in O(n). This approach is the most efficient way to write a program."
},
{
"code": null,
"e": 5168,
"s": 5134,
"text": "Time complexity: O(n) <<< O(2^N)"
},
{
"code": null,
"e": 5240,
"s": 5168,
"text": "Now, let’s see another example (this is an intermediate level problem):"
},
{
"code": null,
"e": 5903,
"s": 5240,
"text": "Problem statement: You have to build a staircase in such a way that, each type of staircase should consist of 2 or more steps. No two steps are allowed to be at the same height — each step must be lower than the previous one. All steps must contain at least one brick. A step’s height is classified as the total amount of bricks that make up that step.For example, when N = 3, you have only 1 choice of how to build the staircase, with the first step having a height of 2, and the second step having a height of 1 i.e.(2,1). But when N = 5, there are two ways you can build a staircase from the given bricks. The two staircases can have heights (4, 1) or (3, 2)."
},
{
"code": null,
"e": 6147,
"s": 5903,
"text": "Write a function called solution(n) that takes a positive integer n and returns the number of different staircases that can be built from exactly n bricks. n will always be at least 3 (so you can have a staircase at all), but no more than 200."
},
{
"code": null,
"e": 6346,
"s": 6147,
"text": "This is a problem I had to solve at level 3 of Google Foobar Challenge. I would suggest you try this question on your own before reading the solution, it will help you understand the concept better."
},
{
"code": null,
"e": 6385,
"s": 6346,
"text": "An intuitive approach to this problem:"
},
{
"code": null,
"e": 6456,
"s": 6385,
"text": "My first intuitive approach was to create a list l of integers till n."
},
{
"code": null,
"e": 6541,
"s": 6456,
"text": "Then append all the possible combinations of integers of list l into a new list sol."
},
{
"code": null,
"e": 6823,
"s": 6541,
"text": "And, at the final step, I used a for loop to check the sum of every element of the list solthat if it is equal to the required value. If the condition is true that element is appended to another new list final. And the length offinal is returned as a final solution to the problem."
},
{
"code": null,
"e": 7127,
"s": 6823,
"text": "from itertools import combinationsdef solution(n): l = [] for i in range(1,n): l.append(i) sol = [] for k in range(2,len(l)+1): for m in combinations(l,k): sol.append(m) final = [] for z in (sol): if sum(z) == n : final.append(z) steps = len(final) return (steps)solution(100)"
},
{
"code": null,
"e": 7407,
"s": 7127,
"text": "This code turned out to be very ineffective and didn’t work for large values because of the same reason i.e. hight time complexity and repeated calculations of certain values. Running this code for large values(like 100) will use all available RAM and code will eventually crash."
},
{
"code": null,
"e": 7448,
"s": 7407,
"text": "Bottom-up approach for the same problem:"
},
{
"code": null,
"e": 7587,
"s": 7448,
"text": "def solution(n): a = [1]+[0]* n for i in range(1, n+1): for k in reversed(range(i, n+1)): a[k] = a[k-i] + a[k] return a[n] - 1"
},
{
"code": null,
"e": 7685,
"s": 7587,
"text": "At the first step, an empty list ‘a’ is initiated to store all the values from the further loops."
},
{
"code": null,
"e": 7831,
"s": 7685,
"text": "After each iteration of the outer loop, a[j] is the number of staircases you can make with height at most i where j is the number of bricks used."
},
{
"code": null,
"e": 7930,
"s": 7831,
"text": "List a is initiated to [1,0,0,...] because there can be only one stair with 0 blocks and 0 height."
},
{
"code": null,
"e": 8179,
"s": 7930,
"text": "In each iteration of the inner loop, list a is transformed from representing max-height i-1 to representing max-height i, by incorporating the possibility of adding a step of height i to any shorter staircase that leaves you with at least i blocks."
},
{
"code": null,
"e": 8378,
"s": 8179,
"text": "In the final step, the number of different staircases that can be built from exactly nbricks is returned by the function (1 is subtracted at the end to exclude the case of single stair of height n)."
},
{
"code": null,
"e": 8480,
"s": 8378,
"text": "This method is effective for large values as well since the time complexity is traded for space here."
},
{
"code": null,
"e": 8675,
"s": 8480,
"text": "This kind of approach can be applied to other problems as well, you just need to identify them and apply the basics of dynamic programming and you will be able to solve the problems efficiently."
},
{
"code": null,
"e": 8850,
"s": 8675,
"text": "Dynamic programming is a very effective technique for the optimization of code. This technique is really simple and easy to learn however it requires some practice to master."
},
{
"code": null,
"e": 8915,
"s": 8850,
"text": "“Those who cannot remember the past are condemned to repeat it.”"
},
{
"code": null,
"e": 8933,
"s": 8915,
"text": "-George Santayana"
}
]
|
map equal_range() in C++ STL - GeeksforGeeks | 05 Mar, 2021
The map::equal_range() is a built-in function in C++ STL which returns a pair of iterators. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. Since the map container only contains unique key, hence the first iterator in the pair returned thus points to the element and the second iterator in the pair points to the next key which comes after key K. If there are no matches with key K and the key K is greater than largest key , the range returned is of length 1 with both iterators pointing to the an element which has a key denoting the size of map and elements as 0. Otherwise the lower bound and the upper bound points to the element just greater than the key K.Syntax:
iterator map_name.equal_range(key)
Parameters: This function accepts a single mandatory parameter key which specifies the element whose range in the container is to be returned. Return Value: The function returns a pair of iterators as explained above.Below programs illustrate the above method: Program 1:
CPP
// C++ program to illustrate the// map::equal_range() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 4, 30 }); mp.insert({ 1, 40 }); mp.insert({ 6, 60 }); pair<map<int, int>::iterator, map<int, int>::iterator> it; // iterator of pairs it = mp.equal_range(1); cout << "The lower bound is " << it.first->first << ":" << it.first->second; cout << "\nThe upper bound is " << it.second->first << ":" << it.second->second; return 0;}
The lower bound is 1:40
The upper bound is 4:30
Program 2:
CPP
// C++ program to illustrate the// map::equal_range() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 4, 30 }); mp.insert({ 1, 40 }); mp.insert({ 6, 60 }); pair<map<int, int>::iterator, map<int, int>::iterator> it; // iterator of pairs it = mp.equal_range(10); cout << "The lower bound is " << it.first->first << ":" << it.first->second; cout << "\nThe upper bound is " << it.second->first << ":" << it.second->second; return 0;}
The lower bound is 3:0
The upper bound is 3:0
aryanrawlani007
gorangshrm3
CPP-Functions
cpp-map
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Friend class and function in C++
Polymorphism in C++
List in C++ Standard Template Library (STL)
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
Queue in C++ Standard Template Library (STL)
new and delete operators in C++ for dynamic memory
Destructors in C++ | [
{
"code": null,
"e": 23731,
"s": 23703,
"text": "\n05 Mar, 2021"
},
{
"code": null,
"e": 24478,
"s": 23731,
"text": "The map::equal_range() is a built-in function in C++ STL which returns a pair of iterators. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. Since the map container only contains unique key, hence the first iterator in the pair returned thus points to the element and the second iterator in the pair points to the next key which comes after key K. If there are no matches with key K and the key K is greater than largest key , the range returned is of length 1 with both iterators pointing to the an element which has a key denoting the size of map and elements as 0. Otherwise the lower bound and the upper bound points to the element just greater than the key K.Syntax: "
},
{
"code": null,
"e": 24513,
"s": 24478,
"text": "iterator map_name.equal_range(key)"
},
{
"code": null,
"e": 24786,
"s": 24513,
"text": "Parameters: This function accepts a single mandatory parameter key which specifies the element whose range in the container is to be returned. Return Value: The function returns a pair of iterators as explained above.Below programs illustrate the above method: Program 1: "
},
{
"code": null,
"e": 24790,
"s": 24786,
"text": "CPP"
},
{
"code": "// C++ program to illustrate the// map::equal_range() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 4, 30 }); mp.insert({ 1, 40 }); mp.insert({ 6, 60 }); pair<map<int, int>::iterator, map<int, int>::iterator> it; // iterator of pairs it = mp.equal_range(1); cout << \"The lower bound is \" << it.first->first << \":\" << it.first->second; cout << \"\\nThe upper bound is \" << it.second->first << \":\" << it.second->second; return 0;}",
"e": 25414,
"s": 24790,
"text": null
},
{
"code": null,
"e": 25462,
"s": 25414,
"text": "The lower bound is 1:40\nThe upper bound is 4:30"
},
{
"code": null,
"e": 25477,
"s": 25464,
"text": "Program 2: "
},
{
"code": null,
"e": 25481,
"s": 25477,
"text": "CPP"
},
{
"code": "// C++ program to illustrate the// map::equal_range() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 4, 30 }); mp.insert({ 1, 40 }); mp.insert({ 6, 60 }); pair<map<int, int>::iterator, map<int, int>::iterator> it; // iterator of pairs it = mp.equal_range(10); cout << \"The lower bound is \" << it.first->first << \":\" << it.first->second; cout << \"\\nThe upper bound is \" << it.second->first << \":\" << it.second->second; return 0;}",
"e": 26106,
"s": 25481,
"text": null
},
{
"code": null,
"e": 26152,
"s": 26106,
"text": "The lower bound is 3:0\nThe upper bound is 3:0"
},
{
"code": null,
"e": 26170,
"s": 26154,
"text": "aryanrawlani007"
},
{
"code": null,
"e": 26182,
"s": 26170,
"text": "gorangshrm3"
},
{
"code": null,
"e": 26196,
"s": 26182,
"text": "CPP-Functions"
},
{
"code": null,
"e": 26204,
"s": 26196,
"text": "cpp-map"
},
{
"code": null,
"e": 26208,
"s": 26204,
"text": "STL"
},
{
"code": null,
"e": 26212,
"s": 26208,
"text": "C++"
},
{
"code": null,
"e": 26216,
"s": 26212,
"text": "STL"
},
{
"code": null,
"e": 26220,
"s": 26216,
"text": "CPP"
},
{
"code": null,
"e": 26318,
"s": 26220,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26327,
"s": 26318,
"text": "Comments"
},
{
"code": null,
"e": 26340,
"s": 26327,
"text": "Old Comments"
},
{
"code": null,
"e": 26368,
"s": 26340,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26392,
"s": 26368,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 26425,
"s": 26392,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 26445,
"s": 26425,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 26489,
"s": 26445,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26533,
"s": 26489,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26569,
"s": 26533,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 26614,
"s": 26569,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26665,
"s": 26614,
"text": "new and delete operators in C++ for dynamic memory"
}
]
|
Adjust for Overdispersion in Poisson Regression | by Yufeng | Towards Data Science | The Poisson regression model naturally arises when we want to model the average number of occurrences per unit of time or space. For example, the incidence of rare cancer, the number of car crossing at the crossroad, or the number of earthquakes.
One feature of the Poisson distribution is that the mean equals the variance. However, over- or underdispersion happens in Poisson models, where the variance is larger or smaller than the mean value, respectively. In reality, overdispersion happens more frequently with a limited amount of data.
The overdispersion issue affects the interpretation of the model. It is necessary to address the problem in order to avoid the wrong estimation of the coefficients.
In this post, I am going to discuss some basic methods to adjust for the overdispersion phenomenon in the Poisson regression model. The implementation will be shown in R codes. I hope this article is helpful.
Suppose we want to model count responses Yi using a vector of predictors xi. We know that the response variable Yi follows a Poisson distribution with parameter μi.
where the probability function is
The log link function is used to link the linear combination of the predictors, Xi with the Poisson parameter μi.
Let’s build a simple model with the example introduced in Faraway’s book.
## R codelibrary(faraway)data(gala)gala = gala[,-2]pois_mod = glm(Species ~ .,family=poisson,gala)summary(pois_mod)
This is the summary of the Poisson model.
Call:glm(formula = Species ~ ., family = poisson, data = gala)Deviance Residuals: Min 1Q Median 3Q Max -8.2752 -4.4966 -0.9443 1.9168 10.1849 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 3.155e+00 5.175e-02 60.963 < 2e-16 ***Area -5.799e-04 2.627e-05 -22.074 < 2e-16 ***Elevation 3.541e-03 8.741e-05 40.507 < 2e-16 ***Nearest 8.826e-03 1.821e-03 4.846 1.26e-06 ***Scruz -5.709e-03 6.256e-04 -9.126 < 2e-16 ***Adjacent -6.630e-04 2.933e-05 -22.608 < 2e-16 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for poisson family taken to be 1) Null deviance: 3510.73 on 29 degrees of freedomResidual deviance: 716.85 on 24 degrees of freedomAIC: 889.68Number of Fisher Scoring iterations: 5
Don’t be fooled by the super significant coefficients. Those beautiful p-values are exactly the consequences of the overdispersion issue. We can check the overdispersion either visually or quantitatively.
Let’s first plot out the estimated variance against the mean.
## R codeplot(log(fitted(pois_mod)),log((gala$Species-fitted(pois_mod))^2),xlab=expression(hat(mu)),ylab=expression((y-hat(mu))^2),pch=20,col="blue")abline(0,1) ## 'varianc = mean' line
We can see that the majority of the variance is larger than the mean, which is a warning of overdispersion.
Quantitatively, the dispersion parameter φ can be estimated using Pearson’s Chi-squared statistic and the degree of freedom.
When φ is larger than 1, it is overdispersion. To manually calculate the parameter, we use the code below.
## R codedp = sum(residuals(pois_mod,type ="pearson")^2)/pois_mod$df.residualdp
which gives us 31.74914 and confirms this simple Poisson model has the overdispersion problem.
Alternatively, we can apply a significance test directly on the fitted model to check the overdispersion.
## R codelibrary(AER)dispersiontest(pois_mod)
which yields,
Overdispersion testdata: pois_modz = 3.3759, p-value = 0.0003678alternative hypothesis: true dispersion is greater than 1sample estimates:dispersion 25.39503
This overdispersion test reports the significance of the overdispersion issue within the model.
We can check how much the coefficient estimations are affected by overdispersion.
## R codesummary(pois_mod,dispersion = dp)
which yields,
Call:glm(formula = Species ~ ., family = poisson, data = gala)Deviance Residuals: Min 1Q Median 3Q Max -8.2752 -4.4966 -0.9443 1.9168 10.1849 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 3.1548079 0.2915897 10.819 < 2e-16 ***Area -0.0005799 0.0001480 -3.918 8.95e-05 ***Elevation 0.0035406 0.0004925 7.189 6.53e-13 ***Nearest 0.0088256 0.0102621 0.860 0.390 Scruz -0.0057094 0.0035251 -1.620 0.105 Adjacent -0.0006630 0.0001653 -4.012 6.01e-05 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for poisson family taken to be 31.74914) Null deviance: 3510.73 on 29 degrees of freedomResidual deviance: 716.85 on 24 degrees of freedomAIC: 889.68Number of Fisher Scoring iterations: 5
Now around half of the predictors become insignificant, which changes the entire interpretation of the model.
Alright, let’s address the problem in the following two ways.
A simple way to adjust the overdispersion is as straightforward as to estimate the dispersion parameter within the model. This could be done via the quasi-families in R.
qpoi_mod = glm(Species ~ .,family=quasipoisson, gala)summary(qpoi_mod)
which yields,
Call:glm(formula = Species ~ ., family = quasipoisson, data = gala)Deviance Residuals: Min 1Q Median 3Q Max -8.2752 -4.4966 -0.9443 1.9168 10.1849 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 3.1548079 0.2915901 10.819 1.03e-10 ***Area -0.0005799 0.0001480 -3.918 0.000649 ***Elevation 0.0035406 0.0004925 7.189 1.98e-07 ***Nearest 0.0088256 0.0102622 0.860 0.398292 Scruz -0.0057094 0.0035251 -1.620 0.118380 Adjacent -0.0006630 0.0001653 -4.012 0.000511 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for quasipoisson family taken to be 31.74921) Null deviance: 3510.73 on 29 degrees of freedomResidual deviance: 716.85 on 24 degrees of freedomAIC: NANumber of Fisher Scoring iterations: 5
We can see that the dispersion parameter is estimated to be 31.74921, which is very close to our manual calculation as aforementioned. This procedure tells us that only three of the predictors’ coefficients are significant.
Another way to address the overdispersion in the model is to change our distributional assumption to the Negative binomial in which the variance is larger than the mean.
Let’s implement the negative binomial model in R.
## R codelibrary(MASS)nb_mod = glm.nb(Species ~ .,data = gala)summary(nb_mod)
which yields,
Call:glm.nb(formula = Species ~ ., data = gala, init.theta = 1.674602286, link = log)Deviance Residuals: Min 1Q Median 3Q Max -2.1344 -0.8597 -0.1476 0.4576 1.8416 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 2.9065247 0.2510344 11.578 < 2e-16 ***Area -0.0006336 0.0002865 -2.211 0.027009 * Elevation 0.0038551 0.0006916 5.574 2.49e-08 ***Nearest 0.0028264 0.0136618 0.207 0.836100 Scruz -0.0018976 0.0028096 -0.675 0.499426 Adjacent -0.0007605 0.0002278 -3.338 0.000842 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for Negative Binomial(1.6746) family taken to be 1) Null deviance: 88.431 on 29 degrees of freedomResidual deviance: 33.196 on 24 degrees of freedomAIC: 304.22Number of Fisher Scoring iterations: 1 Theta: 1.675 Std. Err.: 0.442 2 x log-likelihood: -290.223
It is a better fit to the data because the ratio of deviance over degrees of freedom is only slightly larger than 1 here.
A. Overdispersion can affect the interpretation of the poisson model.
B. To avoid the overdispersion issue in our model, we can use a quasi-family to estimate the dispersion parameter.
C. We can also use the negative binomial instead of the poisson model.
https://biometry.github.io/APES/LectureNotes/2016-JAGS/Overdispersion/OverdispersionJAGS.pdf
Faraway, Julian J. Extending the linear model with R: generalized linear, mixed effects and nonparametric regression models. CRC press, 2016. | [
{
"code": null,
"e": 419,
"s": 172,
"text": "The Poisson regression model naturally arises when we want to model the average number of occurrences per unit of time or space. For example, the incidence of rare cancer, the number of car crossing at the crossroad, or the number of earthquakes."
},
{
"code": null,
"e": 715,
"s": 419,
"text": "One feature of the Poisson distribution is that the mean equals the variance. However, over- or underdispersion happens in Poisson models, where the variance is larger or smaller than the mean value, respectively. In reality, overdispersion happens more frequently with a limited amount of data."
},
{
"code": null,
"e": 880,
"s": 715,
"text": "The overdispersion issue affects the interpretation of the model. It is necessary to address the problem in order to avoid the wrong estimation of the coefficients."
},
{
"code": null,
"e": 1089,
"s": 880,
"text": "In this post, I am going to discuss some basic methods to adjust for the overdispersion phenomenon in the Poisson regression model. The implementation will be shown in R codes. I hope this article is helpful."
},
{
"code": null,
"e": 1254,
"s": 1089,
"text": "Suppose we want to model count responses Yi using a vector of predictors xi. We know that the response variable Yi follows a Poisson distribution with parameter μi."
},
{
"code": null,
"e": 1288,
"s": 1254,
"text": "where the probability function is"
},
{
"code": null,
"e": 1402,
"s": 1288,
"text": "The log link function is used to link the linear combination of the predictors, Xi with the Poisson parameter μi."
},
{
"code": null,
"e": 1476,
"s": 1402,
"text": "Let’s build a simple model with the example introduced in Faraway’s book."
},
{
"code": null,
"e": 1592,
"s": 1476,
"text": "## R codelibrary(faraway)data(gala)gala = gala[,-2]pois_mod = glm(Species ~ .,family=poisson,gala)summary(pois_mod)"
},
{
"code": null,
"e": 1634,
"s": 1592,
"text": "This is the summary of the Poisson model."
},
{
"code": null,
"e": 2473,
"s": 1634,
"text": "Call:glm(formula = Species ~ ., family = poisson, data = gala)Deviance Residuals: Min 1Q Median 3Q Max -8.2752 -4.4966 -0.9443 1.9168 10.1849 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 3.155e+00 5.175e-02 60.963 < 2e-16 ***Area -5.799e-04 2.627e-05 -22.074 < 2e-16 ***Elevation 3.541e-03 8.741e-05 40.507 < 2e-16 ***Nearest 8.826e-03 1.821e-03 4.846 1.26e-06 ***Scruz -5.709e-03 6.256e-04 -9.126 < 2e-16 ***Adjacent -6.630e-04 2.933e-05 -22.608 < 2e-16 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for poisson family taken to be 1) Null deviance: 3510.73 on 29 degrees of freedomResidual deviance: 716.85 on 24 degrees of freedomAIC: 889.68Number of Fisher Scoring iterations: 5"
},
{
"code": null,
"e": 2678,
"s": 2473,
"text": "Don’t be fooled by the super significant coefficients. Those beautiful p-values are exactly the consequences of the overdispersion issue. We can check the overdispersion either visually or quantitatively."
},
{
"code": null,
"e": 2740,
"s": 2678,
"text": "Let’s first plot out the estimated variance against the mean."
},
{
"code": null,
"e": 2926,
"s": 2740,
"text": "## R codeplot(log(fitted(pois_mod)),log((gala$Species-fitted(pois_mod))^2),xlab=expression(hat(mu)),ylab=expression((y-hat(mu))^2),pch=20,col=\"blue\")abline(0,1) ## 'varianc = mean' line"
},
{
"code": null,
"e": 3034,
"s": 2926,
"text": "We can see that the majority of the variance is larger than the mean, which is a warning of overdispersion."
},
{
"code": null,
"e": 3159,
"s": 3034,
"text": "Quantitatively, the dispersion parameter φ can be estimated using Pearson’s Chi-squared statistic and the degree of freedom."
},
{
"code": null,
"e": 3266,
"s": 3159,
"text": "When φ is larger than 1, it is overdispersion. To manually calculate the parameter, we use the code below."
},
{
"code": null,
"e": 3346,
"s": 3266,
"text": "## R codedp = sum(residuals(pois_mod,type =\"pearson\")^2)/pois_mod$df.residualdp"
},
{
"code": null,
"e": 3441,
"s": 3346,
"text": "which gives us 31.74914 and confirms this simple Poisson model has the overdispersion problem."
},
{
"code": null,
"e": 3547,
"s": 3441,
"text": "Alternatively, we can apply a significance test directly on the fitted model to check the overdispersion."
},
{
"code": null,
"e": 3593,
"s": 3547,
"text": "## R codelibrary(AER)dispersiontest(pois_mod)"
},
{
"code": null,
"e": 3607,
"s": 3593,
"text": "which yields,"
},
{
"code": null,
"e": 3768,
"s": 3607,
"text": "Overdispersion testdata: pois_modz = 3.3759, p-value = 0.0003678alternative hypothesis: true dispersion is greater than 1sample estimates:dispersion 25.39503"
},
{
"code": null,
"e": 3864,
"s": 3768,
"text": "This overdispersion test reports the significance of the overdispersion issue within the model."
},
{
"code": null,
"e": 3946,
"s": 3864,
"text": "We can check how much the coefficient estimations are affected by overdispersion."
},
{
"code": null,
"e": 3989,
"s": 3946,
"text": "## R codesummary(pois_mod,dispersion = dp)"
},
{
"code": null,
"e": 4003,
"s": 3989,
"text": "which yields,"
},
{
"code": null,
"e": 4849,
"s": 4003,
"text": "Call:glm(formula = Species ~ ., family = poisson, data = gala)Deviance Residuals: Min 1Q Median 3Q Max -8.2752 -4.4966 -0.9443 1.9168 10.1849 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 3.1548079 0.2915897 10.819 < 2e-16 ***Area -0.0005799 0.0001480 -3.918 8.95e-05 ***Elevation 0.0035406 0.0004925 7.189 6.53e-13 ***Nearest 0.0088256 0.0102621 0.860 0.390 Scruz -0.0057094 0.0035251 -1.620 0.105 Adjacent -0.0006630 0.0001653 -4.012 6.01e-05 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for poisson family taken to be 31.74914) Null deviance: 3510.73 on 29 degrees of freedomResidual deviance: 716.85 on 24 degrees of freedomAIC: 889.68Number of Fisher Scoring iterations: 5"
},
{
"code": null,
"e": 4959,
"s": 4849,
"text": "Now around half of the predictors become insignificant, which changes the entire interpretation of the model."
},
{
"code": null,
"e": 5021,
"s": 4959,
"text": "Alright, let’s address the problem in the following two ways."
},
{
"code": null,
"e": 5191,
"s": 5021,
"text": "A simple way to adjust the overdispersion is as straightforward as to estimate the dispersion parameter within the model. This could be done via the quasi-families in R."
},
{
"code": null,
"e": 5262,
"s": 5191,
"text": "qpoi_mod = glm(Species ~ .,family=quasipoisson, gala)summary(qpoi_mod)"
},
{
"code": null,
"e": 5276,
"s": 5262,
"text": "which yields,"
},
{
"code": null,
"e": 6128,
"s": 5276,
"text": "Call:glm(formula = Species ~ ., family = quasipoisson, data = gala)Deviance Residuals: Min 1Q Median 3Q Max -8.2752 -4.4966 -0.9443 1.9168 10.1849 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 3.1548079 0.2915901 10.819 1.03e-10 ***Area -0.0005799 0.0001480 -3.918 0.000649 ***Elevation 0.0035406 0.0004925 7.189 1.98e-07 ***Nearest 0.0088256 0.0102622 0.860 0.398292 Scruz -0.0057094 0.0035251 -1.620 0.118380 Adjacent -0.0006630 0.0001653 -4.012 0.000511 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for quasipoisson family taken to be 31.74921) Null deviance: 3510.73 on 29 degrees of freedomResidual deviance: 716.85 on 24 degrees of freedomAIC: NANumber of Fisher Scoring iterations: 5"
},
{
"code": null,
"e": 6352,
"s": 6128,
"text": "We can see that the dispersion parameter is estimated to be 31.74921, which is very close to our manual calculation as aforementioned. This procedure tells us that only three of the predictors’ coefficients are significant."
},
{
"code": null,
"e": 6522,
"s": 6352,
"text": "Another way to address the overdispersion in the model is to change our distributional assumption to the Negative binomial in which the variance is larger than the mean."
},
{
"code": null,
"e": 6572,
"s": 6522,
"text": "Let’s implement the negative binomial model in R."
},
{
"code": null,
"e": 6650,
"s": 6572,
"text": "## R codelibrary(MASS)nb_mod = glm.nb(Species ~ .,data = gala)summary(nb_mod)"
},
{
"code": null,
"e": 6664,
"s": 6650,
"text": "which yields,"
},
{
"code": null,
"e": 7632,
"s": 6664,
"text": "Call:glm.nb(formula = Species ~ ., data = gala, init.theta = 1.674602286, link = log)Deviance Residuals: Min 1Q Median 3Q Max -2.1344 -0.8597 -0.1476 0.4576 1.8416 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 2.9065247 0.2510344 11.578 < 2e-16 ***Area -0.0006336 0.0002865 -2.211 0.027009 * Elevation 0.0038551 0.0006916 5.574 2.49e-08 ***Nearest 0.0028264 0.0136618 0.207 0.836100 Scruz -0.0018976 0.0028096 -0.675 0.499426 Adjacent -0.0007605 0.0002278 -3.338 0.000842 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1(Dispersion parameter for Negative Binomial(1.6746) family taken to be 1) Null deviance: 88.431 on 29 degrees of freedomResidual deviance: 33.196 on 24 degrees of freedomAIC: 304.22Number of Fisher Scoring iterations: 1 Theta: 1.675 Std. Err.: 0.442 2 x log-likelihood: -290.223"
},
{
"code": null,
"e": 7754,
"s": 7632,
"text": "It is a better fit to the data because the ratio of deviance over degrees of freedom is only slightly larger than 1 here."
},
{
"code": null,
"e": 7824,
"s": 7754,
"text": "A. Overdispersion can affect the interpretation of the poisson model."
},
{
"code": null,
"e": 7939,
"s": 7824,
"text": "B. To avoid the overdispersion issue in our model, we can use a quasi-family to estimate the dispersion parameter."
},
{
"code": null,
"e": 8010,
"s": 7939,
"text": "C. We can also use the negative binomial instead of the poisson model."
},
{
"code": null,
"e": 8103,
"s": 8010,
"text": "https://biometry.github.io/APES/LectureNotes/2016-JAGS/Overdispersion/OverdispersionJAGS.pdf"
}
]
|
Implementing a Simple Auto-Encoder in Tensorflow | by Edoardo Barp | Towards Data Science | Generative Adversarial Networks (GAN) have recently risen in popularity through the display of some of their capabilities, initially by imitating famous painters’ art styles, but more recently through DeepFake, which allows to seamlessly replace facial expression in videos, while keeping a high output quality.
One of the pillars of GANs is the use of auto-encoders. An auto-encoder is a neural network with two properties: the input and output data are the same, and the network includes a layer of lower dimension than the input. At first, this might sound confusing and useless, but by training the network to copy the input data, while having a “bottleneck”, what we are really doing is getting the network to learn a “compressed” version of the data, and then de-compressing it. In jargon, this translates to finding a “latent space” representation of our data.
In this post, I will explain how to implement an auto-encoder in python, and how to use it in practice to encode and decode data. It is assumed that you have Python 3 as well as Tensorflowalready installed and working, although the code will require minimal changes to work on Python 2.
So, a good auto-encoder must:1. “Compress” the data, i.e. latent dimension < input dimension2. Replicate the data well (duh!)2. Allow us to get the latent representation a.k.a. encoding3. Allow us to decode an encoded representation
I will show you two ways to do this, the rigorous/pedantic (depends on your point of view really), which uses the low level tensorflowAPI, and the faster and more casual one, which takes advantage of the keras API, although the first one is necessary if you want to properly understand the inner workings of the second.
Only the coolest kids use this one — Bill Gates
This implementation will make direct use of the tensorflow coreAPI, which requires some prerequisite knowledge; I’ll briefly explain three fundamental concepts: the tf.placeholder, tf.Variable,and tf.Tensor.
A tf.placeholder is simply a “variable” which will be an input to the model, but is not part of the model per se. It basically allows us to tell the model it shall expected a variable of a certain type and of a certain dimension. This is very similar to a variable declaration in strong-typed languages.
A tf.Variable is pretty much the same as a variable in other programming language, with a declaration similar to that of most strong-typed languages. The network’s weights, for instance, are tf.Variables.
A tf.Tensor is slightly more complex. In our case, we can think of it as an object which contains the symbolic representation of an operation. For instance, given a placeholder X and a weight variable W, the generic representation of the matrix multiplication W X is a tensor, but the result of it, given a specific value of X and W, is not a tensor.
Now that the introductions are made, the process of building the network is rather simple, but pedantic. We will use the MNIST dataset, which is a dataset of handwritten digits stored as 28x28 pictures. We define D as the input data, in this case the flattened image dimension, 784, and d as the encoding dimension, which I set at 128. The network then has 3 layers of the following dimensions: D, d, D.
We will now implement a simple Auto-encoder class, which will be explained line by line. There’s also a full version of the code available here if you’re interested.
Let’s go! First, we need a placeholder for the input data:
self.X = tf.placeholder(tf.float32, shape=(None, D))
Then, we start the encoding phase, by defining the first layer of weights, with the extra bias, as variables:
self.W1 = tf.Variable(tf.random_normal(shape=(D,d)))self.b1 = tf.Variable(np.zeros(d).astype(np.float32))
Notice that the shape of the weight is Dxd, going from the higher to lower dimension. Next, we create the tensor for the bottleneck layer, as the multiplication between input and weight, with the bias added, all of which is activated by relu.
self.Z = tf.nn.relu( tf.matmul(self.X, self.W1) + self.b1 )
We then proceed to the decoding phase, which is identical to the encoding but going from lower to higher dimensions.
self.W2 = tf.Variable(tf.random_normal(shape=(d,D)))self.b2 = tf.Variable(np.zeros(D).astype(np.float32))
Finally, we define the output tensor, as well as the prediction variable. Sigmoid activation is chosen for simplicity since it’s always in the interval [0,1], which is the same range as the normalised pixel from the input.
logits = tf.matmul(self.Z, self.W2) + self.b2 self.X_hat = tf.nn.sigmoid(logits)
That’s it for the network! We only need a loss function as well as an optimizer, and we’re good to start training. The loss chosen is the sigmoid cross entropy, which implies we’re considering the problem as a binary classification at the pixel level, which makes sense for this dataset of black and white images.
Regarding the optimiser, this is pretty much archaic sorcery. Maybe we should create a model which outputs which optimiser to use, given a problem?
self.cost = tf.reduce_sum( tf.nn.sigmoid_cross_entropy_with_logits( # Expected result (a.k.a. itself for autoencoder) labels=self.X, logits=logits )) self.optimizer = tf.train.RMSPropOptimizer(learning_rate=0.005).minimize(self.cost)
The last slightly technical term regards the session, an object which acts as context manager and connector with the backend, and which needs to be initialised:
self.init_op = tf.global_variables_initializer() if(self.sess == None): self.sess = tf.Session()self.sess = tf.get_default_session()self.sess.run(self.init_op)
That’s it! .. or nearly, now we need to fit the model; but worry not, this is very simple in tensorflow:
# Prepare the batches epochs = 10 batch_size = 64 n_batches = len(X) // bs for i in range(epochs): # Permute the input data X_perm = np.random.permutation(X) for j in range(n_batches): # Load data for current batch batch = X_perm[j*batch_size:(j+1)*batch_size] # Run the batch training! _, costs = self.sess.run((self.optimizer, self.cost), feed_dict={self.X: batch})
The last line is really the only interesting one. It’s telling tensorflow to run a training step using batch as the placeholder input X, and using the given optimizer and loss function to do the weight update.
Let’s see some examples of reconstructions given by this network:
Now this is all well and good, but at the moment we’ve only trained a network which can reconstruct itself.. how can we actually use the auto-encoder? We need to define two more operations, encode and decode.. which is actually very simple:
def encode(self, X): return self.sess.run(self.Z, feed_dict={self.X: X})
Here we tell tensorflow to calculate Z which if you look back, you’ll find is the tensor representing the encoding. The decoding is just as straightforward:
def decode(self, Z): return self.sess.run(self.X_hat, feed_dict={self.Z: Z})
This time, we explicitely give tensorflow the encoding through Z,which we would have previously calculated using the encode function, and we tell it to calculate the predicted output,X_hat .
Now as you can see, this is quite long even for a simple network. Sure we could have parametrised a bit and used lists instead of single variable for every weight, but what happens when we need to test multiple structures quickly or automatically? What about other types of layers than just dense? Worry not, the second (less pedantic) way allows us to do all of that easily!
The simpler, the better — William of Ockham
The first way was long, pedantic, and, let’s be honest, a bit annoying. In addition, the lack of simple generalisation did not help. Therefore, a simpler solution is key, which is available through the use of the keras interface, included in tensorflow.
All the network definition, loss, optimisation, and fitting fits in a few lines:
t_model = Sequential()t_model.add(Dense(256, input_shape=(784,)))t_model.add(Dense(128, name='bottleneck'))t_model.add(Dense(784, activation=tf.nn.sigmoid))t_model.compile(optimizer=tf.train.AdamOptimizer(0.001), loss=tf.losses.sigmoid_cross_entropy)t_model.fit(x, x, batch_size=32, epochs=10)
That’s it, we’ve got a trained network. Isn’t life nice sometimes?
...but what about the whole encoding/decoding? Yeah, that’s when it gets slightly trickier, but worry not, your guide is here.So, to be able to do that, we’re going to need a few things:
A session variable
The input tensor, to specify the input in thefeed_dict argument
The encoded tensor, to retrieve the encoding, and to use as input for the decoding feed_dict argument
The decoded/output tensor, to retrieve the decoded value
We achieve this by simply getting the required tensors from the layers of interest! Note that by naming the bottleneck layer, I make it very easy to retrieve it.
session = tf.get_default_session()if(self.sess == None): self.sess = tf.Session()# Get input tensordef get_input_tensor(model): return model.layers[0].input# get bottleneck tensordef get_encode_tensor(model): return model.get_layer(name='encode').output# Get output tensordef get_output_tensor(model): return model.layers[-1].output
That’s it! Now given a trained model, you can get all the variables you need through these lines:
t_input = get_input_tensor(t_model)t_enc = get_bottleneck_tensor(t_model)t_dec = get_output_tensor(t_model)session = tf.get_default_session()# enc will store the actual encoded values of xenc = session.run(t_enc, feed_dict={t_input:x})# dec will store the actual decoded values of encdec = session.run(t_dec, feed_dict={t_enc:enc})
I hope you’ve enjoyed this post, and that it was useful or at least interesting. Initially I made it especially for the session part, which is not well documented. It took me hours trying to understand what a tensors were, what the session is, and how to actually compute only a part of the network, to evaluate and retrieve specific tensors, but all in all it actually helped consolidate the various tensorflow concepts which are far from intuitive, but very powerful once understood.
Thank you for reading, don’t hesitate to comment, and have a nice day! | [
{
"code": null,
"e": 483,
"s": 171,
"text": "Generative Adversarial Networks (GAN) have recently risen in popularity through the display of some of their capabilities, initially by imitating famous painters’ art styles, but more recently through DeepFake, which allows to seamlessly replace facial expression in videos, while keeping a high output quality."
},
{
"code": null,
"e": 1039,
"s": 483,
"text": "One of the pillars of GANs is the use of auto-encoders. An auto-encoder is a neural network with two properties: the input and output data are the same, and the network includes a layer of lower dimension than the input. At first, this might sound confusing and useless, but by training the network to copy the input data, while having a “bottleneck”, what we are really doing is getting the network to learn a “compressed” version of the data, and then de-compressing it. In jargon, this translates to finding a “latent space” representation of our data."
},
{
"code": null,
"e": 1326,
"s": 1039,
"text": "In this post, I will explain how to implement an auto-encoder in python, and how to use it in practice to encode and decode data. It is assumed that you have Python 3 as well as Tensorflowalready installed and working, although the code will require minimal changes to work on Python 2."
},
{
"code": null,
"e": 1559,
"s": 1326,
"text": "So, a good auto-encoder must:1. “Compress” the data, i.e. latent dimension < input dimension2. Replicate the data well (duh!)2. Allow us to get the latent representation a.k.a. encoding3. Allow us to decode an encoded representation"
},
{
"code": null,
"e": 1879,
"s": 1559,
"text": "I will show you two ways to do this, the rigorous/pedantic (depends on your point of view really), which uses the low level tensorflowAPI, and the faster and more casual one, which takes advantage of the keras API, although the first one is necessary if you want to properly understand the inner workings of the second."
},
{
"code": null,
"e": 1927,
"s": 1879,
"text": "Only the coolest kids use this one — Bill Gates"
},
{
"code": null,
"e": 2135,
"s": 1927,
"text": "This implementation will make direct use of the tensorflow coreAPI, which requires some prerequisite knowledge; I’ll briefly explain three fundamental concepts: the tf.placeholder, tf.Variable,and tf.Tensor."
},
{
"code": null,
"e": 2439,
"s": 2135,
"text": "A tf.placeholder is simply a “variable” which will be an input to the model, but is not part of the model per se. It basically allows us to tell the model it shall expected a variable of a certain type and of a certain dimension. This is very similar to a variable declaration in strong-typed languages."
},
{
"code": null,
"e": 2644,
"s": 2439,
"text": "A tf.Variable is pretty much the same as a variable in other programming language, with a declaration similar to that of most strong-typed languages. The network’s weights, for instance, are tf.Variables."
},
{
"code": null,
"e": 2995,
"s": 2644,
"text": "A tf.Tensor is slightly more complex. In our case, we can think of it as an object which contains the symbolic representation of an operation. For instance, given a placeholder X and a weight variable W, the generic representation of the matrix multiplication W X is a tensor, but the result of it, given a specific value of X and W, is not a tensor."
},
{
"code": null,
"e": 3399,
"s": 2995,
"text": "Now that the introductions are made, the process of building the network is rather simple, but pedantic. We will use the MNIST dataset, which is a dataset of handwritten digits stored as 28x28 pictures. We define D as the input data, in this case the flattened image dimension, 784, and d as the encoding dimension, which I set at 128. The network then has 3 layers of the following dimensions: D, d, D."
},
{
"code": null,
"e": 3565,
"s": 3399,
"text": "We will now implement a simple Auto-encoder class, which will be explained line by line. There’s also a full version of the code available here if you’re interested."
},
{
"code": null,
"e": 3624,
"s": 3565,
"text": "Let’s go! First, we need a placeholder for the input data:"
},
{
"code": null,
"e": 3677,
"s": 3624,
"text": "self.X = tf.placeholder(tf.float32, shape=(None, D))"
},
{
"code": null,
"e": 3787,
"s": 3677,
"text": "Then, we start the encoding phase, by defining the first layer of weights, with the extra bias, as variables:"
},
{
"code": null,
"e": 3893,
"s": 3787,
"text": "self.W1 = tf.Variable(tf.random_normal(shape=(D,d)))self.b1 = tf.Variable(np.zeros(d).astype(np.float32))"
},
{
"code": null,
"e": 4136,
"s": 3893,
"text": "Notice that the shape of the weight is Dxd, going from the higher to lower dimension. Next, we create the tensor for the bottleneck layer, as the multiplication between input and weight, with the bias added, all of which is activated by relu."
},
{
"code": null,
"e": 4196,
"s": 4136,
"text": "self.Z = tf.nn.relu( tf.matmul(self.X, self.W1) + self.b1 )"
},
{
"code": null,
"e": 4313,
"s": 4196,
"text": "We then proceed to the decoding phase, which is identical to the encoding but going from lower to higher dimensions."
},
{
"code": null,
"e": 4419,
"s": 4313,
"text": "self.W2 = tf.Variable(tf.random_normal(shape=(d,D)))self.b2 = tf.Variable(np.zeros(D).astype(np.float32))"
},
{
"code": null,
"e": 4642,
"s": 4419,
"text": "Finally, we define the output tensor, as well as the prediction variable. Sigmoid activation is chosen for simplicity since it’s always in the interval [0,1], which is the same range as the normalised pixel from the input."
},
{
"code": null,
"e": 4723,
"s": 4642,
"text": "logits = tf.matmul(self.Z, self.W2) + self.b2 self.X_hat = tf.nn.sigmoid(logits)"
},
{
"code": null,
"e": 5037,
"s": 4723,
"text": "That’s it for the network! We only need a loss function as well as an optimizer, and we’re good to start training. The loss chosen is the sigmoid cross entropy, which implies we’re considering the problem as a binary classification at the pixel level, which makes sense for this dataset of black and white images."
},
{
"code": null,
"e": 5185,
"s": 5037,
"text": "Regarding the optimiser, this is pretty much archaic sorcery. Maybe we should create a model which outputs which optimiser to use, given a problem?"
},
{
"code": null,
"e": 5453,
"s": 5185,
"text": "self.cost = tf.reduce_sum( tf.nn.sigmoid_cross_entropy_with_logits( # Expected result (a.k.a. itself for autoencoder) labels=self.X, logits=logits )) self.optimizer = tf.train.RMSPropOptimizer(learning_rate=0.005).minimize(self.cost)"
},
{
"code": null,
"e": 5614,
"s": 5453,
"text": "The last slightly technical term regards the session, an object which acts as context manager and connector with the backend, and which needs to be initialised:"
},
{
"code": null,
"e": 5792,
"s": 5614,
"text": "self.init_op = tf.global_variables_initializer() if(self.sess == None): self.sess = tf.Session()self.sess = tf.get_default_session()self.sess.run(self.init_op)"
},
{
"code": null,
"e": 5897,
"s": 5792,
"text": "That’s it! .. or nearly, now we need to fit the model; but worry not, this is very simple in tensorflow:"
},
{
"code": null,
"e": 6350,
"s": 5897,
"text": "# Prepare the batches epochs = 10 batch_size = 64 n_batches = len(X) // bs for i in range(epochs): # Permute the input data X_perm = np.random.permutation(X) for j in range(n_batches): # Load data for current batch batch = X_perm[j*batch_size:(j+1)*batch_size] # Run the batch training! _, costs = self.sess.run((self.optimizer, self.cost), feed_dict={self.X: batch})"
},
{
"code": null,
"e": 6560,
"s": 6350,
"text": "The last line is really the only interesting one. It’s telling tensorflow to run a training step using batch as the placeholder input X, and using the given optimizer and loss function to do the weight update."
},
{
"code": null,
"e": 6626,
"s": 6560,
"text": "Let’s see some examples of reconstructions given by this network:"
},
{
"code": null,
"e": 6867,
"s": 6626,
"text": "Now this is all well and good, but at the moment we’ve only trained a network which can reconstruct itself.. how can we actually use the auto-encoder? We need to define two more operations, encode and decode.. which is actually very simple:"
},
{
"code": null,
"e": 6943,
"s": 6867,
"text": "def encode(self, X): return self.sess.run(self.Z, feed_dict={self.X: X})"
},
{
"code": null,
"e": 7100,
"s": 6943,
"text": "Here we tell tensorflow to calculate Z which if you look back, you’ll find is the tensor representing the encoding. The decoding is just as straightforward:"
},
{
"code": null,
"e": 7180,
"s": 7100,
"text": "def decode(self, Z): return self.sess.run(self.X_hat, feed_dict={self.Z: Z})"
},
{
"code": null,
"e": 7371,
"s": 7180,
"text": "This time, we explicitely give tensorflow the encoding through Z,which we would have previously calculated using the encode function, and we tell it to calculate the predicted output,X_hat ."
},
{
"code": null,
"e": 7747,
"s": 7371,
"text": "Now as you can see, this is quite long even for a simple network. Sure we could have parametrised a bit and used lists instead of single variable for every weight, but what happens when we need to test multiple structures quickly or automatically? What about other types of layers than just dense? Worry not, the second (less pedantic) way allows us to do all of that easily!"
},
{
"code": null,
"e": 7791,
"s": 7747,
"text": "The simpler, the better — William of Ockham"
},
{
"code": null,
"e": 8045,
"s": 7791,
"text": "The first way was long, pedantic, and, let’s be honest, a bit annoying. In addition, the lack of simple generalisation did not help. Therefore, a simpler solution is key, which is available through the use of the keras interface, included in tensorflow."
},
{
"code": null,
"e": 8126,
"s": 8045,
"text": "All the network definition, loss, optimisation, and fitting fits in a few lines:"
},
{
"code": null,
"e": 8433,
"s": 8126,
"text": "t_model = Sequential()t_model.add(Dense(256, input_shape=(784,)))t_model.add(Dense(128, name='bottleneck'))t_model.add(Dense(784, activation=tf.nn.sigmoid))t_model.compile(optimizer=tf.train.AdamOptimizer(0.001), loss=tf.losses.sigmoid_cross_entropy)t_model.fit(x, x, batch_size=32, epochs=10)"
},
{
"code": null,
"e": 8500,
"s": 8433,
"text": "That’s it, we’ve got a trained network. Isn’t life nice sometimes?"
},
{
"code": null,
"e": 8687,
"s": 8500,
"text": "...but what about the whole encoding/decoding? Yeah, that’s when it gets slightly trickier, but worry not, your guide is here.So, to be able to do that, we’re going to need a few things:"
},
{
"code": null,
"e": 8706,
"s": 8687,
"text": "A session variable"
},
{
"code": null,
"e": 8770,
"s": 8706,
"text": "The input tensor, to specify the input in thefeed_dict argument"
},
{
"code": null,
"e": 8872,
"s": 8770,
"text": "The encoded tensor, to retrieve the encoding, and to use as input for the decoding feed_dict argument"
},
{
"code": null,
"e": 8929,
"s": 8872,
"text": "The decoded/output tensor, to retrieve the decoded value"
},
{
"code": null,
"e": 9091,
"s": 8929,
"text": "We achieve this by simply getting the required tensors from the layers of interest! Note that by naming the bottleneck layer, I make it very easy to retrieve it."
},
{
"code": null,
"e": 9436,
"s": 9091,
"text": "session = tf.get_default_session()if(self.sess == None): self.sess = tf.Session()# Get input tensordef get_input_tensor(model): return model.layers[0].input# get bottleneck tensordef get_encode_tensor(model): return model.get_layer(name='encode').output# Get output tensordef get_output_tensor(model): return model.layers[-1].output"
},
{
"code": null,
"e": 9534,
"s": 9436,
"text": "That’s it! Now given a trained model, you can get all the variables you need through these lines:"
},
{
"code": null,
"e": 9866,
"s": 9534,
"text": "t_input = get_input_tensor(t_model)t_enc = get_bottleneck_tensor(t_model)t_dec = get_output_tensor(t_model)session = tf.get_default_session()# enc will store the actual encoded values of xenc = session.run(t_enc, feed_dict={t_input:x})# dec will store the actual decoded values of encdec = session.run(t_dec, feed_dict={t_enc:enc})"
},
{
"code": null,
"e": 10352,
"s": 9866,
"text": "I hope you’ve enjoyed this post, and that it was useful or at least interesting. Initially I made it especially for the session part, which is not well documented. It took me hours trying to understand what a tensors were, what the session is, and how to actually compute only a part of the network, to evaluate and retrieve specific tensors, but all in all it actually helped consolidate the various tensorflow concepts which are far from intuitive, but very powerful once understood."
}
]
|
Understanding Decision Trees for Classification (Python) | by Michael Galarnyk | Towards Data Science | Decision trees are a popular supervised learning method for a variety of reasons. Benefits of decision trees include that they can be used for both regression and classification, they are easy to interpret and they don’t require feature scaling. They have several flaws including being prone to overfitting. This tutorial covers decision trees for classification also known as classification trees.
Additionally, this tutorial will cover:
The anatomy of classification trees (depth of a tree, root nodes, decision nodes, leaf nodes/terminal nodes).
How classification trees make predictions
How to use scikit-learn (Python) to make classification trees
Hyperparameter tuning
As always, the code used in this tutorial is available on my GitHub (anatomy, predictions). With that, let’s get started!
Classification and Regression Trees (CART) is a term introduced by Leo Breiman to refer to the Decision Tree algorithm that can be learned for classification or regression predictive modeling problems. This post covers classification trees.
Classification trees are essentially a series of questions designed to assign a classification. The image below is a classification tree trained on the IRIS dataset (flower species). Root (brown) and decision (blue) nodes contain questions which split into subnodes. The root node is just the topmost decision node. In other words, it is where you start traversing the classification tree. The leaf nodes (green), also called terminal nodes, are nodes that don’t split into more nodes. Leaf nodes are where classes are assigned by majority vote.
How to use a Classification Tree
To use a classification tree, start at the root node (brown), and traverse the tree until you reach a leaf (terminal) node. Using the classification tree in the the image below, imagine you had a flower with a petal length of 4.5 cm and you wanted to classify it. Starting at the root node, you would first ask “Is the petal length (cm) ≤ 2.45”? The length is greater than 2.45 so that question is False. Proceed to the next decision node and ask, “Is the petal length (cm) ≤ 4.95”? This is True so you could predict the flower species as versicolor. This is just one example.
How are Classification Trees Grown? (Non Math Version)
A classification tree learns a sequence of if then questions with each question involving one feature and one split point. Look at the partial tree below (A), the question, “petal length (cm) ≤ 2.45” splits the data into two branches based on some value (2.45 in this case). The value between the nodes is called a split point. A good value (one that results in largest information gain) for a split point is one that does a good job of separating one class from the others. Looking at part B of the figure below, all the points to the left of the split point are classified as setosa while all the points to the right of the split point are classified as versicolor.
The figure shows that setosa was correctly classified for all 38 points. It is a pure node. Classification trees don’t split on pure nodes. It would result in no further information gain. However, impure nodes can split further. Notice the rightside of figure B shows that many points are misclassified as versicolor. In other words, it contains points that are of two different classes (virginica and versicolor). Classification trees are a greedy algorithm which means by default it will continue to split until it has a pure node. Again, the algorithm chooses the best split point (we will get into mathematical methods in the next section) for the impure node.
In the image above, the tree has a maximum depth of 2 . Tree depth is a measure of how many splits a tree can make before coming to a prediction. This process could be continued further with more splitting until the tree is as pure as possible. The problem with many repetitions of this process is that this can lead to a very deep classification tree with many nodes. This often leads to overfitting on the training dataset. Luckily, most classification tree implementations allow you to control for the maximum depth of a tree which reduces overfitting. For example, Python’s scikit-learn allows you to preprune decision trees. In other words, you can set the maximum depth to stop the growth of the decision tree past a certain depth. For a visual understanding of maximum depth, you can look at the image below.
This section is really about understanding what is a good split point for root/decision nodes on classification trees. Decision trees split on the feature and corresponding split point that results in the largest information gain (IG) for a given criterion (gini or entropy in this example). Loosely, we can define information gain as
IG = information before splitting (parent) — information after splitting (children)
For a clearer understanding of parent and children, look at the decision tree below.
A more proper formula for information gain formula is below.
Since classification trees have binary splits, the formula can be simplified into the formula below.
Two common criterion I, used to measure the impurity of a node are Gini index and entropy.
For the sake of understanding these formulas a bit better, the image below shows how information gain was calculated for a decision tree with Gini criterion.
The image below shows how information gain was calculated for a decision tree with entropy.
I am not going to go into more detail on this as it should be noted that different impurity measures (Gini index and entropy) usually yield similar results. The graph below shows that Gini index and entropy are very similar impurity criterion. I am guessing one of the reasons why Gini is the default value in scikit-learn is that entropy might be a little slower to compute (because it makes use of a logarithm).
Before finishing this section, I should note that are various decision tree algorithms that differ from each other. Some of the more popular algorithms are ID3, C4.5, and CART. Scikit-learn uses an optimized version of the CART algorithm. You can learn about it’s time complexity here.
The previous sections went over the theory of classification trees. One of the reasons why it is good to learn how to make decision trees in a programming language is that working with data can help in understanding the algorithm.
The Iris dataset is one of datasets scikit-learn comes with that do not require the downloading of any file from some external website. The code below loads the iris dataset.
import pandas as pdfrom sklearn.datasets import load_irisdata = load_iris()df = pd.DataFrame(data.data, columns=data.feature_names)df['target'] = data.target
The code below puts 75% of the data into a training set and 25% of the data into a test set.
X_train, X_test, Y_train, Y_test = train_test_split(df[data.feature_names], df['target'], random_state=0)
Note, one of the benefits of Decision Trees is that you don’t have to standardize your data unlike PCA and logistic regression which are sensitive to effects of not standardizing your data.
Step 1: Import the model you want to use
In scikit-learn, all machine learning models are implemented as Python classes
from sklearn.tree import DecisionTreeClassifier
Step 2: Make an instance of the Model
In the code below, I set the max_depth = 2 to preprune my tree to make sure it doesn’t have a depth greater than 2. I should note the next section of the tutorial will go over how to choose an optimal max_depth for your tree.
Also note that in my code below, I made random_state = 0 so that you can get the same results as me.
clf = DecisionTreeClassifier(max_depth = 2, random_state = 0)
Step 3: Train the model on the data
The model is learning the relationship between X(sepal length, sepal width, petal length, and petal width) and Y(species of iris)
clf.fit(X_train, Y_train)
Step 4: Predict labels of unseen (test) data
# Predict for 1 observationclf.predict(X_test.iloc[0].values.reshape(1, -1))# Predict for multiple observationsclf.predict(X_test[0:10])
Remember, a prediction is just the majority class of the instances in a leaf node.
While there are other ways of measuring model performance (precision, recall, F1 Score, ROC Curve, etc), we are going to keep this simple and use accuracy as our metric.
Accuracy is defined as:
(fraction of correct predictions): correct predictions / total number of data points
# The score method returns the accuracy of the modelscore = clf.score(X_test, Y_test)print(score)
Finding the optimal value formax_depth is one way way to tune your model. The code below outputs the accuracy for decision trees with different values for max_depth.
# List of values to try for max_depth:max_depth_range = list(range(1, 6))# List to store the accuracy for each value of max_depth:accuracy = []for depth in max_depth_range: clf = DecisionTreeClassifier(max_depth = depth, random_state = 0) clf.fit(X_train, Y_train) score = clf.score(X_test, Y_test) accuracy.append(score)
Since the graph below shows that the best accuracy for the model is when the parameter max_depth is greater than or equal to 3, it might be best to choose the least complicated model with max_depth = 3.
It is important to keep in mind that max_depth is not the same thing as depth of a decision tree. max_depth is a way to preprune a decision tree. In other words, if a tree is already as pure as possible at a depth, it will not continue to split. The image below shows decision trees with max_depth values of 3, 4, and 5. Notice that the trees with a max_depth of 4 and 5 are identical. They both have a depth of 4.
If you ever wonder what the depth of your trained decision tree is, you can use the get_depth method. Additionally, you can get the number of leaf nodes for a trained decision tree by using the get_n_leaves method.
While this tutorial has covered changing selection criterion (Gini index, entropy, etc) and max_depth of a tree, keep in mind that you can also tune minimum samples for a node to split (min_samples_leaf), max number of leaf nodes (max_leaf_nodes), and more.
One advantage of classification trees is that they are relatively easy to interpret. Classification trees in scikit-learn allow you to calculate feature importance which is the total amount that gini index or entropy decrease due to splits over a given feature. Scikit-learn outputs a number between 0 and 1 for each feature. All feature importances are normalized to sum to 1. The code below shows feature importances for each feature in a decision tree model.
importances = pd.DataFrame({'feature':X_train.columns,'importance':np.round(clf.feature_importances_,3)})importances = importances.sort_values('importance',ascending=False)
In the example above (for a particular train test split of iris), the petal width has the highest feature importance weight. We can confirm by looking at the corresponding decision tree.
Keep in mind that if a feature has a low feature importance value, it doesn’t necessarily mean that the feature isn’t important for prediction, it just means that the particular feature wasn’t chosen at a particularly early level of the tree. It could also be that the feature could be identical or highly correlated with another informative feature. Feature importance values also don’t tell you which class they are very predictive for or relationships between features which may influence prediction. It is important to note that when performing cross validation or similar, you can use an average of the feature importance values from multiple train test splits.
Classification and Regression Trees (CART) are a relatively old technique (1984) that is the basis for more sophisticated techniques.Benefits of decision trees include that they can be used for both regression and classification, they don’t require feature scaling, and they are relatively easy to interpret as you can visualize decision trees. I should note that if you are interested in learning how to visualize decision trees using matplotlib and/or Graphviz) , I have a post on it here. If you have any questions or thoughts on the tutorial, feel free to reach out in the comments below or through Twitter. If you want to learn how I made some of my graphs or how to utilize Pandas, Matplotlib, or Seaborn libraries, please consider taking my Python for Data Visualization LinkedIn Learning course. | [
{
"code": null,
"e": 571,
"s": 172,
"text": "Decision trees are a popular supervised learning method for a variety of reasons. Benefits of decision trees include that they can be used for both regression and classification, they are easy to interpret and they don’t require feature scaling. They have several flaws including being prone to overfitting. This tutorial covers decision trees for classification also known as classification trees."
},
{
"code": null,
"e": 611,
"s": 571,
"text": "Additionally, this tutorial will cover:"
},
{
"code": null,
"e": 721,
"s": 611,
"text": "The anatomy of classification trees (depth of a tree, root nodes, decision nodes, leaf nodes/terminal nodes)."
},
{
"code": null,
"e": 763,
"s": 721,
"text": "How classification trees make predictions"
},
{
"code": null,
"e": 825,
"s": 763,
"text": "How to use scikit-learn (Python) to make classification trees"
},
{
"code": null,
"e": 847,
"s": 825,
"text": "Hyperparameter tuning"
},
{
"code": null,
"e": 969,
"s": 847,
"text": "As always, the code used in this tutorial is available on my GitHub (anatomy, predictions). With that, let’s get started!"
},
{
"code": null,
"e": 1210,
"s": 969,
"text": "Classification and Regression Trees (CART) is a term introduced by Leo Breiman to refer to the Decision Tree algorithm that can be learned for classification or regression predictive modeling problems. This post covers classification trees."
},
{
"code": null,
"e": 1756,
"s": 1210,
"text": "Classification trees are essentially a series of questions designed to assign a classification. The image below is a classification tree trained on the IRIS dataset (flower species). Root (brown) and decision (blue) nodes contain questions which split into subnodes. The root node is just the topmost decision node. In other words, it is where you start traversing the classification tree. The leaf nodes (green), also called terminal nodes, are nodes that don’t split into more nodes. Leaf nodes are where classes are assigned by majority vote."
},
{
"code": null,
"e": 1789,
"s": 1756,
"text": "How to use a Classification Tree"
},
{
"code": null,
"e": 2366,
"s": 1789,
"text": "To use a classification tree, start at the root node (brown), and traverse the tree until you reach a leaf (terminal) node. Using the classification tree in the the image below, imagine you had a flower with a petal length of 4.5 cm and you wanted to classify it. Starting at the root node, you would first ask “Is the petal length (cm) ≤ 2.45”? The length is greater than 2.45 so that question is False. Proceed to the next decision node and ask, “Is the petal length (cm) ≤ 4.95”? This is True so you could predict the flower species as versicolor. This is just one example."
},
{
"code": null,
"e": 2421,
"s": 2366,
"text": "How are Classification Trees Grown? (Non Math Version)"
},
{
"code": null,
"e": 3089,
"s": 2421,
"text": "A classification tree learns a sequence of if then questions with each question involving one feature and one split point. Look at the partial tree below (A), the question, “petal length (cm) ≤ 2.45” splits the data into two branches based on some value (2.45 in this case). The value between the nodes is called a split point. A good value (one that results in largest information gain) for a split point is one that does a good job of separating one class from the others. Looking at part B of the figure below, all the points to the left of the split point are classified as setosa while all the points to the right of the split point are classified as versicolor."
},
{
"code": null,
"e": 3754,
"s": 3089,
"text": "The figure shows that setosa was correctly classified for all 38 points. It is a pure node. Classification trees don’t split on pure nodes. It would result in no further information gain. However, impure nodes can split further. Notice the rightside of figure B shows that many points are misclassified as versicolor. In other words, it contains points that are of two different classes (virginica and versicolor). Classification trees are a greedy algorithm which means by default it will continue to split until it has a pure node. Again, the algorithm chooses the best split point (we will get into mathematical methods in the next section) for the impure node."
},
{
"code": null,
"e": 4570,
"s": 3754,
"text": "In the image above, the tree has a maximum depth of 2 . Tree depth is a measure of how many splits a tree can make before coming to a prediction. This process could be continued further with more splitting until the tree is as pure as possible. The problem with many repetitions of this process is that this can lead to a very deep classification tree with many nodes. This often leads to overfitting on the training dataset. Luckily, most classification tree implementations allow you to control for the maximum depth of a tree which reduces overfitting. For example, Python’s scikit-learn allows you to preprune decision trees. In other words, you can set the maximum depth to stop the growth of the decision tree past a certain depth. For a visual understanding of maximum depth, you can look at the image below."
},
{
"code": null,
"e": 4905,
"s": 4570,
"text": "This section is really about understanding what is a good split point for root/decision nodes on classification trees. Decision trees split on the feature and corresponding split point that results in the largest information gain (IG) for a given criterion (gini or entropy in this example). Loosely, we can define information gain as"
},
{
"code": null,
"e": 4989,
"s": 4905,
"text": "IG = information before splitting (parent) — information after splitting (children)"
},
{
"code": null,
"e": 5074,
"s": 4989,
"text": "For a clearer understanding of parent and children, look at the decision tree below."
},
{
"code": null,
"e": 5135,
"s": 5074,
"text": "A more proper formula for information gain formula is below."
},
{
"code": null,
"e": 5236,
"s": 5135,
"text": "Since classification trees have binary splits, the formula can be simplified into the formula below."
},
{
"code": null,
"e": 5327,
"s": 5236,
"text": "Two common criterion I, used to measure the impurity of a node are Gini index and entropy."
},
{
"code": null,
"e": 5485,
"s": 5327,
"text": "For the sake of understanding these formulas a bit better, the image below shows how information gain was calculated for a decision tree with Gini criterion."
},
{
"code": null,
"e": 5577,
"s": 5485,
"text": "The image below shows how information gain was calculated for a decision tree with entropy."
},
{
"code": null,
"e": 5991,
"s": 5577,
"text": "I am not going to go into more detail on this as it should be noted that different impurity measures (Gini index and entropy) usually yield similar results. The graph below shows that Gini index and entropy are very similar impurity criterion. I am guessing one of the reasons why Gini is the default value in scikit-learn is that entropy might be a little slower to compute (because it makes use of a logarithm)."
},
{
"code": null,
"e": 6277,
"s": 5991,
"text": "Before finishing this section, I should note that are various decision tree algorithms that differ from each other. Some of the more popular algorithms are ID3, C4.5, and CART. Scikit-learn uses an optimized version of the CART algorithm. You can learn about it’s time complexity here."
},
{
"code": null,
"e": 6508,
"s": 6277,
"text": "The previous sections went over the theory of classification trees. One of the reasons why it is good to learn how to make decision trees in a programming language is that working with data can help in understanding the algorithm."
},
{
"code": null,
"e": 6683,
"s": 6508,
"text": "The Iris dataset is one of datasets scikit-learn comes with that do not require the downloading of any file from some external website. The code below loads the iris dataset."
},
{
"code": null,
"e": 6841,
"s": 6683,
"text": "import pandas as pdfrom sklearn.datasets import load_irisdata = load_iris()df = pd.DataFrame(data.data, columns=data.feature_names)df['target'] = data.target"
},
{
"code": null,
"e": 6934,
"s": 6841,
"text": "The code below puts 75% of the data into a training set and 25% of the data into a test set."
},
{
"code": null,
"e": 7040,
"s": 6934,
"text": "X_train, X_test, Y_train, Y_test = train_test_split(df[data.feature_names], df['target'], random_state=0)"
},
{
"code": null,
"e": 7230,
"s": 7040,
"text": "Note, one of the benefits of Decision Trees is that you don’t have to standardize your data unlike PCA and logistic regression which are sensitive to effects of not standardizing your data."
},
{
"code": null,
"e": 7271,
"s": 7230,
"text": "Step 1: Import the model you want to use"
},
{
"code": null,
"e": 7350,
"s": 7271,
"text": "In scikit-learn, all machine learning models are implemented as Python classes"
},
{
"code": null,
"e": 7398,
"s": 7350,
"text": "from sklearn.tree import DecisionTreeClassifier"
},
{
"code": null,
"e": 7436,
"s": 7398,
"text": "Step 2: Make an instance of the Model"
},
{
"code": null,
"e": 7662,
"s": 7436,
"text": "In the code below, I set the max_depth = 2 to preprune my tree to make sure it doesn’t have a depth greater than 2. I should note the next section of the tutorial will go over how to choose an optimal max_depth for your tree."
},
{
"code": null,
"e": 7763,
"s": 7662,
"text": "Also note that in my code below, I made random_state = 0 so that you can get the same results as me."
},
{
"code": null,
"e": 7854,
"s": 7763,
"text": "clf = DecisionTreeClassifier(max_depth = 2, random_state = 0)"
},
{
"code": null,
"e": 7890,
"s": 7854,
"text": "Step 3: Train the model on the data"
},
{
"code": null,
"e": 8020,
"s": 7890,
"text": "The model is learning the relationship between X(sepal length, sepal width, petal length, and petal width) and Y(species of iris)"
},
{
"code": null,
"e": 8046,
"s": 8020,
"text": "clf.fit(X_train, Y_train)"
},
{
"code": null,
"e": 8091,
"s": 8046,
"text": "Step 4: Predict labels of unseen (test) data"
},
{
"code": null,
"e": 8228,
"s": 8091,
"text": "# Predict for 1 observationclf.predict(X_test.iloc[0].values.reshape(1, -1))# Predict for multiple observationsclf.predict(X_test[0:10])"
},
{
"code": null,
"e": 8311,
"s": 8228,
"text": "Remember, a prediction is just the majority class of the instances in a leaf node."
},
{
"code": null,
"e": 8481,
"s": 8311,
"text": "While there are other ways of measuring model performance (precision, recall, F1 Score, ROC Curve, etc), we are going to keep this simple and use accuracy as our metric."
},
{
"code": null,
"e": 8505,
"s": 8481,
"text": "Accuracy is defined as:"
},
{
"code": null,
"e": 8590,
"s": 8505,
"text": "(fraction of correct predictions): correct predictions / total number of data points"
},
{
"code": null,
"e": 8688,
"s": 8590,
"text": "# The score method returns the accuracy of the modelscore = clf.score(X_test, Y_test)print(score)"
},
{
"code": null,
"e": 8854,
"s": 8688,
"text": "Finding the optimal value formax_depth is one way way to tune your model. The code below outputs the accuracy for decision trees with different values for max_depth."
},
{
"code": null,
"e": 9221,
"s": 8854,
"text": "# List of values to try for max_depth:max_depth_range = list(range(1, 6))# List to store the accuracy for each value of max_depth:accuracy = []for depth in max_depth_range: clf = DecisionTreeClassifier(max_depth = depth, random_state = 0) clf.fit(X_train, Y_train) score = clf.score(X_test, Y_test) accuracy.append(score)"
},
{
"code": null,
"e": 9424,
"s": 9221,
"text": "Since the graph below shows that the best accuracy for the model is when the parameter max_depth is greater than or equal to 3, it might be best to choose the least complicated model with max_depth = 3."
},
{
"code": null,
"e": 9839,
"s": 9424,
"text": "It is important to keep in mind that max_depth is not the same thing as depth of a decision tree. max_depth is a way to preprune a decision tree. In other words, if a tree is already as pure as possible at a depth, it will not continue to split. The image below shows decision trees with max_depth values of 3, 4, and 5. Notice that the trees with a max_depth of 4 and 5 are identical. They both have a depth of 4."
},
{
"code": null,
"e": 10054,
"s": 9839,
"text": "If you ever wonder what the depth of your trained decision tree is, you can use the get_depth method. Additionally, you can get the number of leaf nodes for a trained decision tree by using the get_n_leaves method."
},
{
"code": null,
"e": 10312,
"s": 10054,
"text": "While this tutorial has covered changing selection criterion (Gini index, entropy, etc) and max_depth of a tree, keep in mind that you can also tune minimum samples for a node to split (min_samples_leaf), max number of leaf nodes (max_leaf_nodes), and more."
},
{
"code": null,
"e": 10774,
"s": 10312,
"text": "One advantage of classification trees is that they are relatively easy to interpret. Classification trees in scikit-learn allow you to calculate feature importance which is the total amount that gini index or entropy decrease due to splits over a given feature. Scikit-learn outputs a number between 0 and 1 for each feature. All feature importances are normalized to sum to 1. The code below shows feature importances for each feature in a decision tree model."
},
{
"code": null,
"e": 10947,
"s": 10774,
"text": "importances = pd.DataFrame({'feature':X_train.columns,'importance':np.round(clf.feature_importances_,3)})importances = importances.sort_values('importance',ascending=False)"
},
{
"code": null,
"e": 11134,
"s": 10947,
"text": "In the example above (for a particular train test split of iris), the petal width has the highest feature importance weight. We can confirm by looking at the corresponding decision tree."
},
{
"code": null,
"e": 11801,
"s": 11134,
"text": "Keep in mind that if a feature has a low feature importance value, it doesn’t necessarily mean that the feature isn’t important for prediction, it just means that the particular feature wasn’t chosen at a particularly early level of the tree. It could also be that the feature could be identical or highly correlated with another informative feature. Feature importance values also don’t tell you which class they are very predictive for or relationships between features which may influence prediction. It is important to note that when performing cross validation or similar, you can use an average of the feature importance values from multiple train test splits."
}
]
|
C++ Program to Perform Postorder Recursive Traversal of a Given Binary Tree | Tree traversal is a form of graph traversal. It involves checking or printing each node in the tree exactly once. The postorder traversal of a binary search tree involves visiting each of the nodes in the tree in the order (Left, Right, Root).
An example of postorder traversal of a binary tree is as follows.
A binary tree is given as follows.
Postorder Traversal is: 1 5 4 8 6
The program to perform post-order recursive traversal is given as follows.
Live Demo
#include<iostream>
using namespace std;
struct node {
int data;
struct node *left;
struct node *right;
};
struct node *createNode(int val) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}
void postorder(struct node *root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
}
}
struct node* insertNode(struct node* node, int val) {
if (node == NULL) return createNode(val);
if (val < node->data)
node->left = insertNode(node->left, val);
else if (val > node->data)
node->right = insertNode(node->right, val);
return node;
}
int main() {
struct node *root = NULL;
root = insertNode(root, 4);
insertNode(root, 5);
insertNode(root, 2);
insertNode(root, 9);
insertNode(root, 1);
insertNode(root, 3);
cout<<"Post-Order traversal of the Binary Search Tree is: ";
postorder(root);
return 0;
}
Post-Order traversal of the Binary Search Tree is: 1 3 2 9 5 4
In the above program, the structure node creates the node of a tree. This structure is a self referential structure as it contains pointers of struct node type. This structure is shown as follows.
struct node {
int data;
struct node *left;
struct node *right;
};
The function createNode() creates a node temp and allocates it memory using malloc. The data value val is stored in data of temp. NULL is stored in left and right pointers of temp. This is demonstrated by the following code snippet.
struct node *createNode(int val) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}
The function postorder() takes the root of the binary tree as argument and prints the elements of the tree in postorder. It is a recursive function. It is demonstrated using the following code.
void postorder(struct node *root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
}
}
The function insertNode() inserts the required value in the binary tree at its correct position. If the node is NULL, then createNode is called. Otherwise, the correct position for the node is found in the tree. This can be observed in the following code snippet.
struct node* insertNode(struct node* node, int val) {
if (node == NULL) return createNode(val);
if (val < node->data)
node->left = insertNode(node->left, val);
else if (val > node->data)
node->right = insertNode(node->right, val);
return node;
}
In the main() function, the root node is first defined as NULL. Then all the nodes with the required values are inserted into the binary search tree. This is shown below.
struct node *root = NULL;
root = insertNode(root, 4);
insertNode(root, 5);
insertNode(root, 2);
insertNode(root, 9);
insertNode(root, 1);
insertNode(root, 3);
Finally, the function postorder() is called using the root node of the tree and all the tree values are displayed in postorder. This is given below.
cout<<"Post-Order traversal of the Binary Search Tree is: ";
postorder(root); | [
{
"code": null,
"e": 1306,
"s": 1062,
"text": "Tree traversal is a form of graph traversal. It involves checking or printing each node in the tree exactly once. The postorder traversal of a binary search tree involves visiting each of the nodes in the tree in the order (Left, Right, Root)."
},
{
"code": null,
"e": 1372,
"s": 1306,
"text": "An example of postorder traversal of a binary tree is as follows."
},
{
"code": null,
"e": 1407,
"s": 1372,
"text": "A binary tree is given as follows."
},
{
"code": null,
"e": 1441,
"s": 1407,
"text": "Postorder Traversal is: 1 5 4 8 6"
},
{
"code": null,
"e": 1516,
"s": 1441,
"text": "The program to perform post-order recursive traversal is given as follows."
},
{
"code": null,
"e": 1527,
"s": 1516,
"text": " Live Demo"
},
{
"code": null,
"e": 2529,
"s": 1527,
"text": "#include<iostream>\nusing namespace std;\nstruct node {\n int data;\n struct node *left;\n struct node *right;\n};\nstruct node *createNode(int val) {\n struct node *temp = (struct node *)malloc(sizeof(struct node));\n temp->data = val;\n temp->left = temp->right = NULL;\n return temp;\n}\nvoid postorder(struct node *root) {\n if (root != NULL) {\n postorder(root->left);\n postorder(root->right);\n cout<<root->data<<\" \";\n }\n}\nstruct node* insertNode(struct node* node, int val) {\n if (node == NULL) return createNode(val);\n if (val < node->data)\n node->left = insertNode(node->left, val);\n else if (val > node->data)\n node->right = insertNode(node->right, val);\n return node;\n}\nint main() {\n struct node *root = NULL;\n root = insertNode(root, 4);\n insertNode(root, 5);\n insertNode(root, 2);\n insertNode(root, 9);\n insertNode(root, 1);\n insertNode(root, 3);\n cout<<\"Post-Order traversal of the Binary Search Tree is: \";\n postorder(root);\n return 0;\n}"
},
{
"code": null,
"e": 2592,
"s": 2529,
"text": "Post-Order traversal of the Binary Search Tree is: 1 3 2 9 5 4"
},
{
"code": null,
"e": 2789,
"s": 2592,
"text": "In the above program, the structure node creates the node of a tree. This structure is a self referential structure as it contains pointers of struct node type. This structure is shown as follows."
},
{
"code": null,
"e": 2864,
"s": 2789,
"text": "struct node {\n int data;\n struct node *left;\n struct node *right;\n};"
},
{
"code": null,
"e": 3097,
"s": 2864,
"text": "The function createNode() creates a node temp and allocates it memory using malloc. The data value val is stored in data of temp. NULL is stored in left and right pointers of temp. This is demonstrated by the following code snippet."
},
{
"code": null,
"e": 3274,
"s": 3097,
"text": "struct node *createNode(int val) {\n struct node *temp = (struct node *)malloc(sizeof(struct node));\n temp->data = val;\n temp->left = temp->right = NULL;\n return temp;\n}"
},
{
"code": null,
"e": 3468,
"s": 3274,
"text": "The function postorder() takes the root of the binary tree as argument and prints the elements of the tree in postorder. It is a recursive function. It is demonstrated using the following code."
},
{
"code": null,
"e": 3622,
"s": 3468,
"text": "void postorder(struct node *root) {\n if (root != NULL) {\n postorder(root->left);\n postorder(root->right);\n cout<<root->data<<\" \";\n }\n}"
},
{
"code": null,
"e": 3886,
"s": 3622,
"text": "The function insertNode() inserts the required value in the binary tree at its correct position. If the node is NULL, then createNode is called. Otherwise, the correct position for the node is found in the tree. This can be observed in the following code snippet."
},
{
"code": null,
"e": 4150,
"s": 3886,
"text": "struct node* insertNode(struct node* node, int val) {\n if (node == NULL) return createNode(val);\n if (val < node->data)\n node->left = insertNode(node->left, val);\n else if (val > node->data)\n node->right = insertNode(node->right, val);\n return node;\n}"
},
{
"code": null,
"e": 4321,
"s": 4150,
"text": "In the main() function, the root node is first defined as NULL. Then all the nodes with the required values are inserted into the binary search tree. This is shown below."
},
{
"code": null,
"e": 4480,
"s": 4321,
"text": "struct node *root = NULL;\nroot = insertNode(root, 4);\ninsertNode(root, 5);\ninsertNode(root, 2);\ninsertNode(root, 9);\ninsertNode(root, 1);\ninsertNode(root, 3);"
},
{
"code": null,
"e": 4629,
"s": 4480,
"text": "Finally, the function postorder() is called using the root node of the tree and all the tree values are displayed in postorder. This is given below."
},
{
"code": null,
"e": 4707,
"s": 4629,
"text": "cout<<\"Post-Order traversal of the Binary Search Tree is: \";\npostorder(root);"
}
]
|
How to deserialize a JSON string using @JsonCreator annotation in Java? | The @JsonProperty annotation can be used to indicate the property name in JSON. This annotation can be used for a constructor or factory method. The @JsonCreator annotation is useful in situations where the @JsonSetter annotation cannot be used. For instance, immutable objects do not have any setter methods, so they need their initial values injected into the constructor.
import com.fasterxml.jackson.annotation.*;
import java.io.IOException;
import com.fasterxml.jackson.databind.*;
public class JsonCreatorTest1 {
public static void main(String[] args) throws IOException {
ObjectMapper om = new ObjectMapper();
String jsonString = "{\"id\":\"101\", \"fullname\":\"Ravi Chandra\", \"location\":\"Pune\"}";
System.out.println("JSON: " + jsonString);
Customer customer = om.readValue(jsonString, Customer.class);
System.out.println(customer);
}
}
// Customer class
class Customer {
private String id;
private String name;
private String address;
public Customer() {
}
@JsonCreator
public Customer(
@JsonProperty("id") String id,
@JsonProperty("fullname") String name,
@JsonProperty("location") String address) {
this.id = id;
this.name = name;
this.address = address;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
}
}
JSON: {"id":"101", "fullname":"Ravi Chandra", "location":"Pune"}
Customer [id=101, name=Ravi Chandra, address=Pune]
import com.fasterxml.jackson.annotation.*;
import java.io.IOException;
import com.fasterxml.jackson.databind.*;
public class JsonCreatorTest2 {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"id\":\"102\", \"fullname\":\"Raja Ramesh\", \"location\":\"Hyderabad\"}";
System.out.println("JSON: " + jsonString);
Customer customer = mapper.readValue(jsonString, Customer.class);
System.out.println(customer);
}
}
// Customer class
class Customer {
private String id;
private String name;
private String address;
public Customer() {
}
@JsonCreator
public static Customer createCustomer(
@JsonProperty("id") String id,
@JsonProperty("fullname") String name,
@JsonProperty("location") String address) {
Customer customer = new Customer();
customer.id = id;
customer.name = name;
customer.address = address;
return customer;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
}
}
JSON: {"id":"101", "fullname":"Raja Ramesh", "location":"Hyderabad"}
Customer [id=102, name=Raja Ramesh, address=Hyderabad] | [
{
"code": null,
"e": 1437,
"s": 1062,
"text": "The @JsonProperty annotation can be used to indicate the property name in JSON. This annotation can be used for a constructor or factory method. The @JsonCreator annotation is useful in situations where the @JsonSetter annotation cannot be used. For instance, immutable objects do not have any setter methods, so they need their initial values injected into the constructor."
},
{
"code": null,
"e": 2468,
"s": 1437,
"text": "import com.fasterxml.jackson.annotation.*;\nimport java.io.IOException;\nimport com.fasterxml.jackson.databind.*;\npublic class JsonCreatorTest1 {\n public static void main(String[] args) throws IOException {\n ObjectMapper om = new ObjectMapper();\n String jsonString = \"{\\\"id\\\":\\\"101\\\", \\\"fullname\\\":\\\"Ravi Chandra\\\", \\\"location\\\":\\\"Pune\\\"}\";\n System.out.println(\"JSON: \" + jsonString);\n Customer customer = om.readValue(jsonString, Customer.class);\n System.out.println(customer);\n }\n}\n// Customer class\nclass Customer {\n private String id;\n private String name;\n private String address;\n public Customer() {\n }\n @JsonCreator\n public Customer(\n @JsonProperty(\"id\") String id,\n @JsonProperty(\"fullname\") String name, \n @JsonProperty(\"location\") String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n @Override\n public String toString() {\n return \"Customer [id=\" + id + \", name=\" + name + \", address=\" + address + \"]\";\n }\n}"
},
{
"code": null,
"e": 2584,
"s": 2468,
"text": "JSON: {\"id\":\"101\", \"fullname\":\"Ravi Chandra\", \"location\":\"Pune\"}\nCustomer [id=101, name=Ravi Chandra, address=Pune]"
},
{
"code": null,
"e": 3733,
"s": 2584,
"text": "import com.fasterxml.jackson.annotation.*;\nimport java.io.IOException;\nimport com.fasterxml.jackson.databind.*;\npublic class JsonCreatorTest2 {\n public static void main(String[] args) throws IOException {\n ObjectMapper mapper = new ObjectMapper();\n String jsonString = \"{\\\"id\\\":\\\"102\\\", \\\"fullname\\\":\\\"Raja Ramesh\\\", \\\"location\\\":\\\"Hyderabad\\\"}\";\n System.out.println(\"JSON: \" + jsonString);\n Customer customer = mapper.readValue(jsonString, Customer.class);\n System.out.println(customer);\n }\n}\n// Customer class\nclass Customer {\n private String id;\n private String name;\n private String address;\n public Customer() {\n }\n @JsonCreator\n public static Customer createCustomer(\n @JsonProperty(\"id\") String id,\n @JsonProperty(\"fullname\") String name,\n @JsonProperty(\"location\") String address) {\n Customer customer = new Customer();\n customer.id = id;\n customer.name = name;\n customer.address = address;\n return customer;\n }\n @Override\n public String toString() {\n return \"Customer [id=\" + id + \", name=\" + name + \", address=\" + address + \"]\";\n }\n}"
},
{
"code": null,
"e": 3857,
"s": 3733,
"text": "JSON: {\"id\":\"101\", \"fullname\":\"Raja Ramesh\", \"location\":\"Hyderabad\"}\nCustomer [id=102, name=Raja Ramesh, address=Hyderabad]"
}
]
|
Ext.js - Table Layout | As the name implies, this layout arranges the components in a container in the HTML table format.
Following is a simple syntax to use the Table layout.
layout: 'table'
Following is a simple example showing the usage of Table layout.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.container.Container', {
renderTo : Ext.getBody(),
layout : {
type :'table',
columns : 3,
tableAttrs: {
style: {
width: '100%'
}
}
},
width:600,
height:200,
items : [{
title : 'Panel1',
html : 'This panel has colspan = 2',
colspan :2
},{
title : 'Panel2',
html : 'This panel has rowspan = 2',
rowspan: 2
},{
title : 'Panel3',
html : 'This s panel 3'
},{
title : 'Panel4',
html : 'This is panel 4'
},{
title : 'Panel5',
html : 'This is panel 5'
}]
});
});
</script>
</head>
<body>
</body>
</html>
The above program will produce the following result −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2121,
"s": 2023,
"text": "As the name implies, this layout arranges the components in a container in the HTML table format."
},
{
"code": null,
"e": 2175,
"s": 2121,
"text": "Following is a simple syntax to use the Table layout."
},
{
"code": null,
"e": 2193,
"s": 2175,
"text": "layout: 'table' \n"
},
{
"code": null,
"e": 2258,
"s": 2193,
"text": "Following is a simple example showing the usage of Table layout."
},
{
"code": null,
"e": 3773,
"s": 2258,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.container.Container', {\n renderTo : Ext.getBody(),\n layout : {\n type :'table',\n columns : 3,\n tableAttrs: {\n style: {\n width: '100%'\n }\n } \n },\n width:600,\n height:200,\n \n items : [{\n title : 'Panel1',\n html : 'This panel has colspan = 2',\n colspan :2\n },{\n title : 'Panel2',\n html : 'This panel has rowspan = 2',\n rowspan: 2\n },{\n title : 'Panel3',\n html : 'This s panel 3'\n },{\n title : 'Panel4',\n html : 'This is panel 4'\n },{\n title : 'Panel5',\n html : 'This is panel 5'\n }]\n });\n });\n </script>\n </head>\n \n <body>\n </body>\n</html>"
},
{
"code": null,
"e": 3827,
"s": 3773,
"text": "The above program will produce the following result −"
},
{
"code": null,
"e": 3834,
"s": 3827,
"text": " Print"
},
{
"code": null,
"e": 3845,
"s": 3834,
"text": " Add Notes"
}
]
|
A Python Beginner’s Look at .loc. As a Python beginner, using .loc to... | by Joseph H | Towards Data Science | As a Python beginner, using .loc to retrieve and update values in a pandas dataframe just wasn’t clicking for me. The SettingWithCopyWarning message Python kept throwing at me made it clear that I needed to use it, but it felt like a lot of trial-and-error-messages to get it to do what I needed.
I sat down played around enough with it that I’m now starting to get comfortable, so I figured I’d share my walkthrough; if you’re a beginner, hopefully it will help you. In this post, I cover how to get data with .loc; I’ll cover how to set data in a future post.
I did my “poking” around using a Pokémon dataset (#dadjokes) from the first week of my Data Science Immersive course at General Assembly in Atlanta.
Here’s what df.head(10) looks like:
My first tip is that .loc is not a dataframe method; using () instead of [] cost me 45 minutes one Saturday. Inside those square brackets, .loc takes two inputs: a row “indexer” and an (optional, separated by a comma) column “indexer”: no other arguments, like inplace or axis.
So what can you use as indexers? The pandas documentation lays out the allowed inputs, and the first one it discusses is a single label, so let’s dive in.
Passing a single indexer (since this dataframe is RangeIndexed, we pass an integer) returns a pandas series with the data for the row with that index value, in this case Charmander:
df.loc[4]Name CharmanderType FireTotal 309HP 39Attack 52Defense 43SpecialAttack 60SpecialDefense 50Speed 65Name: 4, dtype: object
.loc will always interpret integers as labels, not as integer positions along the index (you can use .iloc for that).
Passing just a column label or a blank row indexer will give you an error, because the first position of the bracketed index is looking for the row index, and it’s required:
>>>df.loc['Type']KeyError: 'Type'>>>df.loc[, 'Type']SyntaxError: invalid syntax
But passing the column label after using Python slice notation to specify what rows you want (e.g. [:]for all rows) will give you the column data in a pandas Series. Note that, unlike the usual Python convention, .loc slices include both endpoints:
df.loc[:5,'Type']0 GrassPoison1 GrassPoison2 GrassPoison3 GrassPoison4 Fire5 FireName: Type, dtype: object
Slice-ability on row and column index names is a nice advantage of .loc, since normal bracket notation on a dataframe doesn’t allow it:
df.loc[:5,'Type':'Speed']
You can also pass lists with row or column index names to get a subset of the data. (List comprehensions work, too!):
df.loc[[2,4,10,99],['Name','HP']]
The last type of value you can pass as an indexer is a Boolean array, or a list of True and False values. This method has some real power, and great application later when we start using .loc to set values. Rows and columns that correspond to False values in the indexer will be filtered out. The array doesn’t have to be the same size as the corresponding index, but .loc will treat the missing values as if they were False:
df.loc[ [True, False, False, True, True], [True, False, True, False, False, True]]
You can also use Boolean masks to generate the Boolean arrays you pass to .loc. If we want to see just the “Fire” type Pokémon, we’d first generate a Boolean mask — df[‘Type’] == ‘Fire’ — which returns a series of True/False values for each row in the dataframe. We then pass that mask as the row indexer in .loc:
df.loc[df['Type'] == 'Fire']
All sorts of possibilities here, like getting Pokémon with more than 175 attack:
df.loc[df['Attack'] > 175]
Or those with less than 100 hit points and greater than 650 total stats:
df.loc[(df['HP'] < 100) & (df['Total'] > 650)]
Or those with either the letter “X” in their names or of the “PsychicFairy” type:
df.loc[ (df['Name'].str.contains('X')) | (df['Type'].str.contains('PsychicFairy'))]
Of course, you can do much of this with normal bracket notation on a DataFrame, so what’s so special? In this post, I talk about how .loc allows you to set values in the DataFrame. | [
{
"code": null,
"e": 468,
"s": 171,
"text": "As a Python beginner, using .loc to retrieve and update values in a pandas dataframe just wasn’t clicking for me. The SettingWithCopyWarning message Python kept throwing at me made it clear that I needed to use it, but it felt like a lot of trial-and-error-messages to get it to do what I needed."
},
{
"code": null,
"e": 733,
"s": 468,
"text": "I sat down played around enough with it that I’m now starting to get comfortable, so I figured I’d share my walkthrough; if you’re a beginner, hopefully it will help you. In this post, I cover how to get data with .loc; I’ll cover how to set data in a future post."
},
{
"code": null,
"e": 883,
"s": 733,
"text": "I did my “poking” around using a Pokémon dataset (#dadjokes) from the first week of my Data Science Immersive course at General Assembly in Atlanta."
},
{
"code": null,
"e": 919,
"s": 883,
"text": "Here’s what df.head(10) looks like:"
},
{
"code": null,
"e": 1197,
"s": 919,
"text": "My first tip is that .loc is not a dataframe method; using () instead of [] cost me 45 minutes one Saturday. Inside those square brackets, .loc takes two inputs: a row “indexer” and an (optional, separated by a comma) column “indexer”: no other arguments, like inplace or axis."
},
{
"code": null,
"e": 1352,
"s": 1197,
"text": "So what can you use as indexers? The pandas documentation lays out the allowed inputs, and the first one it discusses is a single label, so let’s dive in."
},
{
"code": null,
"e": 1534,
"s": 1352,
"text": "Passing a single indexer (since this dataframe is RangeIndexed, we pass an integer) returns a pandas series with the data for the row with that index value, in this case Charmander:"
},
{
"code": null,
"e": 1818,
"s": 1534,
"text": "df.loc[4]Name CharmanderType FireTotal 309HP 39Attack 52Defense 43SpecialAttack 60SpecialDefense 50Speed 65Name: 4, dtype: object"
},
{
"code": null,
"e": 1936,
"s": 1818,
"text": ".loc will always interpret integers as labels, not as integer positions along the index (you can use .iloc for that)."
},
{
"code": null,
"e": 2110,
"s": 1936,
"text": "Passing just a column label or a blank row indexer will give you an error, because the first position of the bracketed index is looking for the row index, and it’s required:"
},
{
"code": null,
"e": 2190,
"s": 2110,
"text": ">>>df.loc['Type']KeyError: 'Type'>>>df.loc[, 'Type']SyntaxError: invalid syntax"
},
{
"code": null,
"e": 2439,
"s": 2190,
"text": "But passing the column label after using Python slice notation to specify what rows you want (e.g. [:]for all rows) will give you the column data in a pandas Series. Note that, unlike the usual Python convention, .loc slices include both endpoints:"
},
{
"code": null,
"e": 2578,
"s": 2439,
"text": "df.loc[:5,'Type']0 GrassPoison1 GrassPoison2 GrassPoison3 GrassPoison4 Fire5 FireName: Type, dtype: object"
},
{
"code": null,
"e": 2714,
"s": 2578,
"text": "Slice-ability on row and column index names is a nice advantage of .loc, since normal bracket notation on a dataframe doesn’t allow it:"
},
{
"code": null,
"e": 2740,
"s": 2714,
"text": "df.loc[:5,'Type':'Speed']"
},
{
"code": null,
"e": 2858,
"s": 2740,
"text": "You can also pass lists with row or column index names to get a subset of the data. (List comprehensions work, too!):"
},
{
"code": null,
"e": 2892,
"s": 2858,
"text": "df.loc[[2,4,10,99],['Name','HP']]"
},
{
"code": null,
"e": 3318,
"s": 2892,
"text": "The last type of value you can pass as an indexer is a Boolean array, or a list of True and False values. This method has some real power, and great application later when we start using .loc to set values. Rows and columns that correspond to False values in the indexer will be filtered out. The array doesn’t have to be the same size as the corresponding index, but .loc will treat the missing values as if they were False:"
},
{
"code": null,
"e": 3413,
"s": 3318,
"text": "df.loc[ [True, False, False, True, True], [True, False, True, False, False, True]]"
},
{
"code": null,
"e": 3728,
"s": 3413,
"text": "You can also use Boolean masks to generate the Boolean arrays you pass to .loc. If we want to see just the “Fire” type Pokémon, we’d first generate a Boolean mask — df[‘Type’] == ‘Fire’ — which returns a series of True/False values for each row in the dataframe. We then pass that mask as the row indexer in .loc:"
},
{
"code": null,
"e": 3757,
"s": 3728,
"text": "df.loc[df['Type'] == 'Fire']"
},
{
"code": null,
"e": 3839,
"s": 3757,
"text": "All sorts of possibilities here, like getting Pokémon with more than 175 attack:"
},
{
"code": null,
"e": 3866,
"s": 3839,
"text": "df.loc[df['Attack'] > 175]"
},
{
"code": null,
"e": 3939,
"s": 3866,
"text": "Or those with less than 100 hit points and greater than 650 total stats:"
},
{
"code": null,
"e": 3986,
"s": 3939,
"text": "df.loc[(df['HP'] < 100) & (df['Total'] > 650)]"
},
{
"code": null,
"e": 4068,
"s": 3986,
"text": "Or those with either the letter “X” in their names or of the “PsychicFairy” type:"
},
{
"code": null,
"e": 4163,
"s": 4068,
"text": "df.loc[ (df['Name'].str.contains('X')) | (df['Type'].str.contains('PsychicFairy'))]"
}
]
|
Find a document with ObjectID in MongoDB? | To find a document with Objectid in MongoDB, use the following syntax −
db.yourCollectionName.find({"_id":ObjectId("yourObjectIdValue")}).pretty();
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Larry"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e4384afe5c1d2279d69b")
}
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Mike","UserAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e4444afe5c1d2279d69c")
}
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Carol","UserAge":26,"UserHobby":["Learning","Photography"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e4704afe5c1d2279d69d")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.findDocumentWithObjectIdDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c90e4384afe5c1d2279d69b"), "UserName" : "Larry" }
{
"_id" : ObjectId("5c90e4444afe5c1d2279d69c"),
"UserName" : "Mike",
"UserAge" : 23
}
{
"_id" : ObjectId("5c90e4704afe5c1d2279d69d"),
"UserName" : "Carol",
"UserAge" : 26,
"UserHobby" : [
"Learning",
"Photography"
]
}
Case 1 − Here is the query to find a document with ObjectId in MongoDB.
> db.findDocumentWithObjectIdDemo.find({"_id":ObjectId("5c90e4704afe5c1d2279d69d")}).pretty();
The following is the output −
{
"_id" : ObjectId("5c90e4704afe5c1d2279d69d"),
"UserName" : "Carol",
"UserAge" : 26,
"UserHobby" : [
"Learning",
"Photography"
]
}
Case 2 − Here is the query to find another document with ObjectId in MongoDB.
The query is as follows −
> db.findDocumentWithObjectIdDemo.find({"_id": ObjectId("5c90e4444afe5c1d2279d69c")}).pretty();
The following is the output −
{
"_id" : ObjectId("5c90e4444afe5c1d2279d69c"),
"UserName" : "Mike",
"UserAge" : 23
} | [
{
"code": null,
"e": 1134,
"s": 1062,
"text": "To find a document with Objectid in MongoDB, use the following syntax −"
},
{
"code": null,
"e": 1210,
"s": 1134,
"text": "db.yourCollectionName.find({\"_id\":ObjectId(\"yourObjectIdValue\")}).pretty();"
},
{
"code": null,
"e": 1353,
"s": 1210,
"text": "To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −"
},
{
"code": null,
"e": 1874,
"s": 1353,
"text": "> db.findDocumentWithObjectIdDemo.insertOne({\"UserName\":\"Larry\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c90e4384afe5c1d2279d69b\")\n}\n> db.findDocumentWithObjectIdDemo.insertOne({\"UserName\":\"Mike\",\"UserAge\":23});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c90e4444afe5c1d2279d69c\")\n}\n\n> db.findDocumentWithObjectIdDemo.insertOne({\"UserName\":\"Carol\",\"UserAge\":26,\"UserHobby\":[\"Learning\",\"Photography\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c90e4704afe5c1d2279d69d\")\n}"
},
{
"code": null,
"e": 1972,
"s": 1874,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 2023,
"s": 1972,
"text": "> db.findDocumentWithObjectIdDemo.find().pretty();"
},
{
"code": null,
"e": 2053,
"s": 2023,
"text": "The following is the output −"
},
{
"code": null,
"e": 2378,
"s": 2053,
"text": "{ \"_id\" : ObjectId(\"5c90e4384afe5c1d2279d69b\"), \"UserName\" : \"Larry\" }\n{\n \"_id\" : ObjectId(\"5c90e4444afe5c1d2279d69c\"),\n \"UserName\" : \"Mike\",\n \"UserAge\" : 23\n}\n{\n \"_id\" : ObjectId(\"5c90e4704afe5c1d2279d69d\"),\n \"UserName\" : \"Carol\",\n \"UserAge\" : 26,\n \"UserHobby\" : [\n \"Learning\",\n \"Photography\"\n ]\n}"
},
{
"code": null,
"e": 2450,
"s": 2378,
"text": "Case 1 − Here is the query to find a document with ObjectId in MongoDB."
},
{
"code": null,
"e": 2545,
"s": 2450,
"text": "> db.findDocumentWithObjectIdDemo.find({\"_id\":ObjectId(\"5c90e4704afe5c1d2279d69d\")}).pretty();"
},
{
"code": null,
"e": 2575,
"s": 2545,
"text": "The following is the output −"
},
{
"code": null,
"e": 2734,
"s": 2575,
"text": "{\n \"_id\" : ObjectId(\"5c90e4704afe5c1d2279d69d\"),\n \"UserName\" : \"Carol\",\n \"UserAge\" : 26,\n \"UserHobby\" : [\n \"Learning\",\n \"Photography\"\n ]\n}"
},
{
"code": null,
"e": 2812,
"s": 2734,
"text": "Case 2 − Here is the query to find another document with ObjectId in MongoDB."
},
{
"code": null,
"e": 2838,
"s": 2812,
"text": "The query is as follows −"
},
{
"code": null,
"e": 2934,
"s": 2838,
"text": "> db.findDocumentWithObjectIdDemo.find({\"_id\": ObjectId(\"5c90e4444afe5c1d2279d69c\")}).pretty();"
},
{
"code": null,
"e": 2964,
"s": 2934,
"text": "The following is the output −"
},
{
"code": null,
"e": 3059,
"s": 2964,
"text": "{\n \"_id\" : ObjectId(\"5c90e4444afe5c1d2279d69c\"),\n \"UserName\" : \"Mike\",\n \"UserAge\" : 23\n}"
}
]
|
DecimalFormat("00E00") in Java | DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers.
Let us set DecimalFormat("00E00") first.
Format f = new DecimalFormat("00E00");
Now, we will format a number and display the result in a string using the format() method −
String res = f.format(-5977.3427);
Since, we have used both Format and DecimalFormat class in Java, therefore importing the following packages in a must −
import java.text.DecimalFormat;
import java.text.Format;
The following the complete example −
Live Demo
import java.text.DecimalFormat;
import java.text.Format;
public class Demo {
public static void main(String[] argv) throws Exception {
Format f = new DecimalFormat("00E00");
String res = f.format(-5977.3427);
System.out.println(res);
}
}
-60E02 | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers."
},
{
"code": null,
"e": 1186,
"s": 1145,
"text": "Let us set DecimalFormat(\"00E00\") first."
},
{
"code": null,
"e": 1225,
"s": 1186,
"text": "Format f = new DecimalFormat(\"00E00\");"
},
{
"code": null,
"e": 1317,
"s": 1225,
"text": "Now, we will format a number and display the result in a string using the format() method −"
},
{
"code": null,
"e": 1352,
"s": 1317,
"text": "String res = f.format(-5977.3427);"
},
{
"code": null,
"e": 1472,
"s": 1352,
"text": "Since, we have used both Format and DecimalFormat class in Java, therefore importing the following packages in a must −"
},
{
"code": null,
"e": 1529,
"s": 1472,
"text": "import java.text.DecimalFormat;\nimport java.text.Format;"
},
{
"code": null,
"e": 1566,
"s": 1529,
"text": "The following the complete example −"
},
{
"code": null,
"e": 1577,
"s": 1566,
"text": " Live Demo"
},
{
"code": null,
"e": 1839,
"s": 1577,
"text": "import java.text.DecimalFormat;\nimport java.text.Format;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n Format f = new DecimalFormat(\"00E00\");\n String res = f.format(-5977.3427);\n System.out.println(res);\n }\n}"
},
{
"code": null,
"e": 1846,
"s": 1839,
"text": "-60E02"
}
]
|
How can I get a random number in Kotlin? | Kotlin provides multiple ways to generate a random number. In this article, we will see different ways to generate a random number and access it throughout the program.
Random() is an abstract class which generates random numbers with the given conditions. It can be accessed after importing Kotlin.random.Random.
As per the Kotlin documentation, the companion object Random.Default is the default instance of Random class. In the following example, we will generate a list of random values with int (1-30) .
import kotlin.random.Random
fun main() {
val myRandomValues = List(5) { Random.nextInt(0, 30) }
// Prints a new sequence every time
println(myRandomValues)
}
It generated the following random numbers. You may get a different set of numbers, as the output is random in nature.
[8, 21, 16, 29, 16]
Kotlin does provide a random() function to generate random numbers. It takes a series of numbers as an input and it returns a random Int as an output.
fun main() {
// It generates a random number between 0 to 10
println((0..10).random())
}
On execution, it produced the following output −
0
Kotlin does provide another method to generate random numbers between a sequence. We can use shuffled() to generate a random number in between 1 to 100.
fun main() {
val random1 = (0..100).shuffled().last()
println(random1)
}
On execution, it produced the following output. It could be different in your case, as the output is random in nature.
42 | [
{
"code": null,
"e": 1231,
"s": 1062,
"text": "Kotlin provides multiple ways to generate a random number. In this article, we will see different ways to generate a random number and access it throughout the program."
},
{
"code": null,
"e": 1376,
"s": 1231,
"text": "Random() is an abstract class which generates random numbers with the given conditions. It can be accessed after importing Kotlin.random.Random."
},
{
"code": null,
"e": 1571,
"s": 1376,
"text": "As per the Kotlin documentation, the companion object Random.Default is the default instance of Random class. In the following example, we will generate a list of random values with int (1-30) ."
},
{
"code": null,
"e": 1741,
"s": 1571,
"text": "import kotlin.random.Random\n\nfun main() {\n val myRandomValues = List(5) { Random.nextInt(0, 30) }\n\n // Prints a new sequence every time\n println(myRandomValues)\n\n}"
},
{
"code": null,
"e": 1859,
"s": 1741,
"text": "It generated the following random numbers. You may get a different set of numbers, as the output is random in nature."
},
{
"code": null,
"e": 1880,
"s": 1859,
"text": "[8, 21, 16, 29, 16]\n"
},
{
"code": null,
"e": 2031,
"s": 1880,
"text": "Kotlin does provide a random() function to generate random numbers. It takes a series of numbers as an input and it returns a random Int as an output."
},
{
"code": null,
"e": 2126,
"s": 2031,
"text": "fun main() {\n // It generates a random number between 0 to 10\n println((0..10).random())\n}"
},
{
"code": null,
"e": 2175,
"s": 2126,
"text": "On execution, it produced the following output −"
},
{
"code": null,
"e": 2178,
"s": 2175,
"text": "0\n"
},
{
"code": null,
"e": 2331,
"s": 2178,
"text": "Kotlin does provide another method to generate random numbers between a sequence. We can use shuffled() to generate a random number in between 1 to 100."
},
{
"code": null,
"e": 2410,
"s": 2331,
"text": "fun main() {\n val random1 = (0..100).shuffled().last()\n println(random1)\n}"
},
{
"code": null,
"e": 2529,
"s": 2410,
"text": "On execution, it produced the following output. It could be different in your case, as the output is random in nature."
},
{
"code": null,
"e": 2533,
"s": 2529,
"text": "42\n"
}
]
|
Using PettingZoo with RLlib for Multi-Agent Deep Reinforcement Learning | by J K Terry | Towards Data Science | Thank you Yuri Plotkin, Rohan Potdar, Ben Black and Kaan Ozdogru, who each created or edited large parts of this article.
This tutorial provides an overview for using the RLlib Python library with PettingZoo environments for multi-agent deep reinforcement learning. More details about using the PettingZoo environment can be found in this recent blog post. In the following article, we will cover how to train and evaluate an RLlib policy using two PettingZoo environments:
Pistonball — No illegal actions exist, all agents step simultaneously
Leduc Hold’em — Illegal action masking, turn based actions
PettingZoo and Pistonball
PettingZoo is a Python library developed for multi-agent reinforcement-learning simulations. The current software provides a standard API to train on environments using other well-known open source reinforcement learning libraries. You can think of the library as analogous to OpenAI’s Gym library, however, tailored for multi-agent reinforcement learning. Similar to others, the basic API usage is as follows:
from pettingzoo.butterfly import pistonball_v5env = pistonball_v5.env() env.reset() for agent in env.agent_iter(): observation, reward, done, info = env.last() action = policy(observation, agent) env.step(action)
Pistonball is a cooperative PettingZoo environment, and is visualized in the rendering below:
The goal of the environment is to train the pistons to cooperatively work together to move the ball to the left as quickly as possible.
Each piston acts as an independent agent controlled by a policy π trained with function approximation techniques such as neural networks (hence deep reinforcement learning). The observation space of each agent is a window above and to the side of each piston (see below).
We assume full observability, and the policy π returns an action that serves to either raise or lower the piston from +4 to -4 pixels (image dimension is 84x84 pixels).
Following an action by each piston, the environment outputs both a global reward of
(ΔX/Xe) * 100 + τt
Where ΔX is the change in the ball’s x-position, Xe is the ball’s starting position and τ is the time penalty (with default value of 0.1) times the length of time t.
For more details about the PettingZoo environment, please check out the following description.
The Code
Let’s step through the code in greater detail.
First, to run the reinforcement learning environment, we import the required libraries:
from ray import tunefrom ray.rllib.models import ModelCatalogfrom ray.rllib.models.torch.torch_modelv2 import TorchModelV2from ray.tune.registry import register_envfrom ray.rllib.env.wrappers.pettingzoo_env import ParallelPettingZooEnvfrom pettingzoo.butterfly import pistonball_v5import supersuit as ssimport torchfrom torch import nn
The multi-agent reinforcement learning environment requires distributed training. To set up the environment, we use the open-source library Ray. Ray is a framework developed to provide a universal API for building distributed applications. Tune is a library built on top of Ray for scalable hyperparameter tuning in distributed reinforcement learning. We therefore only use Tune to execute a single training run in RLlib. Since we will require the use of a custom model to train our policy π, we first register the model in RLlib’s ModelCatalog. To create a custom model, we subclass the TorchModelV2 class from RLlib.
To use the PettingZoo environment with Tune, we first register the environment using the register_env function. ParallelPettingZooEnv is a wrapper used with PettingZoo environments such as Pistonball to interface with RLlib’s multi-agent API. SuperSuit is a library that provides preprocessing functions for both Gym and PettingZoo environments, as we’ll see below.
Initially, we create a convolutional neural network model in Pytorch for training our policy π:
class CNNModelV2(TorchModelV2, nn.Module):def __init__(self, obs_space, act_space, num_outputs, *args, **kwargs):TorchModelV2.__init__(self, obs_space, act_space, num_outputs, *args, **kwargs)nn.Module.__init__(self)self.model = nn.Sequential(nn.Conv2d( 3, 32, [8, 8], stride=(4, 4)),nn.ReLU(),nn.Conv2d( 32, 64, [4, 4], stride=(2, 2)),nn.ReLU(),nn.Conv2d( 64, 64, [3, 3], stride=(1, 1)),nn.ReLU(),nn.Flatten(),(nn.Linear(3136,512)),nn.ReLU(),)self.policy_fn = nn.Linear(512, num_outputs)self.value_fn = nn.Linear(512, 1)def forward(self, input_dict, state, seq_lens):model_out = self.model(input_dict[“obs”].permute(0, 3, 1, 2))self._value_out = self.value_fn(model_out)return self.policy_fn(model_out), statedef value_function(self):return self._value_out.flatten()
You can find more information on how to use custom models with the RLlib library here. We then need to define a function to create and return the environment:
def env_creator(args):env = pistonball_v4.parallel_env(n_pistons=20, local_ratio=0, time_penalty=-0.1, continuous=True, random_drop=True, random_rotate=True, ball_mass=0.75, ball_friction=0.3, ball_elasticity=1.5, max_cycles=125)env = ss.color_reduction_v0(env, mode=’B’)env = ss.dtype_v0(env, ‘float32’)env = ss.resize_v0(env, x_size=84, y_size=84)env = ss.frame_stack_v1(env, 3)env = ss.normalize_obs_v0(env, env_min=0, env_max=1)return env
We use PettingZoo’s parallel API to create the environment. The arguments to the parallel_env function control the environment’s properties and behavior. We additionally use SuperSuit’s wrapper functions for preprocessing operations.
The first function is employed to convert the full-color observations images produced by the environment to grayscale for reducing the computational complexity and cost. Subsequently, we cast the pixel image data type from uint8 to float32, downscale it to a 84x84 grid representation and normalize pixel intensity. Lastly, in order to measure the change in the ball’s direction ΔX (used in calculating the total reward), 3 consecutive frames of observations are stacked together to give the policy an easy way to learn.
A more detailed explanation of these preprocessing operations can be found in the previous tutorial.
After defining our model and environment, we can run the trainer using the tune.run() function using the parameters in the config dictionary. You can read about these hyperparameters in detail here. Of note, we instantiate a multi-agent specific configuration wherein we specify our policies using a dictionary mapping:
policy_id strings → tuples of (policy_cls, obs_space, act_space, config).
The policy_mapping_fn is a function mapping agent_ids to policy_ids. In our particular case, we use parameter sharing for training the pistons as described in the previous tutorial i.e. all the pistons are controlled by the same policy π with id ‘policy_0’.
if __name__ == “__main__”:env_name = “pistonball_v4”register_env(env_name, lambda config: ParallelPettingZooEnv(env_creator(config)))test_env = ParallelPettingZooEnv(env_creator({}))obs_space = test_env.observation_spaceact_space = test_env.action_spaceModelCatalog.register_custom_model(“CNNModelV2”, CNNModelV2)def gen_policy(i):config = {“model”: {“custom_model”: “CNNModelV2”,},“gamma”: 0.99,}return (None, obs_space, act_space, config)policies = {“policy_0”: gen_policy(0)}policy_ids = list(policies.keys())tune.run(“PPO”,name=”PPO”,stop={“timesteps_total”: 5000000},checkpoint_freq=10,local_dir=”~/ray_results/”+env_name,config={# Environment specific“env”: env_name,# General“log_level”: “ERROR”,“framework”: “torch”,“num_gpus”: 1,“num_workers”: 4,“num_envs_per_worker”: 1,“compress_observations”: False,“batch_mode”: ‘truncate_episodes’,# ‘use_critic’: True,‘use_gae’: True,“lambda”: 0.9,“gamma”: .99,# “kl_coeff”: 0.001,# “kl_target”: 1000.,“clip_param”: 0.4,‘grad_clip’: None,“entropy_coeff”: 0.1,‘vf_loss_coeff’: 0.25,“sgd_minibatch_size”: 64,“num_sgd_iter”: 10, # epoc‘rollout_fragment_length’: 512,“train_batch_size”: 512*4,‘lr’: 2e-05,“clip_actions”: True,# Method specific“multiagent”: {“policies”: policies,“policy_mapping_fn”: (lambda agent_id: policy_ids[0]),},},)
Now, we can watch our trained policy execute itself in the environment. During training, the policy is saved at each checkpoint, according to the frequency specified by checkpoint_freq. By default, RLlib stores the checkpoints in ~/ray_results. We first specify the path to our checkpoints:
checkpoint_path = “foo”
We can then load and restore our trained policy π, and use the policy to choose actions while rendering the environment at each timestep. We save the rendered video as a GIF:
with open(params_path, “rb”) as f:config = pickle.load(f)# num_workers not needed since we are not trainingdel config[‘num_workers’]del config[‘num_gpus’]ray.init(num_cpus=8, num_gpus=1)PPOagent = PPOTrainer(env=env_name, config=config)PPOagent.restore(checkpoint_path)reward_sum = 0frame_list = []i = 0env.reset()for agent in env.agent_iter():observation, reward, done, info = env.last()reward_sum += rewardif done:action = Noneelse:action, _, _ = PPOagent.get_policy(“policy_0”).compute_single_action(observation)env.step(action)i += 1if i % (len(env.possible_agents)+1) == 0:frame_list.append(PIL.Image.fromarray(env.render(mode=’rgb_array’)))env.close()print(reward_sum)frame_list[0].save(“out.gif”, save_all=True, append_images=frame_list[1:], duration=3, loop=0)
A gif of the solved environment can be seen above.
The entire training code detailed in this tutorial can be located here. And the code for rendering can be found here. For any improvements to the codebase or for any issues encountered with this article, please create an issue in the PettingZoo repository.
Leduc Hold’em
Leduc Hold’em is a poker variant popular in AI research detailed here and here; we’ll be using the two player variant. This environment is notable in that it is a purely turn based game and some actions are illegal (e.g. action masking is required).
To begin, the initial code we need looks much the same:
from copy import deepcopyimport osimport rayfrom ray import tunefrom ray.rllib.agents.registry import get_agent_classfrom ray.rllib.env import PettingZooEnvfrom pettingzoo.classic import leduc_holdem_v2from ray.rllib.models import ModelCatalogfrom ray.tune.registry import register_envfrom gym.spaces import Boxfrom ray.rllib.agents.dqn.dqn_torch_model import DQNTorchModelfrom ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFCfrom ray.rllib.utils.framework import try_import_torchfrom ray.rllib.utils.torch_ops import FLOAT_MAXtorch, nn = try_import_torch()
Initializing a suitable policy with action masking via parametric action masking then looks like this:
class TorchMaskedActions(DQNTorchModel):“””PyTorch version of above ParametricActionsModel.”””def __init__(self,obs_space,action_space,num_outputs,model_config,name,**kw):DQNTorchModel.__init__(self, obs_space, action_space, num_outputs,model_config, name, **kw)obs_len = obs_space.shape[0]-action_space.norig_obs_space = Box(shape=(obs_len,), low=obs_space.low[:obs_len], high=obs_space.high[:obs_len])self.action_embed_model = TorchFC(orig_obs_space, action_space, action_space.n, model_config, name + “_action_embed”)def forward(self, input_dict, state, seq_lens):# Extract the available actions tensor from the observation.action_mask = input_dict[“obs”][“action_mask”]# Compute the predicted action embeddingaction_logits, _ = self.action_embed_model({“obs”: input_dict[“obs”][‘observation’]})# turns probit action mask into logit action maskinf_mask = torch.clamp(torch.log(action_mask), -1e10, FLOAT_MAX)return action_logits + inf_mask, statedef value_function(self):return self.action_embed_model.value_function()
Rendering in Leduc Hold’em functions similarly to that of Pistonball, using this code snippet:
import rayimport pickle5 as picklefrom ray.tune.registry import register_envfrom ray.rllib.agents.dqn import DQNTrainerfrom pettingzoo.classic import leduc_holdem_v4import supersuit as ssfrom ray.rllib.env.wrappers.pettingzoo_env import PettingZooEnvimport PILfrom ray.rllib.models import ModelCatalogimport numpy as npimport osfrom ray.rllib.agents.registry import get_agent_classfrom copy import deepcopyimport argparsefrom pathlib import Pathfrom rllib_leduc_holdem import TorchMaskedActionsos.environ[“SDL_VIDEODRIVER”] = “dummy”parser = argparse.ArgumentParser(description=’Render pretrained policy loaded from checkpoint’)parser.add_argument(“checkpoint_path”, help=”Path to the checkpoint. This path will likely be something like this: `~/ray_results/pistonball_v4/PPO/PPO_pistonball_v4_660ce_00000_0_2021–06–11_12–30–57/checkpoint_000050/checkpoint-50`”)args = parser.parse_args()checkpoint_path = os.path.expanduser(args.checkpoint_path)params_path = Path(checkpoint_path).parent.parent/”params.pkl”alg_name = “DQN”ModelCatalog.register_custom_model(“pa_model”, TorchMaskedActions)# function that outputs the environment you wish to register.def env_creator():env = leduc_holdem_v4.env()return envnum_cpus = 1config = deepcopy(get_agent_class(alg_name)._default_config)register_env(“leduc_holdem”,lambda config: PettingZooEnv(env_creator()))env = (env_creator())# obs_space = env.observation_space# print(obs_space)# act_space = test_env.action_spacewith open(params_path, “rb”) as f:config = pickle.load(f)# num_workers not needed since we are not trainingdel config[‘num_workers’]del config[‘num_gpus’]ray.init(num_cpus=8, num_gpus=0)DQNAgent = DQNTrainer(env=”leduc_holdem”, config=config)DQNAgent.restore(checkpoint_path)reward_sums = {a:0 for a in env.possible_agents}i = 0env.reset()for agent in env.agent_iter():observation, reward, done, info = env.last()obs = observation[‘observation’]reward_sums[agent] += rewardif done:action = Noneelse:print(DQNAgent.get_policy(agent))policy = DQNAgent.get_policy(agent)batch_obs = {‘obs’:{‘observation’: np.expand_dims(observation[‘observation’], 0),‘action_mask’: np.expand_dims(observation[‘action_mask’],0)}}batched_action, state_out, info = policy.compute_actions_from_input_dict(batch_obs)single_action = batched_action[0]action = single_actionenv.step(action)i += 1env.render()print(“rewards:”)print(reward_sums)
Similar to before, the full training code used in this tutorial can be found here and the rendering code can be found here. If you have any improvements to this code or encounter any issues with this article, please create an issue on the PettingZoo repository and we’d be happy to help. | [
{
"code": null,
"e": 294,
"s": 172,
"text": "Thank you Yuri Plotkin, Rohan Potdar, Ben Black and Kaan Ozdogru, who each created or edited large parts of this article."
},
{
"code": null,
"e": 646,
"s": 294,
"text": "This tutorial provides an overview for using the RLlib Python library with PettingZoo environments for multi-agent deep reinforcement learning. More details about using the PettingZoo environment can be found in this recent blog post. In the following article, we will cover how to train and evaluate an RLlib policy using two PettingZoo environments:"
},
{
"code": null,
"e": 716,
"s": 646,
"text": "Pistonball — No illegal actions exist, all agents step simultaneously"
},
{
"code": null,
"e": 775,
"s": 716,
"text": "Leduc Hold’em — Illegal action masking, turn based actions"
},
{
"code": null,
"e": 801,
"s": 775,
"text": "PettingZoo and Pistonball"
},
{
"code": null,
"e": 1212,
"s": 801,
"text": "PettingZoo is a Python library developed for multi-agent reinforcement-learning simulations. The current software provides a standard API to train on environments using other well-known open source reinforcement learning libraries. You can think of the library as analogous to OpenAI’s Gym library, however, tailored for multi-agent reinforcement learning. Similar to others, the basic API usage is as follows:"
},
{
"code": null,
"e": 1425,
"s": 1212,
"text": "from pettingzoo.butterfly import pistonball_v5env = pistonball_v5.env() env.reset() for agent in env.agent_iter(): observation, reward, done, info = env.last() action = policy(observation, agent) env.step(action)"
},
{
"code": null,
"e": 1519,
"s": 1425,
"text": "Pistonball is a cooperative PettingZoo environment, and is visualized in the rendering below:"
},
{
"code": null,
"e": 1655,
"s": 1519,
"text": "The goal of the environment is to train the pistons to cooperatively work together to move the ball to the left as quickly as possible."
},
{
"code": null,
"e": 1927,
"s": 1655,
"text": "Each piston acts as an independent agent controlled by a policy π trained with function approximation techniques such as neural networks (hence deep reinforcement learning). The observation space of each agent is a window above and to the side of each piston (see below)."
},
{
"code": null,
"e": 2096,
"s": 1927,
"text": "We assume full observability, and the policy π returns an action that serves to either raise or lower the piston from +4 to -4 pixels (image dimension is 84x84 pixels)."
},
{
"code": null,
"e": 2180,
"s": 2096,
"text": "Following an action by each piston, the environment outputs both a global reward of"
},
{
"code": null,
"e": 2199,
"s": 2180,
"text": "(ΔX/Xe) * 100 + τt"
},
{
"code": null,
"e": 2365,
"s": 2199,
"text": "Where ΔX is the change in the ball’s x-position, Xe is the ball’s starting position and τ is the time penalty (with default value of 0.1) times the length of time t."
},
{
"code": null,
"e": 2460,
"s": 2365,
"text": "For more details about the PettingZoo environment, please check out the following description."
},
{
"code": null,
"e": 2469,
"s": 2460,
"text": "The Code"
},
{
"code": null,
"e": 2516,
"s": 2469,
"text": "Let’s step through the code in greater detail."
},
{
"code": null,
"e": 2604,
"s": 2516,
"text": "First, to run the reinforcement learning environment, we import the required libraries:"
},
{
"code": null,
"e": 2940,
"s": 2604,
"text": "from ray import tunefrom ray.rllib.models import ModelCatalogfrom ray.rllib.models.torch.torch_modelv2 import TorchModelV2from ray.tune.registry import register_envfrom ray.rllib.env.wrappers.pettingzoo_env import ParallelPettingZooEnvfrom pettingzoo.butterfly import pistonball_v5import supersuit as ssimport torchfrom torch import nn"
},
{
"code": null,
"e": 3559,
"s": 2940,
"text": "The multi-agent reinforcement learning environment requires distributed training. To set up the environment, we use the open-source library Ray. Ray is a framework developed to provide a universal API for building distributed applications. Tune is a library built on top of Ray for scalable hyperparameter tuning in distributed reinforcement learning. We therefore only use Tune to execute a single training run in RLlib. Since we will require the use of a custom model to train our policy π, we first register the model in RLlib’s ModelCatalog. To create a custom model, we subclass the TorchModelV2 class from RLlib."
},
{
"code": null,
"e": 3925,
"s": 3559,
"text": "To use the PettingZoo environment with Tune, we first register the environment using the register_env function. ParallelPettingZooEnv is a wrapper used with PettingZoo environments such as Pistonball to interface with RLlib’s multi-agent API. SuperSuit is a library that provides preprocessing functions for both Gym and PettingZoo environments, as we’ll see below."
},
{
"code": null,
"e": 4021,
"s": 3925,
"text": "Initially, we create a convolutional neural network model in Pytorch for training our policy π:"
},
{
"code": null,
"e": 4789,
"s": 4021,
"text": "class CNNModelV2(TorchModelV2, nn.Module):def __init__(self, obs_space, act_space, num_outputs, *args, **kwargs):TorchModelV2.__init__(self, obs_space, act_space, num_outputs, *args, **kwargs)nn.Module.__init__(self)self.model = nn.Sequential(nn.Conv2d( 3, 32, [8, 8], stride=(4, 4)),nn.ReLU(),nn.Conv2d( 32, 64, [4, 4], stride=(2, 2)),nn.ReLU(),nn.Conv2d( 64, 64, [3, 3], stride=(1, 1)),nn.ReLU(),nn.Flatten(),(nn.Linear(3136,512)),nn.ReLU(),)self.policy_fn = nn.Linear(512, num_outputs)self.value_fn = nn.Linear(512, 1)def forward(self, input_dict, state, seq_lens):model_out = self.model(input_dict[“obs”].permute(0, 3, 1, 2))self._value_out = self.value_fn(model_out)return self.policy_fn(model_out), statedef value_function(self):return self._value_out.flatten()"
},
{
"code": null,
"e": 4948,
"s": 4789,
"text": "You can find more information on how to use custom models with the RLlib library here. We then need to define a function to create and return the environment:"
},
{
"code": null,
"e": 5391,
"s": 4948,
"text": "def env_creator(args):env = pistonball_v4.parallel_env(n_pistons=20, local_ratio=0, time_penalty=-0.1, continuous=True, random_drop=True, random_rotate=True, ball_mass=0.75, ball_friction=0.3, ball_elasticity=1.5, max_cycles=125)env = ss.color_reduction_v0(env, mode=’B’)env = ss.dtype_v0(env, ‘float32’)env = ss.resize_v0(env, x_size=84, y_size=84)env = ss.frame_stack_v1(env, 3)env = ss.normalize_obs_v0(env, env_min=0, env_max=1)return env"
},
{
"code": null,
"e": 5625,
"s": 5391,
"text": "We use PettingZoo’s parallel API to create the environment. The arguments to the parallel_env function control the environment’s properties and behavior. We additionally use SuperSuit’s wrapper functions for preprocessing operations."
},
{
"code": null,
"e": 6146,
"s": 5625,
"text": "The first function is employed to convert the full-color observations images produced by the environment to grayscale for reducing the computational complexity and cost. Subsequently, we cast the pixel image data type from uint8 to float32, downscale it to a 84x84 grid representation and normalize pixel intensity. Lastly, in order to measure the change in the ball’s direction ΔX (used in calculating the total reward), 3 consecutive frames of observations are stacked together to give the policy an easy way to learn."
},
{
"code": null,
"e": 6247,
"s": 6146,
"text": "A more detailed explanation of these preprocessing operations can be found in the previous tutorial."
},
{
"code": null,
"e": 6567,
"s": 6247,
"text": "After defining our model and environment, we can run the trainer using the tune.run() function using the parameters in the config dictionary. You can read about these hyperparameters in detail here. Of note, we instantiate a multi-agent specific configuration wherein we specify our policies using a dictionary mapping:"
},
{
"code": null,
"e": 6641,
"s": 6567,
"text": "policy_id strings → tuples of (policy_cls, obs_space, act_space, config)."
},
{
"code": null,
"e": 6899,
"s": 6641,
"text": "The policy_mapping_fn is a function mapping agent_ids to policy_ids. In our particular case, we use parameter sharing for training the pistons as described in the previous tutorial i.e. all the pistons are controlled by the same policy π with id ‘policy_0’."
},
{
"code": null,
"e": 8182,
"s": 6899,
"text": "if __name__ == “__main__”:env_name = “pistonball_v4”register_env(env_name, lambda config: ParallelPettingZooEnv(env_creator(config)))test_env = ParallelPettingZooEnv(env_creator({}))obs_space = test_env.observation_spaceact_space = test_env.action_spaceModelCatalog.register_custom_model(“CNNModelV2”, CNNModelV2)def gen_policy(i):config = {“model”: {“custom_model”: “CNNModelV2”,},“gamma”: 0.99,}return (None, obs_space, act_space, config)policies = {“policy_0”: gen_policy(0)}policy_ids = list(policies.keys())tune.run(“PPO”,name=”PPO”,stop={“timesteps_total”: 5000000},checkpoint_freq=10,local_dir=”~/ray_results/”+env_name,config={# Environment specific“env”: env_name,# General“log_level”: “ERROR”,“framework”: “torch”,“num_gpus”: 1,“num_workers”: 4,“num_envs_per_worker”: 1,“compress_observations”: False,“batch_mode”: ‘truncate_episodes’,# ‘use_critic’: True,‘use_gae’: True,“lambda”: 0.9,“gamma”: .99,# “kl_coeff”: 0.001,# “kl_target”: 1000.,“clip_param”: 0.4,‘grad_clip’: None,“entropy_coeff”: 0.1,‘vf_loss_coeff’: 0.25,“sgd_minibatch_size”: 64,“num_sgd_iter”: 10, # epoc‘rollout_fragment_length’: 512,“train_batch_size”: 512*4,‘lr’: 2e-05,“clip_actions”: True,# Method specific“multiagent”: {“policies”: policies,“policy_mapping_fn”: (lambda agent_id: policy_ids[0]),},},)"
},
{
"code": null,
"e": 8473,
"s": 8182,
"text": "Now, we can watch our trained policy execute itself in the environment. During training, the policy is saved at each checkpoint, according to the frequency specified by checkpoint_freq. By default, RLlib stores the checkpoints in ~/ray_results. We first specify the path to our checkpoints:"
},
{
"code": null,
"e": 8497,
"s": 8473,
"text": "checkpoint_path = “foo”"
},
{
"code": null,
"e": 8672,
"s": 8497,
"text": "We can then load and restore our trained policy π, and use the policy to choose actions while rendering the environment at each timestep. We save the rendered video as a GIF:"
},
{
"code": null,
"e": 9441,
"s": 8672,
"text": "with open(params_path, “rb”) as f:config = pickle.load(f)# num_workers not needed since we are not trainingdel config[‘num_workers’]del config[‘num_gpus’]ray.init(num_cpus=8, num_gpus=1)PPOagent = PPOTrainer(env=env_name, config=config)PPOagent.restore(checkpoint_path)reward_sum = 0frame_list = []i = 0env.reset()for agent in env.agent_iter():observation, reward, done, info = env.last()reward_sum += rewardif done:action = Noneelse:action, _, _ = PPOagent.get_policy(“policy_0”).compute_single_action(observation)env.step(action)i += 1if i % (len(env.possible_agents)+1) == 0:frame_list.append(PIL.Image.fromarray(env.render(mode=’rgb_array’)))env.close()print(reward_sum)frame_list[0].save(“out.gif”, save_all=True, append_images=frame_list[1:], duration=3, loop=0)"
},
{
"code": null,
"e": 9492,
"s": 9441,
"text": "A gif of the solved environment can be seen above."
},
{
"code": null,
"e": 9749,
"s": 9492,
"text": "The entire training code detailed in this tutorial can be located here. And the code for rendering can be found here. For any improvements to the codebase or for any issues encountered with this article, please create an issue in the PettingZoo repository."
},
{
"code": null,
"e": 9763,
"s": 9749,
"text": "Leduc Hold’em"
},
{
"code": null,
"e": 10013,
"s": 9763,
"text": "Leduc Hold’em is a poker variant popular in AI research detailed here and here; we’ll be using the two player variant. This environment is notable in that it is a purely turn based game and some actions are illegal (e.g. action masking is required)."
},
{
"code": null,
"e": 10069,
"s": 10013,
"text": "To begin, the initial code we need looks much the same:"
},
{
"code": null,
"e": 10647,
"s": 10069,
"text": "from copy import deepcopyimport osimport rayfrom ray import tunefrom ray.rllib.agents.registry import get_agent_classfrom ray.rllib.env import PettingZooEnvfrom pettingzoo.classic import leduc_holdem_v2from ray.rllib.models import ModelCatalogfrom ray.tune.registry import register_envfrom gym.spaces import Boxfrom ray.rllib.agents.dqn.dqn_torch_model import DQNTorchModelfrom ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFCfrom ray.rllib.utils.framework import try_import_torchfrom ray.rllib.utils.torch_ops import FLOAT_MAXtorch, nn = try_import_torch()"
},
{
"code": null,
"e": 10750,
"s": 10647,
"text": "Initializing a suitable policy with action masking via parametric action masking then looks like this:"
},
{
"code": null,
"e": 11772,
"s": 10750,
"text": "class TorchMaskedActions(DQNTorchModel):“””PyTorch version of above ParametricActionsModel.”””def __init__(self,obs_space,action_space,num_outputs,model_config,name,**kw):DQNTorchModel.__init__(self, obs_space, action_space, num_outputs,model_config, name, **kw)obs_len = obs_space.shape[0]-action_space.norig_obs_space = Box(shape=(obs_len,), low=obs_space.low[:obs_len], high=obs_space.high[:obs_len])self.action_embed_model = TorchFC(orig_obs_space, action_space, action_space.n, model_config, name + “_action_embed”)def forward(self, input_dict, state, seq_lens):# Extract the available actions tensor from the observation.action_mask = input_dict[“obs”][“action_mask”]# Compute the predicted action embeddingaction_logits, _ = self.action_embed_model({“obs”: input_dict[“obs”][‘observation’]})# turns probit action mask into logit action maskinf_mask = torch.clamp(torch.log(action_mask), -1e10, FLOAT_MAX)return action_logits + inf_mask, statedef value_function(self):return self.action_embed_model.value_function()"
},
{
"code": null,
"e": 11867,
"s": 11772,
"text": "Rendering in Leduc Hold’em functions similarly to that of Pistonball, using this code snippet:"
},
{
"code": null,
"e": 14243,
"s": 11867,
"text": "import rayimport pickle5 as picklefrom ray.tune.registry import register_envfrom ray.rllib.agents.dqn import DQNTrainerfrom pettingzoo.classic import leduc_holdem_v4import supersuit as ssfrom ray.rllib.env.wrappers.pettingzoo_env import PettingZooEnvimport PILfrom ray.rllib.models import ModelCatalogimport numpy as npimport osfrom ray.rllib.agents.registry import get_agent_classfrom copy import deepcopyimport argparsefrom pathlib import Pathfrom rllib_leduc_holdem import TorchMaskedActionsos.environ[“SDL_VIDEODRIVER”] = “dummy”parser = argparse.ArgumentParser(description=’Render pretrained policy loaded from checkpoint’)parser.add_argument(“checkpoint_path”, help=”Path to the checkpoint. This path will likely be something like this: `~/ray_results/pistonball_v4/PPO/PPO_pistonball_v4_660ce_00000_0_2021–06–11_12–30–57/checkpoint_000050/checkpoint-50`”)args = parser.parse_args()checkpoint_path = os.path.expanduser(args.checkpoint_path)params_path = Path(checkpoint_path).parent.parent/”params.pkl”alg_name = “DQN”ModelCatalog.register_custom_model(“pa_model”, TorchMaskedActions)# function that outputs the environment you wish to register.def env_creator():env = leduc_holdem_v4.env()return envnum_cpus = 1config = deepcopy(get_agent_class(alg_name)._default_config)register_env(“leduc_holdem”,lambda config: PettingZooEnv(env_creator()))env = (env_creator())# obs_space = env.observation_space# print(obs_space)# act_space = test_env.action_spacewith open(params_path, “rb”) as f:config = pickle.load(f)# num_workers not needed since we are not trainingdel config[‘num_workers’]del config[‘num_gpus’]ray.init(num_cpus=8, num_gpus=0)DQNAgent = DQNTrainer(env=”leduc_holdem”, config=config)DQNAgent.restore(checkpoint_path)reward_sums = {a:0 for a in env.possible_agents}i = 0env.reset()for agent in env.agent_iter():observation, reward, done, info = env.last()obs = observation[‘observation’]reward_sums[agent] += rewardif done:action = Noneelse:print(DQNAgent.get_policy(agent))policy = DQNAgent.get_policy(agent)batch_obs = {‘obs’:{‘observation’: np.expand_dims(observation[‘observation’], 0),‘action_mask’: np.expand_dims(observation[‘action_mask’],0)}}batched_action, state_out, info = policy.compute_actions_from_input_dict(batch_obs)single_action = batched_action[0]action = single_actionenv.step(action)i += 1env.render()print(“rewards:”)print(reward_sums)"
}
]
|
JSTL - Core <fmt:message> Tag | The <fmt:message> tag maps key to localized message and performs parametric replacement.
The <fmt:message> tag has the following attributes −
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/fmt" prefix = "fmt" %>
<html>
<head>
<title>JSTL fmt:message Tag</title>
</head>
<body>
<fmt:setLocale value = "en"/>
<fmt:setBundle basename = "com.tutorialspoint.Example" var = "lang"/>
<fmt:message key = "count.one" bundle = "${lang}"/><br/>
<fmt:message key = "count.two" bundle = "${lang}"/><br/>
<fmt:message key = "count.three" bundle = "${lang}"/><br/>
</body>
</html>
You will receive the following result −
One
Two
Three
108 Lectures
11 hours
Chaand Sheikh
517 Lectures
57 hours
Chaand Sheikh
41 Lectures
4.5 hours
Karthikeya T
42 Lectures
5.5 hours
TELCOMA Global
15 Lectures
3 hours
TELCOMA Global
44 Lectures
15 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2328,
"s": 2239,
"text": "The <fmt:message> tag maps key to localized message and performs parametric replacement."
},
{
"code": null,
"e": 2381,
"s": 2328,
"text": "The <fmt:message> tag has the following attributes −"
},
{
"code": null,
"e": 2926,
"s": 2381,
"text": "<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/fmt\" prefix = \"fmt\" %>\n\n<html>\n <head>\n <title>JSTL fmt:message Tag</title>\n </head>\n\n <body>\n <fmt:setLocale value = \"en\"/>\n <fmt:setBundle basename = \"com.tutorialspoint.Example\" var = \"lang\"/>\n\n <fmt:message key = \"count.one\" bundle = \"${lang}\"/><br/>\n <fmt:message key = \"count.two\" bundle = \"${lang}\"/><br/>\n <fmt:message key = \"count.three\" bundle = \"${lang}\"/><br/>\n\n </body>\n</html>"
},
{
"code": null,
"e": 2966,
"s": 2926,
"text": "You will receive the following result −"
},
{
"code": null,
"e": 2983,
"s": 2966,
"text": "One \nTwo \nThree\n"
},
{
"code": null,
"e": 3018,
"s": 2983,
"text": "\n 108 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3033,
"s": 3018,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3068,
"s": 3033,
"text": "\n 517 Lectures \n 57 hours \n"
},
{
"code": null,
"e": 3083,
"s": 3068,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3118,
"s": 3083,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3132,
"s": 3118,
"text": " Karthikeya T"
},
{
"code": null,
"e": 3167,
"s": 3132,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3183,
"s": 3167,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3216,
"s": 3183,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3232,
"s": 3216,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3266,
"s": 3232,
"text": "\n 44 Lectures \n 15 hours \n"
},
{
"code": null,
"e": 3274,
"s": 3266,
"text": " Uplatz"
},
{
"code": null,
"e": 3281,
"s": 3274,
"text": " Print"
},
{
"code": null,
"e": 3292,
"s": 3281,
"text": " Add Notes"
}
]
|
Apache Drill - Querying Data using HBase | HBase is a distributed column-oriented database built on top of the Hadoop file system. It is a part of the Hadoop ecosystem that provides random real-time read/write access to data in the Hadoop File System. One can store the data in HDFS either directly or through HBase. The following steps are used to query HBase data in Apache Drill.
Before moving on to querying HBase data, you must need to install the following −
Java installed version 1.7 or greater
Hadoop
HBase
After successful installation navigate to Apache Drill web console and select the storage menu option as shown in the following screenshot.
Then choose HBase Enable option, after that go to the update option and now you will see the response as shown in the following program.
{
"type": "hbase",
"config": {
"hbase.zookeeper.quorum": "localhost",
"hbase.zookeeper.property.clientPort": "2181"
},
"size.calculator.enabled": false,
"enabled": true
}
Here the config settings “hbase.zookeeper.property.clientPort” : “2181” indicates ZooKeeper port id. In the embedded mode, it will automatically assign it to the ZooKeeper, but in the distributed mode, you must specify the ZooKeeper port id’s separately. Now, HBase plugin is enabled in Apache Drill.
After enabling the plugin, first start your Hadoop server then start HBase.
After Hadoop and HBase has been started, you can start the HBase interactive shell using “hbase shell” command as shown in the following query.
/bin/hbase shell
Then you will see the response as shown in the following program.
hbase(main):001:0>
To query HBase, you should complete the following steps −
Pipe the following commands to the HBase shell to create a “customer” table.
hbase(main):001:0> create 'customers','account','address'
Create a simple text file named “hbase-customers.txt” as shown in the following program.
put 'customers','Alice','account:name','Alice'
put 'customers','Alice','address:street','123 Ballmer Av'
put 'customers','Alice','address:zipcode','12345'
put 'customers','Alice','address:state','CA'
put 'customers','Bob','account:name','Bob'
put 'customers','Bob','address:street','1 Infinite Loop'
put 'customers','Bob','address:zipcode','12345'
put 'customers','Bob','address:state','CA'
put 'customers','Frank','account:name','Frank'
put 'customers','Frank','address:street','435 Walker Ct'
put 'customers','Frank','address:zipcode','12345'
put 'customers','Frank','address:state','CA'
put 'customers','Mary','account:name','Mary'
put 'customers','Mary','address:street','56 Southern Pkwy'
put 'customers','Mary','address:zipcode','12345'
put 'customers','Mary','address:state','CA'
Now, issue the following command in hbase shell to load the data into a table.
hbase(main):001:0> cat ../drill_sample/hbase/hbase-customers.txt | bin/hbase shell
Now switch to Apache Drill shell and issue the following command.
0: jdbc:drill:zk = local> select * from hbase.customers;
+------------+---------------------+---------------------------------------------------------------------------+
| row_key | account | address |
+------------+---------------------+---------------------------------------------------------------------------+
| 416C696365 | {"name":"QWxpY2U="} | {"state":"Q0E=","street":"MTIzIEJhbGxtZXIgQXY=","zipcode":"MTIzNDU="} |
| 426F62 | {"name":"Qm9i"} | {"state":"Q0E=","street":"MSBJbmZpbml0ZSBMb29w","zipcode":"MTIzNDU="} |
| 4672616E6B | {"name":"RnJhbms="} | {"state":"Q0E=","street":"NDM1IFdhbGtlciBDdA==","zipcode":"MTIzNDU="} |
| 4D617279 | {"name":"TWFyeQ=="} | {"state":"Q0E=","street":"NTYgU291dGhlcm4gUGt3eQ==","zipcode":"MTIzNDU="} |
+------------+---------------------+---------------------------------------------------------------------------+
The output will be 4 rows selected in 1.211 seconds.
Apache Drill fetches the HBase data as a binary format, which we can convert into readable data using CONVERT_FROM function available in drill. Check and use the following query to get proper data from drill.
0: jdbc:drill:zk = local> SELECT CONVERT_FROM(row_key, 'UTF8') AS customer_id,
. . . . . . . . . . . > CONVERT_FROM(customers.account.name, 'UTF8') AS customers_name,
. . . . . . . . . . . > CONVERT_FROM(customers.address.state, 'UTF8') AS customers_state,
. . . . . . . . . . . > CONVERT_FROM(customers.address.street, 'UTF8') AS customers_street,
. . . . . . . . . . . > CONVERT_FROM(customers.address.zipcode, 'UTF8') AS customers_zipcode
. . . . . . . . . . . > FROM hbase.customers;
+--------------+----------------+-----------------+------------------+--------------------+
| customer_id | customers_name | customers_state | customers_street | customers_zipcode |
+--------------+----------------+-----------------+------------------+--------------------+
| Alice | Alice | CA | 123 Ballmer Av | 12345 |
| Bob | Bob | CA | 1 Infinite Loop | 12345 |
| Frank | Frank | CA | 435 Walker Ct | 12345 |
| Mary | Mary | CA | 56 Southern Pkwy | 12345 |
+--------------+----------------+-----------------+------------------+--------------------+
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2409,
"s": 2069,
"text": "HBase is a distributed column-oriented database built on top of the Hadoop file system. It is a part of the Hadoop ecosystem that provides random real-time read/write access to data in the Hadoop File System. One can store the data in HDFS either directly or through HBase. The following steps are used to query HBase data in Apache Drill."
},
{
"code": null,
"e": 2491,
"s": 2409,
"text": "Before moving on to querying HBase data, you must need to install the following −"
},
{
"code": null,
"e": 2529,
"s": 2491,
"text": "Java installed version 1.7 or greater"
},
{
"code": null,
"e": 2536,
"s": 2529,
"text": "Hadoop"
},
{
"code": null,
"e": 2542,
"s": 2536,
"text": "HBase"
},
{
"code": null,
"e": 2682,
"s": 2542,
"text": "After successful installation navigate to Apache Drill web console and select the storage menu option as shown in the following screenshot."
},
{
"code": null,
"e": 2819,
"s": 2682,
"text": "Then choose HBase Enable option, after that go to the update option and now you will see the response as shown in the following program."
},
{
"code": null,
"e": 3018,
"s": 2819,
"text": "{\n \"type\": \"hbase\",\n \"config\": {\n \"hbase.zookeeper.quorum\": \"localhost\",\n \"hbase.zookeeper.property.clientPort\": \"2181\"\n },\n \"size.calculator.enabled\": false,\n \"enabled\": true\n}\n"
},
{
"code": null,
"e": 3319,
"s": 3018,
"text": "Here the config settings “hbase.zookeeper.property.clientPort” : “2181” indicates ZooKeeper port id. In the embedded mode, it will automatically assign it to the ZooKeeper, but in the distributed mode, you must specify the ZooKeeper port id’s separately. Now, HBase plugin is enabled in Apache Drill."
},
{
"code": null,
"e": 3395,
"s": 3319,
"text": "After enabling the plugin, first start your Hadoop server then start HBase."
},
{
"code": null,
"e": 3539,
"s": 3395,
"text": "After Hadoop and HBase has been started, you can start the HBase interactive shell using “hbase shell” command as shown in the following query."
},
{
"code": null,
"e": 3556,
"s": 3539,
"text": "/bin/hbase shell"
},
{
"code": null,
"e": 3622,
"s": 3556,
"text": "Then you will see the response as shown in the following program."
},
{
"code": null,
"e": 3642,
"s": 3622,
"text": "hbase(main):001:0>\n"
},
{
"code": null,
"e": 3700,
"s": 3642,
"text": "To query HBase, you should complete the following steps −"
},
{
"code": null,
"e": 3777,
"s": 3700,
"text": "Pipe the following commands to the HBase shell to create a “customer” table."
},
{
"code": null,
"e": 3835,
"s": 3777,
"text": "hbase(main):001:0> create 'customers','account','address'"
},
{
"code": null,
"e": 3924,
"s": 3835,
"text": "Create a simple text file named “hbase-customers.txt” as shown in the following program."
},
{
"code": null,
"e": 4711,
"s": 3924,
"text": "put 'customers','Alice','account:name','Alice'\nput 'customers','Alice','address:street','123 Ballmer Av'\nput 'customers','Alice','address:zipcode','12345'\nput 'customers','Alice','address:state','CA'\nput 'customers','Bob','account:name','Bob'\nput 'customers','Bob','address:street','1 Infinite Loop'\nput 'customers','Bob','address:zipcode','12345'\nput 'customers','Bob','address:state','CA'\nput 'customers','Frank','account:name','Frank'\nput 'customers','Frank','address:street','435 Walker Ct'\nput 'customers','Frank','address:zipcode','12345'\nput 'customers','Frank','address:state','CA'\nput 'customers','Mary','account:name','Mary'\nput 'customers','Mary','address:street','56 Southern Pkwy'\nput 'customers','Mary','address:zipcode','12345'\nput 'customers','Mary','address:state','CA'"
},
{
"code": null,
"e": 4790,
"s": 4711,
"text": "Now, issue the following command in hbase shell to load the data into a table."
},
{
"code": null,
"e": 4873,
"s": 4790,
"text": "hbase(main):001:0> cat ../drill_sample/hbase/hbase-customers.txt | bin/hbase shell"
},
{
"code": null,
"e": 4939,
"s": 4873,
"text": "Now switch to Apache Drill shell and issue the following command."
},
{
"code": null,
"e": 4996,
"s": 4939,
"text": "0: jdbc:drill:zk = local> select * from hbase.customers;"
},
{
"code": null,
"e": 5901,
"s": 4996,
"text": "+------------+---------------------+---------------------------------------------------------------------------+\n| row_key | account | address |\n+------------+---------------------+---------------------------------------------------------------------------+\n| 416C696365 | {\"name\":\"QWxpY2U=\"} | {\"state\":\"Q0E=\",\"street\":\"MTIzIEJhbGxtZXIgQXY=\",\"zipcode\":\"MTIzNDU=\"} |\n| 426F62 | {\"name\":\"Qm9i\"} | {\"state\":\"Q0E=\",\"street\":\"MSBJbmZpbml0ZSBMb29w\",\"zipcode\":\"MTIzNDU=\"} |\n| 4672616E6B | {\"name\":\"RnJhbms=\"} | {\"state\":\"Q0E=\",\"street\":\"NDM1IFdhbGtlciBDdA==\",\"zipcode\":\"MTIzNDU=\"} |\n| 4D617279 | {\"name\":\"TWFyeQ==\"} | {\"state\":\"Q0E=\",\"street\":\"NTYgU291dGhlcm4gUGt3eQ==\",\"zipcode\":\"MTIzNDU=\"} |\n+------------+---------------------+---------------------------------------------------------------------------+\n"
},
{
"code": null,
"e": 5954,
"s": 5901,
"text": "The output will be 4 rows selected in 1.211 seconds."
},
{
"code": null,
"e": 6163,
"s": 5954,
"text": "Apache Drill fetches the HBase data as a binary format, which we can convert into readable data using CONVERT_FROM function available in drill. Check and use the following query to get proper data from drill."
},
{
"code": null,
"e": 6651,
"s": 6163,
"text": "0: jdbc:drill:zk = local> SELECT CONVERT_FROM(row_key, 'UTF8') AS customer_id,\n. . . . . . . . . . . > CONVERT_FROM(customers.account.name, 'UTF8') AS customers_name,\n. . . . . . . . . . . > CONVERT_FROM(customers.address.state, 'UTF8') AS customers_state,\n. . . . . . . . . . . > CONVERT_FROM(customers.address.street, 'UTF8') AS customers_street,\n. . . . . . . . . . . > CONVERT_FROM(customers.address.zipcode, 'UTF8') AS customers_zipcode\n. . . . . . . . . . . > FROM hbase.customers;"
},
{
"code": null,
"e": 7388,
"s": 6651,
"text": "+--------------+----------------+-----------------+------------------+--------------------+\n| customer_id | customers_name | customers_state | customers_street | customers_zipcode |\n+--------------+----------------+-----------------+------------------+--------------------+\n| Alice | Alice | CA | 123 Ballmer Av | 12345 |\n| Bob | Bob | CA | 1 Infinite Loop | 12345 |\n| Frank | Frank | CA | 435 Walker Ct | 12345 |\n| Mary | Mary | CA | 56 Southern Pkwy | 12345 |\n+--------------+----------------+-----------------+------------------+--------------------+\n"
},
{
"code": null,
"e": 7423,
"s": 7388,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7442,
"s": 7423,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7477,
"s": 7442,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7498,
"s": 7477,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 7531,
"s": 7498,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7544,
"s": 7531,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 7579,
"s": 7544,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7597,
"s": 7579,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7630,
"s": 7597,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7648,
"s": 7630,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7681,
"s": 7648,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7699,
"s": 7681,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 7706,
"s": 7699,
"text": " Print"
},
{
"code": null,
"e": 7717,
"s": 7706,
"text": " Add Notes"
}
]
|
C++ Program for Topological Sorting - GeeksforGeeks | 06 Dec, 2018
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.
For example, a topological sorting of the following graph is “5 4 2 3 1 0”. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is “4 5 2 3 1 0”. The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no in-coming edges).
// A C++ program to print topological sorting of a DAG#include <iostream>#include <list>#include <stack>using namespace std; // Class to represent a graphclass Graph { int V; // No. of vertices' // Pointer to an array containing adjacency listsList list<int>* adj; // A function used by topologicalSort void topologicalSortUtil(int v, bool visited[], stack<int>& Stack); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints a Topological Sort of the complete graph void topologicalSort();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // A recursive function used by topologicalSortvoid Graph::topologicalSortUtil(int v, bool visited[], stack<int>& Stack){ // Mark the current node as visited. visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) topologicalSortUtil(*i, visited, Stack); // Push current vertex to stack which stores result Stack.push(v);} // The function to do Topological Sort. It uses recursive// topologicalSortUtil()void Graph::topologicalSort(){ stack<int> Stack; // Mark all the vertices as not visited bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to store Topological // Sort starting from all vertices one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, Stack); // Print contents of stack while (Stack.empty() == false) { cout << Stack.top() << " "; Stack.pop(); }} // Driver program to test above functionsint main(){ // Create a graph given in the above diagram Graph g(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); cout << "Following is a Topological Sort of the given graph n"; g.topologicalSort(); return 0;}
Following is a Topological Sort of the given graph n5 4 2 3 1 0
Please refer complete article on Topological Sorting for more details!
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
isdigit() function in C/C++ with Examples
Why it is important to write "using namespace std" in C++ program?
Different ways to print elements of vector
Program to count Number of connected components in an undirected graph
Setting up Sublime Text for C++ Competitive Programming Environment | [
{
"code": null,
"e": 24554,
"s": 24526,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 24794,
"s": 24554,
"text": "Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG."
},
{
"code": null,
"e": 25127,
"s": 24794,
"text": "For example, a topological sorting of the following graph is “5 4 2 3 1 0”. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is “4 5 2 3 1 0”. The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no in-coming edges)."
},
{
"code": "// A C++ program to print topological sorting of a DAG#include <iostream>#include <list>#include <stack>using namespace std; // Class to represent a graphclass Graph { int V; // No. of vertices' // Pointer to an array containing adjacency listsList list<int>* adj; // A function used by topologicalSort void topologicalSortUtil(int v, bool visited[], stack<int>& Stack); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints a Topological Sort of the complete graph void topologicalSort();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // A recursive function used by topologicalSortvoid Graph::topologicalSortUtil(int v, bool visited[], stack<int>& Stack){ // Mark the current node as visited. visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) topologicalSortUtil(*i, visited, Stack); // Push current vertex to stack which stores result Stack.push(v);} // The function to do Topological Sort. It uses recursive// topologicalSortUtil()void Graph::topologicalSort(){ stack<int> Stack; // Mark all the vertices as not visited bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to store Topological // Sort starting from all vertices one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, Stack); // Print contents of stack while (Stack.empty() == false) { cout << Stack.top() << \" \"; Stack.pop(); }} // Driver program to test above functionsint main(){ // Create a graph given in the above diagram Graph g(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); cout << \"Following is a Topological Sort of the given graph n\"; g.topologicalSort(); return 0;}",
"e": 27342,
"s": 25127,
"text": null
},
{
"code": null,
"e": 27407,
"s": 27342,
"text": "Following is a Topological Sort of the given graph n5 4 2 3 1 0\n"
},
{
"code": null,
"e": 27478,
"s": 27407,
"text": "Please refer complete article on Topological Sorting for more details!"
},
{
"code": null,
"e": 27491,
"s": 27478,
"text": "C++ Programs"
},
{
"code": null,
"e": 27589,
"s": 27491,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27630,
"s": 27589,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 27689,
"s": 27630,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 27710,
"s": 27689,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 27722,
"s": 27710,
"text": "cout in C++"
},
{
"code": null,
"e": 27743,
"s": 27722,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 27785,
"s": 27743,
"text": "isdigit() function in C/C++ with Examples"
},
{
"code": null,
"e": 27852,
"s": 27785,
"text": "Why it is important to write \"using namespace std\" in C++ program?"
},
{
"code": null,
"e": 27895,
"s": 27852,
"text": "Different ways to print elements of vector"
},
{
"code": null,
"e": 27966,
"s": 27895,
"text": "Program to count Number of connected components in an undirected graph"
}
]
|
How to display full-screen mode on Tkinter? | Tkinter displays the application window by its default size. However, we can display a full-screen window by using attributes('fullscreen', True) method. The method is generally used for assigning a tkinter window with properties like transparentcolor, alpha, disabled, fullscreen, toolwindow, and topmost.
#Import the tkinter library
from tkinter import *
#Create an instance of tkinter frame
win = Tk()
#Set the geometry
win.geometry("650x250")
#Add a text label and add the font property to it
label= Label(win, text= "Hello World!", font=('Times New Roman bold',20))
label.pack(padx=10, pady=10)
#Create a fullscreen window
win.attributes('-fullscreen', True)
win.mainloop()
Running the above code will display a full-screen window that can be closed by pressing the Alt+ F4 key. | [
{
"code": null,
"e": 1369,
"s": 1062,
"text": "Tkinter displays the application window by its default size. However, we can display a full-screen window by using attributes('fullscreen', True) method. The method is generally used for assigning a tkinter window with properties like transparentcolor, alpha, disabled, fullscreen, toolwindow, and topmost."
},
{
"code": null,
"e": 1746,
"s": 1369,
"text": "#Import the tkinter library\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin = Tk()\n\n#Set the geometry\nwin.geometry(\"650x250\")\n\n#Add a text label and add the font property to it\nlabel= Label(win, text= \"Hello World!\", font=('Times New Roman bold',20))\nlabel.pack(padx=10, pady=10)\n\n#Create a fullscreen window\nwin.attributes('-fullscreen', True)\n\nwin.mainloop()"
},
{
"code": null,
"e": 1851,
"s": 1746,
"text": "Running the above code will display a full-screen window that can be closed by pressing the Alt+ F4 key."
}
]
|
How to Deal with Imbalanced Data. A Step-by-Step Guide to handling... | by Numal Jayawardena | Towards Data Science | A dataset with imbalanced classes is a common data science problem as well as a common interview question. In this article, I provide a step-by-step guideline to improve your model and handle the imbalanced data well. The most common areas where you see imbalanced data are classification problems such as spam filtering, fraud detection and medical diagnosis.
Almost every dataset has an unequal representation of classes. This isn’t a problem as long as the difference is small. However, when one or more classes are very rare, many models don’t work too well at identifying the minority classes. In this article, I’ll assume a two-class problem (one majority class and one minority class) for simplicity, but most of these techniques work for multiple datasets as well.
Usually, we look at accuracy on the validation split to determine whether our model is performing well. However, when the data is imbalanced, accuracy can be misleading. For example, say you have a dataset in which 92% of the data is labelled as ‘Not Fraud’ and the remaining 8% are cases of ‘Fraud’. The data is clearly imbalanced. Now say our model ends up as classifying everything it sees as ‘Not Fraud’. If we look at the accuracy, however, it’s a magnificent 92%. But the bank still cares about those ‘Fraud’ cases. That’s what it loses money on. So how do we improve our model?
The following are a series of steps and decisions you can carry out in order to overcome the issues with an imbalanced dataset.
You might say, “Well random guy on the internet, if I could collect more data, I wouldn’t be reading this, now would I? ColLECt MorE dAta”.
But hear me out. Take a step back and consider things such as:
Was the data you received filtered on conditions that might have resulted in the minor class observations being dropped.
How many years of history do you have, if you go back a year or two do you get more instances of the minor class with the data still remaining reasonable.
If it is customer data, can we use customers that are no longer subscribers of our service, without it impacting the parameters we are trying to solve. Maybe using these previous customer records, along with a “current customer? (Y/N)” boolean variable will help.
Can you combine your minority classes into a single class. For example, if you are classifying different types of anomalies in a person’s heartbeat, instead of trying to classify each type of anomaly, will the model still be useful if we combine them all into a single ‘Abnormal Heartbeat’ class.
Just some ideas and a reminder to always think about different possibilities.
Since, as explained above, accuracy isn’t a good measure when working with imbalanced datasets, let’s consider more appropriate measures.
Based on the confusion matrix we can measure the following:
Precision: True Positives / All Predicted Positives = TP / (TP+FP). Precision is a measure of a classifier’s exactness. Low precision indicates a high number of false positives.
Recall: True Positives / All actual positives = TP / (TP + FN). Recall is a measure of a classifier’s completeness. It is also the same as Sensitivity or the True positive rate. Low recall indicates a high number of false negatives.
F1 score: 2TP/(2TP + FP + FN) A weighted average of precision and recall. If we wanted a balance between precision and recall then we’d look at F1 score.
See this wikipedia page for a list of the performance metric formulas.
We can also take a look at:
Sensitivity/Specificity from ROC Curve: The Sensitivity is basically the same as recall and tells us the True Positive Rate.
Kappa (or Cohen’s kappa): Classification accuracy normalized by the imbalance of the classes in the data.
In these sorts of scenarios we want to be looking for high recall/sensitivity and f1 scores instead of accuracy to see how well our models do in predicting the minor class.
Jason Brownlee has more information on selecting different performance measures here.
As with most Data science problems, it’s always good practice to try a few different suitable algorithms on the data.
There are two main types of algorithms that seem to be effective with imbalanced dataset problems.
Decision trees seem to perform pretty well with imbalanced datasets. Since they work by coming up with conditions/rules at each stage of splitting, they end up taking both classes into consideration.
We can try a few different decision tree algorithms like Random Forest, CART, C4.5.
Penalized learning models (Cost-sensitive training) impose an additional cost on the model for making classification mistakes on the minority class during training. This forces the model to pay more attention to the minority class observations.
If it’s just the 2 classes, the majority class and the minority, then you could consider using an anomaly detection model instead of a classification model. What these anomaly models try to do is to create a profile for the majority class. Any observation that does not fit this profile is considered an anomaly or outlier, in our case an observation from the minority class. These sorts of models are used in situations such as fraud detection.
This step can be done while trying the different models approach mentioned above. The different types of resampling are as follows:
Under-sampling the majority classOversampling the minority class
Under-sampling the majority class
Oversampling the minority class
Under-sampling randomly removes observations of the majority class. This reduces the number of majority class observations used in the training set and as a result balances the number of observations of the two classes better. This is suitable when you have a lots of observations in your dataset (>10K observations). The risk is you are losing information and so may lead to underfitting.
Scikit-learn provides a ‘resample’ method which we can use for undersampling. The imbalanced-learn package also provides more advanced functionality. A Python code sample is shown below:
Since many of the observations of the majority class have been dropped, the resulting dataset is now much smaller. The ratio between the two classes is now 1:1.
Note: we don’t necessarily have to use a 1:1 ratio, we can just reduce the number of majority class observations to any reasonable ratio using this method.
Oversampling randomly duplicates observations from the minority class in order to make its signal stronger. The simplest form of oversampling is sampling with replacement. Oversampling is suitable when you don’t have a lots of observations in your dataset (<10K observations). The risk is if you duplicate too many observations, well then you are overfitting.
We can use the same scikit-learn ‘resample’ method but with different parameters. A code sample is shown below:
This time we sample with replacement to have more representation in the final training set. But as I mentioned this could lead to overfitting. So, how can we do things better to avoid overfitting?
In order to reduce overfitting during upsampling, we can try creating synthetic samples.
A popular algorithm is SMOTE (Synthetic Minority Over Sampling Technique). Instead of using copies of observations to oversample, SMOTE varies attributes of the observations to create new synthetic samples.
You can find an example of SMOTE here.
Similar to SMOTE, if your data is things like audio or images, then you can perform transformations to the original files to create new samples as well.
As with most things in data science and machine learning algorithms, there is no definitive right approach that works every time. Depending on the nature of your dataset, distribution of classes, predictors and model, some of the above-mentioned methods will work better than the others. It is up to you to figure out the best combination.
A few pointers to keep in mind are:
Always do the train/test split before creating synthetic/augmented samples. You want to validate and test your model on original data observations
Use the same metrics for comparison — every time you try something new, remember to compare them right. Don’t look at only accuracy for one model and sensitivity for another.
In addition to these steps, don’t forget that you still have to do things such as data cleaning, feature selection and hyper-parameter tuning.
Hope this helped!
if_you_like(this_article): please(CLAPS) # Do this :)else: initiate_sad_author() # Don't do this :(# Thanks :)
Boyle, Tara. “Methods for Dealing with Imbalanced Data.” Medium. February 04, 2019. Accessed June 21, 2020. https://towardsdatascience.com/methods-for-dealing-with-imbalanced-data-5b761be45a18.
Brownlee, Jason. “8 Tactics to Combat Imbalanced Classes in Your Machine Learning Dataset.” Machine Learning Mastery. January 14, 2020. Accessed June 21, 2020. https://machinelearningmastery.com/tactics-to-combat-imbalanced-classes-in-your-machine-learning-dataset/.
“How to Handle Imbalanced Classes in Machine Learning.” May 23, 2020. https://elitedatascience.com/imbalanced-classes. | [
{
"code": null,
"e": 533,
"s": 172,
"text": "A dataset with imbalanced classes is a common data science problem as well as a common interview question. In this article, I provide a step-by-step guideline to improve your model and handle the imbalanced data well. The most common areas where you see imbalanced data are classification problems such as spam filtering, fraud detection and medical diagnosis."
},
{
"code": null,
"e": 945,
"s": 533,
"text": "Almost every dataset has an unequal representation of classes. This isn’t a problem as long as the difference is small. However, when one or more classes are very rare, many models don’t work too well at identifying the minority classes. In this article, I’ll assume a two-class problem (one majority class and one minority class) for simplicity, but most of these techniques work for multiple datasets as well."
},
{
"code": null,
"e": 1530,
"s": 945,
"text": "Usually, we look at accuracy on the validation split to determine whether our model is performing well. However, when the data is imbalanced, accuracy can be misleading. For example, say you have a dataset in which 92% of the data is labelled as ‘Not Fraud’ and the remaining 8% are cases of ‘Fraud’. The data is clearly imbalanced. Now say our model ends up as classifying everything it sees as ‘Not Fraud’. If we look at the accuracy, however, it’s a magnificent 92%. But the bank still cares about those ‘Fraud’ cases. That’s what it loses money on. So how do we improve our model?"
},
{
"code": null,
"e": 1658,
"s": 1530,
"text": "The following are a series of steps and decisions you can carry out in order to overcome the issues with an imbalanced dataset."
},
{
"code": null,
"e": 1798,
"s": 1658,
"text": "You might say, “Well random guy on the internet, if I could collect more data, I wouldn’t be reading this, now would I? ColLECt MorE dAta”."
},
{
"code": null,
"e": 1861,
"s": 1798,
"text": "But hear me out. Take a step back and consider things such as:"
},
{
"code": null,
"e": 1982,
"s": 1861,
"text": "Was the data you received filtered on conditions that might have resulted in the minor class observations being dropped."
},
{
"code": null,
"e": 2137,
"s": 1982,
"text": "How many years of history do you have, if you go back a year or two do you get more instances of the minor class with the data still remaining reasonable."
},
{
"code": null,
"e": 2401,
"s": 2137,
"text": "If it is customer data, can we use customers that are no longer subscribers of our service, without it impacting the parameters we are trying to solve. Maybe using these previous customer records, along with a “current customer? (Y/N)” boolean variable will help."
},
{
"code": null,
"e": 2698,
"s": 2401,
"text": "Can you combine your minority classes into a single class. For example, if you are classifying different types of anomalies in a person’s heartbeat, instead of trying to classify each type of anomaly, will the model still be useful if we combine them all into a single ‘Abnormal Heartbeat’ class."
},
{
"code": null,
"e": 2776,
"s": 2698,
"text": "Just some ideas and a reminder to always think about different possibilities."
},
{
"code": null,
"e": 2914,
"s": 2776,
"text": "Since, as explained above, accuracy isn’t a good measure when working with imbalanced datasets, let’s consider more appropriate measures."
},
{
"code": null,
"e": 2974,
"s": 2914,
"text": "Based on the confusion matrix we can measure the following:"
},
{
"code": null,
"e": 3152,
"s": 2974,
"text": "Precision: True Positives / All Predicted Positives = TP / (TP+FP). Precision is a measure of a classifier’s exactness. Low precision indicates a high number of false positives."
},
{
"code": null,
"e": 3385,
"s": 3152,
"text": "Recall: True Positives / All actual positives = TP / (TP + FN). Recall is a measure of a classifier’s completeness. It is also the same as Sensitivity or the True positive rate. Low recall indicates a high number of false negatives."
},
{
"code": null,
"e": 3539,
"s": 3385,
"text": "F1 score: 2TP/(2TP + FP + FN) A weighted average of precision and recall. If we wanted a balance between precision and recall then we’d look at F1 score."
},
{
"code": null,
"e": 3610,
"s": 3539,
"text": "See this wikipedia page for a list of the performance metric formulas."
},
{
"code": null,
"e": 3638,
"s": 3610,
"text": "We can also take a look at:"
},
{
"code": null,
"e": 3763,
"s": 3638,
"text": "Sensitivity/Specificity from ROC Curve: The Sensitivity is basically the same as recall and tells us the True Positive Rate."
},
{
"code": null,
"e": 3869,
"s": 3763,
"text": "Kappa (or Cohen’s kappa): Classification accuracy normalized by the imbalance of the classes in the data."
},
{
"code": null,
"e": 4042,
"s": 3869,
"text": "In these sorts of scenarios we want to be looking for high recall/sensitivity and f1 scores instead of accuracy to see how well our models do in predicting the minor class."
},
{
"code": null,
"e": 4128,
"s": 4042,
"text": "Jason Brownlee has more information on selecting different performance measures here."
},
{
"code": null,
"e": 4246,
"s": 4128,
"text": "As with most Data science problems, it’s always good practice to try a few different suitable algorithms on the data."
},
{
"code": null,
"e": 4345,
"s": 4246,
"text": "There are two main types of algorithms that seem to be effective with imbalanced dataset problems."
},
{
"code": null,
"e": 4545,
"s": 4345,
"text": "Decision trees seem to perform pretty well with imbalanced datasets. Since they work by coming up with conditions/rules at each stage of splitting, they end up taking both classes into consideration."
},
{
"code": null,
"e": 4629,
"s": 4545,
"text": "We can try a few different decision tree algorithms like Random Forest, CART, C4.5."
},
{
"code": null,
"e": 4874,
"s": 4629,
"text": "Penalized learning models (Cost-sensitive training) impose an additional cost on the model for making classification mistakes on the minority class during training. This forces the model to pay more attention to the minority class observations."
},
{
"code": null,
"e": 5320,
"s": 4874,
"text": "If it’s just the 2 classes, the majority class and the minority, then you could consider using an anomaly detection model instead of a classification model. What these anomaly models try to do is to create a profile for the majority class. Any observation that does not fit this profile is considered an anomaly or outlier, in our case an observation from the minority class. These sorts of models are used in situations such as fraud detection."
},
{
"code": null,
"e": 5452,
"s": 5320,
"text": "This step can be done while trying the different models approach mentioned above. The different types of resampling are as follows:"
},
{
"code": null,
"e": 5517,
"s": 5452,
"text": "Under-sampling the majority classOversampling the minority class"
},
{
"code": null,
"e": 5551,
"s": 5517,
"text": "Under-sampling the majority class"
},
{
"code": null,
"e": 5583,
"s": 5551,
"text": "Oversampling the minority class"
},
{
"code": null,
"e": 5973,
"s": 5583,
"text": "Under-sampling randomly removes observations of the majority class. This reduces the number of majority class observations used in the training set and as a result balances the number of observations of the two classes better. This is suitable when you have a lots of observations in your dataset (>10K observations). The risk is you are losing information and so may lead to underfitting."
},
{
"code": null,
"e": 6160,
"s": 5973,
"text": "Scikit-learn provides a ‘resample’ method which we can use for undersampling. The imbalanced-learn package also provides more advanced functionality. A Python code sample is shown below:"
},
{
"code": null,
"e": 6321,
"s": 6160,
"text": "Since many of the observations of the majority class have been dropped, the resulting dataset is now much smaller. The ratio between the two classes is now 1:1."
},
{
"code": null,
"e": 6477,
"s": 6321,
"text": "Note: we don’t necessarily have to use a 1:1 ratio, we can just reduce the number of majority class observations to any reasonable ratio using this method."
},
{
"code": null,
"e": 6837,
"s": 6477,
"text": "Oversampling randomly duplicates observations from the minority class in order to make its signal stronger. The simplest form of oversampling is sampling with replacement. Oversampling is suitable when you don’t have a lots of observations in your dataset (<10K observations). The risk is if you duplicate too many observations, well then you are overfitting."
},
{
"code": null,
"e": 6949,
"s": 6837,
"text": "We can use the same scikit-learn ‘resample’ method but with different parameters. A code sample is shown below:"
},
{
"code": null,
"e": 7146,
"s": 6949,
"text": "This time we sample with replacement to have more representation in the final training set. But as I mentioned this could lead to overfitting. So, how can we do things better to avoid overfitting?"
},
{
"code": null,
"e": 7235,
"s": 7146,
"text": "In order to reduce overfitting during upsampling, we can try creating synthetic samples."
},
{
"code": null,
"e": 7442,
"s": 7235,
"text": "A popular algorithm is SMOTE (Synthetic Minority Over Sampling Technique). Instead of using copies of observations to oversample, SMOTE varies attributes of the observations to create new synthetic samples."
},
{
"code": null,
"e": 7481,
"s": 7442,
"text": "You can find an example of SMOTE here."
},
{
"code": null,
"e": 7634,
"s": 7481,
"text": "Similar to SMOTE, if your data is things like audio or images, then you can perform transformations to the original files to create new samples as well."
},
{
"code": null,
"e": 7974,
"s": 7634,
"text": "As with most things in data science and machine learning algorithms, there is no definitive right approach that works every time. Depending on the nature of your dataset, distribution of classes, predictors and model, some of the above-mentioned methods will work better than the others. It is up to you to figure out the best combination."
},
{
"code": null,
"e": 8010,
"s": 7974,
"text": "A few pointers to keep in mind are:"
},
{
"code": null,
"e": 8157,
"s": 8010,
"text": "Always do the train/test split before creating synthetic/augmented samples. You want to validate and test your model on original data observations"
},
{
"code": null,
"e": 8332,
"s": 8157,
"text": "Use the same metrics for comparison — every time you try something new, remember to compare them right. Don’t look at only accuracy for one model and sensitivity for another."
},
{
"code": null,
"e": 8475,
"s": 8332,
"text": "In addition to these steps, don’t forget that you still have to do things such as data cleaning, feature selection and hyper-parameter tuning."
},
{
"code": null,
"e": 8493,
"s": 8475,
"text": "Hope this helped!"
},
{
"code": null,
"e": 8612,
"s": 8493,
"text": "if_you_like(this_article): please(CLAPS) # Do this :)else: initiate_sad_author() # Don't do this :(# Thanks :)"
},
{
"code": null,
"e": 8806,
"s": 8612,
"text": "Boyle, Tara. “Methods for Dealing with Imbalanced Data.” Medium. February 04, 2019. Accessed June 21, 2020. https://towardsdatascience.com/methods-for-dealing-with-imbalanced-data-5b761be45a18."
},
{
"code": null,
"e": 9073,
"s": 8806,
"text": "Brownlee, Jason. “8 Tactics to Combat Imbalanced Classes in Your Machine Learning Dataset.” Machine Learning Mastery. January 14, 2020. Accessed June 21, 2020. https://machinelearningmastery.com/tactics-to-combat-imbalanced-classes-in-your-machine-learning-dataset/."
}
]
|
What can cause a Cannot find symbol error in java? | Whenever you need to use external classes/interfaces (either user defined or, built-in) in the current program you need to import those classes in your current program using the import keyword.
But, while importing any class −
If the path of the class/interface you are importing is not available to JVM.
If the path of the class/interface you are importing is not available to JVM.
If the absolute class name you have mentioned at the import statement is not accurate (including packages and class name).
If the absolute class name you have mentioned at the import statement is not accurate (including packages and class name).
If you have imported the class/interface used.
If you have imported the class/interface used.
You will get an exception saying “Cannot find symbol ......”
In the following example we are trying to read a string value representing the name of the user from key-board (System.in). For this we are using the scanner class of the Java.Util Package.
public class ReadingdData {
public static void main(String args[]) {
System.out.println("Enter your name: ");
Scanner sc = new Scanner(System.in);
String name = sc.next();
System.out.println("Hello "+name);
}
}
Since we are using a class named Scanner in our program and haven’t imported it in our program. On executing, this program generates the following compile time error −
ReadingdData.java:6: error: cannot find symbol
Scanner sc = new Scanner(System.in);
^
symbol: class Scanner
location: class ReadingdData
ReadingdData.java:6: error: cannot find symbol
Scanner sc = new Scanner(System.in);
^
symbol: class Scanner
location: class ReadingdData
2 errors
You need to set class path for the JAR file holding the required class interface.
You need to set class path for the JAR file holding the required class interface.
Import the required class from the package using the import keyword. While importing you need to specify the absolute name (including the packages and sub packages) of the required class.
Import the required class from the package using the import keyword. While importing you need to specify the absolute name (including the packages and sub packages) of the required class.
Live Demo
import java.util.Scanner;
public class ReadingdData {
public static void main(String args[]) {
System.out.println("Enter your name: ");
Scanner sc = new Scanner(System.in);
String name = sc.next();
System.out.println("Hello "+name);
}
}
Enter your name:
krishna
Hello krishna | [
{
"code": null,
"e": 1256,
"s": 1062,
"text": "Whenever you need to use external classes/interfaces (either user defined or, built-in) in the current program you need to import those classes in your current program using the import keyword."
},
{
"code": null,
"e": 1289,
"s": 1256,
"text": "But, while importing any class −"
},
{
"code": null,
"e": 1367,
"s": 1289,
"text": "If the path of the class/interface you are importing is not available to JVM."
},
{
"code": null,
"e": 1445,
"s": 1367,
"text": "If the path of the class/interface you are importing is not available to JVM."
},
{
"code": null,
"e": 1568,
"s": 1445,
"text": "If the absolute class name you have mentioned at the import statement is not accurate (including packages and class name)."
},
{
"code": null,
"e": 1691,
"s": 1568,
"text": "If the absolute class name you have mentioned at the import statement is not accurate (including packages and class name)."
},
{
"code": null,
"e": 1738,
"s": 1691,
"text": "If you have imported the class/interface used."
},
{
"code": null,
"e": 1785,
"s": 1738,
"text": "If you have imported the class/interface used."
},
{
"code": null,
"e": 1846,
"s": 1785,
"text": "You will get an exception saying “Cannot find symbol ......”"
},
{
"code": null,
"e": 2036,
"s": 1846,
"text": "In the following example we are trying to read a string value representing the name of the user from key-board (System.in). For this we are using the scanner class of the Java.Util Package."
},
{
"code": null,
"e": 2277,
"s": 2036,
"text": "public class ReadingdData {\n public static void main(String args[]) {\n System.out.println(\"Enter your name: \");\n Scanner sc = new Scanner(System.in);\n String name = sc.next();\n System.out.println(\"Hello \"+name);\n }\n}"
},
{
"code": null,
"e": 2445,
"s": 2277,
"text": "Since we are using a class named Scanner in our program and haven’t imported it in our program. On executing, this program generates the following compile time error −"
},
{
"code": null,
"e": 2764,
"s": 2445,
"text": "ReadingdData.java:6: error: cannot find symbol\n Scanner sc = new Scanner(System.in);\n ^\n symbol: class Scanner\n location: class ReadingdData\nReadingdData.java:6: error: cannot find symbol\n Scanner sc = new Scanner(System.in);\n ^\n symbol: class Scanner\n location: class ReadingdData\n2 errors"
},
{
"code": null,
"e": 2846,
"s": 2764,
"text": "You need to set class path for the JAR file holding the required class interface."
},
{
"code": null,
"e": 2928,
"s": 2846,
"text": "You need to set class path for the JAR file holding the required class interface."
},
{
"code": null,
"e": 3116,
"s": 2928,
"text": "Import the required class from the package using the import keyword. While importing you need to specify the absolute name (including the packages and sub packages) of the required class."
},
{
"code": null,
"e": 3304,
"s": 3116,
"text": "Import the required class from the package using the import keyword. While importing you need to specify the absolute name (including the packages and sub packages) of the required class."
},
{
"code": null,
"e": 3315,
"s": 3304,
"text": " Live Demo"
},
{
"code": null,
"e": 3582,
"s": 3315,
"text": "import java.util.Scanner;\npublic class ReadingdData {\n public static void main(String args[]) {\n System.out.println(\"Enter your name: \");\n Scanner sc = new Scanner(System.in);\n String name = sc.next();\n System.out.println(\"Hello \"+name);\n }\n}"
},
{
"code": null,
"e": 3621,
"s": 3582,
"text": "Enter your name:\nkrishna\nHello krishna"
}
]
|
Simulate Random Walks With Python | Towards Data Science | What is a random walk?
Simply put, a random walk is the process of taking successive steps in a “randomized” fashion w.r.t. the current state. Additional conditions can be then applied to this base description to create a random walk for your specific use case. Brownian motion of particles, stock ticker movement, living cell movement in a substrate are just some of the better known random walks seen in real world.
Here, we simulate a simplified random walk in 1-D, 2-D and 3-D starting at origin and a discrete step size chosen from [-1, 0, 1] with equal probability. Starting points are denoted by + and stop points are denoted by o.
For different applications, these conditions change as needed e.g. the walk starts at a chosen stock price, an initial cell position detected using microscopy etc and step choices are usually probabilistic and depend on additional information from past data, projection assumptions, hypothesis being tested etc.
Setup your Jupyter notebook :
%pylab inlinefrom itertools import cyclefrom mpl_toolkits.mplot3d import Axes3Dcolors = cycle(‘bgrcmykbgrcmykbgrcmykbgrcmyk’)
Random walk in 1-D :
We start at origin ( y=0 ) and choose a step to move for each successive step with equal probability. Starting point is shown in red and end point is shown in black. A cumulative sum is plotted in the plot below which shows path followed by a body in 1D over 10k steps.
# Define parameters for the walkdims = 1step_n = 10000step_set = [-1, 0, 1]origin = np.zeros((1,dims))# Simulate steps in 1Dstep_shape = (step_n,dims)steps = np.random.choice(a=step_set, size=step_shape)path = np.concatenate([origin, steps]).cumsum(0)start = path[:1]stop = path[-1:]# Plot the pathfig = plt.figure(figsize=(8,4),dpi=200)ax = fig.add_subplot(111)ax.scatter(np.arange(step_n+1), path, c=’blue’,alpha=0.25,s=0.05);ax.plot(path,c=’blue’,alpha=0.5,lw=0.5,ls=’ — ‘,);ax.plot(0, start, c=’red’, marker=’+’)ax.plot(step_n, stop, c=’black’, marker=’o’)plt.title(‘1D Random Walk’)plt.tight_layout(pad=0)plt.savefig(‘plots/random_walk_1d.png’,dpi=250);
Random walk in 2-D :
We start at origin (x=0,y=0) and take random steps in each direction giving us 9 possible directions for movement at each step (∆x, ∆y ) ⋲ {-1, 0, 1} :
(-1,-1), (-1,0), (-1,1),(0,-1), (0,0), (0,1),(1,-1), (1,0), (1,1)
A simulation over 10k steps gives us the following path. A particle moving on the surface of a fluid exhibits 2D random walk and shows a trajectory like below.
# Define parameters for the walkdims = 2step_n = 10000step_set = [-1, 0, 1]origin = np.zeros((1,dims))# Simulate steps in 2Dstep_shape = (step_n,dims)steps = np.random.choice(a=step_set, size=step_shape)path = np.concatenate([origin, steps]).cumsum(0)start = path[:1]stop = path[-1:]# Plot the pathfig = plt.figure(figsize=(8,8),dpi=200)ax = fig.add_subplot(111)ax.scatter(path[:,0], path[:,1],c=’blue’,alpha=0.25,s=0.05);ax.plot(path[:,0], path[:,1],c=’blue’,alpha=0.5,lw=0.25,ls=’ — ‘);ax.plot(start[:,0], start[:,1],c=’red’, marker=’+’)ax.plot(stop[:,0], stop[:,1],c=’black’, marker=’o’)plt.title(‘2D Random Walk’)plt.tight_layout(pad=0)plt.savefig(‘plots/random_walk_2d.png’,dpi=250);
Simulate k Random Walks in 2D :
Random Walk in 3-D :
A body moving in a volume is an example of random walk in 3D space. We start at origin (x=0,y=0,z=0) and take steps in arandom fashion chosen from a set of 27 directions (∆x, ∆y, ∆z)⋲ {-1, 0, 1} :
# Define parameters for the walkdims = 3step_n = 1000step_set = [-1, 0, 1]origin = np.zeros((1,dims))# Simulate steps in 3Dstep_shape = (step_n,dims)steps = np.random.choice(a=step_set, size=step_shape)path = np.concatenate([origin, steps]).cumsum(0)start = path[:1]stop = path[-1:]# Plot the pathfig = plt.figure(figsize=(10,10),dpi=200)ax = fig.add_subplot(111, projection=’3d’)ax.grid(False)ax.xaxis.pane.fill = ax.yaxis.pane.fill = ax.zaxis.pane.fill = Falseax.set_xlabel(‘X’)ax.set_ylabel(‘Y’)ax.set_zlabel(‘Z’)ax.scatter3D(path[:,0], path[:,1], path[:,2], c=’blue’, alpha=0.25,s=1)ax.plot3D(path[:,0], path[:,1], path[:,2], c=’blue’, alpha=0.5, lw=0.5)ax.plot3D(start[:,0], start[:,1], start[:,2], c=’red’, marker=’+’)ax.plot3D(stop[:,0], stop[:,1], stop[:,2], c=’black’, marker=’o’)plt.title(‘3D Random Walk’)plt.savefig(‘plots/random_walk_3d.png’,dpi=250);
Simulate k Random Walks in 3D :
Now we simulate multiple random walks in 3D. Each random walk represents motion of a point source starting out at the same time with starting point set at points chosen from (x, y, z) ⋲ [-10, 10].
A few cells/particles moving without any sustained directional force would show a trajectory like this. An interesting aspect of 3 dimensional random walk is that even though the starting points are close together, as time progresses, the objects spread out.
# Define parameters for the walkdims = 3n_runs = 10step_n = 1000step_set = [-1, 0 ,1]runs = np.arange(n_runs)step_shape = (step_n,dims)# Plotfig = plt.figure(figsize=(10,10),dpi=250)ax = fig.add_subplot(111, projection=’3d’)ax.grid(False)ax.xaxis.pane.fill = ax.yaxis.pane.fill = ax.zaxis.pane.fill = Falseax.set_xlabel(‘X’)ax.set_ylabel(‘Y’)ax.set_zlabel(‘Z’) for i, col in zip(runs, colors): # Simulate steps in 3D origin = np.random.randint(low=-10,high=10,size=(1,dims)) steps = np.random.choice(a=step_set, size=step_shape) path = np.concatenate([origin, steps]).cumsum(0) start = path[:1] stop = path[-1:] # Plot the path ax.scatter3D(path[:,0], path[:,1], path[:,2], c=col,alpha=0.15,s=1); ax.plot3D(path[:,0], path[:,1], path[:,2], c=col, alpha=0.25,lw=0.25) ax.plot3D(start[:,0], start[:,1], start[:,2], c=col, marker=’+’) ax.plot3D(stop[:,0], stop[:,1], stop[:,2], c=col, marker=’o’);plt.title(‘3D Random Walk - Multiple runs’)plt.savefig(‘plots/random_walk_3d_multiple_runs.png’,dpi=250);
In this post, we discussed how to simulate a barebones random walk in 1D, 2D and 3D. There are different measures that we can use to do a descriptive analysis (distance, displacement, speed, velocity, angle distribution, indicator counts, confinement ratios etc) for random walks exhibited by a population. We can also simulate and discuss directed/biased random walks where the direction of next step depends on current position either due to some form of existing gradient or a directional force. | [
{
"code": null,
"e": 195,
"s": 172,
"text": "What is a random walk?"
},
{
"code": null,
"e": 590,
"s": 195,
"text": "Simply put, a random walk is the process of taking successive steps in a “randomized” fashion w.r.t. the current state. Additional conditions can be then applied to this base description to create a random walk for your specific use case. Brownian motion of particles, stock ticker movement, living cell movement in a substrate are just some of the better known random walks seen in real world."
},
{
"code": null,
"e": 811,
"s": 590,
"text": "Here, we simulate a simplified random walk in 1-D, 2-D and 3-D starting at origin and a discrete step size chosen from [-1, 0, 1] with equal probability. Starting points are denoted by + and stop points are denoted by o."
},
{
"code": null,
"e": 1123,
"s": 811,
"text": "For different applications, these conditions change as needed e.g. the walk starts at a chosen stock price, an initial cell position detected using microscopy etc and step choices are usually probabilistic and depend on additional information from past data, projection assumptions, hypothesis being tested etc."
},
{
"code": null,
"e": 1153,
"s": 1123,
"text": "Setup your Jupyter notebook :"
},
{
"code": null,
"e": 1279,
"s": 1153,
"text": "%pylab inlinefrom itertools import cyclefrom mpl_toolkits.mplot3d import Axes3Dcolors = cycle(‘bgrcmykbgrcmykbgrcmykbgrcmyk’)"
},
{
"code": null,
"e": 1300,
"s": 1279,
"text": "Random walk in 1-D :"
},
{
"code": null,
"e": 1570,
"s": 1300,
"text": "We start at origin ( y=0 ) and choose a step to move for each successive step with equal probability. Starting point is shown in red and end point is shown in black. A cumulative sum is plotted in the plot below which shows path followed by a body in 1D over 10k steps."
},
{
"code": null,
"e": 2229,
"s": 1570,
"text": "# Define parameters for the walkdims = 1step_n = 10000step_set = [-1, 0, 1]origin = np.zeros((1,dims))# Simulate steps in 1Dstep_shape = (step_n,dims)steps = np.random.choice(a=step_set, size=step_shape)path = np.concatenate([origin, steps]).cumsum(0)start = path[:1]stop = path[-1:]# Plot the pathfig = plt.figure(figsize=(8,4),dpi=200)ax = fig.add_subplot(111)ax.scatter(np.arange(step_n+1), path, c=’blue’,alpha=0.25,s=0.05);ax.plot(path,c=’blue’,alpha=0.5,lw=0.5,ls=’ — ‘,);ax.plot(0, start, c=’red’, marker=’+’)ax.plot(step_n, stop, c=’black’, marker=’o’)plt.title(‘1D Random Walk’)plt.tight_layout(pad=0)plt.savefig(‘plots/random_walk_1d.png’,dpi=250);"
},
{
"code": null,
"e": 2250,
"s": 2229,
"text": "Random walk in 2-D :"
},
{
"code": null,
"e": 2402,
"s": 2250,
"text": "We start at origin (x=0,y=0) and take random steps in each direction giving us 9 possible directions for movement at each step (∆x, ∆y ) ⋲ {-1, 0, 1} :"
},
{
"code": null,
"e": 2468,
"s": 2402,
"text": "(-1,-1), (-1,0), (-1,1),(0,-1), (0,0), (0,1),(1,-1), (1,0), (1,1)"
},
{
"code": null,
"e": 2628,
"s": 2468,
"text": "A simulation over 10k steps gives us the following path. A particle moving on the surface of a fluid exhibits 2D random walk and shows a trajectory like below."
},
{
"code": null,
"e": 3317,
"s": 2628,
"text": "# Define parameters for the walkdims = 2step_n = 10000step_set = [-1, 0, 1]origin = np.zeros((1,dims))# Simulate steps in 2Dstep_shape = (step_n,dims)steps = np.random.choice(a=step_set, size=step_shape)path = np.concatenate([origin, steps]).cumsum(0)start = path[:1]stop = path[-1:]# Plot the pathfig = plt.figure(figsize=(8,8),dpi=200)ax = fig.add_subplot(111)ax.scatter(path[:,0], path[:,1],c=’blue’,alpha=0.25,s=0.05);ax.plot(path[:,0], path[:,1],c=’blue’,alpha=0.5,lw=0.25,ls=’ — ‘);ax.plot(start[:,0], start[:,1],c=’red’, marker=’+’)ax.plot(stop[:,0], stop[:,1],c=’black’, marker=’o’)plt.title(‘2D Random Walk’)plt.tight_layout(pad=0)plt.savefig(‘plots/random_walk_2d.png’,dpi=250);"
},
{
"code": null,
"e": 3349,
"s": 3317,
"text": "Simulate k Random Walks in 2D :"
},
{
"code": null,
"e": 3370,
"s": 3349,
"text": "Random Walk in 3-D :"
},
{
"code": null,
"e": 3567,
"s": 3370,
"text": "A body moving in a volume is an example of random walk in 3D space. We start at origin (x=0,y=0,z=0) and take steps in arandom fashion chosen from a set of 27 directions (∆x, ∆y, ∆z)⋲ {-1, 0, 1} :"
},
{
"code": null,
"e": 4475,
"s": 3567,
"text": "# Define parameters for the walkdims = 3step_n = 1000step_set = [-1, 0, 1]origin = np.zeros((1,dims))# Simulate steps in 3Dstep_shape = (step_n,dims)steps = np.random.choice(a=step_set, size=step_shape)path = np.concatenate([origin, steps]).cumsum(0)start = path[:1]stop = path[-1:]# Plot the pathfig = plt.figure(figsize=(10,10),dpi=200)ax = fig.add_subplot(111, projection=’3d’)ax.grid(False)ax.xaxis.pane.fill = ax.yaxis.pane.fill = ax.zaxis.pane.fill = Falseax.set_xlabel(‘X’)ax.set_ylabel(‘Y’)ax.set_zlabel(‘Z’)ax.scatter3D(path[:,0], path[:,1], path[:,2], c=’blue’, alpha=0.25,s=1)ax.plot3D(path[:,0], path[:,1], path[:,2], c=’blue’, alpha=0.5, lw=0.5)ax.plot3D(start[:,0], start[:,1], start[:,2], c=’red’, marker=’+’)ax.plot3D(stop[:,0], stop[:,1], stop[:,2], c=’black’, marker=’o’)plt.title(‘3D Random Walk’)plt.savefig(‘plots/random_walk_3d.png’,dpi=250);"
},
{
"code": null,
"e": 4507,
"s": 4475,
"text": "Simulate k Random Walks in 3D :"
},
{
"code": null,
"e": 4704,
"s": 4507,
"text": "Now we simulate multiple random walks in 3D. Each random walk represents motion of a point source starting out at the same time with starting point set at points chosen from (x, y, z) ⋲ [-10, 10]."
},
{
"code": null,
"e": 4963,
"s": 4704,
"text": "A few cells/particles moving without any sustained directional force would show a trajectory like this. An interesting aspect of 3 dimensional random walk is that even though the starting points are close together, as time progresses, the objects spread out."
},
{
"code": null,
"e": 6052,
"s": 4963,
"text": "# Define parameters for the walkdims = 3n_runs = 10step_n = 1000step_set = [-1, 0 ,1]runs = np.arange(n_runs)step_shape = (step_n,dims)# Plotfig = plt.figure(figsize=(10,10),dpi=250)ax = fig.add_subplot(111, projection=’3d’)ax.grid(False)ax.xaxis.pane.fill = ax.yaxis.pane.fill = ax.zaxis.pane.fill = Falseax.set_xlabel(‘X’)ax.set_ylabel(‘Y’)ax.set_zlabel(‘Z’) for i, col in zip(runs, colors): # Simulate steps in 3D origin = np.random.randint(low=-10,high=10,size=(1,dims)) steps = np.random.choice(a=step_set, size=step_shape) path = np.concatenate([origin, steps]).cumsum(0) start = path[:1] stop = path[-1:] # Plot the path ax.scatter3D(path[:,0], path[:,1], path[:,2], c=col,alpha=0.15,s=1); ax.plot3D(path[:,0], path[:,1], path[:,2], c=col, alpha=0.25,lw=0.25) ax.plot3D(start[:,0], start[:,1], start[:,2], c=col, marker=’+’) ax.plot3D(stop[:,0], stop[:,1], stop[:,2], c=col, marker=’o’);plt.title(‘3D Random Walk - Multiple runs’)plt.savefig(‘plots/random_walk_3d_multiple_runs.png’,dpi=250);"
}
]
|
GWT - Style with CSS | GWT widgets rely on cascading style sheets (CSS) for visual styling. By default, the class name for each component is gwt-<classname>.
For example, the Button widget has a default style of gwt-Button and similar way TextBox widgest has a default style of gwt-TextBox.
In order to give all buttons and text boxes a larger font, you could put the following rule in your application's CSS file
.gwt-Button { font-size: 150%; }
.gwt-TextBox { font-size: 150%; }
By default, neither the browser nor GWT creates default id attributes for widgets. You must explicitly create a unique id for the elements which you can use in CSS. In order to give a particular button with id my-button-id a larger font, you could put the following rule in your application's CSS file −
#my-button-id { font-size: 150%; }
To set the id for a GWT widget, retrieve its DOM Element and then set the id attribute as follows −
Button b = new Button();
DOM.setElementAttribute(b.getElement(), "id", "my-button-id")
There are many APIs available to hangle CSS setting for any GWT widget. Following are few important APIs which will help you in your day to day web programming using GWT −
public void setStyleName(java.lang.String style)
This method will clear any existing styles and set the widget style to the new CSS class provided using style.
public void addStyleName(java.lang.String style)
This method will add a secondary or dependent style name to the widget. A secondary style name is an additional style name that is,so if there were any previous style names applied they are kept.
public void removeStyleName(java.lang.String style)
This method will remove given style from the widget and leaves any others associated with the widget.
public java.lang.String getStyleName()
This method gets all of the object's style names, as a space-separated list.
public void setStylePrimaryName(java.lang.String style)
This method sets the object's primary style name and updates all dependent style names.
For example, let's define two new styles which we will apply to a text −
.gwt-Big-Text {
font-size:150%;
}
.gwt-Small-Text {
font-size:75%;
}
.gwt-Red-Text {
color:red;
}
Now you can use setStyleName(Style) to change the default setting to new setting. After applying the below rule, a text's font will become large
txtWidget.setStyleName("gwt-Big-Text");
We can apply a secondary CSS rule on the same widget to change its color as follows −
txtWidget.addStyleName("gwt-Red-Text");
Using above method you can add as many styles as you like to apply on a widget. If you remove first style from the button widget then second style will still remain with the text.
txtWidget.removeStyleName("gwt-Big-Text");
By default, the primary style name of a widget will be the default style name for its widget class for example gwt-Button for Button widgets. When we add and remove style names using AddStyleName() method, those styles are called secondary styles.
The final appearance of a widget is determined by the sum of all the secondary styles added to it, plus its primary style. You set the primary style of a widget with the setStylePrimaryName(String) method. To illustrate, let's say we have a Label widget. In our CSS file, we have the following rules defined −
.MyText {
color: blue;
}
.BigText {
font-size: large;
}
.LoudText {
font-weight: bold;
}
Let's suppose we want a particular label widget to always display blue text, and in some cases, use a larger, bold font for added emphasis.
We could do something like this −
// set up our primary style
Label someText = new Label();
someText.setStylePrimaryName("MyText");
...
// later on, to really grab the user's attention
someText.addStyleName("BigText");
someText.addStyleName("LoudText");
...
// after the crisis is over
someText.removeStyleName("BigText");
someText.removeStyleName("LoudText");
There are multiple approaches for associating CSS files with your module. Modern GWT applications typically use a combination of CssResource and UiBinder. We are using only first approach in our examples.
Using a <link> tag in the host HTML page.
Using a <link> tag in the host HTML page.
Using the <stylesheet> element in the module XML file.
Using the <stylesheet> element in the module XML file.
Using a CssResource contained within a ClientBundle.
Using a CssResource contained within a ClientBundle.
Using an inline <ui:style> element in a UiBinder template.
Using an inline <ui:style> element in a UiBinder template.
This example will take you through simple steps to apply different CSS rules on your GWT widgest. Let us have working Eclipse IDE along with GWT plug in place and follow the following steps to create a GWT application −
Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name = 'com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. -->
<inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
<!-- Specify the app entry point class. -->
<entry-point class = 'com.tutorialspoint.client.HelloWorld'/>
<!-- Specify the paths for translatable code -->
<source path = 'client'/>
<source path = 'shared'/>
</module>
Following is the content of the modified Style Sheet file war/HelloWorld.css.
body {
text-align: center;
font-family: verdana, sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
.gwt-Button {
font-size: 150%;
font-weight: bold;
width:100px;
height:100px;
}
.gwt-Big-Text {
font-size:150%;
}
.gwt-Small-Text {
font-size:75%;
}
Following is the content of the modified HTML host file war/HelloWorld.html to accomodate two buttons.
<html>
<head>
<title>Hello World</title>
<link rel = "stylesheet" href = "HelloWorld.css"/>
<script language = "javascript" src = "helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<div id = "mytext"><h1>Hello, World!</h1></div>
<div id = "gwtGreenButton"></div>
<div id = "gwtRedButton"></div>
</body>
</html>
Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will take care of adding two buttons in HTML and will apply custom CSS style.
package com.tutorialspoint.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
public class HelloWorld implements EntryPoint {
public void onModuleLoad() {
// add button to change font to big when clicked.
Button Btn1 = new Button("Big Text");
Btn1.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
RootPanel.get("mytext").setStyleName("gwt-Big-Text");
}
});
// add button to change font to small when clicked.
Button Btn2 = new Button("Small Text");
Btn2.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
RootPanel.get("mytext").setStyleName("gwt-Small-Text");
}
});
RootPanel.get("gwtGreenButton").add(Btn1);
RootPanel.get("gwtRedButton").add(Btn2);
}
}
Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −
Now try clicking on the two buttons displayed and observe "Hello, World!" text which keeps changing its font upon clicking on the two buttons.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2158,
"s": 2023,
"text": "GWT widgets rely on cascading style sheets (CSS) for visual styling. By default, the class name for each component is gwt-<classname>."
},
{
"code": null,
"e": 2291,
"s": 2158,
"text": "For example, the Button widget has a default style of gwt-Button and similar way TextBox widgest has a default style of gwt-TextBox."
},
{
"code": null,
"e": 2414,
"s": 2291,
"text": "In order to give all buttons and text boxes a larger font, you could put the following rule in your application's CSS file"
},
{
"code": null,
"e": 2483,
"s": 2414,
"text": ".gwt-Button { font-size: 150%; }\n\n.gwt-TextBox { font-size: 150%; }"
},
{
"code": null,
"e": 2787,
"s": 2483,
"text": "By default, neither the browser nor GWT creates default id attributes for widgets. You must explicitly create a unique id for the elements which you can use in CSS. In order to give a particular button with id my-button-id a larger font, you could put the following rule in your application's CSS file −"
},
{
"code": null,
"e": 2822,
"s": 2787,
"text": "#my-button-id { font-size: 150%; }"
},
{
"code": null,
"e": 2922,
"s": 2822,
"text": "To set the id for a GWT widget, retrieve its DOM Element and then set the id attribute as follows −"
},
{
"code": null,
"e": 3009,
"s": 2922,
"text": "Button b = new Button();\nDOM.setElementAttribute(b.getElement(), \"id\", \"my-button-id\")"
},
{
"code": null,
"e": 3181,
"s": 3009,
"text": "There are many APIs available to hangle CSS setting for any GWT widget. Following are few important APIs which will help you in your day to day web programming using GWT −"
},
{
"code": null,
"e": 3230,
"s": 3181,
"text": "public void setStyleName(java.lang.String style)"
},
{
"code": null,
"e": 3341,
"s": 3230,
"text": "This method will clear any existing styles and set the widget style to the new CSS class provided using style."
},
{
"code": null,
"e": 3390,
"s": 3341,
"text": "public void addStyleName(java.lang.String style)"
},
{
"code": null,
"e": 3586,
"s": 3390,
"text": "This method will add a secondary or dependent style name to the widget. A secondary style name is an additional style name that is,so if there were any previous style names applied they are kept."
},
{
"code": null,
"e": 3638,
"s": 3586,
"text": "public void removeStyleName(java.lang.String style)"
},
{
"code": null,
"e": 3740,
"s": 3638,
"text": "This method will remove given style from the widget and leaves any others associated with the widget."
},
{
"code": null,
"e": 3779,
"s": 3740,
"text": "public java.lang.String getStyleName()"
},
{
"code": null,
"e": 3856,
"s": 3779,
"text": "This method gets all of the object's style names, as a space-separated list."
},
{
"code": null,
"e": 3912,
"s": 3856,
"text": "public void setStylePrimaryName(java.lang.String style)"
},
{
"code": null,
"e": 4000,
"s": 3912,
"text": "This method sets the object's primary style name and updates all dependent style names."
},
{
"code": null,
"e": 4073,
"s": 4000,
"text": "For example, let's define two new styles which we will apply to a text −"
},
{
"code": null,
"e": 4185,
"s": 4073,
"text": ".gwt-Big-Text { \n font-size:150%;\n}\n\n.gwt-Small-Text { \n font-size:75%;\n}\n\n.gwt-Red-Text { \n color:red;\n}"
},
{
"code": null,
"e": 4330,
"s": 4185,
"text": "Now you can use setStyleName(Style) to change the default setting to new setting. After applying the below rule, a text's font will become large"
},
{
"code": null,
"e": 4370,
"s": 4330,
"text": "txtWidget.setStyleName(\"gwt-Big-Text\");"
},
{
"code": null,
"e": 4456,
"s": 4370,
"text": "We can apply a secondary CSS rule on the same widget to change its color as follows −"
},
{
"code": null,
"e": 4496,
"s": 4456,
"text": "txtWidget.addStyleName(\"gwt-Red-Text\");"
},
{
"code": null,
"e": 4676,
"s": 4496,
"text": "Using above method you can add as many styles as you like to apply on a widget. If you remove first style from the button widget then second style will still remain with the text."
},
{
"code": null,
"e": 4719,
"s": 4676,
"text": "txtWidget.removeStyleName(\"gwt-Big-Text\");"
},
{
"code": null,
"e": 4967,
"s": 4719,
"text": "By default, the primary style name of a widget will be the default style name for its widget class for example gwt-Button for Button widgets. When we add and remove style names using AddStyleName() method, those styles are called secondary styles."
},
{
"code": null,
"e": 5277,
"s": 4967,
"text": "The final appearance of a widget is determined by the sum of all the secondary styles added to it, plus its primary style. You set the primary style of a widget with the setStylePrimaryName(String) method. To illustrate, let's say we have a Label widget. In our CSS file, we have the following rules defined −"
},
{
"code": null,
"e": 5378,
"s": 5277,
"text": ".MyText {\n color: blue;\n}\n\n.BigText {\n font-size: large;\n}\n\n.LoudText {\n font-weight: bold;\n}"
},
{
"code": null,
"e": 5518,
"s": 5378,
"text": "Let's suppose we want a particular label widget to always display blue text, and in some cases, use a larger, bold font for added emphasis."
},
{
"code": null,
"e": 5552,
"s": 5518,
"text": "We could do something like this −"
},
{
"code": null,
"e": 5881,
"s": 5552,
"text": "// set up our primary style\nLabel someText = new Label();\nsomeText.setStylePrimaryName(\"MyText\");\n...\n\n// later on, to really grab the user's attention\nsomeText.addStyleName(\"BigText\");\nsomeText.addStyleName(\"LoudText\");\n...\n\n// after the crisis is over\nsomeText.removeStyleName(\"BigText\");\nsomeText.removeStyleName(\"LoudText\");"
},
{
"code": null,
"e": 6086,
"s": 5881,
"text": "There are multiple approaches for associating CSS files with your module. Modern GWT applications typically use a combination of CssResource and UiBinder. We are using only first approach in our examples."
},
{
"code": null,
"e": 6128,
"s": 6086,
"text": "Using a <link> tag in the host HTML page."
},
{
"code": null,
"e": 6170,
"s": 6128,
"text": "Using a <link> tag in the host HTML page."
},
{
"code": null,
"e": 6225,
"s": 6170,
"text": "Using the <stylesheet> element in the module XML file."
},
{
"code": null,
"e": 6280,
"s": 6225,
"text": "Using the <stylesheet> element in the module XML file."
},
{
"code": null,
"e": 6333,
"s": 6280,
"text": "Using a CssResource contained within a ClientBundle."
},
{
"code": null,
"e": 6386,
"s": 6333,
"text": "Using a CssResource contained within a ClientBundle."
},
{
"code": null,
"e": 6445,
"s": 6386,
"text": "Using an inline <ui:style> element in a UiBinder template."
},
{
"code": null,
"e": 6504,
"s": 6445,
"text": "Using an inline <ui:style> element in a UiBinder template."
},
{
"code": null,
"e": 6724,
"s": 6504,
"text": "This example will take you through simple steps to apply different CSS rules on your GWT widgest. Let us have working Eclipse IDE along with GWT plug in place and follow the following steps to create a GWT application −"
},
{
"code": null,
"e": 6826,
"s": 6724,
"text": "Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml."
},
{
"code": null,
"e": 7435,
"s": 6826,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n\n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>"
},
{
"code": null,
"e": 7513,
"s": 7435,
"text": "Following is the content of the modified Style Sheet file war/HelloWorld.css."
},
{
"code": null,
"e": 7872,
"s": 7513,
"text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}\n\n.gwt-Button { \n font-size: 150%; \n font-weight: bold;\n width:100px;\n height:100px;\n}\n\n.gwt-Big-Text { \n font-size:150%;\n}\n\n.gwt-Small-Text { \n font-size:75%;\n}"
},
{
"code": null,
"e": 7975,
"s": 7872,
"text": "Following is the content of the modified HTML host file war/HelloWorld.html to accomodate two buttons."
},
{
"code": null,
"e": 8351,
"s": 7975,
"text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <div id = \"mytext\"><h1>Hello, World!</h1></div>\n <div id = \"gwtGreenButton\"></div>\n <div id = \"gwtRedButton\"></div>\n </body>\n</html>"
},
{
"code": null,
"e": 8517,
"s": 8351,
"text": "Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will take care of adding two buttons in HTML and will apply custom CSS style."
},
{
"code": null,
"e": 9557,
"s": 8517,
"text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.event.dom.client.ClickEvent;\nimport com.google.gwt.event.dom.client.ClickHandler;\nimport com.google.gwt.user.client.ui.Button;\nimport com.google.gwt.user.client.ui.HTML;\nimport com.google.gwt.user.client.ui.RootPanel;\n\npublic class HelloWorld implements EntryPoint {\n public void onModuleLoad() {\n \n // add button to change font to big when clicked.\n Button Btn1 = new Button(\"Big Text\");\n Btn1.addClickHandler(new ClickHandler() {\n public void onClick(ClickEvent event) {\n RootPanel.get(\"mytext\").setStyleName(\"gwt-Big-Text\");\n }\n });\n\n // add button to change font to small when clicked.\n Button Btn2 = new Button(\"Small Text\");\n Btn2.addClickHandler(new ClickHandler() {\n public void onClick(ClickEvent event) {\n RootPanel.get(\"mytext\").setStyleName(\"gwt-Small-Text\");\n }\n });\n\n RootPanel.get(\"gwtGreenButton\").add(Btn1);\n RootPanel.get(\"gwtRedButton\").add(Btn2);\n }\n}"
},
{
"code": null,
"e": 9791,
"s": 9557,
"text": "Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −"
},
{
"code": null,
"e": 9934,
"s": 9791,
"text": "Now try clicking on the two buttons displayed and observe \"Hello, World!\" text which keeps changing its font upon clicking on the two buttons."
},
{
"code": null,
"e": 9941,
"s": 9934,
"text": " Print"
},
{
"code": null,
"e": 9952,
"s": 9941,
"text": " Add Notes"
}
]
|
3D Volume Plots using Plotly in Python - GeeksforGeeks | 10 Jul, 2020
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. Plotly is an interactive visualization library.
A volume plot is a plot with go.volume which shows many partially transparent isosurfaces for rendering the volume. The opacityscale parameter of go. Volume results in a depth effect and generates better volume rendering. Three-dimensional volume visualization is a method that allows one to observe and manipulate 3D volumetric data. It represents 3D objects in terms of surfaces and edges approximated by polygons and lines.
Syntax: plotly.graph_objects.3d_Volume(arg=None, autocolorscale=None, caps=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, contour=None, customdata=None, customdatasrc=None, flatshading=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, isomax=None, isomin=None, legendgroup=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, opacityscale=None, reversescale=None, scene=None, showlegend=None, showscale=None, slices=None, spaceframe=None, stream=None, surface=None, text=None, textsrc=None, uid=None, uirevision=None, value=None, valuesrc=None, visible=None, x=None, xsrc=None, y=None, ysrc=None, z=None, zsrc=None, **kwargs)
Parameters:
x – Sets the X coordinates of the vertices on X axis.
y – Sets the Y coordinates of the vertices on Y axis.
z – Sets the Z coordinates of the vertices on Z axis.
value – Sets the 4th dimension (value) of the vertices.
Example:
Python3
import plotly.graph_objects as goimport numpy as np x1 = np.linspace(-4, 4, 9) y1 = np.linspace(-5, 5, 11) z1 = np.linspace(-5, 5, 11) X, Y, Z = np.meshgrid(x1, y1, z1) values = (np.sin(X**2 + Y**2))/(X**2 + Y**2) fig = go.Figure(data=go.Volume( x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=values.flatten(), opacity=0.1, )) fig.show()
Output:
In plotly, for more clear visualization of the internal surface, it is possible that the cap can be removed. Caps are visible by default.
Example 1:
Python3
import plotly.graph_objects as goimport plotly.express as pximport numpy as np df = px.data.tips() x1 = np.linspace(-4, 4, 9) y1 = np.linspace(-5, 5, 11) z1 = np.linspace(-5, 5, 11) X, Y, Z = np.meshgrid(x1, y1, z1) values = (np.sin(X**2 + Y**2))/(X**2 + Y**2) fig = go.Figure(data=go.Volume( x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=values.flatten(), opacity=0.1, caps= dict(x_show=False, y_show=False, z_show=True), ))fig.show()
Output:
Example 2:
Python3
import plotly.graph_objects as goimport plotly.express as pximport numpy as np df = px.data.tips() x1 = np.linspace(-4, 4, 9) y1 = np.linspace(-5, 5, 11) z1 = np.linspace(-5, 5, 11) X, Y, Z = np.meshgrid(x1, y1, z1) values = (np.sin(X**2 + Y**2))/(X**2 + Y**2) fig = go.Figure(data=go.Volume( x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=values.flatten(), opacity=0.1, caps= dict(x_show=False, y_show=True, z_show=False), ))fig.show()
Output:
In plotly, it is possible to define the custom opacity scale, mapping scalar values proportionate to opacity values. The value is given from 0-1 and the maximum opacity is provided by the opacity keyword.
Example:
Python3
import plotly.graph_objects as goimport plotly.express as pximport numpy as np df = px.data.tips() x1 = np.linspace(-4, 4, 9) y1 = np.linspace(-5, 5, 11) z1 = np.linspace(-5, 5, 11) X, Y, Z = np.meshgrid(x1, y1, z1) values = (np.sin(X**2 + Y**2))/(X**2 + Y**2) fig = go.Figure(data=go.Volume( x=X.flatten(), y=Y.flatten(), z=Z.flatten(), isomin=-0.5, isomax=0.5, value=values.flatten(), opacity=0.1, opacityscale=[[-0.5, 1], [-0.2, 0], [0.2, 0], [0.5, 1]], colorscale='RdBu' )) fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Print lists in Python (4 Different Ways) | [
{
"code": null,
"e": 24357,
"s": 24329,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 24659,
"s": 24357,
"text": "Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. Plotly is an interactive visualization library."
},
{
"code": null,
"e": 25086,
"s": 24659,
"text": "A volume plot is a plot with go.volume which shows many partially transparent isosurfaces for rendering the volume. The opacityscale parameter of go. Volume results in a depth effect and generates better volume rendering. Three-dimensional volume visualization is a method that allows one to observe and manipulate 3D volumetric data. It represents 3D objects in terms of surfaces and edges approximated by polygons and lines."
},
{
"code": null,
"e": 25911,
"s": 25086,
"text": "Syntax: plotly.graph_objects.3d_Volume(arg=None, autocolorscale=None, caps=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, contour=None, customdata=None, customdatasrc=None, flatshading=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, isomax=None, isomin=None, legendgroup=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, opacityscale=None, reversescale=None, scene=None, showlegend=None, showscale=None, slices=None, spaceframe=None, stream=None, surface=None, text=None, textsrc=None, uid=None, uirevision=None, value=None, valuesrc=None, visible=None, x=None, xsrc=None, y=None, ysrc=None, z=None, zsrc=None, **kwargs)"
},
{
"code": null,
"e": 25923,
"s": 25911,
"text": "Parameters:"
},
{
"code": null,
"e": 25977,
"s": 25923,
"text": "x – Sets the X coordinates of the vertices on X axis."
},
{
"code": null,
"e": 26031,
"s": 25977,
"text": "y – Sets the Y coordinates of the vertices on Y axis."
},
{
"code": null,
"e": 26085,
"s": 26031,
"text": "z – Sets the Z coordinates of the vertices on Z axis."
},
{
"code": null,
"e": 26141,
"s": 26085,
"text": "value – Sets the 4th dimension (value) of the vertices."
},
{
"code": null,
"e": 26150,
"s": 26141,
"text": "Example:"
},
{
"code": null,
"e": 26158,
"s": 26150,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as goimport numpy as np x1 = np.linspace(-4, 4, 9) y1 = np.linspace(-5, 5, 11) z1 = np.linspace(-5, 5, 11) X, Y, Z = np.meshgrid(x1, y1, z1) values = (np.sin(X**2 + Y**2))/(X**2 + Y**2) fig = go.Figure(data=go.Volume( x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=values.flatten(), opacity=0.1, )) fig.show()",
"e": 26526,
"s": 26158,
"text": null
},
{
"code": null,
"e": 26534,
"s": 26526,
"text": "Output:"
},
{
"code": null,
"e": 26673,
"s": 26534,
"text": "In plotly, for more clear visualization of the internal surface, it is possible that the cap can be removed. Caps are visible by default. "
},
{
"code": null,
"e": 26684,
"s": 26673,
"text": "Example 1:"
},
{
"code": null,
"e": 26692,
"s": 26684,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as goimport plotly.express as pximport numpy as np df = px.data.tips() x1 = np.linspace(-4, 4, 9) y1 = np.linspace(-5, 5, 11) z1 = np.linspace(-5, 5, 11) X, Y, Z = np.meshgrid(x1, y1, z1) values = (np.sin(X**2 + Y**2))/(X**2 + Y**2) fig = go.Figure(data=go.Volume( x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=values.flatten(), opacity=0.1, caps= dict(x_show=False, y_show=False, z_show=True), ))fig.show()",
"e": 27161,
"s": 26692,
"text": null
},
{
"code": null,
"e": 27169,
"s": 27161,
"text": "Output:"
},
{
"code": null,
"e": 27180,
"s": 27169,
"text": "Example 2:"
},
{
"code": null,
"e": 27188,
"s": 27180,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as goimport plotly.express as pximport numpy as np df = px.data.tips() x1 = np.linspace(-4, 4, 9) y1 = np.linspace(-5, 5, 11) z1 = np.linspace(-5, 5, 11) X, Y, Z = np.meshgrid(x1, y1, z1) values = (np.sin(X**2 + Y**2))/(X**2 + Y**2) fig = go.Figure(data=go.Volume( x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=values.flatten(), opacity=0.1, caps= dict(x_show=False, y_show=True, z_show=False), ))fig.show()",
"e": 27656,
"s": 27188,
"text": null
},
{
"code": null,
"e": 27664,
"s": 27656,
"text": "Output:"
},
{
"code": null,
"e": 27870,
"s": 27664,
"text": "In plotly, it is possible to define the custom opacity scale, mapping scalar values proportionate to opacity values. The value is given from 0-1 and the maximum opacity is provided by the opacity keyword. "
},
{
"code": null,
"e": 27879,
"s": 27870,
"text": "Example:"
},
{
"code": null,
"e": 27887,
"s": 27879,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as goimport plotly.express as pximport numpy as np df = px.data.tips() x1 = np.linspace(-4, 4, 9) y1 = np.linspace(-5, 5, 11) z1 = np.linspace(-5, 5, 11) X, Y, Z = np.meshgrid(x1, y1, z1) values = (np.sin(X**2 + Y**2))/(X**2 + Y**2) fig = go.Figure(data=go.Volume( x=X.flatten(), y=Y.flatten(), z=Z.flatten(), isomin=-0.5, isomax=0.5, value=values.flatten(), opacity=0.1, opacityscale=[[-0.5, 1], [-0.2, 0], [0.2, 0], [0.5, 1]], colorscale='RdBu' )) fig.show()",
"e": 28415,
"s": 27887,
"text": null
},
{
"code": null,
"e": 28423,
"s": 28415,
"text": "Output:"
},
{
"code": null,
"e": 28437,
"s": 28423,
"text": "Python-Plotly"
},
{
"code": null,
"e": 28444,
"s": 28437,
"text": "Python"
},
{
"code": null,
"e": 28542,
"s": 28444,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28551,
"s": 28542,
"text": "Comments"
},
{
"code": null,
"e": 28564,
"s": 28551,
"text": "Old Comments"
},
{
"code": null,
"e": 28582,
"s": 28564,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28604,
"s": 28582,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28636,
"s": 28604,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28678,
"s": 28636,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28704,
"s": 28678,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28729,
"s": 28704,
"text": "sum() function in Python"
},
{
"code": null,
"e": 28766,
"s": 28729,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28822,
"s": 28766,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28851,
"s": 28822,
"text": "*args and **kwargs in Python"
}
]
|
Check if rearranging Array elements can form a Palindrome or not - GeeksforGeeks | 25 Aug, 2021
Given a positive integer array arr of size N, the task is to check if number formed, from any arrangement of array elements, form a palindrome or not.
Examples:
Input: arr = [1, 2, 3, 1, 2]Output: YesExplanation: The elements of a given array can be rearranged as 1, 2, 3, 2, 1. Since 12321 is a palindrome, so output will be “Yes”
Input: arr = [1, 2, 3, 4, 1]Output: NoExplanation: The elements of a given array cannot be rearranged to form a palindrome within all the possible permutations. So the output will be “No”
Approach: Given problem can be solved using map to store the frequency of array elements
Store the frequency of all array elements
Check if frequency of each element is even
For element whose frequency is odd, if there is only one such element, then print Yes. Else print No.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; #define MAX 256 // Function to check whether elements of// an array can form a palindromebool can_form_palindrome(int arr[], int n){ // create an empty string // to append elements of an array string str = ""; // append each element to the string str to form // a string so that we can solve it in easy way for (int i = 0; i < n; i++) { str += arr[i]; } // Create a freq array and initialize all // values as 0 int freq[MAX] = { 0 }; // For each character in formed string, // increment freq in the corresponding // freq array for (int i = 0; str[i]; i++) { freq[str[i]]++; } int count = 0; // Count odd occurring characters for (int i = 0; i < MAX; i++) { if (freq[i] & 1) { count++; } if (count > 1) { return false; } } // Return true if odd count is 0 or 1, return true;}// Drive codeint main(){ int arr[] = { 1, 2, 3, 1, 2 }; int n = sizeof(arr) / sizeof(int); can_form_palindrome(arr, n) ? cout << "YES" : cout << "NO"; return 0;}
// Java implementation of the above approachimport java.io.*;import java.util.Arrays; class GFG{ static int MAX = 256; // Function to check whether elements of // an array can form a palindrome static boolean can_form_palindrome(int []arr, int n) { // create an empty string // to append elements of an array String str = ""; // append each element to the string str to form // a string so that we can solve it in easy way for (int i = 0; i < n; i++) { str += arr[i]; } // Create a freq array and initialize all // values as 0 int freq[] = new int[MAX]; Arrays.fill(freq,0); // For each character in formed string, // increment freq in the corresponding // freq array for (int i = 0; i<str.length(); i++) { freq[str.charAt(i)]++; } int count = 0; // Count odd occurring characters for (int i = 0; i < MAX; i++) { if ((freq[i] & 1)!=0) { count++; } if (count > 1) { return false; } } // Return true if odd count is 0 or 1, return true; } // Drive code public static void main (String[] args) { int []arr = { 1, 2, 3, 1, 2 }; int n = arr.length; if(can_form_palindrome(arr, n)) System.out.println("YES"); else System.out.println("NO"); }} // This code is contributed by shivanisinghss2110
# python implementation of the above approach # Function to check whether elements of# an array can form a palindromedef can_form_palindrome(arr, n): MAX = 256 # create an empty string # to append elements of an array s = "" # append each element to the string str to form # a string so that we can solve it in easy way for i in range(n) : s = s + str(arr[i]) # Create a freq array and initialize all # values as 0 freq = [0]*MAX # For each character in formed string, # increment freq in the corresponding # freq array for i in range(N) : freq[arr[i]]=freq[arr[i]]+1 count = 0 # Count odd occurring characters for i in range(MAX) : if (freq[i] & 1) : count=count+1 if (count > 1) : return False # Return true if odd count is 0 or 1, return True # Driver Codeif __name__ == "__main__": arr = [ 1, 2, 3, 1, 2 ] N = len(arr) # Function Call if(can_form_palindrome(arr, N)): print("YES") else: print("NO") # This code is contributed by anudeep23042002
// C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{ static int MAX = 256; // Function to check whether elements of// an array can form a palindromestatic bool can_form_palindrome(int []arr, int n){ // create an empty string // to append elements of an array string str = ""; // append each element to the string str to form // a string so that we can solve it in easy way for (int i = 0; i < n; i++) { str += arr[i]; } // Create a freq array and initialize all // values as 0 int []freq = new int[MAX]; Array.Clear(freq,0,MAX); // For each character in formed string, // increment freq in the corresponding // freq array for (int i = 0; i<str.Length; i++) { freq[str[i]]++; } int count = 0; // Count odd occurring characters for (int i = 0; i < MAX; i++) { if ((freq[i] & 1)!=0) { count++; } if (count > 1) { return false; } } // Return true if odd count is 0 or 1, return true;} // Drive codepublic static void Main(){ int []arr = { 1, 2, 3, 1, 2 }; int n = arr.Length; if(can_form_palindrome(arr, n)) Console.Write("YES"); else Console.Write("NO");}} // This code is contributed by SURENDRA_GANGWAR.
<script> // JavaScript Program to implement // the above approach let MAX = 256 // Function to check whether elements of // an array can form a palindrome function can_form_palindrome(arr, n) { // create an empty string // to append elements of an array let str = ""; // append each element to the string str to form // a string so that we can solve it in easy way for (let i = 0; i < n; i++) { str += toString(arr[i]); } // Create a freq array and initialize all // values as 0 let freq = new Array(n).fill(0); // For each character in formed string, // increment freq in the corresponding // freq array for (let i = 0; i < str.length; i++) { freq[str.charCodeAt(i)]++; } let count = 0; // Count odd occurring characters for (let i = 0; i < MAX; i++) { if (freq[i] & 1) { count++; } if (count > 1) { return false; } } // Return true if odd count is 0 or 1, return true; } // Drive code let arr = [1, 2, 3, 1, 2]; let n = arr.length; can_form_palindrome(arr, n) ? document.write("YES") : document.write("NO"); // This code is contributed by Potta Lokesh </script>
YES
Time Complexity: O(N)Auxiliary Space: O(N)
anudeep23042002
lokeshpotta20
SURENDRA_GANGWAR
shivanisinghss2110
palindrome
Arrays
Strings
Arrays
Strings
palindrome
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
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
Reverse a string in Java
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 24822,
"s": 24794,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 24973,
"s": 24822,
"text": "Given a positive integer array arr of size N, the task is to check if number formed, from any arrangement of array elements, form a palindrome or not."
},
{
"code": null,
"e": 24983,
"s": 24973,
"text": "Examples:"
},
{
"code": null,
"e": 25154,
"s": 24983,
"text": "Input: arr = [1, 2, 3, 1, 2]Output: YesExplanation: The elements of a given array can be rearranged as 1, 2, 3, 2, 1. Since 12321 is a palindrome, so output will be “Yes”"
},
{
"code": null,
"e": 25342,
"s": 25154,
"text": "Input: arr = [1, 2, 3, 4, 1]Output: NoExplanation: The elements of a given array cannot be rearranged to form a palindrome within all the possible permutations. So the output will be “No”"
},
{
"code": null,
"e": 25431,
"s": 25342,
"text": "Approach: Given problem can be solved using map to store the frequency of array elements"
},
{
"code": null,
"e": 25473,
"s": 25431,
"text": "Store the frequency of all array elements"
},
{
"code": null,
"e": 25516,
"s": 25473,
"text": "Check if frequency of each element is even"
},
{
"code": null,
"e": 25618,
"s": 25516,
"text": "For element whose frequency is odd, if there is only one such element, then print Yes. Else print No."
},
{
"code": null,
"e": 25669,
"s": 25618,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25675,
"s": 25669,
"text": "C++14"
},
{
"code": null,
"e": 25680,
"s": 25675,
"text": "Java"
},
{
"code": null,
"e": 25688,
"s": 25680,
"text": "Python3"
},
{
"code": null,
"e": 25691,
"s": 25688,
"text": "C#"
},
{
"code": null,
"e": 25702,
"s": 25691,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; #define MAX 256 // Function to check whether elements of// an array can form a palindromebool can_form_palindrome(int arr[], int n){ // create an empty string // to append elements of an array string str = \"\"; // append each element to the string str to form // a string so that we can solve it in easy way for (int i = 0; i < n; i++) { str += arr[i]; } // Create a freq array and initialize all // values as 0 int freq[MAX] = { 0 }; // For each character in formed string, // increment freq in the corresponding // freq array for (int i = 0; str[i]; i++) { freq[str[i]]++; } int count = 0; // Count odd occurring characters for (int i = 0; i < MAX; i++) { if (freq[i] & 1) { count++; } if (count > 1) { return false; } } // Return true if odd count is 0 or 1, return true;}// Drive codeint main(){ int arr[] = { 1, 2, 3, 1, 2 }; int n = sizeof(arr) / sizeof(int); can_form_palindrome(arr, n) ? cout << \"YES\" : cout << \"NO\"; return 0;}",
"e": 26885,
"s": 25702,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.io.*;import java.util.Arrays; class GFG{ static int MAX = 256; // Function to check whether elements of // an array can form a palindrome static boolean can_form_palindrome(int []arr, int n) { // create an empty string // to append elements of an array String str = \"\"; // append each element to the string str to form // a string so that we can solve it in easy way for (int i = 0; i < n; i++) { str += arr[i]; } // Create a freq array and initialize all // values as 0 int freq[] = new int[MAX]; Arrays.fill(freq,0); // For each character in formed string, // increment freq in the corresponding // freq array for (int i = 0; i<str.length(); i++) { freq[str.charAt(i)]++; } int count = 0; // Count odd occurring characters for (int i = 0; i < MAX; i++) { if ((freq[i] & 1)!=0) { count++; } if (count > 1) { return false; } } // Return true if odd count is 0 or 1, return true; } // Drive code public static void main (String[] args) { int []arr = { 1, 2, 3, 1, 2 }; int n = arr.length; if(can_form_palindrome(arr, n)) System.out.println(\"YES\"); else System.out.println(\"NO\"); }} // This code is contributed by shivanisinghss2110",
"e": 28223,
"s": 26885,
"text": null
},
{
"code": "# python implementation of the above approach # Function to check whether elements of# an array can form a palindromedef can_form_palindrome(arr, n): MAX = 256 # create an empty string # to append elements of an array s = \"\" # append each element to the string str to form # a string so that we can solve it in easy way for i in range(n) : s = s + str(arr[i]) # Create a freq array and initialize all # values as 0 freq = [0]*MAX # For each character in formed string, # increment freq in the corresponding # freq array for i in range(N) : freq[arr[i]]=freq[arr[i]]+1 count = 0 # Count odd occurring characters for i in range(MAX) : if (freq[i] & 1) : count=count+1 if (count > 1) : return False # Return true if odd count is 0 or 1, return True # Driver Codeif __name__ == \"__main__\": arr = [ 1, 2, 3, 1, 2 ] N = len(arr) # Function Call if(can_form_palindrome(arr, N)): print(\"YES\") else: print(\"NO\") # This code is contributed by anudeep23042002",
"e": 29354,
"s": 28223,
"text": null
},
{
"code": "// C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{ static int MAX = 256; // Function to check whether elements of// an array can form a palindromestatic bool can_form_palindrome(int []arr, int n){ // create an empty string // to append elements of an array string str = \"\"; // append each element to the string str to form // a string so that we can solve it in easy way for (int i = 0; i < n; i++) { str += arr[i]; } // Create a freq array and initialize all // values as 0 int []freq = new int[MAX]; Array.Clear(freq,0,MAX); // For each character in formed string, // increment freq in the corresponding // freq array for (int i = 0; i<str.Length; i++) { freq[str[i]]++; } int count = 0; // Count odd occurring characters for (int i = 0; i < MAX; i++) { if ((freq[i] & 1)!=0) { count++; } if (count > 1) { return false; } } // Return true if odd count is 0 or 1, return true;} // Drive codepublic static void Main(){ int []arr = { 1, 2, 3, 1, 2 }; int n = arr.Length; if(can_form_palindrome(arr, n)) Console.Write(\"YES\"); else Console.Write(\"NO\");}} // This code is contributed by SURENDRA_GANGWAR.",
"e": 30667,
"s": 29354,
"text": null
},
{
"code": "<script> // JavaScript Program to implement // the above approach let MAX = 256 // Function to check whether elements of // an array can form a palindrome function can_form_palindrome(arr, n) { // create an empty string // to append elements of an array let str = \"\"; // append each element to the string str to form // a string so that we can solve it in easy way for (let i = 0; i < n; i++) { str += toString(arr[i]); } // Create a freq array and initialize all // values as 0 let freq = new Array(n).fill(0); // For each character in formed string, // increment freq in the corresponding // freq array for (let i = 0; i < str.length; i++) { freq[str.charCodeAt(i)]++; } let count = 0; // Count odd occurring characters for (let i = 0; i < MAX; i++) { if (freq[i] & 1) { count++; } if (count > 1) { return false; } } // Return true if odd count is 0 or 1, return true; } // Drive code let arr = [1, 2, 3, 1, 2]; let n = arr.length; can_form_palindrome(arr, n) ? document.write(\"YES\") : document.write(\"NO\"); // This code is contributed by Potta Lokesh </script>",
"e": 32223,
"s": 30667,
"text": null
},
{
"code": null,
"e": 32227,
"s": 32223,
"text": "YES"
},
{
"code": null,
"e": 32270,
"s": 32227,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 32288,
"s": 32272,
"text": "anudeep23042002"
},
{
"code": null,
"e": 32302,
"s": 32288,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 32319,
"s": 32302,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 32338,
"s": 32319,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 32349,
"s": 32338,
"text": "palindrome"
},
{
"code": null,
"e": 32356,
"s": 32349,
"text": "Arrays"
},
{
"code": null,
"e": 32364,
"s": 32356,
"text": "Strings"
},
{
"code": null,
"e": 32371,
"s": 32364,
"text": "Arrays"
},
{
"code": null,
"e": 32379,
"s": 32371,
"text": "Strings"
},
{
"code": null,
"e": 32390,
"s": 32379,
"text": "palindrome"
},
{
"code": null,
"e": 32488,
"s": 32390,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32513,
"s": 32488,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32533,
"s": 32513,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 32571,
"s": 32533,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32656,
"s": 32571,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 32705,
"s": 32656,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32730,
"s": 32705,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 32764,
"s": 32730,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 32824,
"s": 32764,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32839,
"s": 32824,
"text": "C++ Data Types"
}
]
|
AWT AdjustmentEvent Class | The Class AdjustmentEvent represents adjustment event emitted by Adjustable objects.
Following is the declaration for java.awt.event.AdjustmentEvent class:
public class AdjustmentEvent
extends AWTEvent
Following are the fields for java.awt.Component class:
static int ADJUSTMENT_FIRST -- Marks the first integer id for the range of adjustment event ids.
static int ADJUSTMENT_FIRST -- Marks the first integer id for the range of adjustment event ids.
static int ADJUSTMENT_LAST -- Marks the last integer id for the range of adjustment event ids.
static int ADJUSTMENT_LAST -- Marks the last integer id for the range of adjustment event ids.
static int ADJUSTMENT_VALUE_CHANGED -- The adjustment value changed event.
static int ADJUSTMENT_VALUE_CHANGED -- The adjustment value changed event.
static int BLOCK_DECREMENT -- The block decrement adjustment type.
static int BLOCK_DECREMENT -- The block decrement adjustment type.
static int BLOCK_INCREMENT -- The block increment adjustment type.
static int BLOCK_INCREMENT -- The block increment adjustment type.
static int TRACK -- The absolute tracking adjustment type.
static int TRACK -- The absolute tracking adjustment type.
static int UNIT_DECREMENT -- The unit decrement adjustment type.
static int UNIT_DECREMENT -- The unit decrement adjustment type.
static int UNIT_INCREMENT -- The unit increment adjustment type.
static int UNIT_INCREMENT -- The unit increment adjustment type.
AdjustmentEvent(Adjustable source, int id, int type, int value)
Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value.
AdjustmentEvent(Adjustable source, int id, int type, int value, boolean isAdjusting)
Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value.
Adjustable getAdjustable()
Returns the Adjustable object where this event originated.
int getAdjustmentType()
Returns the type of adjustment which caused the value changed event.
int getValue()
Returns the current value in the adjustment event.
boolean getValueIsAdjusting()
Returns true if this is one of multiple adjustment events.
String paramString()
Returns a string representing the state of this Event.
This interface inherits methods from the following classes:
java.awt.AWTEvent
java.awt.AWTEvent
java.util.EventObject
java.util.EventObject
java.lang.Object
java.lang.Object
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1832,
"s": 1747,
"text": "The Class AdjustmentEvent represents adjustment event emitted by Adjustable objects."
},
{
"code": null,
"e": 1903,
"s": 1832,
"text": "Following is the declaration for java.awt.event.AdjustmentEvent class:"
},
{
"code": null,
"e": 1952,
"s": 1903,
"text": "public class AdjustmentEvent\n extends AWTEvent"
},
{
"code": null,
"e": 2007,
"s": 1952,
"text": "Following are the fields for java.awt.Component class:"
},
{
"code": null,
"e": 2105,
"s": 2007,
"text": "static int ADJUSTMENT_FIRST -- Marks the first integer id for the range of adjustment event ids."
},
{
"code": null,
"e": 2203,
"s": 2105,
"text": "static int ADJUSTMENT_FIRST -- Marks the first integer id for the range of adjustment event ids."
},
{
"code": null,
"e": 2299,
"s": 2203,
"text": "static int ADJUSTMENT_LAST -- Marks the last integer id for the range of adjustment event ids."
},
{
"code": null,
"e": 2395,
"s": 2299,
"text": "static int ADJUSTMENT_LAST -- Marks the last integer id for the range of adjustment event ids."
},
{
"code": null,
"e": 2471,
"s": 2395,
"text": "static int ADJUSTMENT_VALUE_CHANGED -- The adjustment value changed event."
},
{
"code": null,
"e": 2547,
"s": 2471,
"text": "static int ADJUSTMENT_VALUE_CHANGED -- The adjustment value changed event."
},
{
"code": null,
"e": 2615,
"s": 2547,
"text": "static int BLOCK_DECREMENT -- The block decrement adjustment type."
},
{
"code": null,
"e": 2683,
"s": 2615,
"text": "static int BLOCK_DECREMENT -- The block decrement adjustment type."
},
{
"code": null,
"e": 2751,
"s": 2683,
"text": "static int BLOCK_INCREMENT -- The block increment adjustment type."
},
{
"code": null,
"e": 2819,
"s": 2751,
"text": "static int BLOCK_INCREMENT -- The block increment adjustment type."
},
{
"code": null,
"e": 2879,
"s": 2819,
"text": "static int TRACK -- The absolute tracking adjustment type."
},
{
"code": null,
"e": 2939,
"s": 2879,
"text": "static int TRACK -- The absolute tracking adjustment type."
},
{
"code": null,
"e": 3005,
"s": 2939,
"text": "static int UNIT_DECREMENT -- The unit decrement adjustment type."
},
{
"code": null,
"e": 3071,
"s": 3005,
"text": "static int UNIT_DECREMENT -- The unit decrement adjustment type."
},
{
"code": null,
"e": 3137,
"s": 3071,
"text": "static int UNIT_INCREMENT -- The unit increment adjustment type."
},
{
"code": null,
"e": 3203,
"s": 3137,
"text": "static int UNIT_INCREMENT -- The unit increment adjustment type."
},
{
"code": null,
"e": 3270,
"s": 3203,
"text": "AdjustmentEvent(Adjustable source, int id, int type, int value) \n"
},
{
"code": null,
"e": 3385,
"s": 3270,
"text": "Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value."
},
{
"code": null,
"e": 3473,
"s": 3385,
"text": "AdjustmentEvent(Adjustable source, int id, int type, int value, boolean isAdjusting) \n"
},
{
"code": null,
"e": 3588,
"s": 3473,
"text": "Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value."
},
{
"code": null,
"e": 3617,
"s": 3588,
"text": "Adjustable getAdjustable() "
},
{
"code": null,
"e": 3676,
"s": 3617,
"text": "Returns the Adjustable object where this event originated."
},
{
"code": null,
"e": 3702,
"s": 3676,
"text": "int getAdjustmentType() "
},
{
"code": null,
"e": 3771,
"s": 3702,
"text": "Returns the type of adjustment which caused the value changed event."
},
{
"code": null,
"e": 3788,
"s": 3771,
"text": "int getValue() "
},
{
"code": null,
"e": 3839,
"s": 3788,
"text": "Returns the current value in the adjustment event."
},
{
"code": null,
"e": 3871,
"s": 3839,
"text": "boolean getValueIsAdjusting() "
},
{
"code": null,
"e": 3930,
"s": 3871,
"text": "Returns true if this is one of multiple adjustment events."
},
{
"code": null,
"e": 3953,
"s": 3930,
"text": "String\tparamString() "
},
{
"code": null,
"e": 4008,
"s": 3953,
"text": "Returns a string representing the state of this Event."
},
{
"code": null,
"e": 4068,
"s": 4008,
"text": "This interface inherits methods from the following classes:"
},
{
"code": null,
"e": 4086,
"s": 4068,
"text": "java.awt.AWTEvent"
},
{
"code": null,
"e": 4104,
"s": 4086,
"text": "java.awt.AWTEvent"
},
{
"code": null,
"e": 4126,
"s": 4104,
"text": "java.util.EventObject"
},
{
"code": null,
"e": 4148,
"s": 4126,
"text": "java.util.EventObject"
},
{
"code": null,
"e": 4165,
"s": 4148,
"text": "java.lang.Object"
},
{
"code": null,
"e": 4182,
"s": 4165,
"text": "java.lang.Object"
},
{
"code": null,
"e": 4215,
"s": 4182,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4223,
"s": 4215,
"text": " EduOLC"
},
{
"code": null,
"e": 4230,
"s": 4223,
"text": " Print"
},
{
"code": null,
"e": 4241,
"s": 4230,
"text": " Add Notes"
}
]
|
Insert string at specified position in PHP - GeeksforGeeks | 18 Oct, 2018
Given a sentence, a string and the position, the task is to insert the given string at the specified position. We will start counting the position form zero. See the examples below.
Input : sentence = ‘I am happy today.’string = ‘very’position = 4Output :I amvery happy today.Begin counting with 0. Start counting from the very first character till we reachthe given position in the given sentence.Spaces will also be counted and then insert the given string at the specified position.
Input : sentence = ‘I am happy today.’string = ‘ very’position = 4Output : I am very happy today.
The idea is to use substr_replace()
<?php$sentence = 'I am happy today.';$string = 'very ';$position = '5'; echo substr_replace( $sentence, $string, $position, 0 );?>
I am very happy today.
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.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
How to receive JSON POST with PHP ?
Comparing two dates in PHP
PHP | Converting string to Date and DateTime
Download file from URL using PHP
How to fetch data from localserver database and display on HTML table using PHP ?
Split a comma delimited string into an array in PHP
How to run JavaScript from PHP? | [
{
"code": null,
"e": 24647,
"s": 24619,
"text": "\n18 Oct, 2018"
},
{
"code": null,
"e": 24829,
"s": 24647,
"text": "Given a sentence, a string and the position, the task is to insert the given string at the specified position. We will start counting the position form zero. See the examples below."
},
{
"code": null,
"e": 25133,
"s": 24829,
"text": "Input : sentence = ‘I am happy today.’string = ‘very’position = 4Output :I amvery happy today.Begin counting with 0. Start counting from the very first character till we reachthe given position in the given sentence.Spaces will also be counted and then insert the given string at the specified position."
},
{
"code": null,
"e": 25231,
"s": 25133,
"text": "Input : sentence = ‘I am happy today.’string = ‘ very’position = 4Output : I am very happy today."
},
{
"code": null,
"e": 25267,
"s": 25231,
"text": "The idea is to use substr_replace()"
},
{
"code": "<?php$sentence = 'I am happy today.';$string = 'very ';$position = '5'; echo substr_replace( $sentence, $string, $position, 0 );?>",
"e": 25399,
"s": 25267,
"text": null
},
{
"code": null,
"e": 25423,
"s": 25399,
"text": "I am very happy today.\n"
},
{
"code": null,
"e": 25434,
"s": 25423,
"text": "PHP-string"
},
{
"code": null,
"e": 25441,
"s": 25434,
"text": "Picked"
},
{
"code": null,
"e": 25465,
"s": 25441,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 25469,
"s": 25465,
"text": "PHP"
},
{
"code": null,
"e": 25488,
"s": 25469,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25492,
"s": 25488,
"text": "PHP"
},
{
"code": null,
"e": 25590,
"s": 25492,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25599,
"s": 25590,
"text": "Comments"
},
{
"code": null,
"e": 25612,
"s": 25599,
"text": "Old Comments"
},
{
"code": null,
"e": 25662,
"s": 25612,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 25702,
"s": 25662,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 25752,
"s": 25702,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 25788,
"s": 25752,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 25815,
"s": 25788,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 25860,
"s": 25815,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 25893,
"s": 25860,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 25975,
"s": 25893,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 26027,
"s": 25975,
"text": "Split a comma delimited string into an array in PHP"
}
]
|
Program to find Final Prices With a Special Discount in a Shop in Python | Suppose we have an array called prices where prices[i] represents price of the ith item in a shop. There is a special offer going on, if we buy the ith item, then we will get a discount equivalent to prices[j] where j is the minimum index such that j > i and price of jth item is less or same as price of ith item (i.e. prices[j] <= prices[i]), otherwise, we will not receive any discount at all. We have to find an array where the ith element is the final price that we will pay for the ith item of the shop considering the special discount.
So, if the input is like prices = [16,8,12,4,6], then the output will be [8, 4, 8, 4, 6], as price of item0 is 16, so we will get a discount equivalent to prices[1]=8, then, the final price will be 8 - 4 = 4. For item1 the price[1] is 8 we will receive a discount equivalent to prices[3]=2, so, the final price we will pay is 8 - 4 = 4. For item 2 with price[2] is 12 and we will get a discount value same as prices[3] = 4, therefore, the final price we will pay is 12 - 4 = 8. And for items 3 and 4 we will not receive any discount.
To solve this, we will follow these steps −
for i in range 0 to size of prices, dofor j in range i+1 to size of prices, doif prices[i] >= prices[j], thenprices[i] := prices[i] - prices[j]come out from the loopotherwise,j := j + 1
for i in range 0 to size of prices, do
for j in range i+1 to size of prices, doif prices[i] >= prices[j], thenprices[i] := prices[i] - prices[j]come out from the loopotherwise,j := j + 1
for j in range i+1 to size of prices, do
if prices[i] >= prices[j], thenprices[i] := prices[i] - prices[j]come out from the loop
if prices[i] >= prices[j], then
prices[i] := prices[i] - prices[j]
prices[i] := prices[i] - prices[j]
come out from the loop
come out from the loop
otherwise,j := j + 1
otherwise,
j := j + 1
j := j + 1
return prices
return prices
Let us see the following implementation to get better understanding −
Live Demo
def solve(prices):
for i in range(len(prices)):
for j in range(i+1,len(prices)):
if(prices[i]>=prices[j]):
prices[i]-=prices[j]
break
else:
j+=1
return prices
prices = [16,8,12,4,6]
print(solve(prices))
[16,8,12,4,6]
[8, 4, 8, 4, 6] | [
{
"code": null,
"e": 1605,
"s": 1062,
"text": "Suppose we have an array called prices where prices[i] represents price of the ith item in a shop. There is a special offer going on, if we buy the ith item, then we will get a discount equivalent to prices[j] where j is the minimum index such that j > i and price of jth item is less or same as price of ith item (i.e. prices[j] <= prices[i]), otherwise, we will not receive any discount at all. We have to find an array where the ith element is the final price that we will pay for the ith item of the shop considering the special discount."
},
{
"code": null,
"e": 2139,
"s": 1605,
"text": "So, if the input is like prices = [16,8,12,4,6], then the output will be [8, 4, 8, 4, 6], as price of item0 is 16, so we will get a discount equivalent to prices[1]=8, then, the final price will be 8 - 4 = 4. For item1 the price[1] is 8 we will receive a discount equivalent to prices[3]=2, so, the final price we will pay is 8 - 4 = 4. For item 2 with price[2] is 12 and we will get a discount value same as prices[3] = 4, therefore, the final price we will pay is 12 - 4 = 8. And for items 3 and 4 we will not receive any discount."
},
{
"code": null,
"e": 2183,
"s": 2139,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 2369,
"s": 2183,
"text": "for i in range 0 to size of prices, dofor j in range i+1 to size of prices, doif prices[i] >= prices[j], thenprices[i] := prices[i] - prices[j]come out from the loopotherwise,j := j + 1"
},
{
"code": null,
"e": 2408,
"s": 2369,
"text": "for i in range 0 to size of prices, do"
},
{
"code": null,
"e": 2556,
"s": 2408,
"text": "for j in range i+1 to size of prices, doif prices[i] >= prices[j], thenprices[i] := prices[i] - prices[j]come out from the loopotherwise,j := j + 1"
},
{
"code": null,
"e": 2597,
"s": 2556,
"text": "for j in range i+1 to size of prices, do"
},
{
"code": null,
"e": 2685,
"s": 2597,
"text": "if prices[i] >= prices[j], thenprices[i] := prices[i] - prices[j]come out from the loop"
},
{
"code": null,
"e": 2717,
"s": 2685,
"text": "if prices[i] >= prices[j], then"
},
{
"code": null,
"e": 2752,
"s": 2717,
"text": "prices[i] := prices[i] - prices[j]"
},
{
"code": null,
"e": 2787,
"s": 2752,
"text": "prices[i] := prices[i] - prices[j]"
},
{
"code": null,
"e": 2810,
"s": 2787,
"text": "come out from the loop"
},
{
"code": null,
"e": 2833,
"s": 2810,
"text": "come out from the loop"
},
{
"code": null,
"e": 2854,
"s": 2833,
"text": "otherwise,j := j + 1"
},
{
"code": null,
"e": 2865,
"s": 2854,
"text": "otherwise,"
},
{
"code": null,
"e": 2876,
"s": 2865,
"text": "j := j + 1"
},
{
"code": null,
"e": 2887,
"s": 2876,
"text": "j := j + 1"
},
{
"code": null,
"e": 2901,
"s": 2887,
"text": "return prices"
},
{
"code": null,
"e": 2915,
"s": 2901,
"text": "return prices"
},
{
"code": null,
"e": 2985,
"s": 2915,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2996,
"s": 2985,
"text": " Live Demo"
},
{
"code": null,
"e": 3266,
"s": 2996,
"text": "def solve(prices):\n for i in range(len(prices)):\n for j in range(i+1,len(prices)):\n if(prices[i]>=prices[j]):\n prices[i]-=prices[j]\n break\n else:\n j+=1\n return prices\n\nprices = [16,8,12,4,6]\nprint(solve(prices))"
},
{
"code": null,
"e": 3280,
"s": 3266,
"text": "[16,8,12,4,6]"
},
{
"code": null,
"e": 3296,
"s": 3280,
"text": "[8, 4, 8, 4, 6]"
}
]
|
Cisco Router basic commands - GeeksforGeeks | 09 Nov, 2021
A router is a layer 3 device used to forward packets from one network to another. It forwards the packet through one of its ports on the basis of destination IP address and the entry in the routing table. By using a routing table, it finds an optimized path between the source and destination network.
Here, we will talk about Cisco router’s basic commands like assigning an IP address to an interface, bringing up an interface, applying to enable and secret passwords.
Administrative Configuration:
Giving hostname to the router – It is used to set a name to a device stating an identity to a device. This is important as these hostnames are used in WAN for authentication purposes.
We can set the hostname as:
router(config)#hostname GeeksforGeeksrouter
GeeksforGeeksrouter(config)#
Applying banners – These are specifically used to give a small security notice to the user who wants to access the router. We can customize it According to our needs as like asking for credentials needed for the login.
Types of banners are:
1. banner motd –
GeeksforGeeksrouter(config)#banner motd #
Enter Text message. End with character '#'
$ No unauthorized access allowed. Enter your credentials!! #
Here motd means a message of the day and # means delimiter i.e message should end with the symbol provided. This message will be shown while entering into the router’s user execution mode
2. Exec banner – It will be displayed on the screen when the user will log in through the VTY lines.
3. Login banner – This banner will be displayed after the banner motd but before the login.
These banners are used to make login interactive.
Setting password – There are five passwords used to secure a Cisco device:
1. enable password – The enable password is used for securing privilege mode. This password will be shown in clear text by the command “show running-configuration”. These are replaced by secret passwords nowadays.
router(config)#enable password GeeksforGeeks
2. Enable secret password – This is also used for securing privilege mode but the d the difference is that it will be displayed as a cipher in “show running-configuration”. This password will override the enable password if both passwords are set.
router(config)#enable secret GeeksforGeeks
3. line console password – When a user will take access through the console port then this password will be asked.
router(config)#line console 0
router(config-line)#password GeeksforGeeks
router(config-line)#login
4. line VTY password – When a user wants to access a router through VTY lines (telnet or ssh) then this password will be asked. The following configuration is shown for the telnet password.
router(config)#line VTY 0 4
router(config-line)#password GeeksforGeeks
router(config-line)#exit
5. auxiliary password – This password will secure the aux port.
router(config)#line aux 0
router(config-line)#password GeeksforGeeks
router(config-line)#login
Assigning IP address to a router’s interface – As we know the router is a layer 3 device therefore every port of a router should have an IP address to work. By default, a router’s port has no IP address and its line protocol is also down.
router(config)#interface fa0/0
router(config-if)#ip address 192.168.1.1 255.255.255.0
router(config-if)#no shut
Here first we have to specify the router’s interface on which we want to give an IP address. Then we will enter interface mode where we will give an IP address as shown followed by its subnet mask (255.255.255.0). Then, we have made the router port administratively up by no shut command.
Copying and erasing configuration – We can manually copy the running configuration (configuration in RAM) to startup configuration (configuration in NVRAM). Therefore, when the next time router will boot up, it will load the configuration that we have copied (as by default the configuration of NVRAM is loaded).
router#copy running-config startup-config
To erase the configuration of NVRAM, use the command
router#erase startup-config
chhabradhanvi
23603vaibhav2021
Cisco
Computer Networks
Cisco
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Data encryption standard (DES) | Set 1
Types of Network Topology
Socket Programming in Python
UDP Server-Client implementation in C
TCP 3-Way Handshake Process
Error Detection in Computer Networks
Socket Programming in Java
Hamming Code in Computer Network
Implementation of Diffie-Hellman Algorithm
Differences between IPv4 and IPv6 | [
{
"code": null,
"e": 24634,
"s": 24606,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 24937,
"s": 24634,
"text": "A router is a layer 3 device used to forward packets from one network to another. It forwards the packet through one of its ports on the basis of destination IP address and the entry in the routing table. By using a routing table, it finds an optimized path between the source and destination network. "
},
{
"code": null,
"e": 25106,
"s": 24937,
"text": "Here, we will talk about Cisco router’s basic commands like assigning an IP address to an interface, bringing up an interface, applying to enable and secret passwords. "
},
{
"code": null,
"e": 25137,
"s": 25106,
"text": "Administrative Configuration: "
},
{
"code": null,
"e": 25321,
"s": 25137,
"text": "Giving hostname to the router – It is used to set a name to a device stating an identity to a device. This is important as these hostnames are used in WAN for authentication purposes."
},
{
"code": null,
"e": 25351,
"s": 25321,
"text": " We can set the hostname as: "
},
{
"code": null,
"e": 25424,
"s": 25351,
"text": "router(config)#hostname GeeksforGeeksrouter\nGeeksforGeeksrouter(config)#"
},
{
"code": null,
"e": 25644,
"s": 25424,
"text": "Applying banners – These are specifically used to give a small security notice to the user who wants to access the router. We can customize it According to our needs as like asking for credentials needed for the login. "
},
{
"code": null,
"e": 25667,
"s": 25644,
"text": "Types of banners are: "
},
{
"code": null,
"e": 25685,
"s": 25667,
"text": "1. banner motd – "
},
{
"code": null,
"e": 25831,
"s": 25685,
"text": "GeeksforGeeksrouter(config)#banner motd #\nEnter Text message. End with character '#'\n$ No unauthorized access allowed. Enter your credentials!! #"
},
{
"code": null,
"e": 26020,
"s": 25831,
"text": "Here motd means a message of the day and # means delimiter i.e message should end with the symbol provided. This message will be shown while entering into the router’s user execution mode "
},
{
"code": null,
"e": 26121,
"s": 26020,
"text": "2. Exec banner – It will be displayed on the screen when the user will log in through the VTY lines."
},
{
"code": null,
"e": 26214,
"s": 26121,
"text": "3. Login banner – This banner will be displayed after the banner motd but before the login. "
},
{
"code": null,
"e": 26265,
"s": 26214,
"text": "These banners are used to make login interactive. "
},
{
"code": null,
"e": 26341,
"s": 26265,
"text": "Setting password – There are five passwords used to secure a Cisco device: "
},
{
"code": null,
"e": 26556,
"s": 26341,
"text": "1. enable password – The enable password is used for securing privilege mode. This password will be shown in clear text by the command “show running-configuration”. These are replaced by secret passwords nowadays. "
},
{
"code": null,
"e": 26602,
"s": 26556,
"text": "router(config)#enable password GeeksforGeeks "
},
{
"code": null,
"e": 26851,
"s": 26602,
"text": "2. Enable secret password – This is also used for securing privilege mode but the d the difference is that it will be displayed as a cipher in “show running-configuration”. This password will override the enable password if both passwords are set. "
},
{
"code": null,
"e": 26895,
"s": 26851,
"text": "router(config)#enable secret GeeksforGeeks "
},
{
"code": null,
"e": 27011,
"s": 26895,
"text": "3. line console password – When a user will take access through the console port then this password will be asked. "
},
{
"code": null,
"e": 27111,
"s": 27011,
"text": "router(config)#line console 0\nrouter(config-line)#password GeeksforGeeks \nrouter(config-line)#login"
},
{
"code": null,
"e": 27302,
"s": 27111,
"text": "4. line VTY password – When a user wants to access a router through VTY lines (telnet or ssh) then this password will be asked. The following configuration is shown for the telnet password. "
},
{
"code": null,
"e": 27399,
"s": 27302,
"text": "router(config)#line VTY 0 4\nrouter(config-line)#password GeeksforGeeks \nrouter(config-line)#exit"
},
{
"code": null,
"e": 27464,
"s": 27399,
"text": "5. auxiliary password – This password will secure the aux port. "
},
{
"code": null,
"e": 27560,
"s": 27464,
"text": "router(config)#line aux 0\nrouter(config-line)#password GeeksforGeeks \nrouter(config-line)#login"
},
{
"code": null,
"e": 27800,
"s": 27560,
"text": "Assigning IP address to a router’s interface – As we know the router is a layer 3 device therefore every port of a router should have an IP address to work. By default, a router’s port has no IP address and its line protocol is also down. "
},
{
"code": null,
"e": 27912,
"s": 27800,
"text": "router(config)#interface fa0/0\nrouter(config-if)#ip address 192.168.1.1 255.255.255.0\nrouter(config-if)#no shut"
},
{
"code": null,
"e": 28202,
"s": 27912,
"text": "Here first we have to specify the router’s interface on which we want to give an IP address. Then we will enter interface mode where we will give an IP address as shown followed by its subnet mask (255.255.255.0). Then, we have made the router port administratively up by no shut command. "
},
{
"code": null,
"e": 28516,
"s": 28202,
"text": "Copying and erasing configuration – We can manually copy the running configuration (configuration in RAM) to startup configuration (configuration in NVRAM). Therefore, when the next time router will boot up, it will load the configuration that we have copied (as by default the configuration of NVRAM is loaded). "
},
{
"code": null,
"e": 28558,
"s": 28516,
"text": "router#copy running-config startup-config"
},
{
"code": null,
"e": 28612,
"s": 28558,
"text": "To erase the configuration of NVRAM, use the command "
},
{
"code": null,
"e": 28640,
"s": 28612,
"text": "router#erase startup-config"
},
{
"code": null,
"e": 28656,
"s": 28642,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 28673,
"s": 28656,
"text": "23603vaibhav2021"
},
{
"code": null,
"e": 28679,
"s": 28673,
"text": "Cisco"
},
{
"code": null,
"e": 28697,
"s": 28679,
"text": "Computer Networks"
},
{
"code": null,
"e": 28703,
"s": 28697,
"text": "Cisco"
},
{
"code": null,
"e": 28721,
"s": 28703,
"text": "Computer Networks"
},
{
"code": null,
"e": 28819,
"s": 28721,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28828,
"s": 28819,
"text": "Comments"
},
{
"code": null,
"e": 28841,
"s": 28828,
"text": "Old Comments"
},
{
"code": null,
"e": 28880,
"s": 28841,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 28906,
"s": 28880,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 28935,
"s": 28906,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 28973,
"s": 28935,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 29001,
"s": 28973,
"text": "TCP 3-Way Handshake Process"
},
{
"code": null,
"e": 29038,
"s": 29001,
"text": "Error Detection in Computer Networks"
},
{
"code": null,
"e": 29065,
"s": 29038,
"text": "Socket Programming in Java"
},
{
"code": null,
"e": 29098,
"s": 29065,
"text": "Hamming Code in Computer Network"
},
{
"code": null,
"e": 29141,
"s": 29098,
"text": "Implementation of Diffie-Hellman Algorithm"
}
]
|
Collectors toSet() method in Java 8 | The toSet() method of the Collectors class in Java returns a Collector that accumulates the input elements into a new Set.
The syntax is as follows
static <T> Collector<T,?,Set<T>> toSet()
Here, the parameter,
T - Type of the input elements.
Set - A collection that contains no duplicate elements.
To work with Collectors class in Java, import the following package
import java.util.stream.Collectors;
The following is an example to implement toSet() method in Java
Live Demo
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) {
Stream<String> stream = Stream.of("This", "is", "it");
Set<String> set = stream.collect(Collectors.toSet());
System.out.println(set);
}
}
[This, is, it] | [
{
"code": null,
"e": 1185,
"s": 1062,
"text": "The toSet() method of the Collectors class in Java returns a Collector that accumulates the input elements into a new Set."
},
{
"code": null,
"e": 1210,
"s": 1185,
"text": "The syntax is as follows"
},
{
"code": null,
"e": 1251,
"s": 1210,
"text": "static <T> Collector<T,?,Set<T>> toSet()"
},
{
"code": null,
"e": 1272,
"s": 1251,
"text": "Here, the parameter,"
},
{
"code": null,
"e": 1304,
"s": 1272,
"text": "T - Type of the input elements."
},
{
"code": null,
"e": 1360,
"s": 1304,
"text": "Set - A collection that contains no duplicate elements."
},
{
"code": null,
"e": 1428,
"s": 1360,
"text": "To work with Collectors class in Java, import the following package"
},
{
"code": null,
"e": 1464,
"s": 1428,
"text": "import java.util.stream.Collectors;"
},
{
"code": null,
"e": 1528,
"s": 1464,
"text": "The following is an example to implement toSet() method in Java"
},
{
"code": null,
"e": 1539,
"s": 1528,
"text": " Live Demo"
},
{
"code": null,
"e": 1852,
"s": 1539,
"text": "import java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\npublic class Demo {\n public static void main(String[] args) {\n Stream<String> stream = Stream.of(\"This\", \"is\", \"it\");\n Set<String> set = stream.collect(Collectors.toSet());\n System.out.println(set);\n }\n}"
},
{
"code": null,
"e": 1867,
"s": 1852,
"text": "[This, is, it]"
}
]
|
Autocomplete Search using jQuery and Wikipedia OpenSearch API - GeeksforGeeks | 21 Aug, 2020
In web design, the autocomplete feature is a common one. When the user types some value in the search text box, it automatically shows a relevant list of suggestions in the form of dropdown that can be chosen by the user easily. For jQuery Autocomplete feature, refer this article.
Approach: In this article, we use the Wikipedia Opensearch API and the jQuery Autocomplete UI. Basic HTML code is used for the user interface for keyword search in an input text box. While using the jQuery code, the search request is sent to Wikipedia which in turn returns a list of suggestions based on user entry. The data response is in JSON format.
Syntax: Wikipedia URL for API
"http://en.wikipedia.org/w/api.php"
Setting up environment: For more option settings
https://en.wikipedia.org/w/api.php?action=help&modules=opensearch
The developer can refer the above URL link and make use of many option settings depending on the application’s need.
jQuery and jQuery UI libraries: The following files are used in the code.
<link href=” https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css” rel=”stylesheet” type=”text/css”/><script src=”https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js”></script><script src=””https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
Example: The following example demonstrates the autocomplete search feature by using Wikipedia OpenSearch API and jQuery. The HTML code provides a normal search input box which gives suggestions when the user types some search texts.
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"> </script> <style> body { width: 100%; background: #e9e9e9; margin: 0 auto; padding: 0; color: #7faf7f; font-family: Arial, sans-serif; font-size: 12px; } #searchID input { width: 350px; height: 20px; margin: 0; padding: 15px; background: #fff; border: 1px solid black; color: #727272; float: left; font: 12px "Lucida Sans Unicode", sans-serif; transition: background 0.4s ease-in-out 0s; } #searchID button { width: 45px; height: 45px; text-indent: -9999em; background: url("searchIcon.jpg") #4eac10; transition: background 0.3s ease-in-out 0s; border: 1px solid #fff; } #containerID { width: 50%; margin: 0 auto; } h2 { color: green; text-align: left; } </style></head> <body> <div id="containerID"> <div> <h2>GeeksforGeeks</h2> <b> Autocomplete Search using jQuery and Wikipedia Opensearch API </b> <p></p> <form method="get" id="searchID"> <input type="text" class="searchClass" id="searchInputID" value="" /> <button type="submit">Search</button> </form> </div> </div> <script type="text/javascript"> $(".searchClass").autocomplete({ source: function (request, response) { console.log(request.term); $.ajax({ // Wikipedia API url link url: "http://en.wikipedia.org/w/api.php", dataType: "jsonp", data: { action: "opensearch", // Output format format: "json", search: request.term, namespace: 0, // Maximum number of result // to be shown limit: 8, }, success: function (data) { response(data[1]); }, }); }, }); </script></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
jQuery-Misc
CSS
HTML
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction) | [
{
"code": null,
"e": 25070,
"s": 25042,
"text": "\n21 Aug, 2020"
},
{
"code": null,
"e": 25352,
"s": 25070,
"text": "In web design, the autocomplete feature is a common one. When the user types some value in the search text box, it automatically shows a relevant list of suggestions in the form of dropdown that can be chosen by the user easily. For jQuery Autocomplete feature, refer this article."
},
{
"code": null,
"e": 25706,
"s": 25352,
"text": "Approach: In this article, we use the Wikipedia Opensearch API and the jQuery Autocomplete UI. Basic HTML code is used for the user interface for keyword search in an input text box. While using the jQuery code, the search request is sent to Wikipedia which in turn returns a list of suggestions based on user entry. The data response is in JSON format."
},
{
"code": null,
"e": 25736,
"s": 25706,
"text": "Syntax: Wikipedia URL for API"
},
{
"code": null,
"e": 25772,
"s": 25736,
"text": "\"http://en.wikipedia.org/w/api.php\""
},
{
"code": null,
"e": 25821,
"s": 25772,
"text": "Setting up environment: For more option settings"
},
{
"code": null,
"e": 25887,
"s": 25821,
"text": "https://en.wikipedia.org/w/api.php?action=help&modules=opensearch"
},
{
"code": null,
"e": 26004,
"s": 25887,
"text": "The developer can refer the above URL link and make use of many option settings depending on the application’s need."
},
{
"code": null,
"e": 26078,
"s": 26004,
"text": "jQuery and jQuery UI libraries: The following files are used in the code."
},
{
"code": null,
"e": 26396,
"s": 26078,
"text": "<link href=” https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css” rel=”stylesheet” type=”text/css”/><script src=”https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js”></script><script src=””https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>"
},
{
"code": null,
"e": 26630,
"s": 26396,
"text": "Example: The following example demonstrates the autocomplete search feature by using Wikipedia OpenSearch API and jQuery. The HTML code provides a normal search input box which gives suggestions when the user types some search texts."
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js\"> </script> <style> body { width: 100%; background: #e9e9e9; margin: 0 auto; padding: 0; color: #7faf7f; font-family: Arial, sans-serif; font-size: 12px; } #searchID input { width: 350px; height: 20px; margin: 0; padding: 15px; background: #fff; border: 1px solid black; color: #727272; float: left; font: 12px \"Lucida Sans Unicode\", sans-serif; transition: background 0.4s ease-in-out 0s; } #searchID button { width: 45px; height: 45px; text-indent: -9999em; background: url(\"searchIcon.jpg\") #4eac10; transition: background 0.3s ease-in-out 0s; border: 1px solid #fff; } #containerID { width: 50%; margin: 0 auto; } h2 { color: green; text-align: left; } </style></head> <body> <div id=\"containerID\"> <div> <h2>GeeksforGeeks</h2> <b> Autocomplete Search using jQuery and Wikipedia Opensearch API </b> <p></p> <form method=\"get\" id=\"searchID\"> <input type=\"text\" class=\"searchClass\" id=\"searchInputID\" value=\"\" /> <button type=\"submit\">Search</button> </form> </div> </div> <script type=\"text/javascript\"> $(\".searchClass\").autocomplete({ source: function (request, response) { console.log(request.term); $.ajax({ // Wikipedia API url link url: \"http://en.wikipedia.org/w/api.php\", dataType: \"jsonp\", data: { action: \"opensearch\", // Output format format: \"json\", search: request.term, namespace: 0, // Maximum number of result // to be shown limit: 8, }, success: function (data) { response(data[1]); }, }); }, }); </script></body> </html>",
"e": 29417,
"s": 26630,
"text": null
},
{
"code": null,
"e": 29425,
"s": 29417,
"text": "Output:"
},
{
"code": null,
"e": 29562,
"s": 29425,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 29571,
"s": 29562,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29581,
"s": 29571,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29593,
"s": 29581,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 29597,
"s": 29593,
"text": "CSS"
},
{
"code": null,
"e": 29602,
"s": 29597,
"text": "HTML"
},
{
"code": null,
"e": 29609,
"s": 29602,
"text": "JQuery"
},
{
"code": null,
"e": 29626,
"s": 29609,
"text": "Web Technologies"
},
{
"code": null,
"e": 29653,
"s": 29626,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29658,
"s": 29653,
"text": "HTML"
},
{
"code": null,
"e": 29756,
"s": 29658,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29765,
"s": 29756,
"text": "Comments"
},
{
"code": null,
"e": 29778,
"s": 29765,
"text": "Old Comments"
},
{
"code": null,
"e": 29815,
"s": 29778,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29844,
"s": 29815,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29883,
"s": 29844,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29925,
"s": 29883,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 29960,
"s": 29925,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 30020,
"s": 29960,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30081,
"s": 30020,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30134,
"s": 30081,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 30184,
"s": 30134,
"text": "How to Insert Form Data into Database using PHP ?"
}
]
|
How to use Mail Merge in MS Word? | 29 Oct, 2021
Many day-to-day applications require similar documents containing similar text to be sent to a number of persons. These documents also have a typical common layout. Invitation letters sent to guests have a more-or-less common content and layout. Only the names of the recipients are different in these letters. One obvious way to generate such letters is to type all of them individually, putting the same amount of effort again and again. Another solution could be to copy the same block of text again and again onto the new letters. The names and addresses etc., which are different from each letter, can be entered separately in the documents. Though this method saves a lot of effort, it still requires proper caution. There should be a way where these kinds of documents can be prepared automatically. This task can be easily automated if we use the mail merge feature of a word processor. So, it is time we learnt the mail-merge feature of the word.
Components of mail merge:
The three main components of the merging process are the main document, the data source, and the merged document.
The main document contains the main body of your letter, field names, and merges instructions. The basic information within the main document remains equivalent.The data source (or Recipients’ list) stores the knowledge that changes for every document. This information is inserted in the main document one by one. An example of the data source is a name and address list from which the program gets what you want to include in the main document.The merged document contains the main text from the main document and data from a data source.
The main document contains the main body of your letter, field names, and merges instructions. The basic information within the main document remains equivalent.
The data source (or Recipients’ list) stores the knowledge that changes for every document. This information is inserted in the main document one by one. An example of the data source is a name and address list from which the program gets what you want to include in the main document.
The merged document contains the main text from the main document and data from a data source.
Steps for mail merger:
Step 1:
Open MS Word and click on the command sequence: Mailings tab → Start mail merge group → Select recipients button → Type new List.
A dialog namely “New Address List” will pop up(as shown in the below image). Type here the desired data under the given headings. To add a new record, click on the “New Entry” button at the bottom of the dialog and click OK when you are done.
Step 2: Prepare Master Letter
The second step is to prepare our master letter for use in the mail merge. Before we enter all the letter text we’d like to link this Word file to our list of names.
Create a blank word document.
Click Mailings tab → Start Mail Merge group → Start Mail Merge → Letters command.
Then click the Mailings tab → Start Mail Merge group → Select Recipients button → Use Existing List command.
Now we can start typing the letter.
Now we would like to add the name and address and other details for the people on the list.
Mailings tab→ Write & Insert Field group → Insert Merge Field button.
A pop-down will appear showing all the table headings, so choose Title and press the spacebar to create a space.
Then do this again and choose FirstName, followed by a space (i.e., press only spacebar key and no other key); then choose LastName but this time press the Enter key to create a new line. Then repeat the steps to choose the Address field, and press enter key.
Step 3:
Before we actually carry out the merge, we must first preview what the merged letters will look like.
Mailings tab→ Preview Results group → Preview Results button
Once we are happy with the preview, you can carry out the actual mail merge.
To do this you click the Mailings tab → Finish group → Finish & Merge button and choose Edit Individual Documents.
In the Merge to New Document panel, click All to create a separate letter for each person on the Names list. Word then creates a fresh document with as many pages as there are names on your list, and every page contains a wonderfully merged letter with all the correct individuals’ details.
We can save this with an appropriate name, such as ABC.docx
Question 1: What is a mail merge?
Solution:
Mail Merge, a popular tool for personalizing printed letters, is nowadays also available for emails. Google Mail, Google Sheets make it happen for all Google domain-based emails.
Question 2: what are the uses of mail merge?
Solution:
Writing a letter to a customer to tell them about upcoming offers or inform about some changes in business context.
Mailshot for sending out a survey to a large number of people.
Invoices
School names on to the certificate
Personal
Question 3: Give the advantage of mail merge?
Solution:
Once the merge has been found out , thousands of letters are often produced very quickly.
Easier to check for spelling errors as we need to check and correct at one place only; all letters will show the changes.
Letters can be personalized.
A standard letter can be saved and reused.
In male merge, we can reuse the same data source, and it reduces the risk of errors.
Question 4: What are the main components of the Mail Merge process?
Solution:
The main document.
The data source.
The merged document.
Question 5: How many files are created in Mail Merge?
Solution:
There are two files created in Mail Merge. The first file is called the source file that contains the content of the main document and the second file is known as the data source file that contains the name, address and other important details of the beneficiary.
Question 6: Can we insert an attachment when performing a merge to an e-mail message?
Solution:
No, we cannot insert an attachment when performing a merge to an email message.
Question 7: In Mail Merge, multiple copies of the merged document are often printed.
Solution:
TRUE
surindertarika1234
Picked
class 6
How To
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 984,
"s": 28,
"text": "Many day-to-day applications require similar documents containing similar text to be sent to a number of persons. These documents also have a typical common layout. Invitation letters sent to guests have a more-or-less common content and layout. Only the names of the recipients are different in these letters. One obvious way to generate such letters is to type all of them individually, putting the same amount of effort again and again. Another solution could be to copy the same block of text again and again onto the new letters. The names and addresses etc., which are different from each letter, can be entered separately in the documents. Though this method saves a lot of effort, it still requires proper caution. There should be a way where these kinds of documents can be prepared automatically. This task can be easily automated if we use the mail merge feature of a word processor. So, it is time we learnt the mail-merge feature of the word."
},
{
"code": null,
"e": 1011,
"s": 984,
"text": "Components of mail merge: "
},
{
"code": null,
"e": 1125,
"s": 1011,
"text": "The three main components of the merging process are the main document, the data source, and the merged document."
},
{
"code": null,
"e": 1666,
"s": 1125,
"text": "The main document contains the main body of your letter, field names, and merges instructions. The basic information within the main document remains equivalent.The data source (or Recipients’ list) stores the knowledge that changes for every document. This information is inserted in the main document one by one. An example of the data source is a name and address list from which the program gets what you want to include in the main document.The merged document contains the main text from the main document and data from a data source."
},
{
"code": null,
"e": 1828,
"s": 1666,
"text": "The main document contains the main body of your letter, field names, and merges instructions. The basic information within the main document remains equivalent."
},
{
"code": null,
"e": 2114,
"s": 1828,
"text": "The data source (or Recipients’ list) stores the knowledge that changes for every document. This information is inserted in the main document one by one. An example of the data source is a name and address list from which the program gets what you want to include in the main document."
},
{
"code": null,
"e": 2209,
"s": 2114,
"text": "The merged document contains the main text from the main document and data from a data source."
},
{
"code": null,
"e": 2233,
"s": 2209,
"text": "Steps for mail merger: "
},
{
"code": null,
"e": 2241,
"s": 2233,
"text": "Step 1:"
},
{
"code": null,
"e": 2371,
"s": 2241,
"text": "Open MS Word and click on the command sequence: Mailings tab → Start mail merge group → Select recipients button → Type new List."
},
{
"code": null,
"e": 2614,
"s": 2371,
"text": "A dialog namely “New Address List” will pop up(as shown in the below image). Type here the desired data under the given headings. To add a new record, click on the “New Entry” button at the bottom of the dialog and click OK when you are done."
},
{
"code": null,
"e": 2644,
"s": 2614,
"text": "Step 2: Prepare Master Letter"
},
{
"code": null,
"e": 2811,
"s": 2644,
"text": "The second step is to prepare our master letter for use in the mail merge. Before we enter all the letter text we’d like to link this Word file to our list of names."
},
{
"code": null,
"e": 2841,
"s": 2811,
"text": "Create a blank word document."
},
{
"code": null,
"e": 2923,
"s": 2841,
"text": "Click Mailings tab → Start Mail Merge group → Start Mail Merge → Letters command."
},
{
"code": null,
"e": 3033,
"s": 2923,
"text": "Then click the Mailings tab → Start Mail Merge group → Select Recipients button → Use Existing List command."
},
{
"code": null,
"e": 3069,
"s": 3033,
"text": "Now we can start typing the letter."
},
{
"code": null,
"e": 3161,
"s": 3069,
"text": "Now we would like to add the name and address and other details for the people on the list."
},
{
"code": null,
"e": 3231,
"s": 3161,
"text": "Mailings tab→ Write & Insert Field group → Insert Merge Field button."
},
{
"code": null,
"e": 3344,
"s": 3231,
"text": "A pop-down will appear showing all the table headings, so choose Title and press the spacebar to create a space."
},
{
"code": null,
"e": 3605,
"s": 3344,
"text": "Then do this again and choose FirstName, followed by a space (i.e., press only spacebar key and no other key); then choose LastName but this time press the Enter key to create a new line. Then repeat the steps to choose the Address field, and press enter key. "
},
{
"code": null,
"e": 3613,
"s": 3605,
"text": "Step 3:"
},
{
"code": null,
"e": 3715,
"s": 3613,
"text": "Before we actually carry out the merge, we must first preview what the merged letters will look like."
},
{
"code": null,
"e": 3776,
"s": 3715,
"text": "Mailings tab→ Preview Results group → Preview Results button"
},
{
"code": null,
"e": 3853,
"s": 3776,
"text": "Once we are happy with the preview, you can carry out the actual mail merge."
},
{
"code": null,
"e": 3969,
"s": 3853,
"text": "To do this you click the Mailings tab → Finish group → Finish & Merge button and choose Edit Individual Documents."
},
{
"code": null,
"e": 4260,
"s": 3969,
"text": "In the Merge to New Document panel, click All to create a separate letter for each person on the Names list. Word then creates a fresh document with as many pages as there are names on your list, and every page contains a wonderfully merged letter with all the correct individuals’ details."
},
{
"code": null,
"e": 4320,
"s": 4260,
"text": "We can save this with an appropriate name, such as ABC.docx"
},
{
"code": null,
"e": 4354,
"s": 4320,
"text": "Question 1: What is a mail merge?"
},
{
"code": null,
"e": 4364,
"s": 4354,
"text": "Solution:"
},
{
"code": null,
"e": 4543,
"s": 4364,
"text": "Mail Merge, a popular tool for personalizing printed letters, is nowadays also available for emails. Google Mail, Google Sheets make it happen for all Google domain-based emails."
},
{
"code": null,
"e": 4588,
"s": 4543,
"text": "Question 2: what are the uses of mail merge?"
},
{
"code": null,
"e": 4598,
"s": 4588,
"text": "Solution:"
},
{
"code": null,
"e": 4714,
"s": 4598,
"text": "Writing a letter to a customer to tell them about upcoming offers or inform about some changes in business context."
},
{
"code": null,
"e": 4777,
"s": 4714,
"text": "Mailshot for sending out a survey to a large number of people."
},
{
"code": null,
"e": 4786,
"s": 4777,
"text": "Invoices"
},
{
"code": null,
"e": 4821,
"s": 4786,
"text": "School names on to the certificate"
},
{
"code": null,
"e": 4830,
"s": 4821,
"text": "Personal"
},
{
"code": null,
"e": 4876,
"s": 4830,
"text": "Question 3: Give the advantage of mail merge?"
},
{
"code": null,
"e": 4886,
"s": 4876,
"text": "Solution:"
},
{
"code": null,
"e": 4976,
"s": 4886,
"text": "Once the merge has been found out , thousands of letters are often produced very quickly."
},
{
"code": null,
"e": 5098,
"s": 4976,
"text": "Easier to check for spelling errors as we need to check and correct at one place only; all letters will show the changes."
},
{
"code": null,
"e": 5127,
"s": 5098,
"text": "Letters can be personalized."
},
{
"code": null,
"e": 5170,
"s": 5127,
"text": "A standard letter can be saved and reused."
},
{
"code": null,
"e": 5255,
"s": 5170,
"text": "In male merge, we can reuse the same data source, and it reduces the risk of errors."
},
{
"code": null,
"e": 5323,
"s": 5255,
"text": "Question 4: What are the main components of the Mail Merge process?"
},
{
"code": null,
"e": 5333,
"s": 5323,
"text": "Solution:"
},
{
"code": null,
"e": 5352,
"s": 5333,
"text": "The main document."
},
{
"code": null,
"e": 5369,
"s": 5352,
"text": "The data source."
},
{
"code": null,
"e": 5390,
"s": 5369,
"text": "The merged document."
},
{
"code": null,
"e": 5444,
"s": 5390,
"text": "Question 5: How many files are created in Mail Merge?"
},
{
"code": null,
"e": 5454,
"s": 5444,
"text": "Solution:"
},
{
"code": null,
"e": 5718,
"s": 5454,
"text": "There are two files created in Mail Merge. The first file is called the source file that contains the content of the main document and the second file is known as the data source file that contains the name, address and other important details of the beneficiary."
},
{
"code": null,
"e": 5804,
"s": 5718,
"text": "Question 6: Can we insert an attachment when performing a merge to an e-mail message?"
},
{
"code": null,
"e": 5814,
"s": 5804,
"text": "Solution:"
},
{
"code": null,
"e": 5894,
"s": 5814,
"text": "No, we cannot insert an attachment when performing a merge to an email message."
},
{
"code": null,
"e": 5979,
"s": 5894,
"text": "Question 7: In Mail Merge, multiple copies of the merged document are often printed."
},
{
"code": null,
"e": 5989,
"s": 5979,
"text": "Solution:"
},
{
"code": null,
"e": 5994,
"s": 5989,
"text": "TRUE"
},
{
"code": null,
"e": 6013,
"s": 5994,
"text": "surindertarika1234"
},
{
"code": null,
"e": 6020,
"s": 6013,
"text": "Picked"
},
{
"code": null,
"e": 6028,
"s": 6020,
"text": "class 6"
},
{
"code": null,
"e": 6035,
"s": 6028,
"text": "How To"
},
{
"code": null,
"e": 6051,
"s": 6035,
"text": "School Learning"
},
{
"code": null,
"e": 6070,
"s": 6051,
"text": "School Programming"
}
]
|
Excel VBA | count() functions | 05 Jul, 2018
Visual Basic for Applications (VBA) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft.
With Excel VBA one can automate many tasks in excel and all other office software. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its various functions.Let’s see Count() functions in Excel.
COUNT: It allows to count the number of cells that contain numbers in a range. One can use the COUNT function to calculate the total number of entries in an array of numbers.Syntax:=COUNT(value1, value2...)value1: The very first item required to count numbers.value2: It can be specified upto 255 other entries which you want to count.Note:-> Only those arguments are counted that are numbers or text enclosed between quotation marks, as, “2”.-> Arguments like logical values and text representation of numbers that are typed directly are counted.-> Any values that cannot be translated to numbers are ignored.Example:Output:COUNTA: This counts only those range of cells which are not empty.Syntax:=COUNTA(value1, value2...)value1: It is the first argument to be counted.value2: All additional arguments can be represented that has to becounted. This can be specified upto 255 arguments.Note: This will count cells that contain any kind of information that includes error values or empty text also, but not empty cells.Example:Output:COUNTIF:This will allow user to count the number of cells which meet a certain criteria.Syntax:=COUNTIF(where to look, what to look criteria)Example:Output:COUNTIFS: It will map criteria to cells in multiple ranges and the number of times all criteria met are counted.Syntax:=COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]...)criteria_range1: First range to evaluate criteria.criteria1: Criteria in any form that defines which all cells to be counted.criteria_range2, criteria2, ... : Additional range with their criteria. Specified upto 127 range/criteria.Remarks:-> Wildcard characters can be used.-> If criteria meets an empty cell, it will be treated as 0 value.-> Count increases by 1 as the first cells meet their criteria, then the second cell meet and count again increases by 1 and so on.Example:Output:My Personal Notes
arrow_drop_upSave
COUNT: It allows to count the number of cells that contain numbers in a range. One can use the COUNT function to calculate the total number of entries in an array of numbers.Syntax:=COUNT(value1, value2...)value1: The very first item required to count numbers.value2: It can be specified upto 255 other entries which you want to count.Note:-> Only those arguments are counted that are numbers or text enclosed between quotation marks, as, “2”.-> Arguments like logical values and text representation of numbers that are typed directly are counted.-> Any values that cannot be translated to numbers are ignored.Example:Output:
Syntax:
=COUNT(value1, value2...)
value1: The very first item required to count numbers.value2: It can be specified upto 255 other entries which you want to count.
Note:-> Only those arguments are counted that are numbers or text enclosed between quotation marks, as, “2”.-> Arguments like logical values and text representation of numbers that are typed directly are counted.-> Any values that cannot be translated to numbers are ignored.
Example:
Output:
COUNTA: This counts only those range of cells which are not empty.Syntax:=COUNTA(value1, value2...)value1: It is the first argument to be counted.value2: All additional arguments can be represented that has to becounted. This can be specified upto 255 arguments.Note: This will count cells that contain any kind of information that includes error values or empty text also, but not empty cells.Example:Output:
Syntax:
=COUNTA(value1, value2...)
value1: It is the first argument to be counted.value2: All additional arguments can be represented that has to becounted. This can be specified upto 255 arguments.
Note: This will count cells that contain any kind of information that includes error values or empty text also, but not empty cells.
Example:
Output:
COUNTIF:This will allow user to count the number of cells which meet a certain criteria.Syntax:=COUNTIF(where to look, what to look criteria)Example:Output:
Syntax:
=COUNTIF(where to look, what to look criteria)
Example:
Output:
COUNTIFS: It will map criteria to cells in multiple ranges and the number of times all criteria met are counted.Syntax:=COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]...)criteria_range1: First range to evaluate criteria.criteria1: Criteria in any form that defines which all cells to be counted.criteria_range2, criteria2, ... : Additional range with their criteria. Specified upto 127 range/criteria.Remarks:-> Wildcard characters can be used.-> If criteria meets an empty cell, it will be treated as 0 value.-> Count increases by 1 as the first cells meet their criteria, then the second cell meet and count again increases by 1 and so on.Example:Output:My Personal Notes
arrow_drop_upSave
Syntax:
=COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]...)
criteria_range1: First range to evaluate criteria.criteria1: Criteria in any form that defines which all cells to be counted.criteria_range2, criteria2, ... : Additional range with their criteria. Specified upto 127 range/criteria.
Remarks:
-> Wildcard characters can be used.-> If criteria meets an empty cell, it will be treated as 0 value.-> Count increases by 1 as the first cells meet their criteria, then the second cell meet and count again increases by 1 and so on.
Example:
Output:
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
How to Learn Data Science in 10 weeks?
What is Hashing | A Complete Tutorial
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
Types of Software Testing
What is Data Structure: Types, Classifications and Applications
GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa
Roadmap to Learn JavaScript For Beginners | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jul, 2018"
},
{
"code": null,
"e": 179,
"s": 28,
"text": "Visual Basic for Applications (VBA) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft."
},
{
"code": null,
"e": 431,
"s": 179,
"text": "With Excel VBA one can automate many tasks in excel and all other office software. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its various functions.Let’s see Count() functions in Excel."
},
{
"code": null,
"e": 2332,
"s": 431,
"text": "COUNT: It allows to count the number of cells that contain numbers in a range. One can use the COUNT function to calculate the total number of entries in an array of numbers.Syntax:=COUNT(value1, value2...)value1: The very first item required to count numbers.value2: It can be specified upto 255 other entries which you want to count.Note:-> Only those arguments are counted that are numbers or text enclosed between quotation marks, as, “2”.-> Arguments like logical values and text representation of numbers that are typed directly are counted.-> Any values that cannot be translated to numbers are ignored.Example:Output:COUNTA: This counts only those range of cells which are not empty.Syntax:=COUNTA(value1, value2...)value1: It is the first argument to be counted.value2: All additional arguments can be represented that has to becounted. This can be specified upto 255 arguments.Note: This will count cells that contain any kind of information that includes error values or empty text also, but not empty cells.Example:Output:COUNTIF:This will allow user to count the number of cells which meet a certain criteria.Syntax:=COUNTIF(where to look, what to look criteria)Example:Output:COUNTIFS: It will map criteria to cells in multiple ranges and the number of times all criteria met are counted.Syntax:=COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]...)criteria_range1: First range to evaluate criteria.criteria1: Criteria in any form that defines which all cells to be counted.criteria_range2, criteria2, ... : Additional range with their criteria. Specified upto 127 range/criteria.Remarks:-> Wildcard characters can be used.-> If criteria meets an empty cell, it will be treated as 0 value.-> Count increases by 1 as the first cells meet their criteria, then the second cell meet and count again increases by 1 and so on.Example:Output:My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 2958,
"s": 2332,
"text": "COUNT: It allows to count the number of cells that contain numbers in a range. One can use the COUNT function to calculate the total number of entries in an array of numbers.Syntax:=COUNT(value1, value2...)value1: The very first item required to count numbers.value2: It can be specified upto 255 other entries which you want to count.Note:-> Only those arguments are counted that are numbers or text enclosed between quotation marks, as, “2”.-> Arguments like logical values and text representation of numbers that are typed directly are counted.-> Any values that cannot be translated to numbers are ignored.Example:Output:"
},
{
"code": null,
"e": 2966,
"s": 2958,
"text": "Syntax:"
},
{
"code": null,
"e": 2992,
"s": 2966,
"text": "=COUNT(value1, value2...)"
},
{
"code": null,
"e": 3122,
"s": 2992,
"text": "value1: The very first item required to count numbers.value2: It can be specified upto 255 other entries which you want to count."
},
{
"code": null,
"e": 3398,
"s": 3122,
"text": "Note:-> Only those arguments are counted that are numbers or text enclosed between quotation marks, as, “2”.-> Arguments like logical values and text representation of numbers that are typed directly are counted.-> Any values that cannot be translated to numbers are ignored."
},
{
"code": null,
"e": 3407,
"s": 3398,
"text": "Example:"
},
{
"code": null,
"e": 3415,
"s": 3407,
"text": "Output:"
},
{
"code": null,
"e": 3825,
"s": 3415,
"text": "COUNTA: This counts only those range of cells which are not empty.Syntax:=COUNTA(value1, value2...)value1: It is the first argument to be counted.value2: All additional arguments can be represented that has to becounted. This can be specified upto 255 arguments.Note: This will count cells that contain any kind of information that includes error values or empty text also, but not empty cells.Example:Output:"
},
{
"code": null,
"e": 3833,
"s": 3825,
"text": "Syntax:"
},
{
"code": null,
"e": 3860,
"s": 3833,
"text": "=COUNTA(value1, value2...)"
},
{
"code": null,
"e": 4024,
"s": 3860,
"text": "value1: It is the first argument to be counted.value2: All additional arguments can be represented that has to becounted. This can be specified upto 255 arguments."
},
{
"code": null,
"e": 4157,
"s": 4024,
"text": "Note: This will count cells that contain any kind of information that includes error values or empty text also, but not empty cells."
},
{
"code": null,
"e": 4166,
"s": 4157,
"text": "Example:"
},
{
"code": null,
"e": 4174,
"s": 4166,
"text": "Output:"
},
{
"code": null,
"e": 4331,
"s": 4174,
"text": "COUNTIF:This will allow user to count the number of cells which meet a certain criteria.Syntax:=COUNTIF(where to look, what to look criteria)Example:Output:"
},
{
"code": null,
"e": 4339,
"s": 4331,
"text": "Syntax:"
},
{
"code": null,
"e": 4386,
"s": 4339,
"text": "=COUNTIF(where to look, what to look criteria)"
},
{
"code": null,
"e": 4395,
"s": 4386,
"text": "Example:"
},
{
"code": null,
"e": 4403,
"s": 4395,
"text": "Output:"
},
{
"code": null,
"e": 5114,
"s": 4403,
"text": "COUNTIFS: It will map criteria to cells in multiple ranges and the number of times all criteria met are counted.Syntax:=COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]...)criteria_range1: First range to evaluate criteria.criteria1: Criteria in any form that defines which all cells to be counted.criteria_range2, criteria2, ... : Additional range with their criteria. Specified upto 127 range/criteria.Remarks:-> Wildcard characters can be used.-> If criteria meets an empty cell, it will be treated as 0 value.-> Count increases by 1 as the first cells meet their criteria, then the second cell meet and count again increases by 1 and so on.Example:Output:My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 5122,
"s": 5114,
"text": "Syntax:"
},
{
"code": null,
"e": 5193,
"s": 5122,
"text": "=COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]...)"
},
{
"code": null,
"e": 5425,
"s": 5193,
"text": "criteria_range1: First range to evaluate criteria.criteria1: Criteria in any form that defines which all cells to be counted.criteria_range2, criteria2, ... : Additional range with their criteria. Specified upto 127 range/criteria."
},
{
"code": null,
"e": 5434,
"s": 5425,
"text": "Remarks:"
},
{
"code": null,
"e": 5667,
"s": 5434,
"text": "-> Wildcard characters can be used.-> If criteria meets an empty cell, it will be treated as 0 value.-> Count increases by 1 as the first cells meet their criteria, then the second cell meet and count again increases by 1 and so on."
},
{
"code": null,
"e": 5676,
"s": 5667,
"text": "Example:"
},
{
"code": null,
"e": 5684,
"s": 5676,
"text": "Output:"
},
{
"code": null,
"e": 5690,
"s": 5684,
"text": "GBlog"
},
{
"code": null,
"e": 5788,
"s": 5690,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5813,
"s": 5788,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 5868,
"s": 5813,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 5905,
"s": 5868,
"text": "Geek Streak - 24 Days POTD Challenge"
},
{
"code": null,
"e": 5944,
"s": 5905,
"text": "How to Learn Data Science in 10 weeks?"
},
{
"code": null,
"e": 5982,
"s": 5944,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 6048,
"s": 5982,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 6074,
"s": 6048,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 6138,
"s": 6074,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 6209,
"s": 6138,
"text": "GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa"
}
]
|
SAR command in Linux to monitor system performance | 18 Feb, 2022
sar: System Activity Report
It can be used to monitor Linux system’s resources like CPU usage, Memory utilization, I/O devices consumption, Network monitoring, Disk usage, process and thread allocation, battery performance, Plug and play devices, Processor performance, file system and more.Linux system Monitoring and analyzing aids understanding system resource usage which can help to improve system performance to handle more requests.
By default SAR command displays result on the output screen, in addition result can also be stored in the file specified by the -o filename option. Any user can collect information about system performance using system activities flags. The SAR command will show only CPU monitoring activity if any flag is not specified by user.
Note: sar may not be installed by default. We need to install sysstat before using it (For example, in Ubuntu, we can install using sudo apt install sysstat). After installing sysstat, we need to make sure that data collection is enabled. (For example, in Ubuntu, we can enable data collection by marking ENABLED=”true” in /etc/default/sysstat)
Syntax :
$ sar -[ options ] time_interval number_of_tines_to_display
Examples :
1. To see help
2. To start SAR Service
start sar service
[viyadav@vymac]# systemctl start sysstat.service
3. To verify the sar version :
hduser@mahesh-Inspiron-3543:~$ sar -V
sysstat version 11.2.0
(C) Sebastien Godard (sysstat orange.fr)
4. To report CPU details total 5 times with the interval of 2 seconds. If the interval command is set to zero, average statistics from the time system started are presented. If the count is not provided and the interval is given, statistics are provided continuously after every interval.
hduser@mahesh-Inspiron-3543:~$ sar -u 2 5
Linux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)
04:00:20 IST CPU %user %nice %system %iowait %steal %idle
04:00:22 IST all 0.25 0.00 0.00 0.00 0.00 99.75
04:00:24 IST all 0.25 0.00 0.13 0.00 0.00 99.62
04:00:26 IST all 0.88 0.00 0.25 1.13 0.00 97.75
04:00:28 IST all 0.00 0.00 0.25 0.13 0.00 99.62
04:00:30 IST all 0.25 0.00 0.38 0.12 0.00 99.25
Average: all 0.33 0.00 0.20 0.28 0.00 99.20
5. To report about the amount of memory used, amount of memory free, available cache, available buffers total 3 times with the interval of 1 second.
hduser@mahesh-Inspiron-3543:~$ sar -r 1 3
Linux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)
04:05:12 IST kbmemfree kbmemused %memused kbbuffers kbcached kbcommit %commit kbactive kbinact kbdirty
04:05:13 IST 6067308 2017252 24.95 62300 853612 4303644 35.89 1308856 525628 60
04:05:14 IST 6067308 2017252 24.95 62300 853612 4303644 35.89 1308856 525628 60
04:05:15 IST 6067308 2017252 24.95 62300 853612 4303644 35.89 1308856 525628 60
Average: 6067308 2017252 24.95 62300 853612 4303644 35.89 1308856 525628 60
6. To report about file systems mounted on the device total 5 times with the interval of 2 seconds.
hduser@mahesh-Inspiron-3543:~$ sar -F 2 5
Linux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)
04:02:38 IST MBfsfree MBfsused %fsused %ufsused Ifree Iused %Iused FILESYSTEM
04:02:40 IST 78181 18727 19.32 24.43 6066698 249334 3.95 /dev/sda11
04:02:40 IST 441 55 11.04 11.04 0 0 0.00 /dev/sda1
04:02:40 IST 2123 1747 45.13 45.13 0 0 0.00 /dev/sdb1
04:02:40 IST 28846 205214 87.68 87.68 29589586 145270 0.49 /dev/sda8
7. To report about block devices details total 3 times with the interval of 1 second.
hduser@mahesh-Inspiron-3543:~$ sar -d 1 3
Linux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)
04:04:34 IST DEV tps rd_sec/s wr_sec/s avgrq-sz avgqu-sz await svctm %util
04:04:35 IST dev8-0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
04:04:35 IST dev8-16 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
8. To report run queue length, number of processes and load average
hduser@mahesh-Inspiron-3543:~$ sar -q 2 5
Linux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)
04:01:54 IST runq-sz plist-sz ldavg-1 ldavg-5 ldavg-15 blocked
04:01:56 IST 0 491 0.21 0.16 0.15 0
04:01:58 IST 0 491 0.21 0.16 0.15 0
04:02:00 IST 0 491 0.19 0.16 0.15 0
04:02:02 IST 0 491 0.19 0.16 0.15 0
04:02:04 IST 0 491 0.18 0.16 0.14 0
Average: 0 491 0.20 0.16 0.15 0
9. To report cpu usage for given core :
hduser@mahesh-Inspiron-3543:~$ sar -P 1 1 3
Linux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)
04:16:38 IST CPU %user %nice %system %iowait %steal %idle
04:16:39 IST 1 0.00 0.00 0.00 0.00 0.00 100.00
04:16:40 IST 1 0.99 0.00 0.99 0.00 0.00 98.02
04:16:41 IST 1 1.00 0.00 0.00 0.00 0.00 99.00
Average: 1 0.66 0.00 0.33 0.00 0.00 99.00
10. To report about network interface, network speed, IPV4, TCPV4, ICMPV4 network traffic and errors
hduser@mahesh-Inspiron-3543:~$ sar -n DEV 1 3 | egrep -v lo
Linux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)
04:04:00 IST IFACE rxpck/s txpck/s rxkB/s txkB/s rxcmp/s txcmp/s rxmcst/s %ifutil
04:04:01 IST enp0s29u1u2 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
04:04:01 IST enp7s0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
11. To report details about the process, kernel thread, i-node, and the file tables
hduser@mahesh-Inspiron-3543:~$ sar -v 1 3
Linux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)
04:25:26 IST dentunusd file-nr inode-nr pty-nr
04:25:27 IST 43219 7584 46874 17
04:25:28 IST 43219 7584 46873 17
04:25:29 IST 43219 7584 46873 17
Average: 43219 7584 46873 17
12. To report messages, semaphores and processes details for all processors and system-wide.
hduser@mahesh-Inspiron-3543:~$ sar -mu -P ALL
13. To report statistics about swapping
hduser@mahesh-Inspiron-3543:~$ sar -S 1 3
Linux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)
04:08:09 IST kbswpfree kbswpused %swpused kbswpcad %swpcad
04:08:10 IST 3906556 0 0.00 0 0.00
04:08:11 IST 3906556 0 0.00 0 0.00
04:08:12 IST 3906556 0 0.00 0 0.00
Average: 3906556 0 0.00 0 0.00
14. To report details about I/O operations like transaction per second, read per second, write per second
hduser@mahesh-Inspiron-3543:~$ sar -b 1 3
Linux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)
04:08:41 IST tps rtps wtps bread/s bwrtn/s
04:08:42 IST 0.00 0.00 0.00 0.00 0.00
04:08:43 IST 2.00 0.00 2.00 0.00 64.00
04:08:44 IST 0.00 0.00 0.00 0.00 0.00
Average: 0.67 0.00 0.67 0.00 21.33
15. To report statistics about context switching, number of processes created per second, number of swap per second
hduser@mahesh-Inspiron-3543:~$ sar -w 1 3
Linux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)
04:09:42 IST proc/s cswch/s
04:09:43 IST 0.00 480.00
04:09:44 IST 0.00 637.00
04:09:45 IST 0.00 859.00
Average: 0.00 658.67
16. To report paging statistics (KBs paged-in/sec, KBs paged-out/sec, pagefault/sec etc.)
hatim.lokhandwala@ET-C02PR06MG8:~$ sar -B 2 5
Linux 3.2.0-4-amd64 (ET-C02PR06MG8) 04/26/2019 _x86_64_ (6 CPU)
11:36:32 PM pgpgin/s pgpgout/s fault/s majflt/s pgfree/s pgscank/s pgscand/s pgsteal/s %vmeff
11:36:34 PM 0.00 14.00 13.50 0.00 24.00 0.00 0.00 0.00 0.00
11:36:36 PM 0.00 291.50 6265.50 0.00 1858.00 0.00 0.00 0.00 0.00
11:36:38 PM 0.00 270.00 8.50 0.00 41.00 0.00 0.00 0.00 0.00
11:36:40 PM 0.00 40.50 8.50 0.00 21.00 0.00 0.00 0.00 0.00
11:36:42 PM 0.00 1796.50 8.50 0.00 28.00 0.00 0.00 0.00 0.00
Average: 0.00 482.50 1260.90 0.00 394.40 0.00 0.00 0.00 0.00
HatimLokhandwala
vikeshyadav1
germanshephered48
ashwinkvit
linux-command
Linux-system-commands
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
nohup Command in Linux with Examples
chmod command in Linux with examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 83,
"s": 54,
"text": "sar: System Activity Report "
},
{
"code": null,
"e": 496,
"s": 83,
"text": "It can be used to monitor Linux system’s resources like CPU usage, Memory utilization, I/O devices consumption, Network monitoring, Disk usage, process and thread allocation, battery performance, Plug and play devices, Processor performance, file system and more.Linux system Monitoring and analyzing aids understanding system resource usage which can help to improve system performance to handle more requests. "
},
{
"code": null,
"e": 828,
"s": 496,
"text": "By default SAR command displays result on the output screen, in addition result can also be stored in the file specified by the -o filename option. Any user can collect information about system performance using system activities flags. The SAR command will show only CPU monitoring activity if any flag is not specified by user. "
},
{
"code": null,
"e": 1174,
"s": 828,
"text": "Note: sar may not be installed by default. We need to install sysstat before using it (For example, in Ubuntu, we can install using sudo apt install sysstat). After installing sysstat, we need to make sure that data collection is enabled. (For example, in Ubuntu, we can enable data collection by marking ENABLED=”true” in /etc/default/sysstat) "
},
{
"code": null,
"e": 1243,
"s": 1174,
"text": "Syntax :\n$ sar -[ options ] time_interval number_of_tines_to_display"
},
{
"code": null,
"e": 1255,
"s": 1243,
"text": "Examples : "
},
{
"code": null,
"e": 1271,
"s": 1255,
"text": "1. To see help "
},
{
"code": null,
"e": 1296,
"s": 1271,
"text": "2. To start SAR Service "
},
{
"code": null,
"e": 1363,
"s": 1296,
"text": "start sar service\n[viyadav@vymac]# systemctl start sysstat.service"
},
{
"code": null,
"e": 1395,
"s": 1363,
"text": "3. To verify the sar version : "
},
{
"code": null,
"e": 1498,
"s": 1395,
"text": "hduser@mahesh-Inspiron-3543:~$ sar -V\nsysstat version 11.2.0\n(C) Sebastien Godard (sysstat orange.fr)"
},
{
"code": null,
"e": 1789,
"s": 1498,
"text": "4. To report CPU details total 5 times with the interval of 2 seconds. If the interval command is set to zero, average statistics from the time system started are presented. If the count is not provided and the interval is given, statistics are provided continuously after every interval. "
},
{
"code": null,
"e": 2499,
"s": 1789,
"text": "hduser@mahesh-Inspiron-3543:~$ sar -u 2 5\nLinux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)\n\n04:00:20 IST CPU %user %nice %system %iowait %steal %idle\n04:00:22 IST all 0.25 0.00 0.00 0.00 0.00 99.75\n04:00:24 IST all 0.25 0.00 0.13 0.00 0.00 99.62\n04:00:26 IST all 0.88 0.00 0.25 1.13 0.00 97.75\n04:00:28 IST all 0.00 0.00 0.25 0.13 0.00 99.62\n04:00:30 IST all 0.25 0.00 0.38 0.12 0.00 99.25\nAverage: all 0.33 0.00 0.20 0.28 0.00 99.20"
},
{
"code": null,
"e": 2650,
"s": 2499,
"text": "5. To report about the amount of memory used, amount of memory free, available cache, available buffers total 3 times with the interval of 1 second. "
},
{
"code": null,
"e": 3356,
"s": 2650,
"text": "hduser@mahesh-Inspiron-3543:~$ sar -r 1 3\nLinux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)\n\n04:05:12 IST kbmemfree kbmemused %memused kbbuffers kbcached kbcommit %commit kbactive kbinact kbdirty\n04:05:13 IST 6067308 2017252 24.95 62300 853612 4303644 35.89 1308856 525628 60\n04:05:14 IST 6067308 2017252 24.95 62300 853612 4303644 35.89 1308856 525628 60\n04:05:15 IST 6067308 2017252 24.95 62300 853612 4303644 35.89 1308856 525628 60\nAverage: 6067308 2017252 24.95 62300 853612 4303644 35.89 1308856 525628 60"
},
{
"code": null,
"e": 3458,
"s": 3356,
"text": "6. To report about file systems mounted on the device total 5 times with the interval of 2 seconds. "
},
{
"code": null,
"e": 4068,
"s": 3458,
"text": "hduser@mahesh-Inspiron-3543:~$ sar -F 2 5\nLinux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)\n\n04:02:38 IST MBfsfree MBfsused %fsused %ufsused Ifree Iused %Iused FILESYSTEM\n04:02:40 IST 78181 18727 19.32 24.43 6066698 249334 3.95 /dev/sda11\n04:02:40 IST 441 55 11.04 11.04 0 0 0.00 /dev/sda1\n04:02:40 IST 2123 1747 45.13 45.13 0 0 0.00 /dev/sdb1\n04:02:40 IST 28846 205214 87.68 87.68 29589586 145270 0.49 /dev/sda8"
},
{
"code": null,
"e": 4156,
"s": 4068,
"text": "7. To report about block devices details total 3 times with the interval of 1 second. "
},
{
"code": null,
"e": 4606,
"s": 4156,
"text": "hduser@mahesh-Inspiron-3543:~$ sar -d 1 3\nLinux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)\n\n04:04:34 IST DEV tps rd_sec/s wr_sec/s avgrq-sz avgqu-sz await svctm %util\n04:04:35 IST dev8-0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00\n04:04:35 IST dev8-16 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00"
},
{
"code": null,
"e": 4676,
"s": 4606,
"text": "8. To report run queue length, number of processes and load average "
},
{
"code": null,
"e": 5330,
"s": 4676,
"text": "hduser@mahesh-Inspiron-3543:~$ sar -q 2 5\nLinux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)\n\n04:01:54 IST runq-sz plist-sz ldavg-1 ldavg-5 ldavg-15 blocked\n04:01:56 IST 0 491 0.21 0.16 0.15 0\n04:01:58 IST 0 491 0.21 0.16 0.15 0\n04:02:00 IST 0 491 0.19 0.16 0.15 0\n04:02:02 IST 0 491 0.19 0.16 0.15 0\n04:02:04 IST 0 491 0.18 0.16 0.14 0\nAverage: 0 491 0.20 0.16 0.15 0"
},
{
"code": null,
"e": 5372,
"s": 5330,
"text": "9. To report cpu usage for given core : "
},
{
"code": null,
"e": 5920,
"s": 5372,
"text": "hduser@mahesh-Inspiron-3543:~$ sar -P 1 1 3\nLinux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)\n\n04:16:38 IST CPU %user %nice %system %iowait %steal %idle\n04:16:39 IST 1 0.00 0.00 0.00 0.00 0.00 100.00\n04:16:40 IST 1 0.99 0.00 0.99 0.00 0.00 98.02\n04:16:41 IST 1 1.00 0.00 0.00 0.00 0.00 99.00\nAverage: 1 0.66 0.00 0.33 0.00 0.00 99.00"
},
{
"code": null,
"e": 6023,
"s": 5920,
"text": "10. To report about network interface, network speed, IPV4, TCPV4, ICMPV4 network traffic and errors "
},
{
"code": null,
"e": 6493,
"s": 6023,
"text": "hduser@mahesh-Inspiron-3543:~$ sar -n DEV 1 3 | egrep -v lo\nLinux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)\n\n04:04:00 IST IFACE rxpck/s txpck/s rxkB/s txkB/s rxcmp/s txcmp/s rxmcst/s %ifutil\n04:04:01 IST enp0s29u1u2 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00\n04:04:01 IST enp7s0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00"
},
{
"code": null,
"e": 6579,
"s": 6493,
"text": "11. To report details about the process, kernel thread, i-node, and the file tables "
},
{
"code": null,
"e": 6985,
"s": 6579,
"text": "hduser@mahesh-Inspiron-3543:~$ sar -v 1 3\nLinux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)\n\n04:25:26 IST dentunusd file-nr inode-nr pty-nr\n04:25:27 IST 43219 7584 46874 17\n04:25:28 IST 43219 7584 46873 17\n04:25:29 IST 43219 7584 46873 17\nAverage: 43219 7584 46873 17"
},
{
"code": null,
"e": 7080,
"s": 6985,
"text": "12. To report messages, semaphores and processes details for all processors and system-wide. "
},
{
"code": null,
"e": 7126,
"s": 7080,
"text": "hduser@mahesh-Inspiron-3543:~$ sar -mu -P ALL"
},
{
"code": null,
"e": 7168,
"s": 7126,
"text": "13. To report statistics about swapping "
},
{
"code": null,
"e": 7624,
"s": 7168,
"text": "hduser@mahesh-Inspiron-3543:~$ sar -S 1 3\nLinux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)\n\n04:08:09 IST kbswpfree kbswpused %swpused kbswpcad %swpcad\n04:08:10 IST 3906556 0 0.00 0 0.00\n04:08:11 IST 3906556 0 0.00 0 0.00\n04:08:12 IST 3906556 0 0.00 0 0.00\nAverage: 3906556 0 0.00 0 0.00"
},
{
"code": null,
"e": 7732,
"s": 7624,
"text": "14. To report details about I/O operations like transaction per second, read per second, write per second "
},
{
"code": null,
"e": 8188,
"s": 7732,
"text": "hduser@mahesh-Inspiron-3543:~$ sar -b 1 3\nLinux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)\n\n04:08:41 IST tps rtps wtps bread/s bwrtn/s\n04:08:42 IST 0.00 0.00 0.00 0.00 0.00\n04:08:43 IST 2.00 0.00 2.00 0.00 64.00\n04:08:44 IST 0.00 0.00 0.00 0.00 0.00\nAverage: 0.67 0.00 0.67 0.00 21.33"
},
{
"code": null,
"e": 8306,
"s": 8188,
"text": "15. To report statistics about context switching, number of processes created per second, number of swap per second "
},
{
"code": null,
"e": 8612,
"s": 8306,
"text": "hduser@mahesh-Inspiron-3543:~$ sar -w 1 3\nLinux 4.4.0-31-generic (mahesh-Inspiron-3543) Sunday 18 March 2018 _x86_64_ (4 CPU)\n\n04:09:42 IST proc/s cswch/s\n04:09:43 IST 0.00 480.00\n04:09:44 IST 0.00 637.00\n04:09:45 IST 0.00 859.00\nAverage: 0.00 658.67"
},
{
"code": null,
"e": 8704,
"s": 8612,
"text": "16. To report paging statistics (KBs paged-in/sec, KBs paged-out/sec, pagefault/sec etc.) "
},
{
"code": null,
"e": 9549,
"s": 8704,
"text": "hatim.lokhandwala@ET-C02PR06MG8:~$ sar -B 2 5\nLinux 3.2.0-4-amd64 (ET-C02PR06MG8) 04/26/2019 _x86_64_ (6 CPU)\n\n11:36:32 PM pgpgin/s pgpgout/s fault/s majflt/s pgfree/s pgscank/s pgscand/s pgsteal/s %vmeff\n11:36:34 PM 0.00 14.00 13.50 0.00 24.00 0.00 0.00 0.00 0.00\n11:36:36 PM 0.00 291.50 6265.50 0.00 1858.00 0.00 0.00 0.00 0.00\n11:36:38 PM 0.00 270.00 8.50 0.00 41.00 0.00 0.00 0.00 0.00\n11:36:40 PM 0.00 40.50 8.50 0.00 21.00 0.00 0.00 0.00 0.00\n11:36:42 PM 0.00 1796.50 8.50 0.00 28.00 0.00 0.00 0.00 0.00\nAverage: 0.00 482.50 1260.90 0.00 394.40 0.00 0.00 0.00 0.00"
},
{
"code": null,
"e": 9566,
"s": 9549,
"text": "HatimLokhandwala"
},
{
"code": null,
"e": 9579,
"s": 9566,
"text": "vikeshyadav1"
},
{
"code": null,
"e": 9597,
"s": 9579,
"text": "germanshephered48"
},
{
"code": null,
"e": 9608,
"s": 9597,
"text": "ashwinkvit"
},
{
"code": null,
"e": 9622,
"s": 9608,
"text": "linux-command"
},
{
"code": null,
"e": 9644,
"s": 9622,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 9655,
"s": 9644,
"text": "Linux-Unix"
},
{
"code": null,
"e": 9674,
"s": 9655,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9772,
"s": 9674,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9798,
"s": 9772,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 9833,
"s": 9798,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 9870,
"s": 9833,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 9899,
"s": 9870,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 9933,
"s": 9899,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 9970,
"s": 9933,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 10007,
"s": 9970,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 10046,
"s": 10007,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 10086,
"s": 10046,
"text": "Array Basics in Shell Scripting | Set 1"
}
]
|
Logarithmic and Power Functions in R Programming | 01 Jun, 2020
Logarithm and Power are two very important mathematical functions that help in the calculation of data that is growing exponentially with time.First is the Logarithm, to which the general way to calculate the logarithm of the value in the base is with the log() function which takes two arguments as value and base, by default it computes the natural logarithm and there are shortcuts for common and binary logarithm i.e. base 10 and 2. Value can be number or vector.Second is the Power, to calculate a base number raised to the power of exponent number. In this article, there are three methods shown to calculate the same i.e. baseexponent.
It is the inverse of the exponential function, where it represents the quantity that is the power to the fixed number(base) raised to give the given number. It returns the double value.
Formula:
If y = bxthen logby = x
Example:
if 100 = 102
then log10100 = 2
List of various log() functions:The number is numeric or complex vector and the base is a positive or complex vector with the default value set to exp(1).
The log function [log(number)] in R returns the natural logarithm i.e. base e. log(10) = 2.302585
log(10) = 2.302585
[log10(number)] function returns the common logarithm i.e. base 10. log10(10) := 1
log10(10) := 1
[log2(number)] returns the binary logarithm i.e. base 2. log2(10) := 3.321928
log2(10) := 3.321928
[log(number, b)] return the logarithm with base b. log(10, 3) := 2.095903
log(10, 3) := 2.095903
[log1p(number)] returns log(1+number) for number << 1 precisely. log1p(10) := 2.397895
log1p(10) := 2.397895
[exp(number)] returns the exponential. exp(10) := 22026.47
exp(10) := 22026.47
[expm1(number)] returns the exp(number)-1 for number <<1 precisely. expm1(10) := 22025.47
expm1(10) := 22025.47
Example:
# R program to illustrate use of log functions x <- 10base <- 3 # Computes natural logarithmlog(x) # Computes common logarithmlog10(x) # Computes binary logarithmlog2(x) # Computes logarithm of # x with base blog(x, base) # Computes accurately# log(1+x) for x<<1log1p(x) # Computes exponentialexp(x) # Computes accurately # exp(x)-1 for x<<1expm1(x)
Output:
[1] 2.302585
[1] 1
[1] 3.321928
[1] 2.095903
[1] 2.397895
[1] 22026.47
[1] 22025.47
If there two numbers base and exponent, it finds x raised to the power of y i.e. xy.It returns double value. It needs two arguments:
x = floating point base value
y = floating point power value
Example :
103 = 10*10*10 = 1000
# R program to illustrate # the use of Power Functionx <- 10y <- 3 # 1st Method`^`(x, y) # 2nd Methodx^y # 3rd Methodx**y
Output:
[1] 1000
[1] 1000
[1] 1000
Picked
R-Functions
R-Mathematics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 671,
"s": 28,
"text": "Logarithm and Power are two very important mathematical functions that help in the calculation of data that is growing exponentially with time.First is the Logarithm, to which the general way to calculate the logarithm of the value in the base is with the log() function which takes two arguments as value and base, by default it computes the natural logarithm and there are shortcuts for common and binary logarithm i.e. base 10 and 2. Value can be number or vector.Second is the Power, to calculate a base number raised to the power of exponent number. In this article, there are three methods shown to calculate the same i.e. baseexponent."
},
{
"code": null,
"e": 857,
"s": 671,
"text": "It is the inverse of the exponential function, where it represents the quantity that is the power to the fixed number(base) raised to give the given number. It returns the double value."
},
{
"code": null,
"e": 866,
"s": 857,
"text": "Formula:"
},
{
"code": null,
"e": 890,
"s": 866,
"text": "If y = bxthen logby = x"
},
{
"code": null,
"e": 899,
"s": 890,
"text": "Example:"
},
{
"code": null,
"e": 932,
"s": 899,
"text": " if 100 = 102\nthen log10100 = 2\n"
},
{
"code": null,
"e": 1087,
"s": 932,
"text": "List of various log() functions:The number is numeric or complex vector and the base is a positive or complex vector with the default value set to exp(1)."
},
{
"code": null,
"e": 1186,
"s": 1087,
"text": "The log function [log(number)] in R returns the natural logarithm i.e. base e. log(10) = 2.302585 "
},
{
"code": null,
"e": 1207,
"s": 1186,
"text": " log(10) = 2.302585 "
},
{
"code": null,
"e": 1291,
"s": 1207,
"text": "[log10(number)] function returns the common logarithm i.e. base 10. log10(10) := 1 "
},
{
"code": null,
"e": 1308,
"s": 1291,
"text": " log10(10) := 1 "
},
{
"code": null,
"e": 1387,
"s": 1308,
"text": "[log2(number)] returns the binary logarithm i.e. base 2. log2(10) := 3.321928 "
},
{
"code": null,
"e": 1410,
"s": 1387,
"text": " log2(10) := 3.321928 "
},
{
"code": null,
"e": 1485,
"s": 1410,
"text": "[log(number, b)] return the logarithm with base b. log(10, 3) := 2.095903 "
},
{
"code": null,
"e": 1510,
"s": 1485,
"text": " log(10, 3) := 2.095903 "
},
{
"code": null,
"e": 1598,
"s": 1510,
"text": "[log1p(number)] returns log(1+number) for number << 1 precisely. log1p(10) := 2.397895 "
},
{
"code": null,
"e": 1622,
"s": 1598,
"text": " log1p(10) := 2.397895 "
},
{
"code": null,
"e": 1682,
"s": 1622,
"text": "[exp(number)] returns the exponential. exp(10) := 22026.47 "
},
{
"code": null,
"e": 1704,
"s": 1682,
"text": " exp(10) := 22026.47 "
},
{
"code": null,
"e": 1795,
"s": 1704,
"text": "[expm1(number)] returns the exp(number)-1 for number <<1 precisely. expm1(10) := 22025.47 "
},
{
"code": null,
"e": 1819,
"s": 1795,
"text": " expm1(10) := 22025.47 "
},
{
"code": null,
"e": 1828,
"s": 1819,
"text": "Example:"
},
{
"code": "# R program to illustrate use of log functions x <- 10base <- 3 # Computes natural logarithmlog(x) # Computes common logarithmlog10(x) # Computes binary logarithmlog2(x) # Computes logarithm of # x with base blog(x, base) # Computes accurately# log(1+x) for x<<1log1p(x) # Computes exponentialexp(x) # Computes accurately # exp(x)-1 for x<<1expm1(x)",
"e": 2186,
"s": 1828,
"text": null
},
{
"code": null,
"e": 2194,
"s": 2186,
"text": "Output:"
},
{
"code": null,
"e": 2279,
"s": 2194,
"text": "[1] 2.302585\n[1] 1\n[1] 3.321928\n[1] 2.095903\n[1] 2.397895\n[1] 22026.47\n[1] 22025.47\n"
},
{
"code": null,
"e": 2412,
"s": 2279,
"text": "If there two numbers base and exponent, it finds x raised to the power of y i.e. xy.It returns double value. It needs two arguments:"
},
{
"code": null,
"e": 2473,
"s": 2412,
"text": "x = floating point base value\ny = floating point power value"
},
{
"code": null,
"e": 2483,
"s": 2473,
"text": "Example :"
},
{
"code": null,
"e": 2507,
"s": 2483,
"text": " 103 = 10*10*10 = 1000 "
},
{
"code": "# R program to illustrate # the use of Power Functionx <- 10y <- 3 # 1st Method`^`(x, y) # 2nd Methodx^y # 3rd Methodx**y",
"e": 2632,
"s": 2507,
"text": null
},
{
"code": null,
"e": 2640,
"s": 2632,
"text": "Output:"
},
{
"code": null,
"e": 2668,
"s": 2640,
"text": "[1] 1000\n[1] 1000\n[1] 1000\n"
},
{
"code": null,
"e": 2675,
"s": 2668,
"text": "Picked"
},
{
"code": null,
"e": 2687,
"s": 2675,
"text": "R-Functions"
},
{
"code": null,
"e": 2701,
"s": 2687,
"text": "R-Mathematics"
},
{
"code": null,
"e": 2712,
"s": 2701,
"text": "R Language"
},
{
"code": null,
"e": 2810,
"s": 2712,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2862,
"s": 2810,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2920,
"s": 2862,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2955,
"s": 2920,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2993,
"s": 2955,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3010,
"s": 2993,
"text": "R - if statement"
},
{
"code": null,
"e": 3059,
"s": 3010,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3096,
"s": 3059,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 3139,
"s": 3096,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3176,
"s": 3139,
"text": "How to import an Excel File into R ?"
}
]
|
nproc Command in Linux with Examples | 30 Jun, 2020
nproc is a simple Unix command which is used to print the number of processing units available in the system or to the current process. This command could be used in system diagnostics and related purposes. It is part of GNU Core utils, so it comes pre-installed with all modern Linux operating systems.Syntax:
nproc [OPTION]...
1. Use nproc command
nproc
It prints the number of processing units available to the current process. It may be less than the number of online processors.
2. To print total installed processing units
nproc --all
We use the “–all” option when we want nproc to display the total installed processing units.
3. To exclude some processing units
nproc --ignore=4
We use “–ignore” option when we want nproc to exclude a set number of processing units.
4. To display the help section
nproc --help
This command will display the help section of the nproc command which will have all the information related to the nproc command.
5. To display version
nproc --version
This command will display the version of nproc command in Linux.
6. To display nproc manual
man nproc
This command will print the manual of the nproc command.
linux
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
Introduction to Linux Operating System
chown command in Linux with Examples
How to Permanently Disable Swap in Linux?
SED command in Linux | Set 2
chmod command in Linux with examples
Basic Operators in Shell Scripting
Array Basics in Shell Scripting | Set 1
nohup Command in Linux with Examples | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jun, 2020"
},
{
"code": null,
"e": 365,
"s": 54,
"text": "nproc is a simple Unix command which is used to print the number of processing units available in the system or to the current process. This command could be used in system diagnostics and related purposes. It is part of GNU Core utils, so it comes pre-installed with all modern Linux operating systems.Syntax:"
},
{
"code": null,
"e": 383,
"s": 365,
"text": "nproc [OPTION]..."
},
{
"code": null,
"e": 404,
"s": 383,
"text": "1. Use nproc command"
},
{
"code": null,
"e": 410,
"s": 404,
"text": "nproc"
},
{
"code": null,
"e": 538,
"s": 410,
"text": "It prints the number of processing units available to the current process. It may be less than the number of online processors."
},
{
"code": null,
"e": 583,
"s": 538,
"text": "2. To print total installed processing units"
},
{
"code": null,
"e": 595,
"s": 583,
"text": "nproc --all"
},
{
"code": null,
"e": 688,
"s": 595,
"text": "We use the “–all” option when we want nproc to display the total installed processing units."
},
{
"code": null,
"e": 724,
"s": 688,
"text": "3. To exclude some processing units"
},
{
"code": null,
"e": 741,
"s": 724,
"text": "nproc --ignore=4"
},
{
"code": null,
"e": 829,
"s": 741,
"text": "We use “–ignore” option when we want nproc to exclude a set number of processing units."
},
{
"code": null,
"e": 860,
"s": 829,
"text": "4. To display the help section"
},
{
"code": null,
"e": 873,
"s": 860,
"text": "nproc --help"
},
{
"code": null,
"e": 1003,
"s": 873,
"text": "This command will display the help section of the nproc command which will have all the information related to the nproc command."
},
{
"code": null,
"e": 1025,
"s": 1003,
"text": "5. To display version"
},
{
"code": null,
"e": 1041,
"s": 1025,
"text": "nproc --version"
},
{
"code": null,
"e": 1106,
"s": 1041,
"text": "This command will display the version of nproc command in Linux."
},
{
"code": null,
"e": 1133,
"s": 1106,
"text": "6. To display nproc manual"
},
{
"code": null,
"e": 1143,
"s": 1133,
"text": "man nproc"
},
{
"code": null,
"e": 1200,
"s": 1143,
"text": "This command will print the manual of the nproc command."
},
{
"code": null,
"e": 1206,
"s": 1200,
"text": "linux"
},
{
"code": null,
"e": 1220,
"s": 1206,
"text": "linux-command"
},
{
"code": null,
"e": 1231,
"s": 1220,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1329,
"s": 1231,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1355,
"s": 1329,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1390,
"s": 1355,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1429,
"s": 1390,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 1466,
"s": 1429,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1508,
"s": 1466,
"text": "How to Permanently Disable Swap in Linux?"
},
{
"code": null,
"e": 1537,
"s": 1508,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1574,
"s": 1537,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 1609,
"s": 1574,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 1649,
"s": 1609,
"text": "Array Basics in Shell Scripting | Set 1"
}
]
|
unordered_map at() in C++ | 26 Sep, 2021
Prerequisite : Unordered maps in STLUnordered_map : unordered_map is an associated container that stores elements formed by the combination of key value and a mapped value. The key value is used to uniquely identify the element and mapped value is the content associated with the key. Both key and value can be of any type predefined or user-defined.unordered_map :: at(): This function in C++ unordered_map returns the reference to the value with the element as key k.
Syntax:
unordered_map.at(k);
Parameter:
It is the key value of the element whose mapped value we want to access.
Return type :
A reference to the mapped value of the element with a key value equivalent
Note : The method gives run-time error if key is not present.
CPP
// C++ program to illustrate// std :: unordered_map :: at()#include<iostream>#include<string>#include<unordered_map> using namespace std; int main(){ unordered_map<string,int> mp = { {"first",1}, {"second",2}, {"third",3}, {"fourth",4} }; // returns the reference i.e. the mapped // value with the key 'second' cout<<"Value of key mp['second'] = " <<mp.at("second")<<endl; try { mp.at(); } catch(const out_of_range &e) { cerr << "Exception at " << e.what() << endl; } return 0;}
Output:
Value of key mp['second'] = 2
Exception at _Map_base::at
Practical Application : std :: unordered_map :: at() function can be used to access the mapped value and thus can edit, update etc.
CPP
// CPP program to illustrate// application of this function// Program to correct the marks// given in different subjects#include<iostream>#include<string>#include<unordered_map> using namespace std; // driver codeint main(){ // marks in different subjects unordered_map<string,int> my_marks = { {"Maths", 90}, {"Physics", 87}, {"Chemistry", 98}, {"Computer Application", 94} }; my_marks.at("Physics") = 97; my_marks.at("Maths") += 10; my_marks.at("Computer Application") += 6; for (auto& i: my_marks) { cout<<i.first<<": "<<i.second<<endl; } return 0;}
Output:
Computer Application: 100
Chemistry: 98
Physics: 97
Maths: 100
How unordered_map at() is different from unordered_map operator()
Both at() and operator[] is used to refer the element present at the given position, the only difference is, at() throws out-of-range exception whereas operator[] shows undefined behavior i.e. if operator[] is used to find the value corresponding to key and if key is not present in unordered map, it will first insert the key into the map and then assign the default value ‘0’ corresponding to that key. .
ranjeetgautam13032
kashishsoda
cpp-unordered_map
cpp-unordered_map-functions
STL
C++
Technical Scripter
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++ | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Sep, 2021"
},
{
"code": null,
"e": 525,
"s": 53,
"text": "Prerequisite : Unordered maps in STLUnordered_map : unordered_map is an associated container that stores elements formed by the combination of key value and a mapped value. The key value is used to uniquely identify the element and mapped value is the content associated with the key. Both key and value can be of any type predefined or user-defined.unordered_map :: at(): This function in C++ unordered_map returns the reference to the value with the element as key k. "
},
{
"code": null,
"e": 535,
"s": 525,
"text": "Syntax: "
},
{
"code": null,
"e": 729,
"s": 535,
"text": "unordered_map.at(k);\nParameter:\nIt is the key value of the element whose mapped value we want to access.\nReturn type :\nA reference to the mapped value of the element with a key value equivalent"
},
{
"code": null,
"e": 791,
"s": 729,
"text": "Note : The method gives run-time error if key is not present."
},
{
"code": null,
"e": 795,
"s": 791,
"text": "CPP"
},
{
"code": "// C++ program to illustrate// std :: unordered_map :: at()#include<iostream>#include<string>#include<unordered_map> using namespace std; int main(){ unordered_map<string,int> mp = { {\"first\",1}, {\"second\",2}, {\"third\",3}, {\"fourth\",4} }; // returns the reference i.e. the mapped // value with the key 'second' cout<<\"Value of key mp['second'] = \" <<mp.at(\"second\")<<endl; try { mp.at(); } catch(const out_of_range &e) { cerr << \"Exception at \" << e.what() << endl; } return 0;}",
"e": 1492,
"s": 795,
"text": null
},
{
"code": null,
"e": 1502,
"s": 1492,
"text": "Output: "
},
{
"code": null,
"e": 1559,
"s": 1502,
"text": "Value of key mp['second'] = 2\nException at _Map_base::at"
},
{
"code": null,
"e": 1692,
"s": 1559,
"text": "Practical Application : std :: unordered_map :: at() function can be used to access the mapped value and thus can edit, update etc. "
},
{
"code": null,
"e": 1696,
"s": 1692,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// application of this function// Program to correct the marks// given in different subjects#include<iostream>#include<string>#include<unordered_map> using namespace std; // driver codeint main(){ // marks in different subjects unordered_map<string,int> my_marks = { {\"Maths\", 90}, {\"Physics\", 87}, {\"Chemistry\", 98}, {\"Computer Application\", 94} }; my_marks.at(\"Physics\") = 97; my_marks.at(\"Maths\") += 10; my_marks.at(\"Computer Application\") += 6; for (auto& i: my_marks) { cout<<i.first<<\": \"<<i.second<<endl; } return 0;}",
"e": 2476,
"s": 1696,
"text": null
},
{
"code": null,
"e": 2486,
"s": 2476,
"text": "Output: "
},
{
"code": null,
"e": 2549,
"s": 2486,
"text": "Computer Application: 100\nChemistry: 98\nPhysics: 97\nMaths: 100"
},
{
"code": null,
"e": 2616,
"s": 2549,
"text": "How unordered_map at() is different from unordered_map operator() "
},
{
"code": null,
"e": 3024,
"s": 2616,
"text": "Both at() and operator[] is used to refer the element present at the given position, the only difference is, at() throws out-of-range exception whereas operator[] shows undefined behavior i.e. if operator[] is used to find the value corresponding to key and if key is not present in unordered map, it will first insert the key into the map and then assign the default value ‘0’ corresponding to that key. . "
},
{
"code": null,
"e": 3043,
"s": 3024,
"text": "ranjeetgautam13032"
},
{
"code": null,
"e": 3055,
"s": 3043,
"text": "kashishsoda"
},
{
"code": null,
"e": 3073,
"s": 3055,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 3101,
"s": 3073,
"text": "cpp-unordered_map-functions"
},
{
"code": null,
"e": 3105,
"s": 3101,
"text": "STL"
},
{
"code": null,
"e": 3109,
"s": 3105,
"text": "C++"
},
{
"code": null,
"e": 3128,
"s": 3109,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3132,
"s": 3128,
"text": "STL"
},
{
"code": null,
"e": 3136,
"s": 3132,
"text": "CPP"
},
{
"code": null,
"e": 3234,
"s": 3136,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3258,
"s": 3234,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3278,
"s": 3258,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3311,
"s": 3278,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 3355,
"s": 3311,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3380,
"s": 3355,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3425,
"s": 3380,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3473,
"s": 3425,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 3490,
"s": 3473,
"text": "std::find in C++"
},
{
"code": null,
"e": 3534,
"s": 3490,
"text": "List in C++ Standard Template Library (STL)"
}
]
|
Code Splitting in React | 20 Jan, 2021
Code-Splitting is a feature supported by bundlers like Webpack, Rollup, and Browserify which can create multiple bundles that can be dynamically loaded at runtime.As websites grow larger and go deeper into components, it becomes heavier. This is especially the case when libraries from third parties are included. Code Splitting is a method that helps to generate bundles that are able to run dynamically. It also helps to make the code efficient because the bundle contains all required imports and files.Bundling and its efficiency: Bundling is the method of combining imported files with a single file. It is done with the help of Webpack, Rollup, Browserify as they can create many bundles that can be loaded dynamically at runtime.With the help of code splitting, ‘lazy load’ can be implemented, which means just using the code which is currently needed.
The default way of importing as follows:
javascript
import { add } from './math';console.log(add(x, y)); // Here x, y are two numbers
Using code-splitting this can be done as follows:
javascript
import("./math").then(math => { console.log(math.add(x, y));}); // Here x, y are two numbers
As soon as Webpack gets this type of syntax, code-splitting is started automatically. When using the Create React App, it is already set up and can be used immediately.The Webpack guide on code splitting should be followed if using Webpack. The instructions can be found https://webpack.js.org/guides/code-splitting/.When Babel is being used, it has to be made sure that Babel is not transforming the import syntax, but can parse it dynamically. This can be done using https://classic.yarnpkg.com/en/package/babel-plugin-syntax-dynamic-import package.React.lazy and Suspense: As both React.lazy and Suspense are not available for rendering on the server yet now, it is recommended to use https://github.com/gregberge/loadable-components for code-splitting in a server-rendered app. React.lazy is helpful for rendering dynamic import as a regular component.Before:
import Component from './Component';
After:
const Component = React.lazy(() => import('./Component'));
The Bundle will be loaded on its own which contains the Component when this component is rendered first. The Lazy component should then be rendered inside Suspense Component which helps to reflect some fallback content meanwhile the lazy component loads.
javascript
import React, { Suspense } from 'react';const Component = React.lazy(() => import('./Component'));function MyComponent() { return ( <div> <Suspense fallback={<div>Loading...</div>}> </div>);}
The fallback prop can accept any element of React which will be rendered while waiting for the loading of the Component. The Suspense Component can be placed anywhere above the lazy component. Moreover, multiple lazy components can be wrapped with a single Suspense Component.
javascript
import React, { Suspense } from 'react'; const ComponentOne = React.lazy(() => import('./ComponentOne'));const ComponentTwo = React.lazy(() => import('./ComponentTwo'));function MyComponent() { return (<div><Suspense fallback={<div>Loading...</div>}></div>);}
Error Boundaries: When some modules fail to load due to any issue, an error will be triggered. These errors can be handled properly and provide a good experience to the user by the use of a suitable error page.
javascript
import React, { Suspense } from 'react';import ErrorBoundary from './ErrorBoundary';const ComponentOne = React.lazy(() => import('./ComponentOne'));const ComponentTwo = React.lazy(() => import('./ComponentTwo'));const MyComponent = () => ( <div> <Suspense fallback={<div>Loading...</div>}> </div>);
Route based code splitting: It can be difficult to implement code-splitting in code, the bundles can be split evenly, which will improve the experience for the user.Example:
javascript
import React from 'react';import Suspense from 'react';import lazy from 'react';import {Route, Switch, BrowserRouter } from 'react-router-dom'; const HomePage = lazy(() => import('./routes/HomePage'));const AboutUs = lazy(() => import('./routes/AboutUs'));const App = () => (<Suspense fallback={<div>Loading...</div>}>);
Named Exports: React.lazy currently supports only default exports. An intermediate module that re-exports as default has to be created if one wants to import a module that uses named exports. This ensures the working of tree shaking and prevents the pulling in of unused components.
javascript
// Components.jsexport const Component = /* ... */;export const MyUnusedComponent = /* ... */; // Component.jsexport { Component as default } from "./Components.js"; // MyApp.jsimport {React, lazy} from 'react';const Component = lazy(() => import("./Component.js"));
shubhamyadav4
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jan, 2021"
},
{
"code": null,
"e": 888,
"s": 28,
"text": "Code-Splitting is a feature supported by bundlers like Webpack, Rollup, and Browserify which can create multiple bundles that can be dynamically loaded at runtime.As websites grow larger and go deeper into components, it becomes heavier. This is especially the case when libraries from third parties are included. Code Splitting is a method that helps to generate bundles that are able to run dynamically. It also helps to make the code efficient because the bundle contains all required imports and files.Bundling and its efficiency: Bundling is the method of combining imported files with a single file. It is done with the help of Webpack, Rollup, Browserify as they can create many bundles that can be loaded dynamically at runtime.With the help of code splitting, ‘lazy load’ can be implemented, which means just using the code which is currently needed."
},
{
"code": null,
"e": 931,
"s": 888,
"text": "The default way of importing as follows: "
},
{
"code": null,
"e": 942,
"s": 931,
"text": "javascript"
},
{
"code": "import { add } from './math';console.log(add(x, y)); // Here x, y are two numbers",
"e": 1024,
"s": 942,
"text": null
},
{
"code": null,
"e": 1075,
"s": 1024,
"text": "Using code-splitting this can be done as follows: "
},
{
"code": null,
"e": 1086,
"s": 1075,
"text": "javascript"
},
{
"code": "import(\"./math\").then(math => { console.log(math.add(x, y));}); // Here x, y are two numbers",
"e": 1180,
"s": 1086,
"text": null
},
{
"code": null,
"e": 2045,
"s": 1180,
"text": "As soon as Webpack gets this type of syntax, code-splitting is started automatically. When using the Create React App, it is already set up and can be used immediately.The Webpack guide on code splitting should be followed if using Webpack. The instructions can be found https://webpack.js.org/guides/code-splitting/.When Babel is being used, it has to be made sure that Babel is not transforming the import syntax, but can parse it dynamically. This can be done using https://classic.yarnpkg.com/en/package/babel-plugin-syntax-dynamic-import package.React.lazy and Suspense: As both React.lazy and Suspense are not available for rendering on the server yet now, it is recommended to use https://github.com/gregberge/loadable-components for code-splitting in a server-rendered app. React.lazy is helpful for rendering dynamic import as a regular component.Before: "
},
{
"code": null,
"e": 2082,
"s": 2045,
"text": "import Component from './Component';"
},
{
"code": null,
"e": 2090,
"s": 2082,
"text": "After: "
},
{
"code": null,
"e": 2149,
"s": 2090,
"text": "const Component = React.lazy(() => import('./Component'));"
},
{
"code": null,
"e": 2404,
"s": 2149,
"text": "The Bundle will be loaded on its own which contains the Component when this component is rendered first. The Lazy component should then be rendered inside Suspense Component which helps to reflect some fallback content meanwhile the lazy component loads."
},
{
"code": null,
"e": 2415,
"s": 2404,
"text": "javascript"
},
{
"code": "import React, { Suspense } from 'react';const Component = React.lazy(() => import('./Component'));function MyComponent() { return ( <div> <Suspense fallback={<div>Loading...</div>}> </div>);}",
"e": 2619,
"s": 2415,
"text": null
},
{
"code": null,
"e": 2896,
"s": 2619,
"text": "The fallback prop can accept any element of React which will be rendered while waiting for the loading of the Component. The Suspense Component can be placed anywhere above the lazy component. Moreover, multiple lazy components can be wrapped with a single Suspense Component."
},
{
"code": null,
"e": 2907,
"s": 2896,
"text": "javascript"
},
{
"code": "import React, { Suspense } from 'react'; const ComponentOne = React.lazy(() => import('./ComponentOne'));const ComponentTwo = React.lazy(() => import('./ComponentTwo'));function MyComponent() { return (<div><Suspense fallback={<div>Loading...</div>}></div>);}",
"e": 3168,
"s": 2907,
"text": null
},
{
"code": null,
"e": 3379,
"s": 3168,
"text": "Error Boundaries: When some modules fail to load due to any issue, an error will be triggered. These errors can be handled properly and provide a good experience to the user by the use of a suitable error page."
},
{
"code": null,
"e": 3390,
"s": 3379,
"text": "javascript"
},
{
"code": "import React, { Suspense } from 'react';import ErrorBoundary from './ErrorBoundary';const ComponentOne = React.lazy(() => import('./ComponentOne'));const ComponentTwo = React.lazy(() => import('./ComponentTwo'));const MyComponent = () => ( <div> <Suspense fallback={<div>Loading...</div>}> </div>);",
"e": 3694,
"s": 3390,
"text": null
},
{
"code": null,
"e": 3869,
"s": 3694,
"text": "Route based code splitting: It can be difficult to implement code-splitting in code, the bundles can be split evenly, which will improve the experience for the user.Example: "
},
{
"code": null,
"e": 3880,
"s": 3869,
"text": "javascript"
},
{
"code": "import React from 'react';import Suspense from 'react';import lazy from 'react';import {Route, Switch, BrowserRouter } from 'react-router-dom'; const HomePage = lazy(() => import('./routes/HomePage'));const AboutUs = lazy(() => import('./routes/AboutUs'));const App = () => (<Suspense fallback={<div>Loading...</div>}>);",
"e": 4212,
"s": 3880,
"text": null
},
{
"code": null,
"e": 4495,
"s": 4212,
"text": "Named Exports: React.lazy currently supports only default exports. An intermediate module that re-exports as default has to be created if one wants to import a module that uses named exports. This ensures the working of tree shaking and prevents the pulling in of unused components."
},
{
"code": null,
"e": 4506,
"s": 4495,
"text": "javascript"
},
{
"code": "// Components.jsexport const Component = /* ... */;export const MyUnusedComponent = /* ... */; // Component.jsexport { Component as default } from \"./Components.js\"; // MyApp.jsimport {React, lazy} from 'react';const Component = lazy(() => import(\"./Component.js\"));",
"e": 4773,
"s": 4506,
"text": null
},
{
"code": null,
"e": 4787,
"s": 4773,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 4796,
"s": 4787,
"text": "react-js"
},
{
"code": null,
"e": 4813,
"s": 4796,
"text": "Web Technologies"
}
]
|
Equivalent of Java Static Methods in Kotlin | 27 Dec, 2021
Prerequisite: static Keyword in Java
Static Keyword in Java is a non-access modifier. It is useful for representing meta-data (usually data related to a class). The static keyword serves for efficient memory management as in spite of recurring usages the Java Virtual Machine only once allocates memory for the variable, method, class or block declared as static. Static members are not related to instances being created but are owned by the class itself. In Kotlin however, we don’t have such keywords. So this functionality has to be achieved using some other ways. The most popular methods of implementing functionality similar to that of the static keyword are listed below:
Object expressions or Object declarations in Kotlin are used to create instances of an anonymous class. Using companion identifiers along with such object expressions or declarations facilitates members of the companion object to be called just by using the class name as the qualifier. When the matching class is loaded (resolved), a companion object is created that has the same semantics as a Java static initializer.
Kotlin
class GFG { companion object{ fun getMetaData() : String { return "Static Method of Class" } }} fun main(args: Array<String>) { // Calling method of companion object println(GFG.getMetaData())}
Output:
Static Method of Class
In the case of Java, the method of companion object can be called but we need an additional ‘Companion’ field to be added before the function call after the class name. We can get rid of this too, by either giving our own name to the companion object or by using @JvmStatic annotation.
Adding @JvmStatic annotation simply before the members to be declared as the equivalent of static ones in Java works well in Kotlin to provide the same functionality.
Kotlin
object MyClass{ @JvmStatic fun getMetaData(): String { return "Static Method of the Class" }} fun main(args: Array<String>) { println(GFG.getMetaData())}
Output:
Static Method of Class
An equivalent functionality as that of the static members and methods in Java can also be achieved by making that member, method, class, or block be a package-level member. This can be done by creating a .kt file and placing all such desired members into it without making any class inside. In this way, all these members will be compiled by the JVM as the static parts of the Kotlin class in which the package is being imported.
Kotlin File to achieve the functionality of static keyword:
Kotlin
package com.gfg.samplefun getMetaData() : String { return "Static Method of Package"}
Main Kotlin File:
Kotlin
import com.gfg.sample fun main(args: Array<String>) { println(getMetaData())}
Output:
Static Method of Package
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 65,
"s": 28,
"text": "Prerequisite: static Keyword in Java"
},
{
"code": null,
"e": 708,
"s": 65,
"text": "Static Keyword in Java is a non-access modifier. It is useful for representing meta-data (usually data related to a class). The static keyword serves for efficient memory management as in spite of recurring usages the Java Virtual Machine only once allocates memory for the variable, method, class or block declared as static. Static members are not related to instances being created but are owned by the class itself. In Kotlin however, we don’t have such keywords. So this functionality has to be achieved using some other ways. The most popular methods of implementing functionality similar to that of the static keyword are listed below:"
},
{
"code": null,
"e": 1129,
"s": 708,
"text": "Object expressions or Object declarations in Kotlin are used to create instances of an anonymous class. Using companion identifiers along with such object expressions or declarations facilitates members of the companion object to be called just by using the class name as the qualifier. When the matching class is loaded (resolved), a companion object is created that has the same semantics as a Java static initializer."
},
{
"code": null,
"e": 1136,
"s": 1129,
"text": "Kotlin"
},
{
"code": "class GFG { companion object{ fun getMetaData() : String { return \"Static Method of Class\" } }} fun main(args: Array<String>) { // Calling method of companion object println(GFG.getMetaData())}",
"e": 1382,
"s": 1136,
"text": null
},
{
"code": null,
"e": 1390,
"s": 1382,
"text": "Output:"
},
{
"code": null,
"e": 1413,
"s": 1390,
"text": "Static Method of Class"
},
{
"code": null,
"e": 1699,
"s": 1413,
"text": "In the case of Java, the method of companion object can be called but we need an additional ‘Companion’ field to be added before the function call after the class name. We can get rid of this too, by either giving our own name to the companion object or by using @JvmStatic annotation."
},
{
"code": null,
"e": 1866,
"s": 1699,
"text": "Adding @JvmStatic annotation simply before the members to be declared as the equivalent of static ones in Java works well in Kotlin to provide the same functionality."
},
{
"code": null,
"e": 1873,
"s": 1866,
"text": "Kotlin"
},
{
"code": "object MyClass{ @JvmStatic fun getMetaData(): String { return \"Static Method of the Class\" }} fun main(args: Array<String>) { println(GFG.getMetaData())}",
"e": 2042,
"s": 1873,
"text": null
},
{
"code": null,
"e": 2050,
"s": 2042,
"text": "Output:"
},
{
"code": null,
"e": 2073,
"s": 2050,
"text": "Static Method of Class"
},
{
"code": null,
"e": 2503,
"s": 2073,
"text": "An equivalent functionality as that of the static members and methods in Java can also be achieved by making that member, method, class, or block be a package-level member. This can be done by creating a .kt file and placing all such desired members into it without making any class inside. In this way, all these members will be compiled by the JVM as the static parts of the Kotlin class in which the package is being imported."
},
{
"code": null,
"e": 2563,
"s": 2503,
"text": "Kotlin File to achieve the functionality of static keyword:"
},
{
"code": null,
"e": 2570,
"s": 2563,
"text": "Kotlin"
},
{
"code": "package com.gfg.samplefun getMetaData() : String { return \"Static Method of Package\"}",
"e": 2659,
"s": 2570,
"text": null
},
{
"code": null,
"e": 2677,
"s": 2659,
"text": "Main Kotlin File:"
},
{
"code": null,
"e": 2684,
"s": 2677,
"text": "Kotlin"
},
{
"code": "import com.gfg.sample fun main(args: Array<String>) { println(getMetaData())}",
"e": 2766,
"s": 2684,
"text": null
},
{
"code": null,
"e": 2774,
"s": 2766,
"text": "Output:"
},
{
"code": null,
"e": 2799,
"s": 2774,
"text": "Static Method of Package"
},
{
"code": null,
"e": 2806,
"s": 2799,
"text": "Picked"
},
{
"code": null,
"e": 2813,
"s": 2806,
"text": "Kotlin"
}
]
|
issuperset() in Python | 05 Oct, 2021
Python set issuperset() method returns True if all elements of a set A occupies set B which is passed as an argument and returns false if all elements of B are not present in A. This means if A is a superset of B then it returns true; else False
A.issuperset(B)
checks whether A is a superset of B or not.
True if A is a superset of B; otherwise false.
Python
# Python program to demonstrate working of# issuperset(). A = {4, 1, 3, 5}B = {6, 0, 4, 1, 5, 0, 3, 5} print("A.issuperset(B) : ", A.issuperset(B)) # B is superset of Aprint("B.issuperset(A) : ", B.issuperset(A))
Output:
A.issuperset(B) : False
B.issuperset(A) : True
Python
# Python program to demonstrate working# of issuperset(). A = {1, 2, 3}B = {1, 2, 3, 4, 5}C = {1, 2, 4, 5} print("A.issuperset(B) : ", A.issuperset(B))print("B.issuperset(A) : ", B.issuperset(A))print("A.issuperset(C) : ", A.issuperset(C))print("C.issuperset(B) : ", C.issuperset(B))
Output:
A.issuperset(B) : False
B.issuperset(A) : True
A.issuperset(C) : False
C.issuperset(B) : False
kumar_satyam
python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace() | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 298,
"s": 52,
"text": "Python set issuperset() method returns True if all elements of a set A occupies set B which is passed as an argument and returns false if all elements of B are not present in A. This means if A is a superset of B then it returns true; else False"
},
{
"code": null,
"e": 358,
"s": 298,
"text": "A.issuperset(B)\nchecks whether A is a superset of B or not."
},
{
"code": null,
"e": 405,
"s": 358,
"text": "True if A is a superset of B; otherwise false."
},
{
"code": null,
"e": 412,
"s": 405,
"text": "Python"
},
{
"code": "# Python program to demonstrate working of# issuperset(). A = {4, 1, 3, 5}B = {6, 0, 4, 1, 5, 0, 3, 5} print(\"A.issuperset(B) : \", A.issuperset(B)) # B is superset of Aprint(\"B.issuperset(A) : \", B.issuperset(A))",
"e": 625,
"s": 412,
"text": null
},
{
"code": null,
"e": 634,
"s": 625,
"text": "Output: "
},
{
"code": null,
"e": 683,
"s": 634,
"text": "A.issuperset(B) : False\nB.issuperset(A) : True"
},
{
"code": null,
"e": 690,
"s": 683,
"text": "Python"
},
{
"code": "# Python program to demonstrate working# of issuperset(). A = {1, 2, 3}B = {1, 2, 3, 4, 5}C = {1, 2, 4, 5} print(\"A.issuperset(B) : \", A.issuperset(B))print(\"B.issuperset(A) : \", B.issuperset(A))print(\"A.issuperset(C) : \", A.issuperset(C))print(\"C.issuperset(B) : \", C.issuperset(B))",
"e": 974,
"s": 690,
"text": null
},
{
"code": null,
"e": 983,
"s": 974,
"text": "Output: "
},
{
"code": null,
"e": 1082,
"s": 983,
"text": "A.issuperset(B) : False\nB.issuperset(A) : True\nA.issuperset(C) : False\nC.issuperset(B) : False"
},
{
"code": null,
"e": 1095,
"s": 1082,
"text": "kumar_satyam"
},
{
"code": null,
"e": 1106,
"s": 1095,
"text": "python-set"
},
{
"code": null,
"e": 1113,
"s": 1106,
"text": "Python"
},
{
"code": null,
"e": 1124,
"s": 1113,
"text": "python-set"
},
{
"code": null,
"e": 1222,
"s": 1124,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1250,
"s": 1222,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 1272,
"s": 1250,
"text": "Python map() function"
},
{
"code": null,
"e": 1322,
"s": 1272,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 1340,
"s": 1322,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1384,
"s": 1340,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 1426,
"s": 1384,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1449,
"s": 1426,
"text": "Taking input in Python"
},
{
"code": null,
"e": 1471,
"s": 1449,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1506,
"s": 1471,
"text": "Read a file line by line in Python"
}
]
|
How to create waves on button with CSS and HTML? | 21 Jun, 2020
The wave effect on a button is a type of effect in which the shape of the button turns into a wave on hovering. While there are other ways to create a wave effect, a simple method is to use the keyframe property.
Approach: In order to animate the button, we use keyframe to gradually set the transitions at different stages.HTML Code:The HTML code is a simple structure that contains a wrapper where the span tag is wrapped inside the anchor tag.
<html> <head></head> <body> <div class="wrapper"> <a href="#" class="wave-btn"><span>wave</span></a> </div> </body></html>
CSS Code:
Add basic styles like background color, position the button and set the width and height of the button.
Use animation property with identifier named as wave .
Now use keyframes to animate each frame according to their angle by using the transform property.
<style> @import url("https://fonts.googleapis.com/css?family=Noto+Sans");* { position: relative;} html,body { margin: 0; padding: 0; height: 100%;} .wrapper { height: 100%; background-color: #f5f6fa;} .wave-btn { color: #fff; text-decoration: none; border: 3px solid #fff; padding: 5px 30px; font-size: 22px; font-weight: 600; font-family: "Noto Sans"; line-height: 52px; border-radius: 10px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); overflow: hidden; transition: all 1s;} .wave-btn:before { content: ""; position: absolute; width: 320px; height: 320px; border-radius: 130px; background-color: #0097e6; top: 30px; left: 50%; transform: translate(-50%); animation: wave 5s infinite linear; transition: all 1s;} .wave-btn:hover:before { top: 15px;} @keyframes wave { 0% { transform: translate(-50%) rotate(-180deg); } 100% { transform: translate(-50%) rotate(360deg); }} </style>
Complete Code:
<html> <head> <style> @import url("https://fonts.googleapis.com/css?family=Noto+Sans");* { position: relative;} html,body { margin: 0; padding: 0; height: 100%;} .wrapper { height: 100%; background-color: #f5f6fa;} .wave-btn { color: #fff; text-decoration: none; border: 3px solid #fff; padding: 5px 30px; font-size: 22px; font-weight: 600; font-family: "Noto Sans"; line-height: 52px; border-radius: 10px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); overflow: hidden; transition: all 1s;} .wave-btn:before { content: ""; position: absolute; width: 320px; height: 320px; border-radius: 130px; background-color: #0097e6; top: 30px; left: 50%; transform: translate(-50%); animation: wave 5s infinite linear; transition: all 1s;} .wave-btn:hover:before { top: 15px;} @keyframes wave { 0% { transform: translate(-50%) rotate(-180deg); } 100% { transform: translate(-50%) rotate(360deg); }} </style> </head> <body> <div class="wrapper"> <a href="#" class="wave-btn"><span>wave</span></a> </div> </body></html>
Output:
CSS-Advanced
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Jun, 2020"
},
{
"code": null,
"e": 266,
"s": 53,
"text": "The wave effect on a button is a type of effect in which the shape of the button turns into a wave on hovering. While there are other ways to create a wave effect, a simple method is to use the keyframe property."
},
{
"code": null,
"e": 500,
"s": 266,
"text": "Approach: In order to animate the button, we use keyframe to gradually set the transitions at different stages.HTML Code:The HTML code is a simple structure that contains a wrapper where the span tag is wrapped inside the anchor tag."
},
{
"code": "<html> <head></head> <body> <div class=\"wrapper\"> <a href=\"#\" class=\"wave-btn\"><span>wave</span></a> </div> </body></html>",
"e": 637,
"s": 500,
"text": null
},
{
"code": null,
"e": 647,
"s": 637,
"text": "CSS Code:"
},
{
"code": null,
"e": 751,
"s": 647,
"text": "Add basic styles like background color, position the button and set the width and height of the button."
},
{
"code": null,
"e": 806,
"s": 751,
"text": "Use animation property with identifier named as wave ."
},
{
"code": null,
"e": 904,
"s": 806,
"text": "Now use keyframes to animate each frame according to their angle by using the transform property."
},
{
"code": "<style> @import url(\"https://fonts.googleapis.com/css?family=Noto+Sans\");* { position: relative;} html,body { margin: 0; padding: 0; height: 100%;} .wrapper { height: 100%; background-color: #f5f6fa;} .wave-btn { color: #fff; text-decoration: none; border: 3px solid #fff; padding: 5px 30px; font-size: 22px; font-weight: 600; font-family: \"Noto Sans\"; line-height: 52px; border-radius: 10px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); overflow: hidden; transition: all 1s;} .wave-btn:before { content: \"\"; position: absolute; width: 320px; height: 320px; border-radius: 130px; background-color: #0097e6; top: 30px; left: 50%; transform: translate(-50%); animation: wave 5s infinite linear; transition: all 1s;} .wave-btn:hover:before { top: 15px;} @keyframes wave { 0% { transform: translate(-50%) rotate(-180deg); } 100% { transform: translate(-50%) rotate(360deg); }} </style>",
"e": 1897,
"s": 904,
"text": null
},
{
"code": null,
"e": 1912,
"s": 1897,
"text": "Complete Code:"
},
{
"code": "<html> <head> <style> @import url(\"https://fonts.googleapis.com/css?family=Noto+Sans\");* { position: relative;} html,body { margin: 0; padding: 0; height: 100%;} .wrapper { height: 100%; background-color: #f5f6fa;} .wave-btn { color: #fff; text-decoration: none; border: 3px solid #fff; padding: 5px 30px; font-size: 22px; font-weight: 600; font-family: \"Noto Sans\"; line-height: 52px; border-radius: 10px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); overflow: hidden; transition: all 1s;} .wave-btn:before { content: \"\"; position: absolute; width: 320px; height: 320px; border-radius: 130px; background-color: #0097e6; top: 30px; left: 50%; transform: translate(-50%); animation: wave 5s infinite linear; transition: all 1s;} .wave-btn:hover:before { top: 15px;} @keyframes wave { 0% { transform: translate(-50%) rotate(-180deg); } 100% { transform: translate(-50%) rotate(360deg); }} </style> </head> <body> <div class=\"wrapper\"> <a href=\"#\" class=\"wave-btn\"><span>wave</span></a> </div> </body></html>",
"e": 3055,
"s": 1912,
"text": null
},
{
"code": null,
"e": 3063,
"s": 3055,
"text": "Output:"
},
{
"code": null,
"e": 3076,
"s": 3063,
"text": "CSS-Advanced"
},
{
"code": null,
"e": 3083,
"s": 3076,
"text": "Picked"
},
{
"code": null,
"e": 3087,
"s": 3083,
"text": "CSS"
},
{
"code": null,
"e": 3104,
"s": 3087,
"text": "Web Technologies"
}
]
|
Python program to reverse a Numpy array? | This is a simple program wherein we have to reverse a numpy array. We will use numpy.flip() function for the same.
Step 1: Import numpy.
Step 2: Define a numpy array using numpy.array().
Step 3: Reverse the array using numpy.flip() function.
Step 4: Print the array.
import numpy as np
arr = np.array([10,20,30,40,50])
print("Original Array: \n", arr)
arr_reversed = np.flip(arr)
print("\nReversed Array: \n", arr_reversed)
Original Array:
[10 20 30 40 50]
Reversed Array:
[50 40 30 20 10] | [
{
"code": null,
"e": 1302,
"s": 1187,
"text": "This is a simple program wherein we have to reverse a numpy array. We will use numpy.flip() function for the same."
},
{
"code": null,
"e": 1454,
"s": 1302,
"text": "Step 1: Import numpy.\nStep 2: Define a numpy array using numpy.array().\nStep 3: Reverse the array using numpy.flip() function.\nStep 4: Print the array."
},
{
"code": null,
"e": 1613,
"s": 1454,
"text": "import numpy as np\n\narr = np.array([10,20,30,40,50])\nprint(\"Original Array: \\n\", arr)\n\narr_reversed = np.flip(arr)\nprint(\"\\nReversed Array: \\n\", arr_reversed)"
},
{
"code": null,
"e": 1680,
"s": 1613,
"text": "Original Array:\n[10 20 30 40 50]\n\nReversed Array:\n[50 40 30 20 10]"
}
]
|
Source to Source Compiler | 06 Jun, 2022
A compiler is a software program that transforms a program or code written in a high-level programming language into a low-level machine-readable language. When we write a program or code which can be in a high-level language, such as C, C++ or such as the one given below.
//Simple Java program
public class simple{
public static void main(String[] args){
System.out.printIn("Hello World")
}
}
A high-level language is closer to English, which makes it easier for us to write programs. But we can’t just run the same code onto a computer as machines can’t understand that. All that a computer can understand is binary code, that is ones and zeros. Therefore, the solution to the problem that computers can’t understand high-level languages would be to convert those into machine-understandable binary code. This is the exact task that is done by a compiler.
The compiling process of the simple ‘hello world’ program up there would be as follows –
We create the ‘hello world’ program and save the file as Hello.java.When we complete this program, the compiler generates the equivalent machine code and saves it into the class file of the same name but with class extension Hello.class.And when the program is executed, it is the class file that gets executed and gives the output.
We create the ‘hello world’ program and save the file as Hello.java.
When we complete this program, the compiler generates the equivalent machine code and saves it into the class file of the same name but with class extension Hello.class.
And when the program is executed, it is the class file that gets executed and gives the output.
Compiles are of many types, but in this article, we are going to learn about a specific one, that is Source to Source Compiler.
Source To Source Compiler :A source to source compiler (S2S compiler) is also referred to by three other name, the first is the source to source translator, the second is transcompiler and the third one is transpiler. If we try to summarize the work on the source to source compiler is a sentence, it would be as follows:
A S2S Compiler is given as input the source code of a program to which it returns a source code with the overall same functionality in the same or different programming language.
Unlike the general compiler whose work is to convert a high-level programming language to a machine language that is binary, the source to source compiler converts one source code from one programming language to another programming language which is at the same level of compilation from machine language. For example, while the traditional compiler may convert C to assembly or Java to bytecode, the source to source compiler may convert one scripting language to another such as Javascript to Python, or C++ to Java.
Some examples of traditional compilers are listed below :
Some Examples of Source to Source compilers are listed below :
ActionScript3, JavaScript, Java, C++,
C#, PHP, Python, Lua
One of the main source application of source to source compilers is to convert the old code, that is legacy code, to the newer versions of a programming language or an API which helps in retaining the backward compatibility of the code. Tools come in very handy in updating large and old code bases which otherwise would take too much time to do it manually. An example of it could be converting the program of the older version of C++ to the current stable version that is C++20. Or it could also be the case of an API such as the old Dart program to be converted to the newer Dart 2.0 version. The structure of the newer could is dependent on the compiler. It could either be very similar to the original code to ease the development process from one language to the other or from the older version to the newer. Or the code structure can be completely changed so as to make it look original or different.
If we give a closer look at the table above, we can deduce that the initial use of some of the main programming languages, such as PHP or C++, was started as a source to source compilers, as their main use was to convert to the other mainstream programming languages. Today also, if we take a look around, we can identify languages such as Dart, Typescript, CoffeeScript, Emcscript and others as being mainly used for the conversion to other languages.
Assembly Language Translator :Assembly language translators are one of the most important examples of the source to source compiler. Below we have discussed in brief the four assembly language translators.
Intel CONV86 – It is one of the first compilers which could translate assembly into the binary. Back in the late 70’s, it was made by Intel, which is famous for making processors. The intended purpose for this was to reliably run the program made for an 8-bit processor onto Intel’s 16-bit processor. As per the users, it being one of the first of its kind, it was not able to perform up to the expectations.
SCP TRANS86 – Similar to the Intel CONV86, this translator was developed in 1980 by an engineer named Tim Paterson who is known as the creator of the famous 86-DOS. This translator was designed to translate assembly code from Intel 8080 and Zilog Z80 into .ASM code for Intels 16-bit processor Intel 8086. But similar to its previous counterpart, it was unable to perform the job effectively and required a lot of manual correction.
Sorcim TRANS86 –Socrium is a start-up that also offered an assembly translator to the market in 1980. It was also invented to convert assembly to MS-DOS. This translator proved to be a better substitute for the previous two.
Digital Research XLT86 – This translator appeared in the market in September of 1981 and was developed by Gary Kildall. Before this translator, no one other had the optimizing compiler approach which provided an effective performance. Like SCP TRANS86, its object was also to convert .ASM source code from Intel 8080 into the .A86 code for Intel 8086.
These four assembly code translators mark the beginning for the source to source compilers, which now had made many folds of progress.
adnanirshad158
sumitgumber28
Picked
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Data flow analysis in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Runtime Environments in Compiler Design
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "A compiler is a software program that transforms a program or code written in a high-level programming language into a low-level machine-readable language. When we write a program or code which can be in a high-level language, such as C, C++ or such as the one given below."
},
{
"code": null,
"e": 437,
"s": 302,
"text": "//Simple Java program\npublic class simple{ \n public static void main(String[] args){ \n System.out.printIn(\"Hello World\")\n }\n }"
},
{
"code": null,
"e": 903,
"s": 437,
"text": "A high-level language is closer to English, which makes it easier for us to write programs. But we can’t just run the same code onto a computer as machines can’t understand that. All that a computer can understand is binary code, that is ones and zeros. Therefore, the solution to the problem that computers can’t understand high-level languages would be to convert those into machine-understandable binary code. This is the exact task that is done by a compiler. "
},
{
"code": null,
"e": 992,
"s": 903,
"text": "The compiling process of the simple ‘hello world’ program up there would be as follows –"
},
{
"code": null,
"e": 1325,
"s": 992,
"text": "We create the ‘hello world’ program and save the file as Hello.java.When we complete this program, the compiler generates the equivalent machine code and saves it into the class file of the same name but with class extension Hello.class.And when the program is executed, it is the class file that gets executed and gives the output."
},
{
"code": null,
"e": 1394,
"s": 1325,
"text": "We create the ‘hello world’ program and save the file as Hello.java."
},
{
"code": null,
"e": 1564,
"s": 1394,
"text": "When we complete this program, the compiler generates the equivalent machine code and saves it into the class file of the same name but with class extension Hello.class."
},
{
"code": null,
"e": 1660,
"s": 1564,
"text": "And when the program is executed, it is the class file that gets executed and gives the output."
},
{
"code": null,
"e": 1788,
"s": 1660,
"text": "Compiles are of many types, but in this article, we are going to learn about a specific one, that is Source to Source Compiler."
},
{
"code": null,
"e": 2110,
"s": 1788,
"text": "Source To Source Compiler :A source to source compiler (S2S compiler) is also referred to by three other name, the first is the source to source translator, the second is transcompiler and the third one is transpiler. If we try to summarize the work on the source to source compiler is a sentence, it would be as follows:"
},
{
"code": null,
"e": 2290,
"s": 2110,
"text": "A S2S Compiler is given as input the source code of a program to which it returns a source code with the overall same functionality in the same or different programming language. "
},
{
"code": null,
"e": 2811,
"s": 2290,
"text": "Unlike the general compiler whose work is to convert a high-level programming language to a machine language that is binary, the source to source compiler converts one source code from one programming language to another programming language which is at the same level of compilation from machine language. For example, while the traditional compiler may convert C to assembly or Java to bytecode, the source to source compiler may convert one scripting language to another such as Javascript to Python, or C++ to Java. "
},
{
"code": null,
"e": 2869,
"s": 2811,
"text": "Some examples of traditional compilers are listed below :"
},
{
"code": null,
"e": 2932,
"s": 2869,
"text": "Some Examples of Source to Source compilers are listed below :"
},
{
"code": null,
"e": 2970,
"s": 2932,
"text": "ActionScript3, JavaScript, Java, C++,"
},
{
"code": null,
"e": 2991,
"s": 2970,
"text": "C#, PHP, Python, Lua"
},
{
"code": null,
"e": 3899,
"s": 2991,
"text": "One of the main source application of source to source compilers is to convert the old code, that is legacy code, to the newer versions of a programming language or an API which helps in retaining the backward compatibility of the code. Tools come in very handy in updating large and old code bases which otherwise would take too much time to do it manually. An example of it could be converting the program of the older version of C++ to the current stable version that is C++20. Or it could also be the case of an API such as the old Dart program to be converted to the newer Dart 2.0 version. The structure of the newer could is dependent on the compiler. It could either be very similar to the original code to ease the development process from one language to the other or from the older version to the newer. Or the code structure can be completely changed so as to make it look original or different."
},
{
"code": null,
"e": 4352,
"s": 3899,
"text": "If we give a closer look at the table above, we can deduce that the initial use of some of the main programming languages, such as PHP or C++, was started as a source to source compilers, as their main use was to convert to the other mainstream programming languages. Today also, if we take a look around, we can identify languages such as Dart, Typescript, CoffeeScript, Emcscript and others as being mainly used for the conversion to other languages."
},
{
"code": null,
"e": 4558,
"s": 4352,
"text": "Assembly Language Translator :Assembly language translators are one of the most important examples of the source to source compiler. Below we have discussed in brief the four assembly language translators."
},
{
"code": null,
"e": 4967,
"s": 4558,
"text": "Intel CONV86 – It is one of the first compilers which could translate assembly into the binary. Back in the late 70’s, it was made by Intel, which is famous for making processors. The intended purpose for this was to reliably run the program made for an 8-bit processor onto Intel’s 16-bit processor. As per the users, it being one of the first of its kind, it was not able to perform up to the expectations."
},
{
"code": null,
"e": 5400,
"s": 4967,
"text": "SCP TRANS86 – Similar to the Intel CONV86, this translator was developed in 1980 by an engineer named Tim Paterson who is known as the creator of the famous 86-DOS. This translator was designed to translate assembly code from Intel 8080 and Zilog Z80 into .ASM code for Intels 16-bit processor Intel 8086. But similar to its previous counterpart, it was unable to perform the job effectively and required a lot of manual correction."
},
{
"code": null,
"e": 5625,
"s": 5400,
"text": "Sorcim TRANS86 –Socrium is a start-up that also offered an assembly translator to the market in 1980. It was also invented to convert assembly to MS-DOS. This translator proved to be a better substitute for the previous two."
},
{
"code": null,
"e": 5977,
"s": 5625,
"text": "Digital Research XLT86 – This translator appeared in the market in September of 1981 and was developed by Gary Kildall. Before this translator, no one other had the optimizing compiler approach which provided an effective performance. Like SCP TRANS86, its object was also to convert .ASM source code from Intel 8080 into the .A86 code for Intel 8086."
},
{
"code": null,
"e": 6112,
"s": 5977,
"text": "These four assembly code translators mark the beginning for the source to source compilers, which now had made many folds of progress."
},
{
"code": null,
"e": 6127,
"s": 6112,
"text": "adnanirshad158"
},
{
"code": null,
"e": 6141,
"s": 6127,
"text": "sumitgumber28"
},
{
"code": null,
"e": 6148,
"s": 6141,
"text": "Picked"
},
{
"code": null,
"e": 6164,
"s": 6148,
"text": "Compiler Design"
},
{
"code": null,
"e": 6172,
"s": 6164,
"text": "GATE CS"
},
{
"code": null,
"e": 6270,
"s": 6172,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6328,
"s": 6270,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 6361,
"s": 6328,
"text": "Type Checking in Compiler Design"
},
{
"code": null,
"e": 6392,
"s": 6361,
"text": "Data flow analysis in Compiler"
},
{
"code": null,
"e": 6462,
"s": 6392,
"text": "S - attributed and L - attributed SDTs in Syntax directed translation"
},
{
"code": null,
"e": 6502,
"s": 6462,
"text": "Runtime Environments in Compiler Design"
},
{
"code": null,
"e": 6522,
"s": 6502,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 6546,
"s": 6522,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 6559,
"s": 6546,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 6586,
"s": 6559,
"text": "Types of Operating Systems"
}
]
|
Magic Square | ODD Order | 17 Jun, 2022
A magic square of order n is an arrangement of n2 numbers, usually distinct integers, in a square, such that the n numbers in all rows, all columns, and both diagonals sum to the same constant. A magic square contains the integers from 1 to n2. The constant sum in every row, column and diagonal are called the magic constant or magic sum, M. The magic constant of a normal magic square depends only on n and has the following value: M = n(n2+1)/2
For normal magic squares of order n = 3, 4, 5, ...,
the magic constants are: 15, 34, 65, 111, 175, 260, ...
In this post, we will discuss how programmatically we can generate a magic square of size n. This approach only takes into account odd values of n and doesn’t work for even numbers. Before we go further, consider the below examples:
Magic Square of size 3
-----------------------
2 7 6
9 5 1
4 3 8
Sum in each row & each column = 3*(32+1)/2 = 15
Magic Square of size 5
----------------------
9 3 22 16 15
2 21 20 14 8
25 19 13 7 1
18 12 6 5 24
11 10 4 23 17
Sum in each row & each column = 5*(52+1)/2 = 65
Magic Square of size 7
----------------------
20 12 4 45 37 29 28
11 3 44 36 35 27 19
2 43 42 34 26 18 10
49 41 33 25 17 9 1
40 32 24 16 8 7 48
31 23 15 14 6 47 39
22 21 13 5 46 38 30
Sum in each row & each column = 7*(72+1)/2 = 175
Did you find any pattern in which the numbers are stored?
In any magic square, the first number i.e. 1 is stored at position (n/2, n-1). Let this position be (i,j). The next number is stored at position (i-1, j+1) where we can consider each row & column as circular array i.e. they wrap around.
Three conditions hold:
The position of next number is calculated by decrementing row number of the previous number by 1, and incrementing the column number of the previous number by 1. At any time, if the calculated row position becomes -1, it will wrap around to n-1. Similarly, if the calculated column position becomes n, it will wrap around to 0.If the magic square already contains a number at the calculated position, calculated column position will be decremented by 2, and calculated row position will be incremented by 1.If the calculated row position is -1 & calculated column position is n, the new position would be: (0, n-2).
The position of next number is calculated by decrementing row number of the previous number by 1, and incrementing the column number of the previous number by 1. At any time, if the calculated row position becomes -1, it will wrap around to n-1. Similarly, if the calculated column position becomes n, it will wrap around to 0.
If the magic square already contains a number at the calculated position, calculated column position will be decremented by 2, and calculated row position will be incremented by 1.
If the calculated row position is -1 & calculated column position is n, the new position would be: (0, n-2).
Example:
Magic Square of size 3
----------------------
2 7 6
9 5 1
4 3 8
Steps:
1. position of number 1 = (3/2, 3-1) = (1, 2)
2. position of number 2 = (1-1, 2+1) = (0, 0)
3. position of number 3 = (0-1, 0+1) = (3-1, 1) = (2, 1)
4. position of number 4 = (2-1, 1+1) = (1, 2)
Since, at this position, 1 is there. So, apply condition 2.
new position=(1+1,2-2)=(2,0)
5. position of number 5=(2-1,0+1)=(1,1)
6. position of number 6=(1-1,1+1)=(0,2)
7. position of number 7 = (0-1, 2+1) = (-1,3) // this is tricky, see condition 3
new position = (0, 3-2) = (0,1)
8. position of number 8=(0-1,1+1)=(-1,2)=(2,2) //wrap around
9. position of number 9=(2-1,2+1)=(1,3)=(1,0) //wrap around
Based on the above approach, the following is the working code:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to generate odd sized magic squares#include <bits/stdc++.h>using namespace std; // A function to generate odd sized magic squaresvoid generateSquare(int n){ int magicSquare[n][n]; // set all slots as 0 memset(magicSquare, 0, sizeof(magicSquare)); // Initialize position for 1 int i = n / 2; int j = n - 1; // One by one put all values in magic square for (int num = 1; num <= n * n;) { if (i == -1 && j == n) // 3rd condition { j = n - 2; i = 0; } else { // 1st condition helper if next number // goes to out of square's right side if (j == n) j = 0; // 1st condition helper if next number // is goes to out of square's upper side if (i < 0) i = n - 1; } if (magicSquare[i][j]) // 2nd condition { j -= 2; i++; continue; } else magicSquare[i][j] = num++; // set number j++; i--; // 1st condition } // Print magic square cout << "The Magic Square for n=" << n << ":\nSum of " "each row or column " << n * (n * n + 1) / 2 << ":\n\n"; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) // setw(7) is used so that the matrix gets // printed in a proper square fashion. cout << setw(4) << magicSquare[i][j] << " "; cout << endl; }} // Driver codeint main(){ // Works only when n is odd int n = 7; generateSquare(n); return 0;} // This code is contributed by rathbhupendra
// C program to generate odd sized magic squares#include <stdio.h>#include <string.h> // A function to generate odd sized magic squaresvoid generateSquare(int n){ int magicSquare[n][n]; // set all slots as 0 memset(magicSquare, 0, sizeof(magicSquare)); // Initialize position for 1 int i = n / 2; int j = n - 1; // One by one put all values in magic square for (int num = 1; num <= n * n;) { if (i == -1 && j == n) // 3rd condition { j = n - 2; i = 0; } else { // 1st condition helper if next number // goes to out of square's right side if (j == n) j = 0; // 1st condition helper if next number // is goes to out of square's upper side if (i < 0) i = n - 1; } if (magicSquare[i][j]) // 2nd condition { j -= 2; i++; continue; } else magicSquare[i][j] = num++; // set number j++; i--; // 1st condition } // Print magic square printf("The Magic Square for n=%d:\nSum of " "each row or column %d:\n\n", n, n * (n * n + 1) / 2); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("%3d ", magicSquare[i][j]); printf("\n"); }} // Driver program to test above functionint main(){ int n = 7; // Works only when n is odd generateSquare(n); return 0;}
// Java program to generate odd sized magic squaresimport java.io.*; class GFG { // Function to generate odd sized magic squares static void generateSquare(int n) { int[][] magicSquare = new int[n][n]; // Initialize position for 1 int i = n / 2; int j = n - 1; // One by one put all values in magic square for (int num = 1; num <= n * n;) { if (i == -1 && j == n) // 3rd condition { j = n - 2; i = 0; } else { // 1st condition helper if next number // goes to out of square's right side if (j == n) j = 0; // 1st condition helper if next number is // goes to out of square's upper side if (i < 0) i = n - 1; } // 2nd condition if (magicSquare[i][j] != 0) { j -= 2; i++; continue; } else // set number magicSquare[i][j] = num++; // 1st condition j++; i--; } // print magic square System.out.println("The Magic Square for " + n + ":"); System.out.println("Sum of each row or column " + n * (n * n + 1) / 2 + ":"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) System.out.print(magicSquare[i][j] + " "); System.out.println(); } } // driver program public static void main(String[] args) { // Works only when n is odd int n = 7; generateSquare(n); }} // Contributed by Pramod Kumar
# Python program to generate# odd sized magic squares# A function to generate odd# sized magic squares def generateSquare(n): # 2-D array with all # slots set to 0 magicSquare = [[0 for x in range(n)] for y in range(n)] # initialize position of 1 i = n // 2 j = n - 1 # Fill the magic square # by placing values num = 1 while num <= (n * n): if i == -1 and j == n: # 3rd condition j = n - 2 i = 0 else: # next number goes out of # right side of square if j == n: j = 0 # next number goes # out of upper side if i < 0: i = n - 1 if magicSquare[int(i)][int(j)]: # 2nd condition j = j - 2 i = i + 1 continue else: magicSquare[int(i)][int(j)] = num num = num + 1 j = j + 1 i = i - 1 # 1st condition # Printing magic square print("Magic Square for n =", n) print("Sum of each row or column", n * (n * n + 1) // 2, "\n") for i in range(0, n): for j in range(0, n): print('%2d ' % (magicSquare[i][j]), end='') # To display output # in matrix form if j == n - 1: print() # Driver Code # Works only when n is oddn = 7generateSquare(n) # This code is contributed# by Harshit Agrawal
// C# program to generate odd sized magic squaresusing System; class GFG { // Function to generate odd sized magic squares static void generateSquare(int n) { int[, ] magicSquare = new int[n, n]; // Initialize position for 1 int i = n / 2; int j = n - 1; // One by one put all values in magic square for (int num = 1; num <= n * n;) { if (i == -1 && j == n) // 3rd condition { j = n - 2; i = 0; } else { // 1st condition helper if next number // goes to out of square's right side if (j == n) j = 0; // 1st condition helper if next number is // goes to out of square's upper side if (i < 0) i = n - 1; } // 2nd condition if (magicSquare[i, j] != 0) { j -= 2; i++; continue; } else // set number magicSquare[i, j] = num++; // 1st condition j++; i--; } // print magic square Console.WriteLine("The Magic Square for " + n + ":"); Console.WriteLine("Sum of each row or column " + n * (n * n + 1) / 2 + ":"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) Console.Write(magicSquare[i, j] + " "); Console.WriteLine(); } } // driver program public static void Main() { // Works only when n is odd int n = 7; generateSquare(n); }} // This code is contributed by Sam007.
<?php// php program to generate odd sized// magic squares // A function to generate odd sized// magic squaresfunction generateSquare($n){ // set all slots as 0 $magicSquare; for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $n; $j++) $magicSquare[$i][$j] = 0; // Initialize position for 1 $i = (int)$n / 2; $j = $n - 1; // One by one put all values in // magic square for ($num = 1; $num <= $n * $n; ) { // 3rd condition if ($i == -1 && $j == $n) { $j = $n-2; $i = 0; } else { // 1st condition helper if // next number goes to out // of square's right side if ($j == $n) $j = 0; // 1st condition helper if // next number is goes to // out of square's upper // side if ($i < 0) $i = $n-1; } // 2nd condition if ($magicSquare[$i][$j]) { $j -= 2; $i++; continue; } else // set number $magicSquare[$i][$j] = $num++; // 1st condition $j++; $i--; } // Print magic square echo "The Magic Square for n = " . $n . ":\nSum of each row or column " . $n * ($n * $n + 1) / 2; echo "\n\n"; for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) echo $magicSquare[$i][$j] . " "; echo "\n"; }} // Driver program to test above function // Works only when n is odd$n = 7;generateSquare ($n); // This code is contributed by mits.?>
<script> // javascript program to generate odd sized magic squares // Function to generate odd sized magic squares function generateSquare(n){ magicSquare = Array(n).fill(0).map(x => Array(n).fill(0)); // Initialize position for 1 var i = parseInt(n / 2); var j = n - 1; // One by one put all values in magic square for (num = 1; num <= n * n;) { if (i == -1 && j == n) // 3rd condition { j = n - 2; i = 0; } else { // 1st condition helper if next number // goes to out of square's right side if (j == n) j = 0; // 1st condition helper if next number is // goes to out of square's upper side if (i < 0) i = n - 1; } // 2nd condition if (magicSquare[i][j] != 0) { j -= 2; i++; continue; } else // set number magicSquare[i][j] = num++; // 1st condition j++; i--; } // print magic square document.write("The Magic Square for " + n + ":<br>"); document.write("Sum of each row or column " + parseInt(n * (n * n + 1) / 2) + ":<br>"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) document.write(magicSquare[i][j] + " "); document.write("<br>"); }} // driver program // Works only when n is oddvar n = 7;generateSquare(n); // This code is contributed by 29AjayKumar </script>
The Magic Square for n=7:
Sum of each row or column 175:
20 12 4 45 37 29 28
11 3 44 36 35 27 19
2 43 42 34 26 18 10
49 41 33 25 17 9 1
40 32 24 16 8 7 48
31 23 15 14 6 47 39
22 21 13 5 46 38 30
Time Complexity: O(n2)Auxiliary Space: O(n2)
NOTE: This approach works only for odd values of n.
Mithun Kumar
rathbhupendra
vishwajeet0524
29AjayKumar
surinderdawra388
ananthakrishnaks
sa692
subham348
rishavmahato348
amartyaghoshgfg
hardikkoriintern
Mathematical
Matrix
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Minimum number of jumps to reach end
Matrix Chain Multiplication | DP-8
Print a given matrix in spiral form
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 500,
"s": 52,
"text": "A magic square of order n is an arrangement of n2 numbers, usually distinct integers, in a square, such that the n numbers in all rows, all columns, and both diagonals sum to the same constant. A magic square contains the integers from 1 to n2. The constant sum in every row, column and diagonal are called the magic constant or magic sum, M. The magic constant of a normal magic square depends only on n and has the following value: M = n(n2+1)/2"
},
{
"code": null,
"e": 609,
"s": 500,
"text": "For normal magic squares of order n = 3, 4, 5, ...,\nthe magic constants are: 15, 34, 65, 111, 175, 260, ... "
},
{
"code": null,
"e": 842,
"s": 609,
"text": "In this post, we will discuss how programmatically we can generate a magic square of size n. This approach only takes into account odd values of n and doesn’t work for even numbers. Before we go further, consider the below examples:"
},
{
"code": null,
"e": 1462,
"s": 842,
"text": "Magic Square of size 3\n-----------------------\n 2 7 6\n 9 5 1\n 4 3 8\nSum in each row & each column = 3*(32+1)/2 = 15\n\n\nMagic Square of size 5\n----------------------\n 9 3 22 16 15\n 2 21 20 14 8\n 25 19 13 7 1\n 18 12 6 5 24\n 11 10 4 23 17\nSum in each row & each column = 5*(52+1)/2 = 65\n\n\nMagic Square of size 7\n----------------------\n 20 12 4 45 37 29 28\n 11 3 44 36 35 27 19\n 2 43 42 34 26 18 10\n 49 41 33 25 17 9 1\n 40 32 24 16 8 7 48\n 31 23 15 14 6 47 39\n 22 21 13 5 46 38 30\nSum in each row & each column = 7*(72+1)/2 = 175"
},
{
"code": null,
"e": 1521,
"s": 1462,
"text": "Did you find any pattern in which the numbers are stored? "
},
{
"code": null,
"e": 1758,
"s": 1521,
"text": "In any magic square, the first number i.e. 1 is stored at position (n/2, n-1). Let this position be (i,j). The next number is stored at position (i-1, j+1) where we can consider each row & column as circular array i.e. they wrap around."
},
{
"code": null,
"e": 1781,
"s": 1758,
"text": "Three conditions hold:"
},
{
"code": null,
"e": 2398,
"s": 1781,
"text": "The position of next number is calculated by decrementing row number of the previous number by 1, and incrementing the column number of the previous number by 1. At any time, if the calculated row position becomes -1, it will wrap around to n-1. Similarly, if the calculated column position becomes n, it will wrap around to 0.If the magic square already contains a number at the calculated position, calculated column position will be decremented by 2, and calculated row position will be incremented by 1.If the calculated row position is -1 & calculated column position is n, the new position would be: (0, n-2). "
},
{
"code": null,
"e": 2726,
"s": 2398,
"text": "The position of next number is calculated by decrementing row number of the previous number by 1, and incrementing the column number of the previous number by 1. At any time, if the calculated row position becomes -1, it will wrap around to n-1. Similarly, if the calculated column position becomes n, it will wrap around to 0."
},
{
"code": null,
"e": 2907,
"s": 2726,
"text": "If the magic square already contains a number at the calculated position, calculated column position will be decremented by 2, and calculated row position will be incremented by 1."
},
{
"code": null,
"e": 3017,
"s": 2907,
"text": "If the calculated row position is -1 & calculated column position is n, the new position would be: (0, n-2). "
},
{
"code": null,
"e": 3716,
"s": 3017,
"text": "Example:\nMagic Square of size 3\n----------------------\n 2 7 6\n 9 5 1\n 4 3 8 \n\nSteps:\n1. position of number 1 = (3/2, 3-1) = (1, 2)\n2. position of number 2 = (1-1, 2+1) = (0, 0)\n3. position of number 3 = (0-1, 0+1) = (3-1, 1) = (2, 1)\n4. position of number 4 = (2-1, 1+1) = (1, 2)\n Since, at this position, 1 is there. So, apply condition 2.\n new position=(1+1,2-2)=(2,0)\n5. position of number 5=(2-1,0+1)=(1,1)\n6. position of number 6=(1-1,1+1)=(0,2)\n7. position of number 7 = (0-1, 2+1) = (-1,3) // this is tricky, see condition 3 \n new position = (0, 3-2) = (0,1)\n8. position of number 8=(0-1,1+1)=(-1,2)=(2,2) //wrap around\n9. position of number 9=(2-1,2+1)=(1,3)=(1,0) //wrap around"
},
{
"code": null,
"e": 3781,
"s": 3716,
"text": "Based on the above approach, the following is the working code: "
},
{
"code": null,
"e": 3785,
"s": 3781,
"text": "C++"
},
{
"code": null,
"e": 3787,
"s": 3785,
"text": "C"
},
{
"code": null,
"e": 3792,
"s": 3787,
"text": "Java"
},
{
"code": null,
"e": 3800,
"s": 3792,
"text": "Python3"
},
{
"code": null,
"e": 3803,
"s": 3800,
"text": "C#"
},
{
"code": null,
"e": 3807,
"s": 3803,
"text": "PHP"
},
{
"code": null,
"e": 3818,
"s": 3807,
"text": "Javascript"
},
{
"code": "// C++ program to generate odd sized magic squares#include <bits/stdc++.h>using namespace std; // A function to generate odd sized magic squaresvoid generateSquare(int n){ int magicSquare[n][n]; // set all slots as 0 memset(magicSquare, 0, sizeof(magicSquare)); // Initialize position for 1 int i = n / 2; int j = n - 1; // One by one put all values in magic square for (int num = 1; num <= n * n;) { if (i == -1 && j == n) // 3rd condition { j = n - 2; i = 0; } else { // 1st condition helper if next number // goes to out of square's right side if (j == n) j = 0; // 1st condition helper if next number // is goes to out of square's upper side if (i < 0) i = n - 1; } if (magicSquare[i][j]) // 2nd condition { j -= 2; i++; continue; } else magicSquare[i][j] = num++; // set number j++; i--; // 1st condition } // Print magic square cout << \"The Magic Square for n=\" << n << \":\\nSum of \" \"each row or column \" << n * (n * n + 1) / 2 << \":\\n\\n\"; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) // setw(7) is used so that the matrix gets // printed in a proper square fashion. cout << setw(4) << magicSquare[i][j] << \" \"; cout << endl; }} // Driver codeint main(){ // Works only when n is odd int n = 7; generateSquare(n); return 0;} // This code is contributed by rathbhupendra",
"e": 5470,
"s": 3818,
"text": null
},
{
"code": "// C program to generate odd sized magic squares#include <stdio.h>#include <string.h> // A function to generate odd sized magic squaresvoid generateSquare(int n){ int magicSquare[n][n]; // set all slots as 0 memset(magicSquare, 0, sizeof(magicSquare)); // Initialize position for 1 int i = n / 2; int j = n - 1; // One by one put all values in magic square for (int num = 1; num <= n * n;) { if (i == -1 && j == n) // 3rd condition { j = n - 2; i = 0; } else { // 1st condition helper if next number // goes to out of square's right side if (j == n) j = 0; // 1st condition helper if next number // is goes to out of square's upper side if (i < 0) i = n - 1; } if (magicSquare[i][j]) // 2nd condition { j -= 2; i++; continue; } else magicSquare[i][j] = num++; // set number j++; i--; // 1st condition } // Print magic square printf(\"The Magic Square for n=%d:\\nSum of \" \"each row or column %d:\\n\\n\", n, n * (n * n + 1) / 2); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf(\"%3d \", magicSquare[i][j]); printf(\"\\n\"); }} // Driver program to test above functionint main(){ int n = 7; // Works only when n is odd generateSquare(n); return 0;}",
"e": 6956,
"s": 5470,
"text": null
},
{
"code": "// Java program to generate odd sized magic squaresimport java.io.*; class GFG { // Function to generate odd sized magic squares static void generateSquare(int n) { int[][] magicSquare = new int[n][n]; // Initialize position for 1 int i = n / 2; int j = n - 1; // One by one put all values in magic square for (int num = 1; num <= n * n;) { if (i == -1 && j == n) // 3rd condition { j = n - 2; i = 0; } else { // 1st condition helper if next number // goes to out of square's right side if (j == n) j = 0; // 1st condition helper if next number is // goes to out of square's upper side if (i < 0) i = n - 1; } // 2nd condition if (magicSquare[i][j] != 0) { j -= 2; i++; continue; } else // set number magicSquare[i][j] = num++; // 1st condition j++; i--; } // print magic square System.out.println(\"The Magic Square for \" + n + \":\"); System.out.println(\"Sum of each row or column \" + n * (n * n + 1) / 2 + \":\"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) System.out.print(magicSquare[i][j] + \" \"); System.out.println(); } } // driver program public static void main(String[] args) { // Works only when n is odd int n = 7; generateSquare(n); }} // Contributed by Pramod Kumar",
"e": 8728,
"s": 6956,
"text": null
},
{
"code": "# Python program to generate# odd sized magic squares# A function to generate odd# sized magic squares def generateSquare(n): # 2-D array with all # slots set to 0 magicSquare = [[0 for x in range(n)] for y in range(n)] # initialize position of 1 i = n // 2 j = n - 1 # Fill the magic square # by placing values num = 1 while num <= (n * n): if i == -1 and j == n: # 3rd condition j = n - 2 i = 0 else: # next number goes out of # right side of square if j == n: j = 0 # next number goes # out of upper side if i < 0: i = n - 1 if magicSquare[int(i)][int(j)]: # 2nd condition j = j - 2 i = i + 1 continue else: magicSquare[int(i)][int(j)] = num num = num + 1 j = j + 1 i = i - 1 # 1st condition # Printing magic square print(\"Magic Square for n =\", n) print(\"Sum of each row or column\", n * (n * n + 1) // 2, \"\\n\") for i in range(0, n): for j in range(0, n): print('%2d ' % (magicSquare[i][j]), end='') # To display output # in matrix form if j == n - 1: print() # Driver Code # Works only when n is oddn = 7generateSquare(n) # This code is contributed# by Harshit Agrawal",
"e": 10183,
"s": 8728,
"text": null
},
{
"code": "// C# program to generate odd sized magic squaresusing System; class GFG { // Function to generate odd sized magic squares static void generateSquare(int n) { int[, ] magicSquare = new int[n, n]; // Initialize position for 1 int i = n / 2; int j = n - 1; // One by one put all values in magic square for (int num = 1; num <= n * n;) { if (i == -1 && j == n) // 3rd condition { j = n - 2; i = 0; } else { // 1st condition helper if next number // goes to out of square's right side if (j == n) j = 0; // 1st condition helper if next number is // goes to out of square's upper side if (i < 0) i = n - 1; } // 2nd condition if (magicSquare[i, j] != 0) { j -= 2; i++; continue; } else // set number magicSquare[i, j] = num++; // 1st condition j++; i--; } // print magic square Console.WriteLine(\"The Magic Square for \" + n + \":\"); Console.WriteLine(\"Sum of each row or column \" + n * (n * n + 1) / 2 + \":\"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) Console.Write(magicSquare[i, j] + \" \"); Console.WriteLine(); } } // driver program public static void Main() { // Works only when n is odd int n = 7; generateSquare(n); }} // This code is contributed by Sam007.",
"e": 11940,
"s": 10183,
"text": null
},
{
"code": "<?php// php program to generate odd sized// magic squares // A function to generate odd sized// magic squaresfunction generateSquare($n){ // set all slots as 0 $magicSquare; for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $n; $j++) $magicSquare[$i][$j] = 0; // Initialize position for 1 $i = (int)$n / 2; $j = $n - 1; // One by one put all values in // magic square for ($num = 1; $num <= $n * $n; ) { // 3rd condition if ($i == -1 && $j == $n) { $j = $n-2; $i = 0; } else { // 1st condition helper if // next number goes to out // of square's right side if ($j == $n) $j = 0; // 1st condition helper if // next number is goes to // out of square's upper // side if ($i < 0) $i = $n-1; } // 2nd condition if ($magicSquare[$i][$j]) { $j -= 2; $i++; continue; } else // set number $magicSquare[$i][$j] = $num++; // 1st condition $j++; $i--; } // Print magic square echo \"The Magic Square for n = \" . $n . \":\\nSum of each row or column \" . $n * ($n * $n + 1) / 2; echo \"\\n\\n\"; for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) echo $magicSquare[$i][$j] . \" \"; echo \"\\n\"; }} // Driver program to test above function // Works only when n is odd$n = 7;generateSquare ($n); // This code is contributed by mits.?>",
"e": 13610,
"s": 11940,
"text": null
},
{
"code": "<script> // javascript program to generate odd sized magic squares // Function to generate odd sized magic squares function generateSquare(n){ magicSquare = Array(n).fill(0).map(x => Array(n).fill(0)); // Initialize position for 1 var i = parseInt(n / 2); var j = n - 1; // One by one put all values in magic square for (num = 1; num <= n * n;) { if (i == -1 && j == n) // 3rd condition { j = n - 2; i = 0; } else { // 1st condition helper if next number // goes to out of square's right side if (j == n) j = 0; // 1st condition helper if next number is // goes to out of square's upper side if (i < 0) i = n - 1; } // 2nd condition if (magicSquare[i][j] != 0) { j -= 2; i++; continue; } else // set number magicSquare[i][j] = num++; // 1st condition j++; i--; } // print magic square document.write(\"The Magic Square for \" + n + \":<br>\"); document.write(\"Sum of each row or column \" + parseInt(n * (n * n + 1) / 2) + \":<br>\"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) document.write(magicSquare[i][j] + \" \"); document.write(\"<br>\"); }} // driver program // Works only when n is oddvar n = 7;generateSquare(n); // This code is contributed by 29AjayKumar </script>",
"e": 15153,
"s": 13610,
"text": null
},
{
"code": null,
"e": 15463,
"s": 15153,
"text": "The Magic Square for n=7:\nSum of each row or column 175:\n\n 20 12 4 45 37 29 28 \n 11 3 44 36 35 27 19 \n 2 43 42 34 26 18 10 \n 49 41 33 25 17 9 1 \n 40 32 24 16 8 7 48 \n 31 23 15 14 6 47 39 \n 22 21 13 5 46 38 30 "
},
{
"code": null,
"e": 15508,
"s": 15463,
"text": "Time Complexity: O(n2)Auxiliary Space: O(n2)"
},
{
"code": null,
"e": 15560,
"s": 15508,
"text": "NOTE: This approach works only for odd values of n."
},
{
"code": null,
"e": 15573,
"s": 15560,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 15587,
"s": 15573,
"text": "rathbhupendra"
},
{
"code": null,
"e": 15602,
"s": 15587,
"text": "vishwajeet0524"
},
{
"code": null,
"e": 15614,
"s": 15602,
"text": "29AjayKumar"
},
{
"code": null,
"e": 15631,
"s": 15614,
"text": "surinderdawra388"
},
{
"code": null,
"e": 15648,
"s": 15631,
"text": "ananthakrishnaks"
},
{
"code": null,
"e": 15654,
"s": 15648,
"text": "sa692"
},
{
"code": null,
"e": 15664,
"s": 15654,
"text": "subham348"
},
{
"code": null,
"e": 15680,
"s": 15664,
"text": "rishavmahato348"
},
{
"code": null,
"e": 15696,
"s": 15680,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 15713,
"s": 15696,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 15726,
"s": 15713,
"text": "Mathematical"
},
{
"code": null,
"e": 15733,
"s": 15726,
"text": "Matrix"
},
{
"code": null,
"e": 15746,
"s": 15733,
"text": "Mathematical"
},
{
"code": null,
"e": 15753,
"s": 15746,
"text": "Matrix"
},
{
"code": null,
"e": 15851,
"s": 15753,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15875,
"s": 15851,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 15896,
"s": 15875,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 15918,
"s": 15896,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 15932,
"s": 15918,
"text": "Prime Numbers"
},
{
"code": null,
"e": 15969,
"s": 15932,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 16004,
"s": 15969,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 16040,
"s": 16004,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 16084,
"s": 16040,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 16115,
"s": 16084,
"text": "Rat in a Maze | Backtracking-2"
}
]
|
Git Reset | reset is the command we use when we want to move the repository back to a previous commit, discarding any changes made after that commit.
Step 1: Find the previous commit:
Step 2: Move the repository back to that step:
After the previous chapter, we have a part in our commit history we could go back to. Let's try and do that with reset.
First thing, we need to find the point we want to return to. To do that, we need to go through the
log.
To avoid the very long log list, we are going to use the
--oneline option,
which gives just one line per commit showing:
The first seven characters of the commit hash - this is what we need to
refer to in our reset command.
the commit message
So let's find the point we want to reset to:
git log --oneline
e56ba1f (HEAD -> master) Revert "Just a regular update, definitely no accidents here..."
52418f7 Just a regular update, definitely no accidents here...
9a9add8 (origin/master) Added .gitignore
81912ba Corrected spelling error
3fdaa5b Merge pull request #1 from w3schools-test/update-readme
836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches
daf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta
facaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world
e7de78f Updated index.html. Resized image
5a04b6f Updated README.md with a line about focus
d29d69f Updated README.md with a line about GitHub
e0b6038 merged with hello-world-images after fixing conflicts
1f1584e added new image
dfa79db updated index.html with emergency fix
0312c55 Added image to Hello World
09f4acd Updated index.html with a new line
221ec6e First release of Hello World!
We want to return to the commit:
9a9add8 (origin/master) Added .gitignore,
the last one before we started to mess with things.
We reset our repository back to the specific commit using
git reset
commithash (commithash being
the first 7 characters of the commit hash we found in the
log):
git reset 9a9add8
Now let's check the log again:
git log --oneline
9a9add8 (HEAD -> master, origin/master) Added .gitignore
81912ba Corrected spelling error
3fdaa5b Merge pull request #1 from w3schools-test/update-readme
836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches
daf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta
facaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world
e7de78f Updated index.html. Resized image
5a04b6f Updated README.md with a line about focus
d29d69f Updated README.md with a line about GitHub
e0b6038 merged with hello-world-images after fixing conflicts
1f1584e added new image
dfa79db updated index.html with emergency fix
0312c55 Added image to Hello World
09f4acd Updated index.html with a new line
221ec6e First release of Hello World!
Warning: Messing with the commit history of a repository can be dangerous.
It is usually ok to make these kinds of changes to your own local repository. However, you should avoid making changes that rewrite history to
remote repositories, especially if others are working with them.
Even though the commits are no longer showing up in the
log, it is not removed from Git.
If you know the commit hash you can reset to it:
git reset e56ba1f
Now let's check the log again:
git log --oneline
e56ba1f (HEAD -> master) Revert "Just a regular update, definitely no accidents here..."
52418f7 Just a regular update, definitely no accidents here...
9a9add8 (origin/master) Added .gitignore
81912ba Corrected spelling error
3fdaa5b Merge pull request #1 from w3schools-test/update-readme
836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches
daf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta
facaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world
e7de78f Updated index.html. Resized image
5a04b6f Updated README.md with a line about focus
d29d69f Updated README.md with a line about GitHub
e0b6038 merged with hello-world-images after fixing conflicts
1f1584e added new image
dfa79db updated index.html with emergency fix
0312c55 Added image to Hello World
09f4acd Updated index.html with a new line
221ec6e First release of Hello World!
reset to the commit with the hash abc1234:
git
Start the Exercise
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:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 138,
"s": 0,
"text": "reset is the command we use when we want to move the repository back to a previous commit, discarding any changes made after that commit."
},
{
"code": null,
"e": 172,
"s": 138,
"text": "Step 1: Find the previous commit:"
},
{
"code": null,
"e": 219,
"s": 172,
"text": "Step 2: Move the repository back to that step:"
},
{
"code": null,
"e": 339,
"s": 219,
"text": "After the previous chapter, we have a part in our commit history we could go back to. Let's try and do that with reset."
},
{
"code": null,
"e": 444,
"s": 339,
"text": "First thing, we need to find the point we want to return to. To do that, we need to go through the \nlog."
},
{
"code": null,
"e": 567,
"s": 444,
"text": "To avoid the very long log list, we are going to use the \n--oneline option, \nwhich gives just one line per commit showing:"
},
{
"code": null,
"e": 673,
"s": 567,
"text": "The first seven characters of the commit hash - this is what we need to \n refer to in our reset command."
},
{
"code": null,
"e": 692,
"s": 673,
"text": "the commit message"
},
{
"code": null,
"e": 737,
"s": 692,
"text": "So let's find the point we want to reset to:"
},
{
"code": null,
"e": 1694,
"s": 737,
"text": "git log --oneline\ne56ba1f (HEAD -> master) Revert \"Just a regular update, definitely no accidents here...\"\n52418f7 Just a regular update, definitely no accidents here...\n9a9add8 (origin/master) Added .gitignore\n81912ba Corrected spelling error\n3fdaa5b Merge pull request #1 from w3schools-test/update-readme\n836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches\ndaf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta\nfacaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world\ne7de78f Updated index.html. Resized image\n5a04b6f Updated README.md with a line about focus\nd29d69f Updated README.md with a line about GitHub\ne0b6038 merged with hello-world-images after fixing conflicts\n1f1584e added new image\ndfa79db updated index.html with emergency fix\n0312c55 Added image to Hello World\n09f4acd Updated index.html with a new line\n221ec6e First release of Hello World!"
},
{
"code": null,
"e": 1823,
"s": 1694,
"text": "We want to return to the commit: \n9a9add8 (origin/master) Added .gitignore, \nthe last one before we started to mess with things."
},
{
"code": null,
"e": 1987,
"s": 1823,
"text": "We reset our repository back to the specific commit using \ngit reset \ncommithash (commithash being \nthe first 7 characters of the commit hash we found in the\nlog):"
},
{
"code": null,
"e": 2005,
"s": 1987,
"text": "git reset 9a9add8"
},
{
"code": null,
"e": 2036,
"s": 2005,
"text": "Now let's check the log again:"
},
{
"code": null,
"e": 2857,
"s": 2036,
"text": "git log --oneline\n9a9add8 (HEAD -> master, origin/master) Added .gitignore\n81912ba Corrected spelling error\n3fdaa5b Merge pull request #1 from w3schools-test/update-readme\n836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches\ndaf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta\nfacaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world\ne7de78f Updated index.html. Resized image\n5a04b6f Updated README.md with a line about focus\nd29d69f Updated README.md with a line about GitHub\ne0b6038 merged with hello-world-images after fixing conflicts\n1f1584e added new image\ndfa79db updated index.html with emergency fix\n0312c55 Added image to Hello World\n09f4acd Updated index.html with a new line\n221ec6e First release of Hello World!"
},
{
"code": null,
"e": 3146,
"s": 2857,
"text": "Warning: Messing with the commit history of a repository can be dangerous. \n It is usually ok to make these kinds of changes to your own local repository. However, you should avoid making changes that rewrite history to \n remote repositories, especially if others are working with them."
},
{
"code": null,
"e": 3236,
"s": 3146,
"text": "Even though the commits are no longer showing up in the \nlog, it is not removed from Git."
},
{
"code": null,
"e": 3285,
"s": 3236,
"text": "If you know the commit hash you can reset to it:"
},
{
"code": null,
"e": 3303,
"s": 3285,
"text": "git reset e56ba1f"
},
{
"code": null,
"e": 3334,
"s": 3303,
"text": "Now let's check the log again:"
},
{
"code": null,
"e": 4291,
"s": 3334,
"text": "git log --oneline\ne56ba1f (HEAD -> master) Revert \"Just a regular update, definitely no accidents here...\"\n52418f7 Just a regular update, definitely no accidents here...\n9a9add8 (origin/master) Added .gitignore\n81912ba Corrected spelling error\n3fdaa5b Merge pull request #1 from w3schools-test/update-readme\n836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches\ndaf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta\nfacaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world\ne7de78f Updated index.html. Resized image\n5a04b6f Updated README.md with a line about focus\nd29d69f Updated README.md with a line about GitHub\ne0b6038 merged with hello-world-images after fixing conflicts\n1f1584e added new image\ndfa79db updated index.html with emergency fix\n0312c55 Added image to Hello World\n09f4acd Updated index.html with a new line\n221ec6e First release of Hello World!"
},
{
"code": null,
"e": 4334,
"s": 4291,
"text": "reset to the commit with the hash abc1234:"
},
{
"code": null,
"e": 4341,
"s": 4334,
"text": "git \n"
},
{
"code": null,
"e": 4361,
"s": 4341,
"text": "\nStart the Exercise"
},
{
"code": null,
"e": 4394,
"s": 4361,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 4436,
"s": 4394,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 4543,
"s": 4436,
"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": 4562,
"s": 4543,
"text": "[email protected]"
}
]
|
How to compile unsafe code in C#? | For compiling unsafe code, you have to specify the /unsafe command-line switch with command-line compiler.
For example, to compile a program named one.cs containing unsafe code, from command line, give the command −
csc /unsafe one.cs
Under Visual Studio IDE, enable use of unsafe code in the project properties. The following are the steps −
Open Project properties by double clicking the properties node in the Solution Explorer.
Click on the “Build” tab.
Select the option "Allow unsafe code". | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "For compiling unsafe code, you have to specify the /unsafe command-line switch with command-line compiler."
},
{
"code": null,
"e": 1279,
"s": 1169,
"text": "For example, to compile a program named one.cs containing unsafe code, from command line, give the command − "
},
{
"code": null,
"e": 1299,
"s": 1279,
"text": "csc /unsafe one.cs\n"
},
{
"code": null,
"e": 1408,
"s": 1299,
"text": "Under Visual Studio IDE, enable use of unsafe code in the project properties. The following are the steps − "
},
{
"code": null,
"e": 1497,
"s": 1408,
"text": "Open Project properties by double clicking the properties node in the Solution Explorer."
},
{
"code": null,
"e": 1523,
"s": 1497,
"text": "Click on the “Build” tab."
},
{
"code": null,
"e": 1562,
"s": 1523,
"text": "Select the option \"Allow unsafe code\"."
}
]
|
An Introduction to Genetic Algorithms: The Concept of Biological Evolution in Optimization | by Julian Blank | Towards Data Science | Genetic algorithms (GA) are inspired by the natural selection of species and belong to a broader class of algorithms referred to as Evolutionary Algorithms (EA). The concept of biological evolution is used to solve all different kinds of problems and has become well-known for its reliable global search capabilities. Thus, genetic algorithms have been used to solve myriads of real-world optimization problems and are an essential subject of research in optimization and related fields. They are known for their multidisciplinary usage across disciplines such as natural, social, and earth sciences, finance, or economics. Furthermore, genetic algorithms have been commonly employed to address well-known optimization problems in Data Science, Machine Learning, and Artificial Intelligence, for instance, selecting features in a data set, recognizing patterns, or determining the architecture of neural networks.
After having used genetic algorithms for more than ten years, I still find the concept fascinating and compelling. This article aims to provide you an introduction into genetic algorithms and the usage of evolutionary operators. The theory of genetic algorithms is described, and source code solving a numerical test problem is provided. Developing a genetic algorithm by yourself gives you a deeper understanding of evolution in the context of optimization. If you have always been curious about genetic algorithms but have never found the time to implement one, you should continue reading. Moreover, if you are as passionate as I am about the concept of evolutionary computation and eager to learn more about sophisticated ideas, feel free to sign up for the waiting list of my online course.
Genetic Algorithms are inspired by Charles Darwin’s theory: “Natural selection is survival of the fittest”. The term fit refers to the success of reproduction or, in other words, the capability of creating offsprings for successive generations. Reproductive success reflects how well an organism is adapted to its environment. Thus, the two core components of genetic algorithms are the i) mating (or reproduction) and the ii) survival (or environment selection). The goal of using the concept of biological evolution in the context of optimization is to define meaningful recombination and survival operators and let evolution occur.
Before I start to explain the algorithm’s outline, I would like to talk about the terminology in evolutionary computing. Most genetic algorithms do not use a single solution, but a solution set referred to as population in the context of evolutionary computation. The size of the population is predefined beforehand and referred to as population size. Each solution in the population is usually called an individual. Moreover, an individual resulting from the recombination of two or more parent individuals is known as an offspring. Each iteration of a genetic algorithm consisting of mating and survival is called generation. Understanding the evolutionary computation’s terminology helps follow the ideas presented in this article and, in general, in the literature.
A genetic algorithm starts with initializing individuals forming the population P of a predefined size |P|. The population P undergoes the process of mating, which has the goal of producing offsprings O through recombination. To generate offsprings through mating, the population has to go through parental selection, crossover, and mutation. Then, the population P and offsprings O are merged to the solution set M of size |P+O|. The survival reduces M again to a solution set of size |P| by selecting only the fittest individuals. The resulting truncated population is then used for recombination in the next generation. This process is repeated until the termination criterion is met.
If you are more a pseudo-code kind of person, the following description might look even more appealing to you:
Define pop_size, n_gen;P = initialize(pop_size)evaluate(P)for k in (1, .., n_gen) parents = selection(P) O = mutation(crossover(parents)) evaluate(O) M = merge(P, O) P = survival(M)endfor
Our final implementation will look very similar to this pseudo-code. By looking at this description more carefully, we can notice that the following functions have to be implemented:
Evaluate: The actual problem to be solved, where the function determines the fitness of each individual.
Initialize: This method returns the initial population P.
Selection: A function returning the individuals in the population functioning as parents for recombination.
Crossover: A function creating one or multiple offsprings given two or more parents.
Mutation: A method mutation each offspring with a specific probability.
Survival: A function reducing the merged population to a set of solutions equal to the population size by applying the principle of survival of the fittest.
That looks like a lot. Don’t be intimidated, though. I will guide you through implementing each of the methods. Some of them are only one or two lines of code and rather simple in our case. However, each of them has a specific purpose and can be customized to your optimization problem.
Before I start describing a numerical optimization problem to demonstrate the usage of genetic algorithms, I would like to say a few words about what you have seen so far. I am not sure about you, but when I came in touch with genetic algorithms for the first time, the whole concept sounded like a somewhat mystical thing to me. I could not imagine how applying the principle of evolution can help me actually to solve my optimization problem. Nevertheless, implementing my first genetic algorithm to solve an optimization problem I was facing during that time truly opened my eyes and made me want to know more about evolutionary computation and related concepts. Finally, I also to pursue a Ph.D. in this fascinating research field and combining my fascination with my everyday work. To share a bit of this experience, we will solve a numerical problem using a genetic algorithm. With we, I mean we. I truly encourage you to open an editor or IDE of your choice and follow the steps along this journey we are going to take in this article.
Why is it so important to actually look at a specific optimization problem and to solve it? My answer to that question might be a bit more of a personal nature. Whenever I encounter something knew and I really want to understand it, I follow the steps: read, understand and apply. And applying for me often means implementing it. You won’t belief how often I had the impression of understanding a concept but was not even close being able to develop the code for it. Moreover, I am a person who likes to see things in practice. When I have started to learn coding, I thought I am going to read a book from beginning to end and I am able to code. Whoever has tried the same knows this is fundamentally wrong. Coding requires using the theory in practice. Long story short, this article develops the algorithm based on a numerical problem to not only talk about the benefits of genetic algorithms but actually let you experience them by yourself.
The following optimization problems shall be solved:
In this optimization problem, we consider the sine function with the integer-valued variable x ranging from 0 to 255. As most of you might (and probably really should know), the sine function has a maximum at π/2 considering the range from (0, 2π). With the range of x (which is only mapped to the sine function in range (0, π)) and x being divided by 256, the analytically derived maximum lies at x=128.
Because genetic algorithms operate on binary variables (no worries, the concept is generalizable to any variable type), we consider an 8-bit binary variable. If you haven’t been confronted with binary variables and the conversion of them to decimal values, tons of tutorials and converters can be found online. The illustration below shows you how the binary number 11001001 is converted to its decimal correspondent 201.
And luckily, the conversion of eight bits to decimals directly falls into the range from 0 to 255, which is the defined range of the variable x. If you assume I have constructed the test problem to match precisely this encoding, you might not be wrong (of course, if this shall not be the case for your problems, there are other ways to deal with it). The fitness function’s optimum in the decimal search space 128 is equal to 10000000 in the binary encoding. Thus, this is the binary string with the largest fitness value that can be obtained.
Let us start implementing the fitness function to be used in the genetic algorithm. The evaluate function takes a one-dimensional binary-valued array of length 8. The value is converted to an integer and then plugged in into the equation.
import numpy as npdef evaluate(x): to_int = (x * [128, 64, 32, 16, 8, 4, 2, 1]).sum() return np.sin(to_int / 256 * np.pi)
The power of genetic algorithms is the principle that can be applied to many different optimization problems. This flexibility comes with the burden of defining evolutionary operators for your concrete optimization problem. Fortunately, for common types of optimization problems, this has already been done and can be used. Reading this, you might already suspect this might have been the reason why I have converted the problem to have binary variables. Let us start now to define each of the operators to construct the genetic algorithm finally.
In the beginning, the initial population needs to be created. In practice, this might incorporate some domain knowledge of experts and or already introduce some bias towards more promising solutions. In our case, we keep things simple.
We treat our problem as a black-box optimization problem where no domain-specific information is known beforehand. Thus, our best bet is to initialize the population randomly or, in other words, to create individuals as random sequences of zeros and ones. The initialize method shown below takes care of that and returns a random binary array of length 8.
def initialize(): return np.random.choice([0, 1], size=8)
After the initialization of the population, individuals are selected from the population are selected to participate in mating. In this article, we are going to implement a random selection of parents for reproduction. A random selection is a basic implementation; however, it is worth noting that enhanced selection procedures exist and are usually used in practice. Commonly used, more sophisticated selection strategies are incorporating so-called selection pressure by letting individuals already compete with each other during the selection in a tournament or restricting the selection to the neighborhood of solutions. For this rather simple test problem, the random selection shall be sufficient.
More concrete, the select method needs to know how many matings the algorithm will perform and how many parents are necessary for each recombination. Because we are randomly selecting the parents, we can make use of the randint function and only need to pass the corresponding shape. The result is a two-dimensional integer-valued matrix where each row represents a mating and each column an individual which represents a parent.
def select(n_matings, n_parents): return np.random.randint(0, n_matings, (n_matings, n_parents))
After having selected the parents, the recombination takes place. The crossover produces offsprings given at least two parent individuals. We will implement Uniform Crossover (UX), which takes two parents and returns one offspring. The offspring inherits with uniform probability from the first or second parent’s value for each position. The uniform probability distribution implies that, on average, across all individuals, four values from the first and four values from the second parent will exist in the offspring (this is not necessarily the case for each offspring).
The crossover function performs the reproduction given the two arrays representing the parents ( parent_a and parent_b ). The random value in rnd determines whether the values from the first or second parent are used. Depending on rnd the corresponding values are set to the offspring, which is finally returned by the method.
def crossover(parent_a, parent_b): rnd = np.random.choice([False, True], size=8) offspring = np.empty(8, dtype=np.bool) offspring[rnd] = parent_a[rnd] offspring[~rnd] = parent_b[~rnd] return offspring
Genetic variations can arise from recombination and gene mutations. The latter principle is also transferred to genetic algorithms by applying a mutation operator on the offspring created by the crossover. For binary variables, Bitflip Mutation (BM) is often used practice. As the name already says, the mutation flips an existing but in the gene with a predefined probability. In our implementation, we perform a flipping of a bit with a probability of 1/8=0.125.
The function mutate gets the resulting offspring of the crossover and returns the mutated individual. The probability for a bitflip is considered by creating first a uniformly random real-valued array rnd and then choosing bits to flip if the corresponding number is less than a threshold value of 0.125.
def mutate(o): rnd = np.random.random(8) < 0.125 mut = o.copy() mut[rnd] = ~mut[rnd] return mut
Puhhhhhh. Everything so far was already a lot to digest. I promise there is only one more module to implement before we can put everything together. The survival implementation needs to imitate the natural selection and let the fittest individuals survive. In our case, the fitness corresponds directly to the function value returned by the function. Thus, after merging the parent and offspring population, the survival does nothing else than sorting the individuals by their function values and letting the best individuals survive until the population size is reached.
Merging the two populations is usually already done in the main loop of the algorithm. Thus, the survival method retrieves directly the function values f of the merged population of which n_survivors (usually equal to the population size) individuals need to be selected. The individual selection is achieved by sorting the function values accordingly and truncating the sorted list using the [:index] notation. Note that the function values are sorted ascending and, thus, to maximize the function, the sorting needs to be regarding -f .
def survival(f, n_survivors): return np.argsort(-f)[:n_survivors]
Moreover, in practice, there is one more critical issue to consider. And this is duplicate elimination. For genetic algorithms to be efficient, it is fundamentally important to ensure diversity in the population. In order to ensure diversity, each genome shall exist at most once in the population. Thus, we have to take care of possible duplicates after merging the population and offsprings. No worries if you do not understand the following method’s details; however, keep in mind ensuring diversity and eliminating duplicates is critical.
from scipy.spatial.distance import cdistdef eliminate_duplicates(X): D = cdist(X, X) D[np.triu_indices(len(X))] = np.inf return np.all(D > 1e-32, axis=1)
The implementation of elimininate_duplicate uses the cdist function, which calculates all pairwise distances D. The pairwise distance being zero indicates two genomes are identical. Since we would like to keep one of the duplicates, the upper triangular matrix of Dis filled with np.inf before checking individual (row) is significantly different compared to others.
Finally, you made it this far already. Now we are ready to implement the main loop of a genetic algorithm. Before we start, we have to define two parameters: The population size pop_size and the number of generations n_gen . Both can be challenging to determine in practice. For some more challenging problems, a larger population size (>100) might be required to avoid preliminary convergence. The number of iterations can be replaced by checking how much progress has been made recently in each generation. However, this shall, for this illustrative example, not be of interest. We have set pop_size=5 and n_gen=15, which already is sufficient to solve the optimization problem.
pop_size = 5n_gen = 15# fix random seednp.random.seed(1)# initializationX = np.array([initialize() for _ in range(pop_size)])F = np.array([evaluate(x) for x in X])# for each generation execute the loop until terminationfor k in range(n_gen): # select parents for the mating parents = select(pop_size, 2) # mating consisting of crossover and mutation _X = np.array([mutate(crossover(X[a], X[b])) for a, b in parents]) _F = np.array([evaluate(x) for x in _X]) # merge the population and offsprings X, F = np.row_stack([X, _X]), np.concatenate([F, _F]) # perform a duplicate elimination regarding the x values I = eliminate_duplicates(X) X, F = X[I], F[I] # follow the survival of the fittest principle I = survival(F, pop_size) X, F = X[I], F[I] # print the best result each generation print(k+1, F[0], X[0].astype(np.int))
Running the code results in the following:
1 0.9951847266721969 [1 0 0 0 1 0 0 0]2 0.9951847266721969 [1 0 0 0 1 0 0 0]3 0.9951847266721969 [1 0 0 0 1 0 0 0]4 0.9951847266721969 [1 0 0 0 1 0 0 0]5 0.9951847266721969 [1 0 0 0 1 0 0 0]6 0.9996988186962042 [1 0 0 0 0 0 1 0]7 0.9996988186962042 [1 0 0 0 0 0 1 0]8 0.9996988186962042 [1 0 0 0 0 0 1 0]9 0.9996988186962042 [1 0 0 0 0 0 1 0]10 0.9996988186962042 [1 0 0 0 0 0 1 0]11 0.9996988186962042 [1 0 0 0 0 0 1 0]12 0.9999247018391445 [1 0 0 0 0 0 0 1]13 1.0 [1 0 0 0 0 0 0 0]14 1.0 [1 0 0 0 0 0 0 0]15 1.0 [1 0 0 0 0 0 0 0]
Yessssssssss. The genetic algorithm has found the optimum of our numerical test problem. Isn’t this amazing? The algorithm did not know anything about our problem and yet was able to converge to the optimum. The only thing we have done is we have defined a binary encoding, suitable operators and a fitness function. The evolution has figured out a way to find a solution which matches with the optimum we have derived analytically before. For real-world problems you might not even know the optimum and might be amazed what solutions your genetic algorithm is able to come up with. I hope you are fascinated as much as I am. I hope you already imagine how to apply biological evolution concept to optimization problems you might be facing in the future.
Coding everything up by yourself is useful because it helps to understand each of the evolutionary operators’ roles. However, you probably don’t want to write the same code on and on again. For this purpose, I have written a framework called pymoo, which focuses on evolutionary optimization. To be more precise on evolutionary multi-objective optimization, which is an even more generalized concept. In the following, I will show you how to code up this example in pymoo.
First, the problem needs to be defined. Our problem has eight variables ( n_var=8 ), one objective ( n_obj=1 ) and no constraints ( n_constr=0 ). Then, the _evaluate function is overwritten to set objective values. Note that most optimization frameworks consider only minimization (or only maximization) problems. Thus, the problem needs to be converted to one or the other by multiplying the fitness function by -1. Since pymoo considers minimization, the fitness function has a minus sign before the value is assigned. After defining the problem, the algorithm object GA is initialized, and the evolutionary operators (which are already available in the framework) are passed. In this article, we have implemented several operators and have learned their specific role in a genetic algorithm. Finally, the problem and algorithm objects are passed to the minimize method, and the optimization is started.
import numpy as npfrom pymoo.algorithms.soo.nonconvex.ga import GAfrom pymoo.core.problem import Problemfrom pymoo.factory import get_sampling, get_crossover, get_mutationfrom pymoo.optimize import minimizeclass MyProblem(Problem): def __init__(self): super().__init__(n_var=8, n_obj=1, n_constr=0, elementwise_evaluation=True) def _evaluate(self, x, out, *args, **kwargs): to_int = (x * [128, 64, 32, 16, 8, 4, 2, 1]).sum() out["F"] = - np.sin(to_int / 256 * np.pi)problem = MyProblem()algorithm = GA( pop_size=10, sampling=get_sampling("bin_random"), crossover=get_crossover("bin_ux"), mutation=get_mutation("bin_bitflip"))res = minimize(problem, algorithm, ("n_gen", 10), seed=1, verbose=True)print("X", res.X.astype(np.int))print("F", - res.F[0])
The results are shown below:
=============================================n_gen | n_eval | fopt | favg ============================================= 1 | 10 | -9.99925E-01 | -6.63021E-01 2 | 20 | -9.99925E-01 | -8.89916E-01 3 | 30 | -9.99925E-01 | -9.57400E-01 4 | 40 | -1.00000E+00 | -9.88849E-01 5 | 50 | -1.00000E+00 | -9.91903E-01 6 | 60 | -1.00000E+00 | -9.95706E-01 7 | 70 | -1.00000E+00 | -9.96946E-01 8 | 80 | -1.00000E+00 | -9.97585E-01 9 | 90 | -1.00000E+00 | -9.97585E-01 10 | 100 | -1.00000E+00 | -9.97585E-01X 1F 1.0
Same result. Less code. Using a framework helps you focus on the most important things to solve your problem. If you like pymoo and want to support further development, please give us a like on Github or contribute to it by sending a pull request.
I genuinely hope you have enjoyed coding a genetic algorithm by yourself. You have mastered the basics of genetic algorithms, but trust me, there are many more things to learn. Genetic algorithms are not a single algorithm but an algorithmic framework. Having such flexibility is excellent, but designing and applying evolutionary operators on your optimization problems can be challenging.
I am currently creating an online course that shows the secrets of genetic algorithms in a hands-on manner (similarly to this article). It not only teaches you the theory of biological evolution but also lets you implement various kinds of genetic algorithms to tackle a diversity of optimization problems you might be facing. In this article, I have covered for illustration purpose an optimization problem with binary variables. However, the concept of evolution works on all kinds of data structures such as floats, integers, or even trees. Having such a skillset makes you an optimization expert and lets you see optimization with different eyes.
If you like to be notified when I have released my course, you should sign up on the waiting list.
As promised before, the source code we have developed in this article:
import numpy as npfrom scipy.spatial.distance import cdistdef evaluate(x): to_int = (x * [128, 64, 32, 16, 8, 4, 2, 1]).sum() return np.sin(to_int / 256 * np.pi)def initialize(): return np.random.choice([0, 1], size=8)def select(n_matings, n_parents): return np.random.randint(0, n_matings, (n_matings, n_parents))def crossover(parent_a, parent_b): rnd = np.random.choice([False, True], size=8) offspring = np.empty(8, dtype=np.bool) offspring[rnd] = parent_a[rnd] offspring[~rnd] = parent_b[~rnd] return offspringdef mutate(o): rnd = np.random.random(8) < 0.125 mut = o.copy() mut[rnd] = ~mut[rnd] return mutdef eliminate_duplicates(X): D = cdist(X, X) D[np.triu_indices(len(X))] = np.inf return np.all(D > 1e-32, axis=1)def survival(f, n_survivors): return np.argsort(-f)[:n_survivors]pop_size = 5n_gen = 15# fix random seednp.random.seed(1)# initializationX = np.array([initialize() for _ in range(pop_size)])F = np.array([evaluate(x) for x in X])# for each generation execute the loop until terminationfor k in range(n_gen): # select parents for the mating parents = select(pop_size, 2) # mating consisting of crossover and mutation _X = np.array([mutate(crossover(X[a], X[b])) for a, b in parents]) _F = np.array([evaluate(x) for x in _X]) # merge the population and offsprings X, F = np.row_stack([X, _X]), np.concatenate([F, _F]) # perform a duplicate elimination regarding the x values I = eliminate_duplicates(X) X, F = X[I], F[I] # follow the survival of the fittest principle I = survival(F, pop_size) X, F = X[I], F[I] # print the best result each generation print(k + 1, F[0], X[0].astype(np.int)) | [
{
"code": null,
"e": 1086,
"s": 172,
"text": "Genetic algorithms (GA) are inspired by the natural selection of species and belong to a broader class of algorithms referred to as Evolutionary Algorithms (EA). The concept of biological evolution is used to solve all different kinds of problems and has become well-known for its reliable global search capabilities. Thus, genetic algorithms have been used to solve myriads of real-world optimization problems and are an essential subject of research in optimization and related fields. They are known for their multidisciplinary usage across disciplines such as natural, social, and earth sciences, finance, or economics. Furthermore, genetic algorithms have been commonly employed to address well-known optimization problems in Data Science, Machine Learning, and Artificial Intelligence, for instance, selecting features in a data set, recognizing patterns, or determining the architecture of neural networks."
},
{
"code": null,
"e": 1882,
"s": 1086,
"text": "After having used genetic algorithms for more than ten years, I still find the concept fascinating and compelling. This article aims to provide you an introduction into genetic algorithms and the usage of evolutionary operators. The theory of genetic algorithms is described, and source code solving a numerical test problem is provided. Developing a genetic algorithm by yourself gives you a deeper understanding of evolution in the context of optimization. If you have always been curious about genetic algorithms but have never found the time to implement one, you should continue reading. Moreover, if you are as passionate as I am about the concept of evolutionary computation and eager to learn more about sophisticated ideas, feel free to sign up for the waiting list of my online course."
},
{
"code": null,
"e": 2517,
"s": 1882,
"text": "Genetic Algorithms are inspired by Charles Darwin’s theory: “Natural selection is survival of the fittest”. The term fit refers to the success of reproduction or, in other words, the capability of creating offsprings for successive generations. Reproductive success reflects how well an organism is adapted to its environment. Thus, the two core components of genetic algorithms are the i) mating (or reproduction) and the ii) survival (or environment selection). The goal of using the concept of biological evolution in the context of optimization is to define meaningful recombination and survival operators and let evolution occur."
},
{
"code": null,
"e": 3287,
"s": 2517,
"text": "Before I start to explain the algorithm’s outline, I would like to talk about the terminology in evolutionary computing. Most genetic algorithms do not use a single solution, but a solution set referred to as population in the context of evolutionary computation. The size of the population is predefined beforehand and referred to as population size. Each solution in the population is usually called an individual. Moreover, an individual resulting from the recombination of two or more parent individuals is known as an offspring. Each iteration of a genetic algorithm consisting of mating and survival is called generation. Understanding the evolutionary computation’s terminology helps follow the ideas presented in this article and, in general, in the literature."
},
{
"code": null,
"e": 3975,
"s": 3287,
"text": "A genetic algorithm starts with initializing individuals forming the population P of a predefined size |P|. The population P undergoes the process of mating, which has the goal of producing offsprings O through recombination. To generate offsprings through mating, the population has to go through parental selection, crossover, and mutation. Then, the population P and offsprings O are merged to the solution set M of size |P+O|. The survival reduces M again to a solution set of size |P| by selecting only the fittest individuals. The resulting truncated population is then used for recombination in the next generation. This process is repeated until the termination criterion is met."
},
{
"code": null,
"e": 4086,
"s": 3975,
"text": "If you are more a pseudo-code kind of person, the following description might look even more appealing to you:"
},
{
"code": null,
"e": 4289,
"s": 4086,
"text": "Define pop_size, n_gen;P = initialize(pop_size)evaluate(P)for k in (1, .., n_gen) parents = selection(P) O = mutation(crossover(parents)) evaluate(O) M = merge(P, O) P = survival(M)endfor"
},
{
"code": null,
"e": 4472,
"s": 4289,
"text": "Our final implementation will look very similar to this pseudo-code. By looking at this description more carefully, we can notice that the following functions have to be implemented:"
},
{
"code": null,
"e": 4577,
"s": 4472,
"text": "Evaluate: The actual problem to be solved, where the function determines the fitness of each individual."
},
{
"code": null,
"e": 4635,
"s": 4577,
"text": "Initialize: This method returns the initial population P."
},
{
"code": null,
"e": 4743,
"s": 4635,
"text": "Selection: A function returning the individuals in the population functioning as parents for recombination."
},
{
"code": null,
"e": 4828,
"s": 4743,
"text": "Crossover: A function creating one or multiple offsprings given two or more parents."
},
{
"code": null,
"e": 4900,
"s": 4828,
"text": "Mutation: A method mutation each offspring with a specific probability."
},
{
"code": null,
"e": 5057,
"s": 4900,
"text": "Survival: A function reducing the merged population to a set of solutions equal to the population size by applying the principle of survival of the fittest."
},
{
"code": null,
"e": 5344,
"s": 5057,
"text": "That looks like a lot. Don’t be intimidated, though. I will guide you through implementing each of the methods. Some of them are only one or two lines of code and rather simple in our case. However, each of them has a specific purpose and can be customized to your optimization problem."
},
{
"code": null,
"e": 6387,
"s": 5344,
"text": "Before I start describing a numerical optimization problem to demonstrate the usage of genetic algorithms, I would like to say a few words about what you have seen so far. I am not sure about you, but when I came in touch with genetic algorithms for the first time, the whole concept sounded like a somewhat mystical thing to me. I could not imagine how applying the principle of evolution can help me actually to solve my optimization problem. Nevertheless, implementing my first genetic algorithm to solve an optimization problem I was facing during that time truly opened my eyes and made me want to know more about evolutionary computation and related concepts. Finally, I also to pursue a Ph.D. in this fascinating research field and combining my fascination with my everyday work. To share a bit of this experience, we will solve a numerical problem using a genetic algorithm. With we, I mean we. I truly encourage you to open an editor or IDE of your choice and follow the steps along this journey we are going to take in this article."
},
{
"code": null,
"e": 7332,
"s": 6387,
"text": "Why is it so important to actually look at a specific optimization problem and to solve it? My answer to that question might be a bit more of a personal nature. Whenever I encounter something knew and I really want to understand it, I follow the steps: read, understand and apply. And applying for me often means implementing it. You won’t belief how often I had the impression of understanding a concept but was not even close being able to develop the code for it. Moreover, I am a person who likes to see things in practice. When I have started to learn coding, I thought I am going to read a book from beginning to end and I am able to code. Whoever has tried the same knows this is fundamentally wrong. Coding requires using the theory in practice. Long story short, this article develops the algorithm based on a numerical problem to not only talk about the benefits of genetic algorithms but actually let you experience them by yourself."
},
{
"code": null,
"e": 7385,
"s": 7332,
"text": "The following optimization problems shall be solved:"
},
{
"code": null,
"e": 7790,
"s": 7385,
"text": "In this optimization problem, we consider the sine function with the integer-valued variable x ranging from 0 to 255. As most of you might (and probably really should know), the sine function has a maximum at π/2 considering the range from (0, 2π). With the range of x (which is only mapped to the sine function in range (0, π)) and x being divided by 256, the analytically derived maximum lies at x=128."
},
{
"code": null,
"e": 8212,
"s": 7790,
"text": "Because genetic algorithms operate on binary variables (no worries, the concept is generalizable to any variable type), we consider an 8-bit binary variable. If you haven’t been confronted with binary variables and the conversion of them to decimal values, tons of tutorials and converters can be found online. The illustration below shows you how the binary number 11001001 is converted to its decimal correspondent 201."
},
{
"code": null,
"e": 8757,
"s": 8212,
"text": "And luckily, the conversion of eight bits to decimals directly falls into the range from 0 to 255, which is the defined range of the variable x. If you assume I have constructed the test problem to match precisely this encoding, you might not be wrong (of course, if this shall not be the case for your problems, there are other ways to deal with it). The fitness function’s optimum in the decimal search space 128 is equal to 10000000 in the binary encoding. Thus, this is the binary string with the largest fitness value that can be obtained."
},
{
"code": null,
"e": 8996,
"s": 8757,
"text": "Let us start implementing the fitness function to be used in the genetic algorithm. The evaluate function takes a one-dimensional binary-valued array of length 8. The value is converted to an integer and then plugged in into the equation."
},
{
"code": null,
"e": 9124,
"s": 8996,
"text": "import numpy as npdef evaluate(x): to_int = (x * [128, 64, 32, 16, 8, 4, 2, 1]).sum() return np.sin(to_int / 256 * np.pi)"
},
{
"code": null,
"e": 9672,
"s": 9124,
"text": "The power of genetic algorithms is the principle that can be applied to many different optimization problems. This flexibility comes with the burden of defining evolutionary operators for your concrete optimization problem. Fortunately, for common types of optimization problems, this has already been done and can be used. Reading this, you might already suspect this might have been the reason why I have converted the problem to have binary variables. Let us start now to define each of the operators to construct the genetic algorithm finally."
},
{
"code": null,
"e": 9908,
"s": 9672,
"text": "In the beginning, the initial population needs to be created. In practice, this might incorporate some domain knowledge of experts and or already introduce some bias towards more promising solutions. In our case, we keep things simple."
},
{
"code": null,
"e": 10264,
"s": 9908,
"text": "We treat our problem as a black-box optimization problem where no domain-specific information is known beforehand. Thus, our best bet is to initialize the population randomly or, in other words, to create individuals as random sequences of zeros and ones. The initialize method shown below takes care of that and returns a random binary array of length 8."
},
{
"code": null,
"e": 10325,
"s": 10264,
"text": "def initialize(): return np.random.choice([0, 1], size=8)"
},
{
"code": null,
"e": 11029,
"s": 10325,
"text": "After the initialization of the population, individuals are selected from the population are selected to participate in mating. In this article, we are going to implement a random selection of parents for reproduction. A random selection is a basic implementation; however, it is worth noting that enhanced selection procedures exist and are usually used in practice. Commonly used, more sophisticated selection strategies are incorporating so-called selection pressure by letting individuals already compete with each other during the selection in a tournament or restricting the selection to the neighborhood of solutions. For this rather simple test problem, the random selection shall be sufficient."
},
{
"code": null,
"e": 11459,
"s": 11029,
"text": "More concrete, the select method needs to know how many matings the algorithm will perform and how many parents are necessary for each recombination. Because we are randomly selecting the parents, we can make use of the randint function and only need to pass the corresponding shape. The result is a two-dimensional integer-valued matrix where each row represents a mating and each column an individual which represents a parent."
},
{
"code": null,
"e": 11559,
"s": 11459,
"text": "def select(n_matings, n_parents): return np.random.randint(0, n_matings, (n_matings, n_parents))"
},
{
"code": null,
"e": 12134,
"s": 11559,
"text": "After having selected the parents, the recombination takes place. The crossover produces offsprings given at least two parent individuals. We will implement Uniform Crossover (UX), which takes two parents and returns one offspring. The offspring inherits with uniform probability from the first or second parent’s value for each position. The uniform probability distribution implies that, on average, across all individuals, four values from the first and four values from the second parent will exist in the offspring (this is not necessarily the case for each offspring)."
},
{
"code": null,
"e": 12461,
"s": 12134,
"text": "The crossover function performs the reproduction given the two arrays representing the parents ( parent_a and parent_b ). The random value in rnd determines whether the values from the first or second parent are used. Depending on rnd the corresponding values are set to the offspring, which is finally returned by the method."
},
{
"code": null,
"e": 12677,
"s": 12461,
"text": "def crossover(parent_a, parent_b): rnd = np.random.choice([False, True], size=8) offspring = np.empty(8, dtype=np.bool) offspring[rnd] = parent_a[rnd] offspring[~rnd] = parent_b[~rnd] return offspring"
},
{
"code": null,
"e": 13142,
"s": 12677,
"text": "Genetic variations can arise from recombination and gene mutations. The latter principle is also transferred to genetic algorithms by applying a mutation operator on the offspring created by the crossover. For binary variables, Bitflip Mutation (BM) is often used practice. As the name already says, the mutation flips an existing but in the gene with a predefined probability. In our implementation, we perform a flipping of a bit with a probability of 1/8=0.125."
},
{
"code": null,
"e": 13447,
"s": 13142,
"text": "The function mutate gets the resulting offspring of the crossover and returns the mutated individual. The probability for a bitflip is considered by creating first a uniformly random real-valued array rnd and then choosing bits to flip if the corresponding number is less than a threshold value of 0.125."
},
{
"code": null,
"e": 13555,
"s": 13447,
"text": "def mutate(o): rnd = np.random.random(8) < 0.125 mut = o.copy() mut[rnd] = ~mut[rnd] return mut"
},
{
"code": null,
"e": 14127,
"s": 13555,
"text": "Puhhhhhh. Everything so far was already a lot to digest. I promise there is only one more module to implement before we can put everything together. The survival implementation needs to imitate the natural selection and let the fittest individuals survive. In our case, the fitness corresponds directly to the function value returned by the function. Thus, after merging the parent and offspring population, the survival does nothing else than sorting the individuals by their function values and letting the best individuals survive until the population size is reached."
},
{
"code": null,
"e": 14666,
"s": 14127,
"text": "Merging the two populations is usually already done in the main loop of the algorithm. Thus, the survival method retrieves directly the function values f of the merged population of which n_survivors (usually equal to the population size) individuals need to be selected. The individual selection is achieved by sorting the function values accordingly and truncating the sorted list using the [:index] notation. Note that the function values are sorted ascending and, thus, to maximize the function, the sorting needs to be regarding -f ."
},
{
"code": null,
"e": 14735,
"s": 14666,
"text": "def survival(f, n_survivors): return np.argsort(-f)[:n_survivors]"
},
{
"code": null,
"e": 15278,
"s": 14735,
"text": "Moreover, in practice, there is one more critical issue to consider. And this is duplicate elimination. For genetic algorithms to be efficient, it is fundamentally important to ensure diversity in the population. In order to ensure diversity, each genome shall exist at most once in the population. Thus, we have to take care of possible duplicates after merging the population and offsprings. No worries if you do not understand the following method’s details; however, keep in mind ensuring diversity and eliminating duplicates is critical."
},
{
"code": null,
"e": 15441,
"s": 15278,
"text": "from scipy.spatial.distance import cdistdef eliminate_duplicates(X): D = cdist(X, X) D[np.triu_indices(len(X))] = np.inf return np.all(D > 1e-32, axis=1)"
},
{
"code": null,
"e": 15808,
"s": 15441,
"text": "The implementation of elimininate_duplicate uses the cdist function, which calculates all pairwise distances D. The pairwise distance being zero indicates two genomes are identical. Since we would like to keep one of the duplicates, the upper triangular matrix of Dis filled with np.inf before checking individual (row) is significantly different compared to others."
},
{
"code": null,
"e": 16489,
"s": 15808,
"text": "Finally, you made it this far already. Now we are ready to implement the main loop of a genetic algorithm. Before we start, we have to define two parameters: The population size pop_size and the number of generations n_gen . Both can be challenging to determine in practice. For some more challenging problems, a larger population size (>100) might be required to avoid preliminary convergence. The number of iterations can be replaced by checking how much progress has been made recently in each generation. However, this shall, for this illustrative example, not be of interest. We have set pop_size=5 and n_gen=15, which already is sufficient to solve the optimization problem."
},
{
"code": null,
"e": 17356,
"s": 16489,
"text": "pop_size = 5n_gen = 15# fix random seednp.random.seed(1)# initializationX = np.array([initialize() for _ in range(pop_size)])F = np.array([evaluate(x) for x in X])# for each generation execute the loop until terminationfor k in range(n_gen): # select parents for the mating parents = select(pop_size, 2) # mating consisting of crossover and mutation _X = np.array([mutate(crossover(X[a], X[b])) for a, b in parents]) _F = np.array([evaluate(x) for x in _X]) # merge the population and offsprings X, F = np.row_stack([X, _X]), np.concatenate([F, _F]) # perform a duplicate elimination regarding the x values I = eliminate_duplicates(X) X, F = X[I], F[I] # follow the survival of the fittest principle I = survival(F, pop_size) X, F = X[I], F[I] # print the best result each generation print(k+1, F[0], X[0].astype(np.int))"
},
{
"code": null,
"e": 17399,
"s": 17356,
"text": "Running the code results in the following:"
},
{
"code": null,
"e": 17931,
"s": 17399,
"text": "1 0.9951847266721969 [1 0 0 0 1 0 0 0]2 0.9951847266721969 [1 0 0 0 1 0 0 0]3 0.9951847266721969 [1 0 0 0 1 0 0 0]4 0.9951847266721969 [1 0 0 0 1 0 0 0]5 0.9951847266721969 [1 0 0 0 1 0 0 0]6 0.9996988186962042 [1 0 0 0 0 0 1 0]7 0.9996988186962042 [1 0 0 0 0 0 1 0]8 0.9996988186962042 [1 0 0 0 0 0 1 0]9 0.9996988186962042 [1 0 0 0 0 0 1 0]10 0.9996988186962042 [1 0 0 0 0 0 1 0]11 0.9996988186962042 [1 0 0 0 0 0 1 0]12 0.9999247018391445 [1 0 0 0 0 0 0 1]13 1.0 [1 0 0 0 0 0 0 0]14 1.0 [1 0 0 0 0 0 0 0]15 1.0 [1 0 0 0 0 0 0 0]"
},
{
"code": null,
"e": 18686,
"s": 17931,
"text": "Yessssssssss. The genetic algorithm has found the optimum of our numerical test problem. Isn’t this amazing? The algorithm did not know anything about our problem and yet was able to converge to the optimum. The only thing we have done is we have defined a binary encoding, suitable operators and a fitness function. The evolution has figured out a way to find a solution which matches with the optimum we have derived analytically before. For real-world problems you might not even know the optimum and might be amazed what solutions your genetic algorithm is able to come up with. I hope you are fascinated as much as I am. I hope you already imagine how to apply biological evolution concept to optimization problems you might be facing in the future."
},
{
"code": null,
"e": 19159,
"s": 18686,
"text": "Coding everything up by yourself is useful because it helps to understand each of the evolutionary operators’ roles. However, you probably don’t want to write the same code on and on again. For this purpose, I have written a framework called pymoo, which focuses on evolutionary optimization. To be more precise on evolutionary multi-objective optimization, which is an even more generalized concept. In the following, I will show you how to code up this example in pymoo."
},
{
"code": null,
"e": 20065,
"s": 19159,
"text": "First, the problem needs to be defined. Our problem has eight variables ( n_var=8 ), one objective ( n_obj=1 ) and no constraints ( n_constr=0 ). Then, the _evaluate function is overwritten to set objective values. Note that most optimization frameworks consider only minimization (or only maximization) problems. Thus, the problem needs to be converted to one or the other by multiplying the fitness function by -1. Since pymoo considers minimization, the fitness function has a minus sign before the value is assigned. After defining the problem, the algorithm object GA is initialized, and the evolutionary operators (which are already available in the framework) are passed. In this article, we have implemented several operators and have learned their specific role in a genetic algorithm. Finally, the problem and algorithm objects are passed to the minimize method, and the optimization is started."
},
{
"code": null,
"e": 20983,
"s": 20065,
"text": "import numpy as npfrom pymoo.algorithms.soo.nonconvex.ga import GAfrom pymoo.core.problem import Problemfrom pymoo.factory import get_sampling, get_crossover, get_mutationfrom pymoo.optimize import minimizeclass MyProblem(Problem): def __init__(self): super().__init__(n_var=8, n_obj=1, n_constr=0, elementwise_evaluation=True) def _evaluate(self, x, out, *args, **kwargs): to_int = (x * [128, 64, 32, 16, 8, 4, 2, 1]).sum() out[\"F\"] = - np.sin(to_int / 256 * np.pi)problem = MyProblem()algorithm = GA( pop_size=10, sampling=get_sampling(\"bin_random\"), crossover=get_crossover(\"bin_ux\"), mutation=get_mutation(\"bin_bitflip\"))res = minimize(problem, algorithm, (\"n_gen\", 10), seed=1, verbose=True)print(\"X\", res.X.astype(np.int))print(\"F\", - res.F[0])"
},
{
"code": null,
"e": 21012,
"s": 20983,
"text": "The results are shown below:"
},
{
"code": null,
"e": 21606,
"s": 21012,
"text": "=============================================n_gen | n_eval | fopt | favg ============================================= 1 | 10 | -9.99925E-01 | -6.63021E-01 2 | 20 | -9.99925E-01 | -8.89916E-01 3 | 30 | -9.99925E-01 | -9.57400E-01 4 | 40 | -1.00000E+00 | -9.88849E-01 5 | 50 | -1.00000E+00 | -9.91903E-01 6 | 60 | -1.00000E+00 | -9.95706E-01 7 | 70 | -1.00000E+00 | -9.96946E-01 8 | 80 | -1.00000E+00 | -9.97585E-01 9 | 90 | -1.00000E+00 | -9.97585E-01 10 | 100 | -1.00000E+00 | -9.97585E-01X 1F 1.0"
},
{
"code": null,
"e": 21854,
"s": 21606,
"text": "Same result. Less code. Using a framework helps you focus on the most important things to solve your problem. If you like pymoo and want to support further development, please give us a like on Github or contribute to it by sending a pull request."
},
{
"code": null,
"e": 22245,
"s": 21854,
"text": "I genuinely hope you have enjoyed coding a genetic algorithm by yourself. You have mastered the basics of genetic algorithms, but trust me, there are many more things to learn. Genetic algorithms are not a single algorithm but an algorithmic framework. Having such flexibility is excellent, but designing and applying evolutionary operators on your optimization problems can be challenging."
},
{
"code": null,
"e": 22896,
"s": 22245,
"text": "I am currently creating an online course that shows the secrets of genetic algorithms in a hands-on manner (similarly to this article). It not only teaches you the theory of biological evolution but also lets you implement various kinds of genetic algorithms to tackle a diversity of optimization problems you might be facing. In this article, I have covered for illustration purpose an optimization problem with binary variables. However, the concept of evolution works on all kinds of data structures such as floats, integers, or even trees. Having such a skillset makes you an optimization expert and lets you see optimization with different eyes."
},
{
"code": null,
"e": 22995,
"s": 22896,
"text": "If you like to be notified when I have released my course, you should sign up on the waiting list."
},
{
"code": null,
"e": 23066,
"s": 22995,
"text": "As promised before, the source code we have developed in this article:"
}
]
|
Huggingface🤗Transformers: Retraining roberta-base using the RoBERTa MLM Procedure | by Tanmay Garg | Medium | Towards Data Science | Since BERT (Devlin et al., 2019) came out, the NLP community has been booming with the Transformer (Vaswani et al., 2017) encoder based Language Models enjoying state of the art (SOTA) results on a multitude of downstream tasks.
The RoBERTa model (Liu et al., 2019) introduces some key modifications above the BERT MLM (masked-language modeling) training procedure. The authors highlight “the importance of exploring previously unexplored design choices of BERT”. Details of these design choices can be found in the paper’s Experimental Setup section.
The 🤗Transformers library comes bundled with classes & utilities to apply various tasks on the RoBERTa model.
For example, it is extremely easy to get predictions for a sequence containing a mask token!
Yes! It is that simple!
‘score’: 0.167,‘sequence’: ‘<s>Send these pictures back!</s>’'score': 0.108,'sequence': '<s>Send these photos back!</s>''score': 0.077,'sequence': '<s>Send these emails back!</s>'...
This signifies what the “roberta-base” model predicts to be the best alternatives for the <mask> token.
It is oftentimes desirable to re-train the LM to better capture the language characteristics of a downstream task.
For example, RoBERTa is trained on BookCorpus (Zhu et al., 2015), amongst other datasets.
A recently published work BerTweet (Nguyen et al., 2020) provides a pre-trained BERT model (using the RoBERTa procedure) on vast Twitter corpora in English. They argue that BerTweet better models the characteristic of language used on the Twitter subspace, outperforming previous SOTA models on Tweet NLP tasks.
Hence, it is a good indicator that the performance on downstream tasks is greatly influenced by what our LM captures!
This post does not delve into training the LM and tokenizer from scratch. Training from scratch is quite sufficiently covered in an official 🤗 post here.
Please note that these pre-trained models have been trained using a huge amount of data and computing resources. For example, according to this description, “roberta-base” was trained on 1024 V100 GPUs for 500K steps. Yes, you read that right. 1-0-2-4 GPUs 🤯. Such magnitudes of resources are often not available to us.
However, what we can do is retrain these available models for a few more epochs on a smaller dataset!
Alright then, let’s get started.
We will be using transformers v3.5.1, however, this tutorial should work fine with the recently released v4.0.0 as well.
We will be using the Hate Speech Detection dataset (Basile et al., 2019) made available through TweetEval (Barbieri et al., 2020). Of course, you can use a dataset that better suits your downstream task! 🤩
Since our data is already present in a single file, we can go ahead and use the LineByLineTextDataset class.
The block_size argument gives the largest token length supported by the LM to be trained. “roberta-base” supports sequences of length 512 (including special tokens like <s> (start of sequence) and </s> (end of sequence).
For a finer control over the dataset, you can explore 🤗Datasets here.
The data collator object helps us to form input data batches in a form on which the LM can be trained. For example, it pads all examples of a batch to bring them to the same length.
As the names are quite self-explanatory, the TrainingArguments object holds some fields that help define the training process. The Trainer finally brings all of the objects that we have created till now together to facilitate the train process.
seed=1: seeds the RNG for the Trainer so that the results can be replicated when needed.
It took ~100mins for train to finish on Google Colab.
trainer.save_model(output_dir): helps us save the model to the output_dir so that we can load it using from_pretrained (or as done below).
Go ahead and verify your LM! You’re in luck if your python environment has TensorBoard available, because the Trainer object logs the training in ‘./runs’ directory.
As before, we can get predictions for a sequence containing a mask token!
‘score’: 0.165, ‘sequence’: ‘<s> Send these b*****s back! </s>’‘score’: 0.105, ‘sequence’: ‘<s> Send these refugees back! </s>’‘score’: 0.096, ‘sequence’: ‘<s> Send these people back! </s>’...
Oof, that’s hurtful! 🙉 I had to censor a word out for our PG-13 audiences 👶
Jokes aside, it also tells that our model has trained correctly and has started capturing the hateful language of the dataset.
Go ahead, tweak the hyper-parameters through the TrainerArguments object to see which setting gives the best results for your downstream task!
BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding, Delvin et al., 2019Attention Is All You Need, Vaswani et al., 2017RoBERTa: A Robustly Optimized BERT Pretraining Approach, Liu et al., 2019Aligning Books and Movies: Towards Story-like Visual Explanations by Watching Movies and Reading Books, Zhu et al., 2015BERTweet: A pre-trained language model for English Tweets, Nguyen et al., 2020SemEval-2019 Task 5: Multilingual Detection of Hate Speech Against Immigrants and Women in Twitter, Basile et al., 2019TweetEval:Unified Benchmark and Comparative Evaluation for Tweet Classification, Barbieri et al., 2020
BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding, Delvin et al., 2019
Attention Is All You Need, Vaswani et al., 2017
RoBERTa: A Robustly Optimized BERT Pretraining Approach, Liu et al., 2019
Aligning Books and Movies: Towards Story-like Visual Explanations by Watching Movies and Reading Books, Zhu et al., 2015
BERTweet: A pre-trained language model for English Tweets, Nguyen et al., 2020
SemEval-2019 Task 5: Multilingual Detection of Hate Speech Against Immigrants and Women in Twitter, Basile et al., 2019
TweetEval:Unified Benchmark and Comparative Evaluation for Tweet Classification, Barbieri et al., 2020 | [
{
"code": null,
"e": 401,
"s": 172,
"text": "Since BERT (Devlin et al., 2019) came out, the NLP community has been booming with the Transformer (Vaswani et al., 2017) encoder based Language Models enjoying state of the art (SOTA) results on a multitude of downstream tasks."
},
{
"code": null,
"e": 724,
"s": 401,
"text": "The RoBERTa model (Liu et al., 2019) introduces some key modifications above the BERT MLM (masked-language modeling) training procedure. The authors highlight “the importance of exploring previously unexplored design choices of BERT”. Details of these design choices can be found in the paper’s Experimental Setup section."
},
{
"code": null,
"e": 834,
"s": 724,
"text": "The 🤗Transformers library comes bundled with classes & utilities to apply various tasks on the RoBERTa model."
},
{
"code": null,
"e": 927,
"s": 834,
"text": "For example, it is extremely easy to get predictions for a sequence containing a mask token!"
},
{
"code": null,
"e": 951,
"s": 927,
"text": "Yes! It is that simple!"
},
{
"code": null,
"e": 1134,
"s": 951,
"text": "‘score’: 0.167,‘sequence’: ‘<s>Send these pictures back!</s>’'score': 0.108,'sequence': '<s>Send these photos back!</s>''score': 0.077,'sequence': '<s>Send these emails back!</s>'..."
},
{
"code": null,
"e": 1238,
"s": 1134,
"text": "This signifies what the “roberta-base” model predicts to be the best alternatives for the <mask> token."
},
{
"code": null,
"e": 1353,
"s": 1238,
"text": "It is oftentimes desirable to re-train the LM to better capture the language characteristics of a downstream task."
},
{
"code": null,
"e": 1443,
"s": 1353,
"text": "For example, RoBERTa is trained on BookCorpus (Zhu et al., 2015), amongst other datasets."
},
{
"code": null,
"e": 1755,
"s": 1443,
"text": "A recently published work BerTweet (Nguyen et al., 2020) provides a pre-trained BERT model (using the RoBERTa procedure) on vast Twitter corpora in English. They argue that BerTweet better models the characteristic of language used on the Twitter subspace, outperforming previous SOTA models on Tweet NLP tasks."
},
{
"code": null,
"e": 1873,
"s": 1755,
"text": "Hence, it is a good indicator that the performance on downstream tasks is greatly influenced by what our LM captures!"
},
{
"code": null,
"e": 2027,
"s": 1873,
"text": "This post does not delve into training the LM and tokenizer from scratch. Training from scratch is quite sufficiently covered in an official 🤗 post here."
},
{
"code": null,
"e": 2347,
"s": 2027,
"text": "Please note that these pre-trained models have been trained using a huge amount of data and computing resources. For example, according to this description, “roberta-base” was trained on 1024 V100 GPUs for 500K steps. Yes, you read that right. 1-0-2-4 GPUs 🤯. Such magnitudes of resources are often not available to us."
},
{
"code": null,
"e": 2449,
"s": 2347,
"text": "However, what we can do is retrain these available models for a few more epochs on a smaller dataset!"
},
{
"code": null,
"e": 2482,
"s": 2449,
"text": "Alright then, let’s get started."
},
{
"code": null,
"e": 2603,
"s": 2482,
"text": "We will be using transformers v3.5.1, however, this tutorial should work fine with the recently released v4.0.0 as well."
},
{
"code": null,
"e": 2809,
"s": 2603,
"text": "We will be using the Hate Speech Detection dataset (Basile et al., 2019) made available through TweetEval (Barbieri et al., 2020). Of course, you can use a dataset that better suits your downstream task! 🤩"
},
{
"code": null,
"e": 2918,
"s": 2809,
"text": "Since our data is already present in a single file, we can go ahead and use the LineByLineTextDataset class."
},
{
"code": null,
"e": 3139,
"s": 2918,
"text": "The block_size argument gives the largest token length supported by the LM to be trained. “roberta-base” supports sequences of length 512 (including special tokens like <s> (start of sequence) and </s> (end of sequence)."
},
{
"code": null,
"e": 3209,
"s": 3139,
"text": "For a finer control over the dataset, you can explore 🤗Datasets here."
},
{
"code": null,
"e": 3391,
"s": 3209,
"text": "The data collator object helps us to form input data batches in a form on which the LM can be trained. For example, it pads all examples of a batch to bring them to the same length."
},
{
"code": null,
"e": 3636,
"s": 3391,
"text": "As the names are quite self-explanatory, the TrainingArguments object holds some fields that help define the training process. The Trainer finally brings all of the objects that we have created till now together to facilitate the train process."
},
{
"code": null,
"e": 3725,
"s": 3636,
"text": "seed=1: seeds the RNG for the Trainer so that the results can be replicated when needed."
},
{
"code": null,
"e": 3779,
"s": 3725,
"text": "It took ~100mins for train to finish on Google Colab."
},
{
"code": null,
"e": 3918,
"s": 3779,
"text": "trainer.save_model(output_dir): helps us save the model to the output_dir so that we can load it using from_pretrained (or as done below)."
},
{
"code": null,
"e": 4084,
"s": 3918,
"text": "Go ahead and verify your LM! You’re in luck if your python environment has TensorBoard available, because the Trainer object logs the training in ‘./runs’ directory."
},
{
"code": null,
"e": 4158,
"s": 4084,
"text": "As before, we can get predictions for a sequence containing a mask token!"
},
{
"code": null,
"e": 4351,
"s": 4158,
"text": "‘score’: 0.165, ‘sequence’: ‘<s> Send these b*****s back! </s>’‘score’: 0.105, ‘sequence’: ‘<s> Send these refugees back! </s>’‘score’: 0.096, ‘sequence’: ‘<s> Send these people back! </s>’..."
},
{
"code": null,
"e": 4427,
"s": 4351,
"text": "Oof, that’s hurtful! 🙉 I had to censor a word out for our PG-13 audiences 👶"
},
{
"code": null,
"e": 4554,
"s": 4427,
"text": "Jokes aside, it also tells that our model has trained correctly and has started capturing the hateful language of the dataset."
},
{
"code": null,
"e": 4697,
"s": 4554,
"text": "Go ahead, tweak the hyper-parameters through the TrainerArguments object to see which setting gives the best results for your downstream task!"
},
{
"code": null,
"e": 5338,
"s": 4697,
"text": "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding, Delvin et al., 2019Attention Is All You Need, Vaswani et al., 2017RoBERTa: A Robustly Optimized BERT Pretraining Approach, Liu et al., 2019Aligning Books and Movies: Towards Story-like Visual Explanations by Watching Movies and Reading Books, Zhu et al., 2015BERTweet: A pre-trained language model for English Tweets, Nguyen et al., 2020SemEval-2019 Task 5: Multilingual Detection of Hate Speech Against Immigrants and Women in Twitter, Basile et al., 2019TweetEval:Unified Benchmark and Comparative Evaluation for Tweet Classification, Barbieri et al., 2020"
},
{
"code": null,
"e": 5440,
"s": 5338,
"text": "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding, Delvin et al., 2019"
},
{
"code": null,
"e": 5488,
"s": 5440,
"text": "Attention Is All You Need, Vaswani et al., 2017"
},
{
"code": null,
"e": 5562,
"s": 5488,
"text": "RoBERTa: A Robustly Optimized BERT Pretraining Approach, Liu et al., 2019"
},
{
"code": null,
"e": 5683,
"s": 5562,
"text": "Aligning Books and Movies: Towards Story-like Visual Explanations by Watching Movies and Reading Books, Zhu et al., 2015"
},
{
"code": null,
"e": 5762,
"s": 5683,
"text": "BERTweet: A pre-trained language model for English Tweets, Nguyen et al., 2020"
},
{
"code": null,
"e": 5882,
"s": 5762,
"text": "SemEval-2019 Task 5: Multilingual Detection of Hate Speech Against Immigrants and Women in Twitter, Basile et al., 2019"
}
]
|
Scraping and Exploring The SP500 With R Part 2 | by Bryant Crocker | Towards Data Science | In the first part of this blog post, I walked through scraping a list of SP500 symbols from wikipedia and using that information to pull OHLC (Open, High Low, Close) data for all SP500 tickers from the yahoo finance API.
In the second part of this blog post, I will walk through answering my original question:
Which SP500 assets had the highest average return over the last 3 months?
In part 1, we created tickers_df, a dataframe with all 505 SP500 tickers.
lets take a quick look again at tickers_df:
This data is tidy meaning:
each variable is a column
each observation (or case) is a row
This structure makes the data easy to filter and aggregate, and makes it easier to scale. We can easily extract and visualize one of the assets raw prices over time with just a few lines of code:
ticker = "GOOGL"tickers_df %>% filter(symbol == !!ticker) %>% ggplot(aes(date, adjusted))+ geom_line()
We can look at raw price data all day, but it is hard to compare assets that have drastically different prices. Typically, when we analyze assets, we look at the percentage change in prices or returns. Using the tidyquant package, it is extremely easy to calculate returns. In the following snippet, I convert each assets raw adjusted closing prices to returns. This is done using the tq_transmute() function.
daily_sector = tickers_df %>% group_by(security, gics_sector, symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = "daily") %>% ungroup()
A few things to note:
The data is still tidy
We have information from both the Yahoo finance API and the wikipedia page that we scraped
With this format it is very easy to aggregate by symbol, security or gics_sector
Don’t forget to ungroup! I did initially
Top Performers:
Let’s go ahead and compute the average daily return by security and then sort by this, to answer my question. I will also compute the standard deviation of the returns. In quantitative finance, the standard deviation of returns is generally referred to as volatility.
avg_return =daily_sector %>% group_by(security, gics_sector) %>% summarise(avg_return = round(mean(daily.returns), 4),Volatility = sd(daily.returns)) %>% arrange(desc(avg_return), desc(Volatility))avg_return %>% head()
From this table we can quickly see that Dow Inc, the famous American chemical company, has had the highest average daily return over the last 3 months. This table answers my original question.
Let’s visualize this table as a bar graph using ggplot:
avg_return %>% head(20) %>% ggplot(aes(reorder(security, -avg_return), avg_return, fill = avg_return))+ geom_col()+ coord_flip()+ labs(title = "Securities With Highest Average Returns In SP500 Over Past 3 Month", x = "Security", y = "Average Return")+ theme_classic()+ theme(legend.position="none")
Wow Dow Inc.’s average return is much higher than the rest of the market. There may be something big I’m missing here. A quick google search tells me there’s an obvious reason for this. Dow INC has only been traded as an independent chemical company since the end of March, when it formally split from Dowdupont. The average return is likely only this high because it is a newly traded asset and we don’t have many observations.
Looking at the other top performers I notice a few things:
Many of the top performing companies over the past 30 days have been technology companies.
I’m a bit suprised by the strong performance of Chipotle. They have clearly rebounded from their previous controversies around food poisoning
Nvidia and Advanced Micro Devices, two computer hardware manufacturers, have seen higher returns than there competitor Intel, who historically has performed better.
Typically when you answer a question with data, more questions arise. I already know what stocks had the highest return on average over the last few months, but what about volatility? Volatility is one of the most important investment metrics for a security or portfolio.
According to Wikipedia Investors care about volatility for at least eight reasons:
The wider the swings in an investment’s price, the harder emotionally it is to not worry;Price volatility of a trading instrument can define position sizing in a portfolio;When certain cash flows from selling a security are needed at a specific future date, higher volatility means a greater chance of a shortfall;Higher volatility of returns while saving for retirement results in a wider distribution of possible final portfolio values;Higher volatility of return when retired gives withdrawals a larger permanent impact on the portfolio’s value;Price volatility presents opportunities to buy assets cheaply and sell when overpriced;Portfolio volatility has a negative impact on the compound annual growth rate (CAGR) of that portfolioVolatility affects pricing of options, being a parameter of the Black–Scholes model.
The wider the swings in an investment’s price, the harder emotionally it is to not worry;
Price volatility of a trading instrument can define position sizing in a portfolio;
When certain cash flows from selling a security are needed at a specific future date, higher volatility means a greater chance of a shortfall;
Higher volatility of returns while saving for retirement results in a wider distribution of possible final portfolio values;
Higher volatility of return when retired gives withdrawals a larger permanent impact on the portfolio’s value;
Price volatility presents opportunities to buy assets cheaply and sell when overpriced;
Portfolio volatility has a negative impact on the compound annual growth rate (CAGR) of that portfolio
Volatility affects pricing of options, being a parameter of the Black–Scholes model.
Typically, younger investors can take on more volatility, while investors closer to retirement want to be careful about volatility.
Using ggplot2 we can easily plot the relationship between average return and volatility of returns. I will create a scatter plot, using the asset tickers rather than points in the plot.
plot = avg_return %>% ggplot(aes(avg_return, Volatility))+ geom_text(aes(label = symbol), size = 3)+ labs(title = "Average Return vs Volatility Over Last 3 Months In SP500", x = "Average Return", subtitle = "Data Source: Yahoo Finance")+ theme_minimal() plot
This plot gives a much better idea of what’s happening in the market than our previous bar graph.
A few tickers really stand out compared to the rest of the market
DOW INC has the highest average return and seems to be around market volatility.
AMD and Coty stand out as having above market volatility and return. These might be solid investment opportunities for younger investors
Matel and EA games stand out as having around market returns, but higher volatility. This high volatility gives investors the opportunity to buy when the securities are underpriced and sell when they are overpriced.
The biggest thing that stands out in the top left corner of the figure is the high volatility and low average return of both Fox corporations asset classes
Lets highlight Fox Corporation’s tickers on the graph:
avg_return = avg_return %>% mutate(Indicator = case_when(symbol %in% c('FOX', 'FOXA') ~ "Fox Corporation", TRUE ~ "The Rest of the SP500"))plot = avg_return %>% ggplot(aes(avg_return, Volatility, color = Indicator))+ geom_text(aes(label = symbol), size = 3)+ labs(title = "Average Return vs Volatility Over Last 3 Months In SP500", x = "Average Return", subtitle = "Data Source: Yahoo Finance")+ theme_minimal() plot
Wow! look at that! I walked into this analysis interested in which companies were performing the best. But, at the end, what really stood out is the Fox Corporation which, appears to be performing quite weak relative to the rest of the market over the last 3 months.
The Fox Corporation, especially their news station Faux News (did I spell that right?), has been rather controversial over the years. The network takes a unique perspective on many issues and features much more opinion based shows than the average news network.
Lets get a little more price data for the Fox Corporation tickers:
symbols = c('FOX', 'FOXA')fox = tq_get(symbols, from = '2017/01/01')fox %>% ggplot(aes(date, adjusted))+ geom_line()+ geom_smooth(method = 'lm', alpha = 0.3)+ facet_wrap(~symbol)+ theme_classic()
It appears that over the last few years, both fox symbols have grown steadily
There was a huge drop in the price recently. and a continued downward trend following
Lets zoom in on recent prices:
tickers_df %>% filter(symbol %in% c('FOX', 'FOXA')) %>% ggplot(aes(date, adjusted))+ geom_point(alpha = 0.3, color = 'black')+ geom_line()+ facet_wrap(~symbol)+ theme_classic()
We can see that the price drop happened in early March. There was an initial large drop on March 13, followed by a brief rebound. Following the rebound the price, dropped and has continued trending downward.
Let’s turn to Google to figure out what happened on March 13. A quick Google search tells me that Media Matters organized a large protest against Fox Corporation on March 13th.
Following the March 13th drop, on March 19, 2019, Fox Corp began trading independently of 21st Century Fox. This made the price of the asset radically drop. This did not though represent weak performance by the asset, as one would initially think.
What actually happened is that Fox corporation began trading under 21st Century Fox’s tickers, 21st century Fox is now trading under the tickers TFCF and TFCFA. This led many news outlets to incorrectly report that FOX and FOXA were down 22%.
Finishing Up and Producing a Final Plot:
Alright now we want to share what we have found in an interactive plot, so that none technical users can have a fun, informative plot that they can interact with.
R has a lot of great frameworks for interactive data visualization. My Personal favorite interactive graphing library in R is the plotly library. Plotly is an interactive javascript library with APIs for many different programming languages. I am more familiar with the python API (and the python language in general).
With very similar code to as used in ggplot2 we can produce a beautiful interactive plot. I will embed the plot in this article.
p <- plot_ly(avg_return, x = ~avg_return, y = ~Volatility, type = 'scatter', mode = 'text', text = ~symbol, textposition = 'middle right', color = ~Indicator, colors = 'Set1', textfont = list(size = 8)) %>% layout(title = 'Average Return vs Volatility Over Last 3 Months In SP500', xaxis = list(title = 'Averaage Return', zeroline = FALSE ), yaxis = list(title = 'Volatility' ))
To recap, in this two part series we:
Went over an introduction to scraping, functional programming, and the tidyverse
Imported stock data for the whole SP500
Proposed a question, Which stocks had the highest average return over the last 3 months?
We answered this question, and by asking more questions of our data, we answered the question more fully and found what was ultimately interesting was the seemingly low average return and high volatility of the Fox Corporation tickers relative to the market.
This circular workflow of continuously asking questions of your data is common in data science
We need to be careful about data quality and make sure we understand our data. FOX, FOXA look like they are performing badly and DOW looks like it is performing way better than the rest of the market. These conclusions would be misleading!
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. | [
{
"code": null,
"e": 392,
"s": 171,
"text": "In the first part of this blog post, I walked through scraping a list of SP500 symbols from wikipedia and using that information to pull OHLC (Open, High Low, Close) data for all SP500 tickers from the yahoo finance API."
},
{
"code": null,
"e": 482,
"s": 392,
"text": "In the second part of this blog post, I will walk through answering my original question:"
},
{
"code": null,
"e": 556,
"s": 482,
"text": "Which SP500 assets had the highest average return over the last 3 months?"
},
{
"code": null,
"e": 630,
"s": 556,
"text": "In part 1, we created tickers_df, a dataframe with all 505 SP500 tickers."
},
{
"code": null,
"e": 674,
"s": 630,
"text": "lets take a quick look again at tickers_df:"
},
{
"code": null,
"e": 701,
"s": 674,
"text": "This data is tidy meaning:"
},
{
"code": null,
"e": 727,
"s": 701,
"text": "each variable is a column"
},
{
"code": null,
"e": 763,
"s": 727,
"text": "each observation (or case) is a row"
},
{
"code": null,
"e": 959,
"s": 763,
"text": "This structure makes the data easy to filter and aggregate, and makes it easier to scale. We can easily extract and visualize one of the assets raw prices over time with just a few lines of code:"
},
{
"code": null,
"e": 1067,
"s": 959,
"text": "ticker = \"GOOGL\"tickers_df %>% filter(symbol == !!ticker) %>% ggplot(aes(date, adjusted))+ geom_line()"
},
{
"code": null,
"e": 1477,
"s": 1067,
"text": "We can look at raw price data all day, but it is hard to compare assets that have drastically different prices. Typically, when we analyze assets, we look at the percentage change in prices or returns. Using the tidyquant package, it is extremely easy to calculate returns. In the following snippet, I convert each assets raw adjusted closing prices to returns. This is done using the tq_transmute() function."
},
{
"code": null,
"e": 1692,
"s": 1477,
"text": "daily_sector = tickers_df %>% group_by(security, gics_sector, symbol) %>% tq_transmute(select = adjusted, mutate_fun = periodReturn, period = \"daily\") %>% ungroup()"
},
{
"code": null,
"e": 1714,
"s": 1692,
"text": "A few things to note:"
},
{
"code": null,
"e": 1737,
"s": 1714,
"text": "The data is still tidy"
},
{
"code": null,
"e": 1828,
"s": 1737,
"text": "We have information from both the Yahoo finance API and the wikipedia page that we scraped"
},
{
"code": null,
"e": 1909,
"s": 1828,
"text": "With this format it is very easy to aggregate by symbol, security or gics_sector"
},
{
"code": null,
"e": 1950,
"s": 1909,
"text": "Don’t forget to ungroup! I did initially"
},
{
"code": null,
"e": 1966,
"s": 1950,
"text": "Top Performers:"
},
{
"code": null,
"e": 2234,
"s": 1966,
"text": "Let’s go ahead and compute the average daily return by security and then sort by this, to answer my question. I will also compute the standard deviation of the returns. In quantitative finance, the standard deviation of returns is generally referred to as volatility."
},
{
"code": null,
"e": 2466,
"s": 2234,
"text": "avg_return =daily_sector %>% group_by(security, gics_sector) %>% summarise(avg_return = round(mean(daily.returns), 4),Volatility = sd(daily.returns)) %>% arrange(desc(avg_return), desc(Volatility))avg_return %>% head()"
},
{
"code": null,
"e": 2659,
"s": 2466,
"text": "From this table we can quickly see that Dow Inc, the famous American chemical company, has had the highest average daily return over the last 3 months. This table answers my original question."
},
{
"code": null,
"e": 2715,
"s": 2659,
"text": "Let’s visualize this table as a bar graph using ggplot:"
},
{
"code": null,
"e": 3019,
"s": 2715,
"text": "avg_return %>% head(20) %>% ggplot(aes(reorder(security, -avg_return), avg_return, fill = avg_return))+ geom_col()+ coord_flip()+ labs(title = \"Securities With Highest Average Returns In SP500 Over Past 3 Month\", x = \"Security\", y = \"Average Return\")+ theme_classic()+ theme(legend.position=\"none\")"
},
{
"code": null,
"e": 3448,
"s": 3019,
"text": "Wow Dow Inc.’s average return is much higher than the rest of the market. There may be something big I’m missing here. A quick google search tells me there’s an obvious reason for this. Dow INC has only been traded as an independent chemical company since the end of March, when it formally split from Dowdupont. The average return is likely only this high because it is a newly traded asset and we don’t have many observations."
},
{
"code": null,
"e": 3507,
"s": 3448,
"text": "Looking at the other top performers I notice a few things:"
},
{
"code": null,
"e": 3598,
"s": 3507,
"text": "Many of the top performing companies over the past 30 days have been technology companies."
},
{
"code": null,
"e": 3740,
"s": 3598,
"text": "I’m a bit suprised by the strong performance of Chipotle. They have clearly rebounded from their previous controversies around food poisoning"
},
{
"code": null,
"e": 3905,
"s": 3740,
"text": "Nvidia and Advanced Micro Devices, two computer hardware manufacturers, have seen higher returns than there competitor Intel, who historically has performed better."
},
{
"code": null,
"e": 4177,
"s": 3905,
"text": "Typically when you answer a question with data, more questions arise. I already know what stocks had the highest return on average over the last few months, but what about volatility? Volatility is one of the most important investment metrics for a security or portfolio."
},
{
"code": null,
"e": 4260,
"s": 4177,
"text": "According to Wikipedia Investors care about volatility for at least eight reasons:"
},
{
"code": null,
"e": 5082,
"s": 4260,
"text": "The wider the swings in an investment’s price, the harder emotionally it is to not worry;Price volatility of a trading instrument can define position sizing in a portfolio;When certain cash flows from selling a security are needed at a specific future date, higher volatility means a greater chance of a shortfall;Higher volatility of returns while saving for retirement results in a wider distribution of possible final portfolio values;Higher volatility of return when retired gives withdrawals a larger permanent impact on the portfolio’s value;Price volatility presents opportunities to buy assets cheaply and sell when overpriced;Portfolio volatility has a negative impact on the compound annual growth rate (CAGR) of that portfolioVolatility affects pricing of options, being a parameter of the Black–Scholes model."
},
{
"code": null,
"e": 5172,
"s": 5082,
"text": "The wider the swings in an investment’s price, the harder emotionally it is to not worry;"
},
{
"code": null,
"e": 5256,
"s": 5172,
"text": "Price volatility of a trading instrument can define position sizing in a portfolio;"
},
{
"code": null,
"e": 5399,
"s": 5256,
"text": "When certain cash flows from selling a security are needed at a specific future date, higher volatility means a greater chance of a shortfall;"
},
{
"code": null,
"e": 5524,
"s": 5399,
"text": "Higher volatility of returns while saving for retirement results in a wider distribution of possible final portfolio values;"
},
{
"code": null,
"e": 5635,
"s": 5524,
"text": "Higher volatility of return when retired gives withdrawals a larger permanent impact on the portfolio’s value;"
},
{
"code": null,
"e": 5723,
"s": 5635,
"text": "Price volatility presents opportunities to buy assets cheaply and sell when overpriced;"
},
{
"code": null,
"e": 5826,
"s": 5723,
"text": "Portfolio volatility has a negative impact on the compound annual growth rate (CAGR) of that portfolio"
},
{
"code": null,
"e": 5911,
"s": 5826,
"text": "Volatility affects pricing of options, being a parameter of the Black–Scholes model."
},
{
"code": null,
"e": 6043,
"s": 5911,
"text": "Typically, younger investors can take on more volatility, while investors closer to retirement want to be careful about volatility."
},
{
"code": null,
"e": 6229,
"s": 6043,
"text": "Using ggplot2 we can easily plot the relationship between average return and volatility of returns. I will create a scatter plot, using the asset tickers rather than points in the plot."
},
{
"code": null,
"e": 6494,
"s": 6229,
"text": "plot = avg_return %>% ggplot(aes(avg_return, Volatility))+ geom_text(aes(label = symbol), size = 3)+ labs(title = \"Average Return vs Volatility Over Last 3 Months In SP500\", x = \"Average Return\", subtitle = \"Data Source: Yahoo Finance\")+ theme_minimal() plot"
},
{
"code": null,
"e": 6592,
"s": 6494,
"text": "This plot gives a much better idea of what’s happening in the market than our previous bar graph."
},
{
"code": null,
"e": 6658,
"s": 6592,
"text": "A few tickers really stand out compared to the rest of the market"
},
{
"code": null,
"e": 6739,
"s": 6658,
"text": "DOW INC has the highest average return and seems to be around market volatility."
},
{
"code": null,
"e": 6876,
"s": 6739,
"text": "AMD and Coty stand out as having above market volatility and return. These might be solid investment opportunities for younger investors"
},
{
"code": null,
"e": 7092,
"s": 6876,
"text": "Matel and EA games stand out as having around market returns, but higher volatility. This high volatility gives investors the opportunity to buy when the securities are underpriced and sell when they are overpriced."
},
{
"code": null,
"e": 7248,
"s": 7092,
"text": "The biggest thing that stands out in the top left corner of the figure is the high volatility and low average return of both Fox corporations asset classes"
},
{
"code": null,
"e": 7303,
"s": 7248,
"text": "Lets highlight Fox Corporation’s tickers on the graph:"
},
{
"code": null,
"e": 7758,
"s": 7303,
"text": "avg_return = avg_return %>% mutate(Indicator = case_when(symbol %in% c('FOX', 'FOXA') ~ \"Fox Corporation\", TRUE ~ \"The Rest of the SP500\"))plot = avg_return %>% ggplot(aes(avg_return, Volatility, color = Indicator))+ geom_text(aes(label = symbol), size = 3)+ labs(title = \"Average Return vs Volatility Over Last 3 Months In SP500\", x = \"Average Return\", subtitle = \"Data Source: Yahoo Finance\")+ theme_minimal() plot"
},
{
"code": null,
"e": 8025,
"s": 7758,
"text": "Wow! look at that! I walked into this analysis interested in which companies were performing the best. But, at the end, what really stood out is the Fox Corporation which, appears to be performing quite weak relative to the rest of the market over the last 3 months."
},
{
"code": null,
"e": 8287,
"s": 8025,
"text": "The Fox Corporation, especially their news station Faux News (did I spell that right?), has been rather controversial over the years. The network takes a unique perspective on many issues and features much more opinion based shows than the average news network."
},
{
"code": null,
"e": 8354,
"s": 8287,
"text": "Lets get a little more price data for the Fox Corporation tickers:"
},
{
"code": null,
"e": 8556,
"s": 8354,
"text": "symbols = c('FOX', 'FOXA')fox = tq_get(symbols, from = '2017/01/01')fox %>% ggplot(aes(date, adjusted))+ geom_line()+ geom_smooth(method = 'lm', alpha = 0.3)+ facet_wrap(~symbol)+ theme_classic()"
},
{
"code": null,
"e": 8634,
"s": 8556,
"text": "It appears that over the last few years, both fox symbols have grown steadily"
},
{
"code": null,
"e": 8720,
"s": 8634,
"text": "There was a huge drop in the price recently. and a continued downward trend following"
},
{
"code": null,
"e": 8751,
"s": 8720,
"text": "Lets zoom in on recent prices:"
},
{
"code": null,
"e": 8936,
"s": 8751,
"text": "tickers_df %>% filter(symbol %in% c('FOX', 'FOXA')) %>% ggplot(aes(date, adjusted))+ geom_point(alpha = 0.3, color = 'black')+ geom_line()+ facet_wrap(~symbol)+ theme_classic()"
},
{
"code": null,
"e": 9144,
"s": 8936,
"text": "We can see that the price drop happened in early March. There was an initial large drop on March 13, followed by a brief rebound. Following the rebound the price, dropped and has continued trending downward."
},
{
"code": null,
"e": 9321,
"s": 9144,
"text": "Let’s turn to Google to figure out what happened on March 13. A quick Google search tells me that Media Matters organized a large protest against Fox Corporation on March 13th."
},
{
"code": null,
"e": 9569,
"s": 9321,
"text": "Following the March 13th drop, on March 19, 2019, Fox Corp began trading independently of 21st Century Fox. This made the price of the asset radically drop. This did not though represent weak performance by the asset, as one would initially think."
},
{
"code": null,
"e": 9812,
"s": 9569,
"text": "What actually happened is that Fox corporation began trading under 21st Century Fox’s tickers, 21st century Fox is now trading under the tickers TFCF and TFCFA. This led many news outlets to incorrectly report that FOX and FOXA were down 22%."
},
{
"code": null,
"e": 9853,
"s": 9812,
"text": "Finishing Up and Producing a Final Plot:"
},
{
"code": null,
"e": 10016,
"s": 9853,
"text": "Alright now we want to share what we have found in an interactive plot, so that none technical users can have a fun, informative plot that they can interact with."
},
{
"code": null,
"e": 10335,
"s": 10016,
"text": "R has a lot of great frameworks for interactive data visualization. My Personal favorite interactive graphing library in R is the plotly library. Plotly is an interactive javascript library with APIs for many different programming languages. I am more familiar with the python API (and the python language in general)."
},
{
"code": null,
"e": 10464,
"s": 10335,
"text": "With very similar code to as used in ggplot2 we can produce a beautiful interactive plot. I will embed the plot in this article."
},
{
"code": null,
"e": 10923,
"s": 10464,
"text": "p <- plot_ly(avg_return, x = ~avg_return, y = ~Volatility, type = 'scatter', mode = 'text', text = ~symbol, textposition = 'middle right', color = ~Indicator, colors = 'Set1', textfont = list(size = 8)) %>% layout(title = 'Average Return vs Volatility Over Last 3 Months In SP500', xaxis = list(title = 'Averaage Return', zeroline = FALSE ), yaxis = list(title = 'Volatility' ))"
},
{
"code": null,
"e": 10961,
"s": 10923,
"text": "To recap, in this two part series we:"
},
{
"code": null,
"e": 11042,
"s": 10961,
"text": "Went over an introduction to scraping, functional programming, and the tidyverse"
},
{
"code": null,
"e": 11082,
"s": 11042,
"text": "Imported stock data for the whole SP500"
},
{
"code": null,
"e": 11171,
"s": 11082,
"text": "Proposed a question, Which stocks had the highest average return over the last 3 months?"
},
{
"code": null,
"e": 11430,
"s": 11171,
"text": "We answered this question, and by asking more questions of our data, we answered the question more fully and found what was ultimately interesting was the seemingly low average return and high volatility of the Fox Corporation tickers relative to the market."
},
{
"code": null,
"e": 11525,
"s": 11430,
"text": "This circular workflow of continuously asking questions of your data is common in data science"
},
{
"code": null,
"e": 11765,
"s": 11525,
"text": "We need to be careful about data quality and make sure we understand our data. FOX, FOXA look like they are performing badly and DOW looks like it is performing way better than the rest of the market. These conclusions would be misleading!"
}
]
|
How to align the output using justificationsin C language? | By using justifications in printf statement we can arrange the data in any format.
Right Justification
To implement the right justification, insert a minus sign before the width value in the %s character.
printf("%-15s",text);
Let’s take an example to print data in row and column-wise with the help of justification.
Live Demo
#include<stdio.h>
int main(){
char a[20] = "Names", b[20]="amount to be paid";
char a1[20] = "Bhanu", b1[20]="Hari",c1[20]="Lucky",d1[20]="Puppy";
int a2=200,b2=400,c2=250,d2=460;
printf("%-15s %-15s\n", a, b);
printf("%-15s %-15d\n", a1,a2);
printf("%-15s %-15d\n", b1,b2);
printf("%-15s %-15d\n", c1, c2);
printf("%-15s %-15d\n", d1, d2);
return 0;
}
Names amount to be paid
Bhanu 200
Hari 400
Lucky 250
Puppy 460
Consider the same example by changing the justification −
Live Demo
#include<stdio.h>
int main(){
char a[20] = "Names", b[20]="amount to be paid";
char a1[20] = "Bhanu", b1[20]="Hari",c1[20]="Lucky",d1[20]="Puppy";
int a2=200,b2=400,c2=250,d2=460;
printf("%2s %2s\n", a, b);
printf("%5s %5d\n", a1,a2);
printf("%2s %2d\n", b1,b2);
printf("%5s %5d\n", c1, c2);
printf("%2s %2d\n", d1, d2);
return 0;
}
Names amount to be paid
Bhanu 200
Hari 400
Lucky 250
Puppy 460
Note: Alignment is note in proper if we not use correct justification | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "By using justifications in printf statement we can arrange the data in any format."
},
{
"code": null,
"e": 1165,
"s": 1145,
"text": "Right Justification"
},
{
"code": null,
"e": 1267,
"s": 1165,
"text": "To implement the right justification, insert a minus sign before the width value in the %s character."
},
{
"code": null,
"e": 1289,
"s": 1267,
"text": "printf(\"%-15s\",text);"
},
{
"code": null,
"e": 1380,
"s": 1289,
"text": "Let’s take an example to print data in row and column-wise with the help of justification."
},
{
"code": null,
"e": 1391,
"s": 1380,
"text": " Live Demo"
},
{
"code": null,
"e": 1771,
"s": 1391,
"text": "#include<stdio.h>\nint main(){\n char a[20] = \"Names\", b[20]=\"amount to be paid\";\n char a1[20] = \"Bhanu\", b1[20]=\"Hari\",c1[20]=\"Lucky\",d1[20]=\"Puppy\";\n int a2=200,b2=400,c2=250,d2=460;\n printf(\"%-15s %-15s\\n\", a, b);\n printf(\"%-15s %-15d\\n\", a1,a2);\n printf(\"%-15s %-15d\\n\", b1,b2);\n printf(\"%-15s %-15d\\n\", c1, c2);\n printf(\"%-15s %-15d\\n\", d1, d2);\n return 0;\n}"
},
{
"code": null,
"e": 1860,
"s": 1771,
"text": "Names amount to be paid\nBhanu 200\nHari 400\nLucky 250\nPuppy 460"
},
{
"code": null,
"e": 1918,
"s": 1860,
"text": "Consider the same example by changing the justification −"
},
{
"code": null,
"e": 1929,
"s": 1918,
"text": " Live Demo"
},
{
"code": null,
"e": 2289,
"s": 1929,
"text": "#include<stdio.h>\nint main(){\n char a[20] = \"Names\", b[20]=\"amount to be paid\";\n char a1[20] = \"Bhanu\", b1[20]=\"Hari\",c1[20]=\"Lucky\",d1[20]=\"Puppy\";\n int a2=200,b2=400,c2=250,d2=460;\n printf(\"%2s %2s\\n\", a, b);\n printf(\"%5s %5d\\n\", a1,a2);\n printf(\"%2s %2d\\n\", b1,b2);\n printf(\"%5s %5d\\n\", c1, c2);\n printf(\"%2s %2d\\n\", d1, d2);\n return 0;\n}"
},
{
"code": null,
"e": 2433,
"s": 2289,
"text": "Names amount to be paid\nBhanu 200\nHari 400\nLucky 250\nPuppy 460\nNote: Alignment is note in proper if we not use correct justification"
}
]
|
Python | Pandas dataframe.max() | 19 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.max() function returns the maximum of the values in the given object. If the input is a series, the method will return a scalar which will be the maximum of the values in the series. If the input is a dataframe, then the method will return a series with maximum of values over the specified axis in the dataframe. By default the axis is the index axis.
Syntax: DataFrame.max(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the resultlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
Returns : max : Series or DataFrame (if level specified)
Example #1: Use max() function to find the maximum value over the index axis.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, 44, 1], "B":[5, 2, 54, 3, 2], "C":[20, 16, 7, 3, 8], "D":[14, 3, 17, 2, 6]}) # Print the dataframedf
Let’s use the dataframe.max() function to find the maximum value over the index axis
# Even if we do not specify axis = 0, # the method will return the max over# the index axis by defaultdf.max(axis = 0)
Output : Example #2: Use max() function on a dataframe which has Na values. Also find the maximum over the column axis.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) # skip the Na values while finding the maximumdf.max(axis = 1, skipna = True)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 612,
"s": 242,
"text": "Pandas dataframe.max() function returns the maximum of the values in the given object. If the input is a series, the method will return a scalar which will be the maximum of the values in the series. If the input is a dataframe, then the method will return a series with maximum of values over the specified axis in the dataframe. By default the axis is the index axis."
},
{
"code": null,
"e": 699,
"s": 612,
"text": "Syntax: DataFrame.max(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)"
},
{
"code": null,
"e": 1061,
"s": 699,
"text": "Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the resultlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series."
},
{
"code": null,
"e": 1118,
"s": 1061,
"text": "Returns : max : Series or DataFrame (if level specified)"
},
{
"code": null,
"e": 1196,
"s": 1118,
"text": "Example #1: Use max() function to find the maximum value over the index axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, 44, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 16, 7, 3, 8], \"D\":[14, 3, 17, 2, 6]}) # Print the dataframedf",
"e": 1457,
"s": 1196,
"text": null
},
{
"code": null,
"e": 1542,
"s": 1457,
"text": "Let’s use the dataframe.max() function to find the maximum value over the index axis"
},
{
"code": "# Even if we do not specify axis = 0, # the method will return the max over# the index axis by defaultdf.max(axis = 0)",
"e": 1661,
"s": 1542,
"text": null
},
{
"code": null,
"e": 1781,
"s": 1661,
"text": "Output : Example #2: Use max() function on a dataframe which has Na values. Also find the maximum over the column axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # skip the Na values while finding the maximumdf.max(axis = 1, skipna = True)",
"e": 2104,
"s": 1781,
"text": null
},
{
"code": null,
"e": 2113,
"s": 2104,
"text": "Output :"
},
{
"code": null,
"e": 2137,
"s": 2113,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2169,
"s": 2137,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2183,
"s": 2169,
"text": "Python-pandas"
},
{
"code": null,
"e": 2190,
"s": 2183,
"text": "Python"
}
]
|
C++ Program to find whether a no is power of two | 19 Jul, 2021
Given a positive integer, write a function to find if it is a power of two or not.Examples :
Input : n = 4
Output : Yes
22 = 4
Input : n = 7
Output : No
Input : n = 32
Output : Yes
25 = 32
1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2.
C++
// C++ Program to find whether a// no is power of two#include <bits/stdc++.h>using namespace std; // Function to check if x is power of 2bool isPowerOfTwo(int n){ return (ceil(log2(n)) == floor(log2(n)));} // Driver programint main(){ isPowerOfTwo(31) ? cout << "Yes" << endl : cout << "No" << endl; isPowerOfTwo(64) ? cout << "Yes" << endl : cout << "No" << endl; return 0;} // This code is contributed by Surendra_Gangwar
No
Yes
Time Complexity: O(log2n)
Auxiliary Space: O(1)
2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.3. All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. Please see Count set bits in an integer for counting set bits.4. If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.For example for 4 ( 100) and 16(10000), we get following after subtracting 1 3 –> 011 15 –> 01111So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for adding this case). Please refer complete article on Program to find whether a no is power of two for more details!
souravmahato348
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 123,
"s": 28,
"text": "Given a positive integer, write a function to find if it is a power of two or not.Examples : "
},
{
"code": null,
"e": 221,
"s": 123,
"text": "Input : n = 4\nOutput : Yes\n22 = 4\n\nInput : n = 7\nOutput : No\n\nInput : n = 32\nOutput : Yes\n25 = 32"
},
{
"code": null,
"e": 354,
"s": 221,
"text": "1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2. "
},
{
"code": null,
"e": 358,
"s": 354,
"text": "C++"
},
{
"code": "// C++ Program to find whether a// no is power of two#include <bits/stdc++.h>using namespace std; // Function to check if x is power of 2bool isPowerOfTwo(int n){ return (ceil(log2(n)) == floor(log2(n)));} // Driver programint main(){ isPowerOfTwo(31) ? cout << \"Yes\" << endl : cout << \"No\" << endl; isPowerOfTwo(64) ? cout << \"Yes\" << endl : cout << \"No\" << endl; return 0;} // This code is contributed by Surendra_Gangwar",
"e": 795,
"s": 358,
"text": null
},
{
"code": null,
"e": 802,
"s": 795,
"text": "No\nYes"
},
{
"code": null,
"e": 830,
"s": 804,
"text": "Time Complexity: O(log2n)"
},
{
"code": null,
"e": 852,
"s": 830,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1948,
"s": 852,
"text": "2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.3. All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. Please see Count set bits in an integer for counting set bits.4. If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.For example for 4 ( 100) and 16(10000), we get following after subtracting 1 3 –> 011 15 –> 01111So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for adding this case). Please refer complete article on Program to find whether a no is power of two for more details! "
},
{
"code": null,
"e": 1964,
"s": 1948,
"text": "souravmahato348"
},
{
"code": null,
"e": 1977,
"s": 1964,
"text": "C++ Programs"
}
]
|
Python – Convert Float to digit list | 29 Nov, 2019
Sometimes, while working with Python data, we can have a problem in which we need to convert a float number into a list of digits. This problem is common in day-day programming. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + isdigit()The combination of above functions can be used to perform this task. In this, we first convert the float number to string and then iterate it converting each digit to integer and constructing the list using list comprehension.
# Python3 code to demonstrate working of# Convert Float to digit list# using list comprehension + isdigit() # initialize N N = 6.456 # printing N print("The floating number is : " + str(N)) # Convert Float to digit list# using list comprehension + isdigit()res = [int(ele) for ele in str(N) if ele.isdigit()] # printing resultprint("List of floating numbers is : " + str(res))
The floating number is : 6.456
List of floating numbers is : [6, 4, 5, 6]
Method #2 : Using map() + regex expression + findall()The combination of above functionalities can be used to perform this task. In this, we iterate through list using map() and extract and convert each element of float number using regex expression and findall().
# Python3 code to demonstrate working of# Convert Float to digit list# using map() + regex expression + findall()import re # initialize N N = 6.456 # printing N print("The floating number is : " + str(N)) # Convert Float to digit list# using map() + regex expression + findall()res = list(map(int, re.findall('\d', str(N)))) # printing resultprint("List of floating numbers is : " + str(res))
The floating number is : 6.456
List of floating numbers is : [6, 4, 5, 6]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2019"
},
{
"code": null,
"e": 270,
"s": 28,
"text": "Sometimes, while working with Python data, we can have a problem in which we need to convert a float number into a list of digits. This problem is common in day-day programming. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 545,
"s": 270,
"text": "Method #1 : Using list comprehension + isdigit()The combination of above functions can be used to perform this task. In this, we first convert the float number to string and then iterate it converting each digit to integer and constructing the list using list comprehension."
},
{
"code": "# Python3 code to demonstrate working of# Convert Float to digit list# using list comprehension + isdigit() # initialize N N = 6.456 # printing N print(\"The floating number is : \" + str(N)) # Convert Float to digit list# using list comprehension + isdigit()res = [int(ele) for ele in str(N) if ele.isdigit()] # printing resultprint(\"List of floating numbers is : \" + str(res))",
"e": 932,
"s": 545,
"text": null
},
{
"code": null,
"e": 1007,
"s": 932,
"text": "The floating number is : 6.456\nList of floating numbers is : [6, 4, 5, 6]\n"
},
{
"code": null,
"e": 1274,
"s": 1009,
"text": "Method #2 : Using map() + regex expression + findall()The combination of above functionalities can be used to perform this task. In this, we iterate through list using map() and extract and convert each element of float number using regex expression and findall()."
},
{
"code": "# Python3 code to demonstrate working of# Convert Float to digit list# using map() + regex expression + findall()import re # initialize N N = 6.456 # printing N print(\"The floating number is : \" + str(N)) # Convert Float to digit list# using map() + regex expression + findall()res = list(map(int, re.findall('\\d', str(N)))) # printing resultprint(\"List of floating numbers is : \" + str(res))",
"e": 1675,
"s": 1274,
"text": null
},
{
"code": null,
"e": 1750,
"s": 1675,
"text": "The floating number is : 6.456\nList of floating numbers is : [6, 4, 5, 6]\n"
},
{
"code": null,
"e": 1771,
"s": 1750,
"text": "Python list-programs"
},
{
"code": null,
"e": 1778,
"s": 1771,
"text": "Python"
},
{
"code": null,
"e": 1794,
"s": 1778,
"text": "Python Programs"
},
{
"code": null,
"e": 1892,
"s": 1794,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1910,
"s": 1892,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1952,
"s": 1910,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1974,
"s": 1952,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2009,
"s": 1974,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2035,
"s": 2009,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2078,
"s": 2035,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2139,
"s": 2100,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2177,
"s": 2139,
"text": "Python | Convert a list to dictionary"
}
]
|
fromisoformat() Function Of Datetime.date Class In Python | 23 Aug, 2021
The fromisoformat() function is used to constructs a date object from a specified string that contains a date in ISO format. i.e., yyyy-mm-dd.
Syntax: @classmethod fromisoformat(date_string)
Parameters: This function accepts a parameter which is illustrated below:
date_string: This is the specified ISO format i.e., yyyy-mm-dd date string whose date object is going to be constructed.
Return values: This function returns a date object constructed from the specified ISO format date string.
Example 1: Getting a date object from a specified string that contains date in ISO format. i.e., yyyy-mm-dd
Python3
# Python3.7 code for Getting# a date object from a specified# string that contains date in# ISO format. i.e., yyyy-mm-dd # Importing datetime moduleimport datetime # Initializing a dateDate = "2012-10-12"; # Calling fromisoformat() function to# construct a datetime.date object New_date = datetime.date.fromisoformat(Date); # Printing the new constructed date objectprint("The constructed date object is: %s"%New_date);
Output:
The constructed date object is: 2012-10-12
Example 2: Get the newly created date object for the specified date.
Python3
# Python3.7 code for Getting# a date object from a specified# string that contains date in# ISO format. i.e., yyyy-mm-dd # Importing datetime modulefrom datetime import date # Calling the fromisoformat() function# to Print the new created date object# for the specified date in# ISO format of 2020-10-09print(date.fromisoformat('2020-10-09'))
Output:
2020-10-09
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 171,
"s": 28,
"text": "The fromisoformat() function is used to constructs a date object from a specified string that contains a date in ISO format. i.e., yyyy-mm-dd."
},
{
"code": null,
"e": 219,
"s": 171,
"text": "Syntax: @classmethod fromisoformat(date_string)"
},
{
"code": null,
"e": 293,
"s": 219,
"text": "Parameters: This function accepts a parameter which is illustrated below:"
},
{
"code": null,
"e": 414,
"s": 293,
"text": "date_string: This is the specified ISO format i.e., yyyy-mm-dd date string whose date object is going to be constructed."
},
{
"code": null,
"e": 520,
"s": 414,
"text": "Return values: This function returns a date object constructed from the specified ISO format date string."
},
{
"code": null,
"e": 628,
"s": 520,
"text": "Example 1: Getting a date object from a specified string that contains date in ISO format. i.e., yyyy-mm-dd"
},
{
"code": null,
"e": 636,
"s": 628,
"text": "Python3"
},
{
"code": "# Python3.7 code for Getting# a date object from a specified# string that contains date in# ISO format. i.e., yyyy-mm-dd # Importing datetime moduleimport datetime # Initializing a dateDate = \"2012-10-12\"; # Calling fromisoformat() function to# construct a datetime.date object New_date = datetime.date.fromisoformat(Date); # Printing the new constructed date objectprint(\"The constructed date object is: %s\"%New_date);",
"e": 1060,
"s": 636,
"text": null
},
{
"code": null,
"e": 1068,
"s": 1060,
"text": "Output:"
},
{
"code": null,
"e": 1111,
"s": 1068,
"text": "The constructed date object is: 2012-10-12"
},
{
"code": null,
"e": 1180,
"s": 1111,
"text": "Example 2: Get the newly created date object for the specified date."
},
{
"code": null,
"e": 1188,
"s": 1180,
"text": "Python3"
},
{
"code": "# Python3.7 code for Getting# a date object from a specified# string that contains date in# ISO format. i.e., yyyy-mm-dd # Importing datetime modulefrom datetime import date # Calling the fromisoformat() function# to Print the new created date object# for the specified date in# ISO format of 2020-10-09print(date.fromisoformat('2020-10-09'))",
"e": 1533,
"s": 1188,
"text": null
},
{
"code": null,
"e": 1541,
"s": 1533,
"text": "Output:"
},
{
"code": null,
"e": 1552,
"s": 1541,
"text": "2020-10-09"
},
{
"code": null,
"e": 1559,
"s": 1552,
"text": "Picked"
},
{
"code": null,
"e": 1575,
"s": 1559,
"text": "Python-datetime"
},
{
"code": null,
"e": 1582,
"s": 1575,
"text": "Python"
}
]
|
std::string::find_first_not_of in C++ | 11 Jul, 2017
It searches the string for the first character that does not match any of the characters specified in its arguments. Here we will describe all syntaxes it holds.Return value : Index of first unmatched character when successful or string::npos if no such character found.
Syntax 1: Search for the first character that is not an element of the string str.
size_type string::find_first_not_of (const string& str) const
str : Another string with the set of characters
to be used in the search.
// CPP code for find_first_not_of (const string& str) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str1, string str2){ // Finds first character in str1 which // is not present in str2 string::size_type ch = str1.find_first_not_of(str2); cout << "First unmatched character : "; cout << str1[ch];} // Driver codeint main(){ string str1("Hello World!"); string str2("GeeksforGeeks"); cout << "Original String : " << str1 << endl; cout << "String to be looked in : " << str2 << endl; find_first_not_ofDemo(str1, str2); return 0;}
Output:
Original String : Hello World!
String to be looked in : GeeksforGeeks
First unmatched character : H
Syntax 2: Search for the first character from index idx that is not an element of the string str.
size_type string::find_first_not_of (const string& str, size_type idx) const
str : Another string with the set of characters
to be used in the search.
idx : is the index number from where we have to
start finding first unmatched character.
// CPP code for string::find_first_not_of// (const string& str, size_type idx) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str1, string str2){ // Finds first character in str1 from index 3 which // is not present in str2 string::size_type ch = str1.find_first_not_of(str2, 3); cout << "First unmatched character : "; cout << str1[ch];} // Driver codeint main(){ string str1("geeKsforgeeks"); string str2("GeeksforGeeks"); cout << "Original String : " << str1 << endl; cout << "String to be looked in : " << str2 << endl; find_first_not_ofDemo(str1, str2); return 0;}
Output:
Original String : geeKsforgeeks
String to be looked in : GeeksforGeeks
First unmatched character : K
Syntax 3: Searches for the first character that is or is not also an element of the C-string cstr.
size_type string::find_first_not_of (const char* cstr) const
cstr : Another C-string with the set of characters
to be used in the search.
Note that cstr may not be a null pointer (NULL).
// CPP code for string::find_first_not_of (const char* cstr) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str){ // Finds first character in str which // is not present in "geeksforgeeks" string::size_type ch = str.find_first_not_of("geeksforgeeks"); cout << "First unmatched character : "; cout << str[ch];} // Driver codeint main(){ string str("GeeksforGeeks"); cout << "Original String : " << str << endl; find_first_not_ofDemo(str); return 0;}
Output:
Original String : GeeksforGeeks
First unmatched character : G
Syntax 4: Search for the first character from index idx that is not an element of the C-string cstr
size_type string:: find_first_not_of (const char* cstr, size_type idx) const
cstr : Another string with the set of characters
to be used in the search.
idx : is the index number from where we have to
start finding first unmatched character.
Note that cstr may not be a null pointer (NULL).
// CPP code for size_type string:: find_first_not_of // (const char* cstr, size_type idx) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str){ // Finds first character in str from 5th index which // is not present in "geeksforgeeks" string::size_type ch = str.find_first_not_of("geeksForgeeks", 5); cout << "First unmatched character : "; cout << str[ch];} // Driver codeint main(){ string str("GeeksforGeeks"); cout << "Original String : " << str << endl; find_first_not_ofDemo(str); return 0;}
Output:
Original String : GeeksforGeeks
First unmatched character : f
Syntax 5: Finds first character in str which is not equal to char c.
size_type string::find_first_not_of (char c) const
c Character c with which contents of str are required to be compared.
// CPP code for size_type string:: find_first_not_of (char c) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str){ // Finds first character in str which // is not equal to character 'G' string::size_type ch = str.find_first_not_of('G'); cout << "First unmatched character : "; cout << str[ch];} // Driver codeint main(){ string str("GeeksforGeeks"); cout << "Original String : " << str << endl; find_first_not_ofDemo(str); return 0;}
Output:
Original String : GeeksforGeeks
First unmatched character : e
Syntax 6: Finds first character in str from index idx which is not equal to char c.
size_type string::find_first_not_of (char c, size_type idx) const
c : Character c with which contents of str
are required to be compared.
idx : index from where search of the first
unmatched character is to be started
// CPP code for size_type string::find_first_not_of // (char c, size_type idx) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str){ // Finds first character in str from 6th index which // is not equal to character 'G' string::size_type ch = str.find_first_not_of('G', 6); cout << "First unmatched character : "; cout << str[ch];} // Driver codeint main(){ string str("GeeksforGeeks"); cout << "Original String : " << str << endl; find_first_not_ofDemo(str); return 0;}
Output:
Original String : GeeksforGeeks
First unmatched character : o
Syntax 7: Search for the first character that is also not an element of the chars_len characters of the character array chars, starting at index idx.
size_type string::find_first_not_of
(const char* chars, size_type idx, size_type chars_len) const
*chars : is the character array with which
searching of first unmatched is to be performed.
idx : index number in string
chars_len : is the character length in
*chars to be picked for searching purpose
// CPP code for size_type string::find_first_not_of // (const char* chars, size_type idx, size_type chars_len) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str){ // Finds first character in str from 4th index which // is not equal to any of the first 3 characters from "svmnist" string::size_type ch = str.find_first_not_of("svmnist", 4, 3); cout << "First unmatched character : "; cout << str[ch];} // Driver codeint main(){ string str("GeeksforGeeks"); cout << "Original String : " << str << endl; find_first_not_ofDemo(str); return 0;}
Output:
Original String : GeeksforGeeks
First unmatched character : f
This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
std::find in C++
Inline Functions in C++ | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jul, 2017"
},
{
"code": null,
"e": 299,
"s": 28,
"text": "It searches the string for the first character that does not match any of the characters specified in its arguments. Here we will describe all syntaxes it holds.Return value : Index of first unmatched character when successful or string::npos if no such character found."
},
{
"code": null,
"e": 382,
"s": 299,
"text": "Syntax 1: Search for the first character that is not an element of the string str."
},
{
"code": null,
"e": 519,
"s": 382,
"text": "size_type string::find_first_not_of (const string& str) const\nstr : Another string with the set of characters\nto be used in the search.\n"
},
{
"code": "// CPP code for find_first_not_of (const string& str) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str1, string str2){ // Finds first character in str1 which // is not present in str2 string::size_type ch = str1.find_first_not_of(str2); cout << \"First unmatched character : \"; cout << str1[ch];} // Driver codeint main(){ string str1(\"Hello World!\"); string str2(\"GeeksforGeeks\"); cout << \"Original String : \" << str1 << endl; cout << \"String to be looked in : \" << str2 << endl; find_first_not_ofDemo(str1, str2); return 0;}",
"e": 1180,
"s": 519,
"text": null
},
{
"code": null,
"e": 1188,
"s": 1180,
"text": "Output:"
},
{
"code": null,
"e": 1289,
"s": 1188,
"text": "Original String : Hello World!\nString to be looked in : GeeksforGeeks\nFirst unmatched character : H\n"
},
{
"code": null,
"e": 1387,
"s": 1289,
"text": "Syntax 2: Search for the first character from index idx that is not an element of the string str."
},
{
"code": null,
"e": 1628,
"s": 1387,
"text": "size_type string::find_first_not_of (const string& str, size_type idx) const\nstr : Another string with the set of characters\nto be used in the search.\nidx : is the index number from where we have to\nstart finding first unmatched character.\n"
},
{
"code": "// CPP code for string::find_first_not_of// (const string& str, size_type idx) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str1, string str2){ // Finds first character in str1 from index 3 which // is not present in str2 string::size_type ch = str1.find_first_not_of(str2, 3); cout << \"First unmatched character : \"; cout << str1[ch];} // Driver codeint main(){ string str1(\"geeKsforgeeks\"); string str2(\"GeeksforGeeks\"); cout << \"Original String : \" << str1 << endl; cout << \"String to be looked in : \" << str2 << endl; find_first_not_ofDemo(str1, str2); return 0;}",
"e": 2329,
"s": 1628,
"text": null
},
{
"code": null,
"e": 2337,
"s": 2329,
"text": "Output:"
},
{
"code": null,
"e": 2439,
"s": 2337,
"text": "Original String : geeKsforgeeks\nString to be looked in : GeeksforGeeks\nFirst unmatched character : K\n"
},
{
"code": null,
"e": 2538,
"s": 2439,
"text": "Syntax 3: Searches for the first character that is or is not also an element of the C-string cstr."
},
{
"code": null,
"e": 2677,
"s": 2538,
"text": "size_type string::find_first_not_of (const char* cstr) const\ncstr : Another C-string with the set of characters\nto be used in the search.\n"
},
{
"code": null,
"e": 2726,
"s": 2677,
"text": "Note that cstr may not be a null pointer (NULL)."
},
{
"code": "// CPP code for string::find_first_not_of (const char* cstr) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str){ // Finds first character in str which // is not present in \"geeksforgeeks\" string::size_type ch = str.find_first_not_of(\"geeksforgeeks\"); cout << \"First unmatched character : \"; cout << str[ch];} // Driver codeint main(){ string str(\"GeeksforGeeks\"); cout << \"Original String : \" << str << endl; find_first_not_ofDemo(str); return 0;}",
"e": 3300,
"s": 2726,
"text": null
},
{
"code": null,
"e": 3308,
"s": 3300,
"text": "Output:"
},
{
"code": null,
"e": 3371,
"s": 3308,
"text": "Original String : GeeksforGeeks\nFirst unmatched character : G\n"
},
{
"code": null,
"e": 3471,
"s": 3371,
"text": "Syntax 4: Search for the first character from index idx that is not an element of the C-string cstr"
},
{
"code": null,
"e": 3713,
"s": 3471,
"text": "size_type string:: find_first_not_of (const char* cstr, size_type idx) const\ncstr : Another string with the set of characters\nto be used in the search.\nidx : is the index number from where we have to\nstart finding first unmatched character.\n"
},
{
"code": null,
"e": 3762,
"s": 3713,
"text": "Note that cstr may not be a null pointer (NULL)."
},
{
"code": "// CPP code for size_type string:: find_first_not_of // (const char* cstr, size_type idx) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str){ // Finds first character in str from 5th index which // is not present in \"geeksforgeeks\" string::size_type ch = str.find_first_not_of(\"geeksForgeeks\", 5); cout << \"First unmatched character : \"; cout << str[ch];} // Driver codeint main(){ string str(\"GeeksforGeeks\"); cout << \"Original String : \" << str << endl; find_first_not_ofDemo(str); return 0;}",
"e": 4383,
"s": 3762,
"text": null
},
{
"code": null,
"e": 4391,
"s": 4383,
"text": "Output:"
},
{
"code": null,
"e": 4454,
"s": 4391,
"text": "Original String : GeeksforGeeks\nFirst unmatched character : f\n"
},
{
"code": null,
"e": 4523,
"s": 4454,
"text": "Syntax 5: Finds first character in str which is not equal to char c."
},
{
"code": null,
"e": 4645,
"s": 4523,
"text": "size_type string::find_first_not_of (char c) const\nc Character c with which contents of str are required to be compared.\n"
},
{
"code": "// CPP code for size_type string:: find_first_not_of (char c) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str){ // Finds first character in str which // is not equal to character 'G' string::size_type ch = str.find_first_not_of('G'); cout << \"First unmatched character : \"; cout << str[ch];} // Driver codeint main(){ string str(\"GeeksforGeeks\"); cout << \"Original String : \" << str << endl; find_first_not_ofDemo(str); return 0;}",
"e": 5204,
"s": 4645,
"text": null
},
{
"code": null,
"e": 5212,
"s": 5204,
"text": "Output:"
},
{
"code": null,
"e": 5275,
"s": 5212,
"text": "Original String : GeeksforGeeks\nFirst unmatched character : e\n"
},
{
"code": null,
"e": 5359,
"s": 5275,
"text": "Syntax 6: Finds first character in str from index idx which is not equal to char c."
},
{
"code": null,
"e": 5579,
"s": 5359,
"text": "size_type string::find_first_not_of (char c, size_type idx) const\nc : Character c with which contents of str\nare required to be compared.\nidx : index from where search of the first\nunmatched character is to be started\n"
},
{
"code": "// CPP code for size_type string::find_first_not_of // (char c, size_type idx) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str){ // Finds first character in str from 6th index which // is not equal to character 'G' string::size_type ch = str.find_first_not_of('G', 6); cout << \"First unmatched character : \"; cout << str[ch];} // Driver codeint main(){ string str(\"GeeksforGeeks\"); cout << \"Original String : \" << str << endl; find_first_not_ofDemo(str); return 0;}",
"e": 6173,
"s": 5579,
"text": null
},
{
"code": null,
"e": 6181,
"s": 6173,
"text": "Output:"
},
{
"code": null,
"e": 6244,
"s": 6181,
"text": "Original String : GeeksforGeeks\nFirst unmatched character : o\n"
},
{
"code": null,
"e": 6394,
"s": 6244,
"text": "Syntax 7: Search for the first character that is also not an element of the chars_len characters of the character array chars, starting at index idx."
},
{
"code": null,
"e": 6699,
"s": 6394,
"text": "size_type string::find_first_not_of \n(const char* chars, size_type idx, size_type chars_len) const\n*chars : is the character array with which \nsearching of first unmatched is to be performed.\nidx : index number in string\nchars_len : is the character length in \n*chars to be picked for searching purpose\n"
},
{
"code": "// CPP code for size_type string::find_first_not_of // (const char* chars, size_type idx, size_type chars_len) const #include <iostream>using namespace std; // Function to demonstrate find_first_not_ofvoid find_first_not_ofDemo(string str){ // Finds first character in str from 4th index which // is not equal to any of the first 3 characters from \"svmnist\" string::size_type ch = str.find_first_not_of(\"svmnist\", 4, 3); cout << \"First unmatched character : \"; cout << str[ch];} // Driver codeint main(){ string str(\"GeeksforGeeks\"); cout << \"Original String : \" << str << endl; find_first_not_ofDemo(str); return 0;}",
"e": 7365,
"s": 6699,
"text": null
},
{
"code": null,
"e": 7373,
"s": 7365,
"text": "Output:"
},
{
"code": null,
"e": 7436,
"s": 7373,
"text": "Original String : GeeksforGeeks\nFirst unmatched character : f\n"
},
{
"code": null,
"e": 7754,
"s": 7436,
"text": "This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 7879,
"s": 7754,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 7899,
"s": 7879,
"text": "cpp-strings-library"
},
{
"code": null,
"e": 7903,
"s": 7899,
"text": "STL"
},
{
"code": null,
"e": 7907,
"s": 7903,
"text": "C++"
},
{
"code": null,
"e": 7911,
"s": 7907,
"text": "STL"
},
{
"code": null,
"e": 7915,
"s": 7911,
"text": "CPP"
},
{
"code": null,
"e": 8013,
"s": 7915,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8037,
"s": 8013,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 8057,
"s": 8037,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 8082,
"s": 8057,
"text": "std::string class in C++"
},
{
"code": null,
"e": 8115,
"s": 8082,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 8159,
"s": 8115,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 8204,
"s": 8159,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 8252,
"s": 8204,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 8296,
"s": 8252,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 8313,
"s": 8296,
"text": "std::find in C++"
}
]
|
NodeJS Program Lifecycle | 19 Feb, 2021
Node.js is a JavaScript runtime that is built on Chrome’s V8 JavaScript engine and its run-time environment includes everything which we need to execute a program written in JavaScript. It uses an event-driven, non-blocking I/O model that makes it most scalable and popular. Non-blocking simply means multiple requests can be processed in parallel.
Lifecycle of Node.js program: In order to understand its lifecycle you must be familiar with the event loop. Event loops are something that makes your task very fast and also it perform multitasking. It allows Node.js to perform non-blocking I/O operations. You can learn more about event loop here. When you run your node file using node app.js then the script starts executing. It will be parsed by the parser into machine language that simply means all the functions and variables get registered in a memory location. After parsing the code our program reaches the point where it will not exit and will run an infinite no. of times which is possible all because of the event loop. Once the event loop has started executing and it will run as long as event listeners are registered.
Example: You have the database and you have to access data from the database or you want to insert something into a database that simply requires some calling of the functions so when you call them it will take some amount of time (maybe nanoseconds or microseconds but it will take some time) so it is not possible for every request that we can wait for that particular time and then we move on to next request so that is where event loop comes into the picture. Your database part will be run in the background and the event loop will be running continuously so that it can handle the need for another request as well. This will be done on a single thread in node.js. You can also come out of the loop explicitly by using process.exit().
Javascript
const http = require('http');const server = http.createServer(function (req, res) { console.log("server is running");process.exit(); }); server.listen(8000);
Explanation: In the above program inside createServer() method, you have written simply process..exit() so as soon as you will run this program using node app your server will wait for listening to your request and once you will provide it with the request it will exit from the event loop. By calling this function, Node.js will force the current process which is currently running to abort as soon as possible and if there are any asynchronous operations taking place, they will also be terminated immediately.
Timers: The timer modules in Node.js consists of functions that help to control the timings of code execution. It includes setTimeout(), setImmediate(), and setInterval() methods.
setTimeout() Method: The setTimeout() method is used to schedule code execution after a designated amount of milliseconds. The specified function will be executed once. We can use the clearTimeout() method to prevent the function from running. The setTimeout() method returns the ID that can be used in clearTimeout() method.JavascriptJavascriptlet str = 'GeeksforGeeks!'; setTimeout(function () { return console.log(str); }, 5000); // This console log is executed right away console.log('Executing setTimeout() method');
Javascript
let str = 'GeeksforGeeks!'; setTimeout(function () { return console.log(str); }, 5000); // This console log is executed right away console.log('Executing setTimeout() method');
setImmediate() Method: The setImmediate() method is used to execute code at the end of the current event loop cycle. Any function passed as the setImmediate() argument is a callback that can be executed in the next iteration of the event loop.JavascriptJavascriptlet str = 'GeeksforGeeks!'; setImmediate(function () { return console.log(str); }); // This console log is executed right away console.log('Executing setImmediate() method');
Javascript
let str = 'GeeksforGeeks!'; setImmediate(function () { return console.log(str); }); // This console log is executed right away console.log('Executing setImmediate() method');
setInterval() Method: The setInterval() method is used to call a function at specified intervals (in milliseconds). It is used to execute the function only once after a specified period.We can use the clearInterval() method to prevent the function from running. The setInterval() method returns the ID which can be used in clearInterval() method.JavascriptJavascriptlet str = 'GeeksforGeeks!'; setInterval(function() { return console.log(str); }, 5000); // This console log is executed right away console.log('Executing setInterval() method');
Javascript
let str = 'GeeksforGeeks!'; setInterval(function() { return console.log(str); }, 5000); // This console log is executed right away console.log('Executing setInterval() method');
Learn more about timers in Node.js here.
process.nextTick(callback) Method:Whenever a new queue of operations is initialized we can think of it as a new tick. The process.nextTick() method adds the callback function to the start of the next event queue. It is to be noted that, at the start of the program process.nextTick() method is called for the first time before the event loop is processed.
timers–>pending callbacks–>idle,prepare–>connections(poll,data,etc)–>check–>close callbacks
NodeJS-Questions
Picked
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": "\n19 Feb, 2021"
},
{
"code": null,
"e": 377,
"s": 28,
"text": "Node.js is a JavaScript runtime that is built on Chrome’s V8 JavaScript engine and its run-time environment includes everything which we need to execute a program written in JavaScript. It uses an event-driven, non-blocking I/O model that makes it most scalable and popular. Non-blocking simply means multiple requests can be processed in parallel."
},
{
"code": null,
"e": 1162,
"s": 377,
"text": "Lifecycle of Node.js program: In order to understand its lifecycle you must be familiar with the event loop. Event loops are something that makes your task very fast and also it perform multitasking. It allows Node.js to perform non-blocking I/O operations. You can learn more about event loop here. When you run your node file using node app.js then the script starts executing. It will be parsed by the parser into machine language that simply means all the functions and variables get registered in a memory location. After parsing the code our program reaches the point where it will not exit and will run an infinite no. of times which is possible all because of the event loop. Once the event loop has started executing and it will run as long as event listeners are registered."
},
{
"code": null,
"e": 1902,
"s": 1162,
"text": "Example: You have the database and you have to access data from the database or you want to insert something into a database that simply requires some calling of the functions so when you call them it will take some amount of time (maybe nanoseconds or microseconds but it will take some time) so it is not possible for every request that we can wait for that particular time and then we move on to next request so that is where event loop comes into the picture. Your database part will be run in the background and the event loop will be running continuously so that it can handle the need for another request as well. This will be done on a single thread in node.js. You can also come out of the loop explicitly by using process.exit()."
},
{
"code": null,
"e": 1913,
"s": 1902,
"text": "Javascript"
},
{
"code": "const http = require('http');const server = http.createServer(function (req, res) { console.log(\"server is running\");process.exit(); }); server.listen(8000);",
"e": 2074,
"s": 1913,
"text": null
},
{
"code": null,
"e": 2587,
"s": 2074,
"text": "Explanation: In the above program inside createServer() method, you have written simply process..exit() so as soon as you will run this program using node app your server will wait for listening to your request and once you will provide it with the request it will exit from the event loop. By calling this function, Node.js will force the current process which is currently running to abort as soon as possible and if there are any asynchronous operations taking place, they will also be terminated immediately."
},
{
"code": null,
"e": 2767,
"s": 2587,
"text": "Timers: The timer modules in Node.js consists of functions that help to control the timings of code execution. It includes setTimeout(), setImmediate(), and setInterval() methods."
},
{
"code": null,
"e": 3298,
"s": 2767,
"text": "setTimeout() Method: The setTimeout() method is used to schedule code execution after a designated amount of milliseconds. The specified function will be executed once. We can use the clearTimeout() method to prevent the function from running. The setTimeout() method returns the ID that can be used in clearTimeout() method.JavascriptJavascriptlet str = 'GeeksforGeeks!'; setTimeout(function () { return console.log(str); }, 5000); // This console log is executed right away console.log('Executing setTimeout() method'); "
},
{
"code": null,
"e": 3309,
"s": 3298,
"text": "Javascript"
},
{
"code": "let str = 'GeeksforGeeks!'; setTimeout(function () { return console.log(str); }, 5000); // This console log is executed right away console.log('Executing setTimeout() method'); ",
"e": 3495,
"s": 3309,
"text": null
},
{
"code": null,
"e": 3942,
"s": 3495,
"text": "setImmediate() Method: The setImmediate() method is used to execute code at the end of the current event loop cycle. Any function passed as the setImmediate() argument is a callback that can be executed in the next iteration of the event loop.JavascriptJavascriptlet str = 'GeeksforGeeks!'; setImmediate(function () { return console.log(str); }); // This console log is executed right away console.log('Executing setImmediate() method'); "
},
{
"code": null,
"e": 3953,
"s": 3942,
"text": "Javascript"
},
{
"code": "let str = 'GeeksforGeeks!'; setImmediate(function () { return console.log(str); }); // This console log is executed right away console.log('Executing setImmediate() method'); ",
"e": 4137,
"s": 3953,
"text": null
},
{
"code": null,
"e": 4692,
"s": 4137,
"text": "setInterval() Method: The setInterval() method is used to call a function at specified intervals (in milliseconds). It is used to execute the function only once after a specified period.We can use the clearInterval() method to prevent the function from running. The setInterval() method returns the ID which can be used in clearInterval() method.JavascriptJavascriptlet str = 'GeeksforGeeks!'; setInterval(function() { return console.log(str); }, 5000); // This console log is executed right away console.log('Executing setInterval() method'); "
},
{
"code": null,
"e": 4703,
"s": 4692,
"text": "Javascript"
},
{
"code": "let str = 'GeeksforGeeks!'; setInterval(function() { return console.log(str); }, 5000); // This console log is executed right away console.log('Executing setInterval() method'); ",
"e": 4892,
"s": 4703,
"text": null
},
{
"code": null,
"e": 4933,
"s": 4892,
"text": "Learn more about timers in Node.js here."
},
{
"code": null,
"e": 5289,
"s": 4933,
"text": "process.nextTick(callback) Method:Whenever a new queue of operations is initialized we can think of it as a new tick. The process.nextTick() method adds the callback function to the start of the next event queue. It is to be noted that, at the start of the program process.nextTick() method is called for the first time before the event loop is processed."
},
{
"code": null,
"e": 5381,
"s": 5289,
"text": "timers–>pending callbacks–>idle,prepare–>connections(poll,data,etc)–>check–>close callbacks"
},
{
"code": null,
"e": 5398,
"s": 5381,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 5405,
"s": 5398,
"text": "Picked"
},
{
"code": null,
"e": 5422,
"s": 5405,
"text": "Web Technologies"
}
]
|
Front Controller Design Pattern | 16 Jul, 2020
The front controller design pattern means that all requests that come for a resource in an application will be handled by a single handler and then dispatched to the appropriate handler for that type of request. The front controller may use other helpers to achieve the dispatching mechanism.
UML Diagram Front Controller Design Pattern
Design components
Controller : The controller is the initial contact point for handling all requests in the system. The controller may delegate to a helper to complete authentication and authorization of a user or to initiate contact retrieval.
View: A view represents and displays information to the client. The view retrieves information from a model. Helpers support views by encapsulating and adapting the underlying data model for use in the display.
Dispatcher: A dispatcher is responsible for view management and navigation, managing the choice of the next view to present to the user, and providing the mechanism for vectoring control to this resource.
Helper : A helper is responsible for helping a view or controller complete its processing. Thus, helpers have numerous responsibilities, including gathering data required by the view and storing this intermediate model, in which case the helper is sometimes referred to as a value bean.
Let’s see an example of Front Controller Design Pattern.
class TeacherView { public void display() { System.out.println("Teacher View"); }} class StudentView { public void display() { System.out.println("Student View"); }} class Dispatching { private StudentView studentView; private TeacherView teacherView; public Dispatching() { studentView = new StudentView(); teacherView = new TeacherView(); } public void dispatch(String request) { if(request.equalsIgnoreCase("Student")) { studentView.display(); } else { teacherView.display(); } }} class FrontController { private Dispatching Dispatching; public FrontController() { Dispatching = new Dispatching(); } private boolean isAuthenticUser() { System.out.println("Authentication successful."); return true; } private void trackRequest(String request) { System.out.println("Requested View: " + request); } public void dispatchRequest(String request) { trackRequest(request); if(isAuthenticUser()) { Dispatching.dispatch(request); } }} class FrontControllerPattern{ public static void main(String[] args) { FrontController frontController = new FrontController(); frontController.dispatchRequest("Teacher"); frontController.dispatchRequest("Student"); }}
Output:
Requested View: Teacher
Authentication successful.
Teacher View
Requested View: Student
Authentication successful.
Student View
Advantages :
Centralized control : Front controller handles all the requests to the Web application. This implementation of centralized control that avoids using multiple controllers is desirable for enforcing application-wide policies such as users tracking and security.
Thread-safety : A new command object arises when receiving a new request and the command objects are not meant to be thread-safe. Thus, it will be safe in the command classes. Though safety is not guaranteed when threading issues are gathered, codes that act with the command are still thread safe.
Disadvantages :
It is not possible to scale an application using a front controller.
Performance is better if you deal with a single request uniquely.
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
nidhi_biet
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 321,
"s": 28,
"text": "The front controller design pattern means that all requests that come for a resource in an application will be handled by a single handler and then dispatched to the appropriate handler for that type of request. The front controller may use other helpers to achieve the dispatching mechanism."
},
{
"code": null,
"e": 365,
"s": 321,
"text": "UML Diagram Front Controller Design Pattern"
},
{
"code": null,
"e": 383,
"s": 365,
"text": "Design components"
},
{
"code": null,
"e": 610,
"s": 383,
"text": "Controller : The controller is the initial contact point for handling all requests in the system. The controller may delegate to a helper to complete authentication and authorization of a user or to initiate contact retrieval."
},
{
"code": null,
"e": 821,
"s": 610,
"text": "View: A view represents and displays information to the client. The view retrieves information from a model. Helpers support views by encapsulating and adapting the underlying data model for use in the display."
},
{
"code": null,
"e": 1026,
"s": 821,
"text": "Dispatcher: A dispatcher is responsible for view management and navigation, managing the choice of the next view to present to the user, and providing the mechanism for vectoring control to this resource."
},
{
"code": null,
"e": 1313,
"s": 1026,
"text": "Helper : A helper is responsible for helping a view or controller complete its processing. Thus, helpers have numerous responsibilities, including gathering data required by the view and storing this intermediate model, in which case the helper is sometimes referred to as a value bean."
},
{
"code": null,
"e": 1370,
"s": 1313,
"text": "Let’s see an example of Front Controller Design Pattern."
},
{
"code": "class TeacherView { public void display() { System.out.println(\"Teacher View\"); }} class StudentView { public void display() { System.out.println(\"Student View\"); }} class Dispatching { private StudentView studentView; private TeacherView teacherView; public Dispatching() { studentView = new StudentView(); teacherView = new TeacherView(); } public void dispatch(String request) { if(request.equalsIgnoreCase(\"Student\")) { studentView.display(); } else { teacherView.display(); } }} class FrontController { private Dispatching Dispatching; public FrontController() { Dispatching = new Dispatching(); } private boolean isAuthenticUser() { System.out.println(\"Authentication successful.\"); return true; } private void trackRequest(String request) { System.out.println(\"Requested View: \" + request); } public void dispatchRequest(String request) { trackRequest(request); if(isAuthenticUser()) { Dispatching.dispatch(request); } }} class FrontControllerPattern{ public static void main(String[] args) { FrontController frontController = new FrontController(); frontController.dispatchRequest(\"Teacher\"); frontController.dispatchRequest(\"Student\"); }}",
"e": 2824,
"s": 1370,
"text": null
},
{
"code": null,
"e": 2832,
"s": 2824,
"text": "Output:"
},
{
"code": null,
"e": 2961,
"s": 2832,
"text": "Requested View: Teacher\nAuthentication successful.\nTeacher View\nRequested View: Student\nAuthentication successful.\nStudent View\n"
},
{
"code": null,
"e": 2974,
"s": 2961,
"text": "Advantages :"
},
{
"code": null,
"e": 3234,
"s": 2974,
"text": "Centralized control : Front controller handles all the requests to the Web application. This implementation of centralized control that avoids using multiple controllers is desirable for enforcing application-wide policies such as users tracking and security."
},
{
"code": null,
"e": 3533,
"s": 3234,
"text": "Thread-safety : A new command object arises when receiving a new request and the command objects are not meant to be thread-safe. Thus, it will be safe in the command classes. Though safety is not guaranteed when threading issues are gathered, codes that act with the command are still thread safe."
},
{
"code": null,
"e": 3549,
"s": 3533,
"text": "Disadvantages :"
},
{
"code": null,
"e": 3618,
"s": 3549,
"text": "It is not possible to scale an application using a front controller."
},
{
"code": null,
"e": 3684,
"s": 3618,
"text": "Performance is better if you deal with a single request uniquely."
},
{
"code": null,
"e": 3983,
"s": 3684,
"text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4108,
"s": 3983,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4121,
"s": 4108,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4132,
"s": 4121,
"text": "nidhi_biet"
},
{
"code": null,
"e": 4147,
"s": 4132,
"text": "Design Pattern"
}
]
|
Logger getLogger() Method in Java with Examples | 24 Apr, 2019
The getLogger() method of a Logger class used find or create a logger. If there is a logger exists with the passed name then the method will return that logger else method will create a new logger with that name and return it.There are two types of getLogger() method depending upon no of the parameter passed.
getLogger(java.lang.String): This method is used to find or create a logger with the name passed as parameter. It will create a new logger if logger does not exist with the passed name. If a new logger is created by this method then its log level will be configured based on the LogManager configuration and it will be configured to also send logging output to its parent’s Handlers. It will be registered in the LogManager global namespace.Syntax:public static Logger getLogger(String name)
Parameters: This method accepts a single parameter name which is the String representing name for the logger. This should be a dot-separated name and should normally be based on the package name or class name of the subsystem, such as java.net or javax.swingReturn value: This method returns a suitable Logger.Exception: This method will throw NullPointerException if the passed name is null.Below programs illustrate getLogger(java.lang.String) method:Program 1:// Java program to demonstrate// Logger.getLogger(java.lang.String) method import java.util.logging.*; public class GFG { public static void main(String[] args) { // Create a Logger with class name GFG Logger logger = Logger.getLogger(GFG.class.getName()); // Call info method logger.info("Message 1"); logger.info("Message 2"); }}The output printed on console is shown below.Output:Program 2:// Java program to demonstrate Exception thrown by// Logger.getLogger(java.lang.String) methodimport java.util.logging.*; public class GFG { public static void main(String[] args) { String LoggerName = null; // Create a Logger with a null value try { Logger logger = Logger.getLogger(LoggerName); } catch (NullPointerException e) { System.out.println("Exception Thrown: " + e); } }}The output printed on console is shown below.Output:getLogger(String name, String resourceBundleName): This method is used to find or creates a logger with the passed name. If a logger has already been created with the given name it is returned. Otherwise, a new logger is created. If the Logger with the passed name already exists and does not have a localization resource bundle then the given resource bundle name is used as a localization resource bundle for this logger. If the named Logger has a different resource bundle name then an IllegalArgumentException is thrown by this method.Syntax:public static Logger getLogger(String name, String resourceBundleName)
Parameters: This method accepts two different parameters:name: which is the name for the logger. This name should be a dot-separated name and should normally be based on the package name or class name of the subsystem, such as java.net or javax.swingresourceBundleName: which is the name of ResourceBundle to be used for localizing messages for this logger.Return value: This method returns a suitable Logger.Exception: This method will throws following Exceptions:NullPointerException: if the passed name is null.MissingResourceException: if the resourceBundleName is non-null and no corresponding resource can be found.IllegalArgumentException: if the Logger already exists and uses a different resource bundle name; or if resourceBundleName is null but the named logger has a resource bundle set.Below programs illustrate getLogger(String name, String resourceBundleName) method:Program 1:// Java program to demonstrate// getLogger(String name, String resourceBundleName) method import java.util.ResourceBundle;import java.util.logging.*; public class GFG { public static void main(String[] args) { // Create ResourceBundle using getBundle // myResource is a properties file ResourceBundle bundle = ResourceBundle .getBundle("resourceBundle"); // Create a Logger // with GFG.class and resourceBundle Logger logger = Logger.getLogger( GFG.class.getName(), bundle.getBaseBundleName()); // Log the info logger.info("Message 1 for logger"); }}For the above program, there is a properties file name resourceBundle. we have to add this file alongside the class to execute the program.Output:
getLogger(java.lang.String): This method is used to find or create a logger with the name passed as parameter. It will create a new logger if logger does not exist with the passed name. If a new logger is created by this method then its log level will be configured based on the LogManager configuration and it will be configured to also send logging output to its parent’s Handlers. It will be registered in the LogManager global namespace.Syntax:public static Logger getLogger(String name)
Parameters: This method accepts a single parameter name which is the String representing name for the logger. This should be a dot-separated name and should normally be based on the package name or class name of the subsystem, such as java.net or javax.swingReturn value: This method returns a suitable Logger.Exception: This method will throw NullPointerException if the passed name is null.Below programs illustrate getLogger(java.lang.String) method:Program 1:// Java program to demonstrate// Logger.getLogger(java.lang.String) method import java.util.logging.*; public class GFG { public static void main(String[] args) { // Create a Logger with class name GFG Logger logger = Logger.getLogger(GFG.class.getName()); // Call info method logger.info("Message 1"); logger.info("Message 2"); }}The output printed on console is shown below.Output:Program 2:// Java program to demonstrate Exception thrown by// Logger.getLogger(java.lang.String) methodimport java.util.logging.*; public class GFG { public static void main(String[] args) { String LoggerName = null; // Create a Logger with a null value try { Logger logger = Logger.getLogger(LoggerName); } catch (NullPointerException e) { System.out.println("Exception Thrown: " + e); } }}The output printed on console is shown below.Output:
Syntax:
public static Logger getLogger(String name)
Parameters: This method accepts a single parameter name which is the String representing name for the logger. This should be a dot-separated name and should normally be based on the package name or class name of the subsystem, such as java.net or javax.swing
Return value: This method returns a suitable Logger.
Exception: This method will throw NullPointerException if the passed name is null.
Below programs illustrate getLogger(java.lang.String) method:Program 1:
// Java program to demonstrate// Logger.getLogger(java.lang.String) method import java.util.logging.*; public class GFG { public static void main(String[] args) { // Create a Logger with class name GFG Logger logger = Logger.getLogger(GFG.class.getName()); // Call info method logger.info("Message 1"); logger.info("Message 2"); }}
The output printed on console is shown below.Output:
Program 2:
// Java program to demonstrate Exception thrown by// Logger.getLogger(java.lang.String) methodimport java.util.logging.*; public class GFG { public static void main(String[] args) { String LoggerName = null; // Create a Logger with a null value try { Logger logger = Logger.getLogger(LoggerName); } catch (NullPointerException e) { System.out.println("Exception Thrown: " + e); } }}
The output printed on console is shown below.Output:
getLogger(String name, String resourceBundleName): This method is used to find or creates a logger with the passed name. If a logger has already been created with the given name it is returned. Otherwise, a new logger is created. If the Logger with the passed name already exists and does not have a localization resource bundle then the given resource bundle name is used as a localization resource bundle for this logger. If the named Logger has a different resource bundle name then an IllegalArgumentException is thrown by this method.Syntax:public static Logger getLogger(String name, String resourceBundleName)
Parameters: This method accepts two different parameters:name: which is the name for the logger. This name should be a dot-separated name and should normally be based on the package name or class name of the subsystem, such as java.net or javax.swingresourceBundleName: which is the name of ResourceBundle to be used for localizing messages for this logger.Return value: This method returns a suitable Logger.Exception: This method will throws following Exceptions:NullPointerException: if the passed name is null.MissingResourceException: if the resourceBundleName is non-null and no corresponding resource can be found.IllegalArgumentException: if the Logger already exists and uses a different resource bundle name; or if resourceBundleName is null but the named logger has a resource bundle set.Below programs illustrate getLogger(String name, String resourceBundleName) method:Program 1:// Java program to demonstrate// getLogger(String name, String resourceBundleName) method import java.util.ResourceBundle;import java.util.logging.*; public class GFG { public static void main(String[] args) { // Create ResourceBundle using getBundle // myResource is a properties file ResourceBundle bundle = ResourceBundle .getBundle("resourceBundle"); // Create a Logger // with GFG.class and resourceBundle Logger logger = Logger.getLogger( GFG.class.getName(), bundle.getBaseBundleName()); // Log the info logger.info("Message 1 for logger"); }}For the above program, there is a properties file name resourceBundle. we have to add this file alongside the class to execute the program.Output:
Syntax:
public static Logger getLogger(String name, String resourceBundleName)
Parameters: This method accepts two different parameters:
name: which is the name for the logger. This name should be a dot-separated name and should normally be based on the package name or class name of the subsystem, such as java.net or javax.swing
resourceBundleName: which is the name of ResourceBundle to be used for localizing messages for this logger.
Return value: This method returns a suitable Logger.
Exception: This method will throws following Exceptions:
NullPointerException: if the passed name is null.MissingResourceException: if the resourceBundleName is non-null and no corresponding resource can be found.IllegalArgumentException: if the Logger already exists and uses a different resource bundle name; or if resourceBundleName is null but the named logger has a resource bundle set.
NullPointerException: if the passed name is null.
MissingResourceException: if the resourceBundleName is non-null and no corresponding resource can be found.
IllegalArgumentException: if the Logger already exists and uses a different resource bundle name; or if resourceBundleName is null but the named logger has a resource bundle set.
Below programs illustrate getLogger(String name, String resourceBundleName) method:
Program 1:
// Java program to demonstrate// getLogger(String name, String resourceBundleName) method import java.util.ResourceBundle;import java.util.logging.*; public class GFG { public static void main(String[] args) { // Create ResourceBundle using getBundle // myResource is a properties file ResourceBundle bundle = ResourceBundle .getBundle("resourceBundle"); // Create a Logger // with GFG.class and resourceBundle Logger logger = Logger.getLogger( GFG.class.getName(), bundle.getBaseBundleName()); // Log the info logger.info("Message 1 for logger"); }}
For the above program, there is a properties file name resourceBundle. we have to add this file alongside the class to execute the program.Output:
References:
https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#getLogger(java.lang.String, java.lang.String)
https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#getLogger(java.lang.String)
Java - util package
Java-Functions
Java-Logger
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Apr, 2019"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "The getLogger() method of a Logger class used find or create a logger. If there is a logger exists with the passed name then the method will return that logger else method will create a new logger with that name and return it.There are two types of getLogger() method depending upon no of the parameter passed."
},
{
"code": null,
"e": 4659,
"s": 339,
"text": "getLogger(java.lang.String): This method is used to find or create a logger with the name passed as parameter. It will create a new logger if logger does not exist with the passed name. If a new logger is created by this method then its log level will be configured based on the LogManager configuration and it will be configured to also send logging output to its parent’s Handlers. It will be registered in the LogManager global namespace.Syntax:public static Logger getLogger(String name)\nParameters: This method accepts a single parameter name which is the String representing name for the logger. This should be a dot-separated name and should normally be based on the package name or class name of the subsystem, such as java.net or javax.swingReturn value: This method returns a suitable Logger.Exception: This method will throw NullPointerException if the passed name is null.Below programs illustrate getLogger(java.lang.String) method:Program 1:// Java program to demonstrate// Logger.getLogger(java.lang.String) method import java.util.logging.*; public class GFG { public static void main(String[] args) { // Create a Logger with class name GFG Logger logger = Logger.getLogger(GFG.class.getName()); // Call info method logger.info(\"Message 1\"); logger.info(\"Message 2\"); }}The output printed on console is shown below.Output:Program 2:// Java program to demonstrate Exception thrown by// Logger.getLogger(java.lang.String) methodimport java.util.logging.*; public class GFG { public static void main(String[] args) { String LoggerName = null; // Create a Logger with a null value try { Logger logger = Logger.getLogger(LoggerName); } catch (NullPointerException e) { System.out.println(\"Exception Thrown: \" + e); } }}The output printed on console is shown below.Output:getLogger(String name, String resourceBundleName): This method is used to find or creates a logger with the passed name. If a logger has already been created with the given name it is returned. Otherwise, a new logger is created. If the Logger with the passed name already exists and does not have a localization resource bundle then the given resource bundle name is used as a localization resource bundle for this logger. If the named Logger has a different resource bundle name then an IllegalArgumentException is thrown by this method.Syntax:public static Logger getLogger(String name, String resourceBundleName)\nParameters: This method accepts two different parameters:name: which is the name for the logger. This name should be a dot-separated name and should normally be based on the package name or class name of the subsystem, such as java.net or javax.swingresourceBundleName: which is the name of ResourceBundle to be used for localizing messages for this logger.Return value: This method returns a suitable Logger.Exception: This method will throws following Exceptions:NullPointerException: if the passed name is null.MissingResourceException: if the resourceBundleName is non-null and no corresponding resource can be found.IllegalArgumentException: if the Logger already exists and uses a different resource bundle name; or if resourceBundleName is null but the named logger has a resource bundle set.Below programs illustrate getLogger(String name, String resourceBundleName) method:Program 1:// Java program to demonstrate// getLogger(String name, String resourceBundleName) method import java.util.ResourceBundle;import java.util.logging.*; public class GFG { public static void main(String[] args) { // Create ResourceBundle using getBundle // myResource is a properties file ResourceBundle bundle = ResourceBundle .getBundle(\"resourceBundle\"); // Create a Logger // with GFG.class and resourceBundle Logger logger = Logger.getLogger( GFG.class.getName(), bundle.getBaseBundleName()); // Log the info logger.info(\"Message 1 for logger\"); }}For the above program, there is a properties file name resourceBundle. we have to add this file alongside the class to execute the program.Output:"
},
{
"code": null,
"e": 6630,
"s": 4659,
"text": "getLogger(java.lang.String): This method is used to find or create a logger with the name passed as parameter. It will create a new logger if logger does not exist with the passed name. If a new logger is created by this method then its log level will be configured based on the LogManager configuration and it will be configured to also send logging output to its parent’s Handlers. It will be registered in the LogManager global namespace.Syntax:public static Logger getLogger(String name)\nParameters: This method accepts a single parameter name which is the String representing name for the logger. This should be a dot-separated name and should normally be based on the package name or class name of the subsystem, such as java.net or javax.swingReturn value: This method returns a suitable Logger.Exception: This method will throw NullPointerException if the passed name is null.Below programs illustrate getLogger(java.lang.String) method:Program 1:// Java program to demonstrate// Logger.getLogger(java.lang.String) method import java.util.logging.*; public class GFG { public static void main(String[] args) { // Create a Logger with class name GFG Logger logger = Logger.getLogger(GFG.class.getName()); // Call info method logger.info(\"Message 1\"); logger.info(\"Message 2\"); }}The output printed on console is shown below.Output:Program 2:// Java program to demonstrate Exception thrown by// Logger.getLogger(java.lang.String) methodimport java.util.logging.*; public class GFG { public static void main(String[] args) { String LoggerName = null; // Create a Logger with a null value try { Logger logger = Logger.getLogger(LoggerName); } catch (NullPointerException e) { System.out.println(\"Exception Thrown: \" + e); } }}The output printed on console is shown below.Output:"
},
{
"code": null,
"e": 6638,
"s": 6630,
"text": "Syntax:"
},
{
"code": null,
"e": 6683,
"s": 6638,
"text": "public static Logger getLogger(String name)\n"
},
{
"code": null,
"e": 6942,
"s": 6683,
"text": "Parameters: This method accepts a single parameter name which is the String representing name for the logger. This should be a dot-separated name and should normally be based on the package name or class name of the subsystem, such as java.net or javax.swing"
},
{
"code": null,
"e": 6995,
"s": 6942,
"text": "Return value: This method returns a suitable Logger."
},
{
"code": null,
"e": 7078,
"s": 6995,
"text": "Exception: This method will throw NullPointerException if the passed name is null."
},
{
"code": null,
"e": 7150,
"s": 7078,
"text": "Below programs illustrate getLogger(java.lang.String) method:Program 1:"
},
{
"code": "// Java program to demonstrate// Logger.getLogger(java.lang.String) method import java.util.logging.*; public class GFG { public static void main(String[] args) { // Create a Logger with class name GFG Logger logger = Logger.getLogger(GFG.class.getName()); // Call info method logger.info(\"Message 1\"); logger.info(\"Message 2\"); }}",
"e": 7545,
"s": 7150,
"text": null
},
{
"code": null,
"e": 7598,
"s": 7545,
"text": "The output printed on console is shown below.Output:"
},
{
"code": null,
"e": 7609,
"s": 7598,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate Exception thrown by// Logger.getLogger(java.lang.String) methodimport java.util.logging.*; public class GFG { public static void main(String[] args) { String LoggerName = null; // Create a Logger with a null value try { Logger logger = Logger.getLogger(LoggerName); } catch (NullPointerException e) { System.out.println(\"Exception Thrown: \" + e); } }}",
"e": 8117,
"s": 7609,
"text": null
},
{
"code": null,
"e": 8170,
"s": 8117,
"text": "The output printed on console is shown below.Output:"
},
{
"code": null,
"e": 10520,
"s": 8170,
"text": "getLogger(String name, String resourceBundleName): This method is used to find or creates a logger with the passed name. If a logger has already been created with the given name it is returned. Otherwise, a new logger is created. If the Logger with the passed name already exists and does not have a localization resource bundle then the given resource bundle name is used as a localization resource bundle for this logger. If the named Logger has a different resource bundle name then an IllegalArgumentException is thrown by this method.Syntax:public static Logger getLogger(String name, String resourceBundleName)\nParameters: This method accepts two different parameters:name: which is the name for the logger. This name should be a dot-separated name and should normally be based on the package name or class name of the subsystem, such as java.net or javax.swingresourceBundleName: which is the name of ResourceBundle to be used for localizing messages for this logger.Return value: This method returns a suitable Logger.Exception: This method will throws following Exceptions:NullPointerException: if the passed name is null.MissingResourceException: if the resourceBundleName is non-null and no corresponding resource can be found.IllegalArgumentException: if the Logger already exists and uses a different resource bundle name; or if resourceBundleName is null but the named logger has a resource bundle set.Below programs illustrate getLogger(String name, String resourceBundleName) method:Program 1:// Java program to demonstrate// getLogger(String name, String resourceBundleName) method import java.util.ResourceBundle;import java.util.logging.*; public class GFG { public static void main(String[] args) { // Create ResourceBundle using getBundle // myResource is a properties file ResourceBundle bundle = ResourceBundle .getBundle(\"resourceBundle\"); // Create a Logger // with GFG.class and resourceBundle Logger logger = Logger.getLogger( GFG.class.getName(), bundle.getBaseBundleName()); // Log the info logger.info(\"Message 1 for logger\"); }}For the above program, there is a properties file name resourceBundle. we have to add this file alongside the class to execute the program.Output:"
},
{
"code": null,
"e": 10528,
"s": 10520,
"text": "Syntax:"
},
{
"code": null,
"e": 10600,
"s": 10528,
"text": "public static Logger getLogger(String name, String resourceBundleName)\n"
},
{
"code": null,
"e": 10658,
"s": 10600,
"text": "Parameters: This method accepts two different parameters:"
},
{
"code": null,
"e": 10852,
"s": 10658,
"text": "name: which is the name for the logger. This name should be a dot-separated name and should normally be based on the package name or class name of the subsystem, such as java.net or javax.swing"
},
{
"code": null,
"e": 10960,
"s": 10852,
"text": "resourceBundleName: which is the name of ResourceBundle to be used for localizing messages for this logger."
},
{
"code": null,
"e": 11013,
"s": 10960,
"text": "Return value: This method returns a suitable Logger."
},
{
"code": null,
"e": 11070,
"s": 11013,
"text": "Exception: This method will throws following Exceptions:"
},
{
"code": null,
"e": 11405,
"s": 11070,
"text": "NullPointerException: if the passed name is null.MissingResourceException: if the resourceBundleName is non-null and no corresponding resource can be found.IllegalArgumentException: if the Logger already exists and uses a different resource bundle name; or if resourceBundleName is null but the named logger has a resource bundle set."
},
{
"code": null,
"e": 11455,
"s": 11405,
"text": "NullPointerException: if the passed name is null."
},
{
"code": null,
"e": 11563,
"s": 11455,
"text": "MissingResourceException: if the resourceBundleName is non-null and no corresponding resource can be found."
},
{
"code": null,
"e": 11742,
"s": 11563,
"text": "IllegalArgumentException: if the Logger already exists and uses a different resource bundle name; or if resourceBundleName is null but the named logger has a resource bundle set."
},
{
"code": null,
"e": 11826,
"s": 11742,
"text": "Below programs illustrate getLogger(String name, String resourceBundleName) method:"
},
{
"code": null,
"e": 11837,
"s": 11826,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// getLogger(String name, String resourceBundleName) method import java.util.ResourceBundle;import java.util.logging.*; public class GFG { public static void main(String[] args) { // Create ResourceBundle using getBundle // myResource is a properties file ResourceBundle bundle = ResourceBundle .getBundle(\"resourceBundle\"); // Create a Logger // with GFG.class and resourceBundle Logger logger = Logger.getLogger( GFG.class.getName(), bundle.getBaseBundleName()); // Log the info logger.info(\"Message 1 for logger\"); }}",
"e": 12532,
"s": 11837,
"text": null
},
{
"code": null,
"e": 12679,
"s": 12532,
"text": "For the above program, there is a properties file name resourceBundle. we have to add this file alongside the class to execute the program.Output:"
},
{
"code": null,
"e": 12691,
"s": 12679,
"text": "References:"
},
{
"code": null,
"e": 12810,
"s": 12691,
"text": "https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#getLogger(java.lang.String, java.lang.String)"
},
{
"code": null,
"e": 12911,
"s": 12810,
"text": "https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#getLogger(java.lang.String)"
},
{
"code": null,
"e": 12931,
"s": 12911,
"text": "Java - util package"
},
{
"code": null,
"e": 12946,
"s": 12931,
"text": "Java-Functions"
},
{
"code": null,
"e": 12958,
"s": 12946,
"text": "Java-Logger"
},
{
"code": null,
"e": 12963,
"s": 12958,
"text": "Java"
},
{
"code": null,
"e": 12968,
"s": 12963,
"text": "Java"
}
]
|
How to tag an image and push that image to Dockerhub ? | 23 Sep, 2020
By pushing an image to the Docker hub registry, we can create an instance of an image in which a particular type of software and applications are pre-installed and can be pulled again whenever you want to work on that particular type of image or applications and run that kind of virtual machine. In the docker hub, there are millions of images you can also pull the default images which are created by the particular organizations for example you can pull the Ubuntu image which is uploaded by Linux and then install any software or application into that image like curl command, Jenkins, etc and then push that image to your docker hub registry.
A docker hub account.
Installed docker software in your respective operating system.
A pulled image in your docker container which you want to pull in docker hub repository.
Follow the below steps to achieve so:
Step 1: The first step is to give a tag to your docker image which is a reference to your docker image ID which conveys the information regarding the image version. If you login to your docker hub account and search for a standard image of MySQL, HTTP, etc there you notice these tags.
docker image tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]
If you do not mention the tag then the default tag is the latest. For example,
docker image tag ubuntu:14.04 XYZ/ubuntu:2.0
Command to tag an image
Ubuntu is a source image in our docker container 14.04 is the tag to that source image.XYZ in the target image name has to be similar to your docker hub account username and the tag is 2.0.
Step 2: Now if you try to push the image then it will give an error:
denied: requested access to the resource is denied
The reason is that for pushing the image in your docker hub account first you have to log in. So the second step is to log in to your docker hub account. To login, the command is
docker login
Docker login
Now write your respective username and password you give while creating a docker hub account.
Note: If you are a Mac user after pushing your image do not forget to logout because the authentication key is written to a file to remember you as user of that docker hub account in the future if it is your personal device no need to do this.
docker logout
docker logout
Step 3: Now after you login you are able to push the image the command is:
docker image push [OPTIONS] NAME[:TAG]
For example,
docker image push XYZ/ubuntu:2.0
Push command
After running this command your image will be pulled to the docker hub repository.
Note: Write sudo before every command if your image is in the root account and XYZ is your username of docker hub account.
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Basics of API Testing Using Postman
Copying Files to and from Docker Containers
Getting Started with System Design
Principal Component Analysis with Python
Python | Implementation of Polynomial Regression
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
OpenCV - Overview | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 677,
"s": 28,
"text": "By pushing an image to the Docker hub registry, we can create an instance of an image in which a particular type of software and applications are pre-installed and can be pulled again whenever you want to work on that particular type of image or applications and run that kind of virtual machine. In the docker hub, there are millions of images you can also pull the default images which are created by the particular organizations for example you can pull the Ubuntu image which is uploaded by Linux and then install any software or application into that image like curl command, Jenkins, etc and then push that image to your docker hub registry. "
},
{
"code": null,
"e": 699,
"s": 677,
"text": "A docker hub account."
},
{
"code": null,
"e": 762,
"s": 699,
"text": "Installed docker software in your respective operating system."
},
{
"code": null,
"e": 851,
"s": 762,
"text": "A pulled image in your docker container which you want to pull in docker hub repository."
},
{
"code": null,
"e": 889,
"s": 851,
"text": "Follow the below steps to achieve so:"
},
{
"code": null,
"e": 1175,
"s": 889,
"text": "Step 1: The first step is to give a tag to your docker image which is a reference to your docker image ID which conveys the information regarding the image version. If you login to your docker hub account and search for a standard image of MySQL, HTTP, etc there you notice these tags."
},
{
"code": null,
"e": 1231,
"s": 1175,
"text": "docker image tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]\n"
},
{
"code": null,
"e": 1310,
"s": 1231,
"text": "If you do not mention the tag then the default tag is the latest. For example,"
},
{
"code": null,
"e": 1356,
"s": 1310,
"text": "docker image tag ubuntu:14.04 XYZ/ubuntu:2.0\n"
},
{
"code": null,
"e": 1380,
"s": 1356,
"text": "Command to tag an image"
},
{
"code": null,
"e": 1575,
"s": 1380,
"text": "Ubuntu is a source image in our docker container 14.04 is the tag to that source image.XYZ in the target image name has to be similar to your docker hub account username and the tag is 2.0. "
},
{
"code": null,
"e": 1644,
"s": 1575,
"text": "Step 2: Now if you try to push the image then it will give an error:"
},
{
"code": null,
"e": 1696,
"s": 1644,
"text": "denied: requested access to the resource is denied\n"
},
{
"code": null,
"e": 1883,
"s": 1696,
"text": "The reason is that for pushing the image in your docker hub account first you have to log in. So the second step is to log in to your docker hub account. To login, the command is "
},
{
"code": null,
"e": 1897,
"s": 1883,
"text": "docker login\n"
},
{
"code": null,
"e": 1910,
"s": 1897,
"text": "Docker login"
},
{
"code": null,
"e": 2020,
"s": 1913,
"text": "Now write your respective username and password you give while creating a docker hub account. "
},
{
"code": null,
"e": 2264,
"s": 2020,
"text": "Note: If you are a Mac user after pushing your image do not forget to logout because the authentication key is written to a file to remember you as user of that docker hub account in the future if it is your personal device no need to do this."
},
{
"code": null,
"e": 2279,
"s": 2264,
"text": "docker logout\n"
},
{
"code": null,
"e": 2293,
"s": 2279,
"text": "docker logout"
},
{
"code": null,
"e": 2368,
"s": 2293,
"text": "Step 3: Now after you login you are able to push the image the command is:"
},
{
"code": null,
"e": 2408,
"s": 2368,
"text": "docker image push [OPTIONS] NAME[:TAG]\n"
},
{
"code": null,
"e": 2422,
"s": 2408,
"text": " For example,"
},
{
"code": null,
"e": 2456,
"s": 2422,
"text": "docker image push XYZ/ubuntu:2.0\n"
},
{
"code": null,
"e": 2469,
"s": 2456,
"text": "Push command"
},
{
"code": null,
"e": 2552,
"s": 2469,
"text": "After running this command your image will be pulled to the docker hub repository."
},
{
"code": null,
"e": 2675,
"s": 2552,
"text": "Note: Write sudo before every command if your image is in the root account and XYZ is your username of docker hub account."
},
{
"code": null,
"e": 2701,
"s": 2675,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 2799,
"s": 2701,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2835,
"s": 2799,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2859,
"s": 2835,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 2895,
"s": 2859,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 2939,
"s": 2895,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 2974,
"s": 2939,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 3015,
"s": 2974,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 3064,
"s": 3015,
"text": "Python | Implementation of Polynomial Regression"
},
{
"code": null,
"e": 3112,
"s": 3064,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 3153,
"s": 3112,
"text": "Monolithic vs Microservices architecture"
}
]
|
Python | Finding strings with given substring in list | 24 Dec, 2018
The classical problem that can be handled quite easily by Python and has been also dealt with many times is finding if a string is substring of other. But sometimes, one wishes to extend this on list of strings, and hence then requires to traverse the entire container and perform the generic algorithm.
Let’s discuss certain ways to find strings with given substring in list.
Method #1 : Using list comprehensionList comprehension is an elegant way to perform any particular task as it increases readability in a long run. This task can be performed using naive method and hence can be reduced to list comprehension as well.
# Python code to demonstrate # to find strings with substrings # using list comprehension # initializing list test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] # printing original list print ("The original list is : " + str(test_list)) # initializing substringsubs = 'Geek' # using list comprehension # to get string with substring res = [i for i in test_list if subs in i] # printing result print ("All strings with given substring are : " + str(res))
The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings with given substring are : ['GeeksforGeeks', 'Geeky']
Method #2 : Using filter() + lambdaThis function can also perform this task of finding the strings with the help of lambda. It just filters out all the strings matching the particular substring and then adds it in a new list.
# Python code to demonstrate # to find strings with substrings # using filter() + lambda # initializing list test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] # printing original list print ("The original list is : " + str(test_list)) # initializing substringsubs = 'Geek' # using filter() + lambda # to get string with substring res = list(filter(lambda x: subs in x, test_list)) # printing result print ("All strings with given substring are : " + str(res))
The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings with given substring are : ['GeeksforGeeks', 'Geeky']
Method #3 : Using re + search()Regular expressions can be used to perform many task in python. To perform this particular task also, regular expressions can come handy. It finds all the matching substring using search() and returns result.
# Python code to demonstrate # to find strings with substrings # using re + search()import re # initializing list test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] # printing original list print ("The original list is : " + str(test_list)) # initializing substringsubs = 'Geek' # using re + search()# to get string with substring res = [x for x in test_list if re.search(subs, x)] # printing result print ("All strings with given substring are : " + str(res))
The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings with given substring are : ['GeeksforGeeks', 'Geeky']
Python list-programs
substring
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Dec, 2018"
},
{
"code": null,
"e": 358,
"s": 54,
"text": "The classical problem that can be handled quite easily by Python and has been also dealt with many times is finding if a string is substring of other. But sometimes, one wishes to extend this on list of strings, and hence then requires to traverse the entire container and perform the generic algorithm."
},
{
"code": null,
"e": 431,
"s": 358,
"text": "Let’s discuss certain ways to find strings with given substring in list."
},
{
"code": null,
"e": 680,
"s": 431,
"text": "Method #1 : Using list comprehensionList comprehension is an elegant way to perform any particular task as it increases readability in a long run. This task can be performed using naive method and hence can be reduced to list comprehension as well."
},
{
"code": "# Python code to demonstrate # to find strings with substrings # using list comprehension # initializing list test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] # printing original list print (\"The original list is : \" + str(test_list)) # initializing substringsubs = 'Geek' # using list comprehension # to get string with substring res = [i for i in test_list if subs in i] # printing result print (\"All strings with given substring are : \" + str(res))",
"e": 1155,
"s": 680,
"text": null
},
{
"code": null,
"e": 1299,
"s": 1155,
"text": "The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']\nAll strings with given substring are : ['GeeksforGeeks', 'Geeky']\n"
},
{
"code": null,
"e": 1526,
"s": 1299,
"text": " Method #2 : Using filter() + lambdaThis function can also perform this task of finding the strings with the help of lambda. It just filters out all the strings matching the particular substring and then adds it in a new list."
},
{
"code": "# Python code to demonstrate # to find strings with substrings # using filter() + lambda # initializing list test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] # printing original list print (\"The original list is : \" + str(test_list)) # initializing substringsubs = 'Geek' # using filter() + lambda # to get string with substring res = list(filter(lambda x: subs in x, test_list)) # printing result print (\"All strings with given substring are : \" + str(res))",
"e": 2007,
"s": 1526,
"text": null
},
{
"code": null,
"e": 2151,
"s": 2007,
"text": "The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']\nAll strings with given substring are : ['GeeksforGeeks', 'Geeky']\n"
},
{
"code": null,
"e": 2392,
"s": 2151,
"text": " Method #3 : Using re + search()Regular expressions can be used to perform many task in python. To perform this particular task also, regular expressions can come handy. It finds all the matching substring using search() and returns result."
},
{
"code": "# Python code to demonstrate # to find strings with substrings # using re + search()import re # initializing list test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] # printing original list print (\"The original list is : \" + str(test_list)) # initializing substringsubs = 'Geek' # using re + search()# to get string with substring res = [x for x in test_list if re.search(subs, x)] # printing result print (\"All strings with given substring are : \" + str(res))",
"e": 2873,
"s": 2392,
"text": null
},
{
"code": null,
"e": 3017,
"s": 2873,
"text": "The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']\nAll strings with given substring are : ['GeeksforGeeks', 'Geeky']\n"
},
{
"code": null,
"e": 3038,
"s": 3017,
"text": "Python list-programs"
},
{
"code": null,
"e": 3048,
"s": 3038,
"text": "substring"
},
{
"code": null,
"e": 3055,
"s": 3048,
"text": "Python"
},
{
"code": null,
"e": 3071,
"s": 3055,
"text": "Python Programs"
},
{
"code": null,
"e": 3169,
"s": 3071,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3187,
"s": 3169,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3229,
"s": 3187,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3251,
"s": 3229,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3283,
"s": 3251,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3312,
"s": 3283,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3334,
"s": 3312,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3373,
"s": 3334,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3411,
"s": 3373,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3448,
"s": 3411,
"text": "Python Program for Fibonacci numbers"
}
]
|
PHP | array_intersect() Function | 08 Mar, 2018
This builtin function of PHP is used to compute the intersection of two or more arrays. The function is used to compare the values of two or more arrays and returns the matches. The function prints only those elements of the first array that are present in all other arrays.
Syntax:
array array_intersect($array1, $array2, $array3, $array4...)
Parameters: The array_intersect() function takes at least two arrays as arguments. It can take any number of arrays greater than or equal to two separated by commas (‘,’).
Return Type: The function returns another array containing the elements of the first array that are present in all other arrays passed as the parameter. If no element matches then, a NULL array is returned.
Note: The keys of elements are preserved. That is, the keys of elements in output array will be same as that of keys of those elements in the first array.
Examples:
Input : $array1 = array(5, 10, 15, 20, 25, 30)
$array2 = array(20, 10, 15, 55, 110, 30)
$array3 = array(10, 15, 30, 55, 100, 95)
Output :
Array
(
[1] => 10
[2] => 15
[5] => 30
)
Input : $array1 = array("ram", "laxman", "rishi", "ayush");
$array2 = array("ayush", "gaurav", "rishi", "rohan");
$array3 = array("rishi", "gaurav", "ayush", "ravi");
Output :
Array
(
[2] => rishi
[3] => ayush
)
Below program illustrates the array_intersect() function in PHP:
<?php // PHP function to illustrate the use of array_intersect()function Intersect($array1, $array2, $array3){ $result = array_intersect($array1, $array2, $array3); return($result);} $array1 = array(5, 10, 15, 20, 25, 30);$array2 = array(20, 10, 15, 55, 100, 110, 30);$array3 = array(10, 15, 30, 55, 100, 95);print_r(Intersect($array1, $array2, $array3)); ?>
Output:
Array
(
[1] => 10
[2] => 15
[5] => 30
)
Reference: http://php.net/manual/en/function.array-intersect.php
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to receive JSON POST with PHP ?
How to get parameters from a URL string in PHP?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Mar, 2018"
},
{
"code": null,
"e": 303,
"s": 28,
"text": "This builtin function of PHP is used to compute the intersection of two or more arrays. The function is used to compare the values of two or more arrays and returns the matches. The function prints only those elements of the first array that are present in all other arrays."
},
{
"code": null,
"e": 311,
"s": 303,
"text": "Syntax:"
},
{
"code": null,
"e": 372,
"s": 311,
"text": "array array_intersect($array1, $array2, $array3, $array4...)"
},
{
"code": null,
"e": 544,
"s": 372,
"text": "Parameters: The array_intersect() function takes at least two arrays as arguments. It can take any number of arrays greater than or equal to two separated by commas (‘,’)."
},
{
"code": null,
"e": 751,
"s": 544,
"text": "Return Type: The function returns another array containing the elements of the first array that are present in all other arrays passed as the parameter. If no element matches then, a NULL array is returned."
},
{
"code": null,
"e": 906,
"s": 751,
"text": "Note: The keys of elements are preserved. That is, the keys of elements in output array will be same as that of keys of those elements in the first array."
},
{
"code": null,
"e": 916,
"s": 906,
"text": "Examples:"
},
{
"code": null,
"e": 1443,
"s": 916,
"text": "Input : $array1 = array(5, 10, 15, 20, 25, 30)\n $array2 = array(20, 10, 15, 55, 110, 30)\n $array3 = array(10, 15, 30, 55, 100, 95)\nOutput :\n Array\n (\n [1] => 10\n [2] => 15\n [5] => 30\n )\n\nInput : $array1 = array(\"ram\", \"laxman\", \"rishi\", \"ayush\");\n $array2 = array(\"ayush\", \"gaurav\", \"rishi\", \"rohan\");\n $array3 = array(\"rishi\", \"gaurav\", \"ayush\", \"ravi\");\nOutput :\n Array\n (\n [2] => rishi\n [3] => ayush\n )\n"
},
{
"code": null,
"e": 1508,
"s": 1443,
"text": "Below program illustrates the array_intersect() function in PHP:"
},
{
"code": "<?php // PHP function to illustrate the use of array_intersect()function Intersect($array1, $array2, $array3){ $result = array_intersect($array1, $array2, $array3); return($result);} $array1 = array(5, 10, 15, 20, 25, 30);$array2 = array(20, 10, 15, 55, 100, 110, 30);$array3 = array(10, 15, 30, 55, 100, 95);print_r(Intersect($array1, $array2, $array3)); ?> ",
"e": 1878,
"s": 1508,
"text": null
},
{
"code": null,
"e": 1886,
"s": 1878,
"text": "Output:"
},
{
"code": null,
"e": 1939,
"s": 1886,
"text": "Array\n(\n [1] => 10\n [2] => 15\n [5] => 30\n)\n"
},
{
"code": null,
"e": 2004,
"s": 1939,
"text": "Reference: http://php.net/manual/en/function.array-intersect.php"
},
{
"code": null,
"e": 2014,
"s": 2004,
"text": "PHP-array"
},
{
"code": null,
"e": 2027,
"s": 2014,
"text": "PHP-function"
},
{
"code": null,
"e": 2031,
"s": 2027,
"text": "PHP"
},
{
"code": null,
"e": 2048,
"s": 2031,
"text": "Web Technologies"
},
{
"code": null,
"e": 2052,
"s": 2048,
"text": "PHP"
},
{
"code": null,
"e": 2150,
"s": 2052,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2200,
"s": 2150,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2240,
"s": 2200,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2285,
"s": 2240,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2321,
"s": 2285,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 2369,
"s": 2321,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 2402,
"s": 2369,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2464,
"s": 2402,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2506,
"s": 2464,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2567,
"s": 2506,
"text": "Difference between var, let and const keywords in JavaScript"
}
]
|
Setup OpenCV With PyCharm Environment | 01 Oct, 2020
If you love working on image processing and video analysis using python then you have come to the right place. Python is one of the key languages which is used to process videos and images.
32- or a 64-bit computer.
Windows, macOS or Linux.
Python 2.7, 3.4, 3.5 or 3.6.
PyCharm is a cross-platform IDE used in computer programming specifically for Python. The platform developed by JetBrains is mainly used in code analysis, graphical debugger etc... It supports web development with Django as well as Data Science with Anaconda.
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. It was initially built by Intel but later managed by Willow Garag, presently it is managed by Itseez. It is a cross-platform library which available for programming languages apart from python.
1) Go to the terminal option at the bottom of the IDE window.
2) The pip (package manager) can also be used to download and install OpenCV. To install OpenCV, just type the following command:
Python3
pip install opencv-python
3) Now simply import OpenCV in your python program in which you want to use image processing functions.
To check if OpenCV is correctly installed, just run the following program in PyCharm to perform a version check:
Python3
import cv2print("GeeksForGeeks")print("Your OpenCV version is: " + cv2.__version__)
GeeksForGeeks
Your OpenCV version is: 4.4.0
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 243,
"s": 53,
"text": "If you love working on image processing and video analysis using python then you have come to the right place. Python is one of the key languages which is used to process videos and images."
},
{
"code": null,
"e": 269,
"s": 243,
"text": "32- or a 64-bit computer."
},
{
"code": null,
"e": 294,
"s": 269,
"text": "Windows, macOS or Linux."
},
{
"code": null,
"e": 323,
"s": 294,
"text": "Python 2.7, 3.4, 3.5 or 3.6."
},
{
"code": null,
"e": 583,
"s": 323,
"text": "PyCharm is a cross-platform IDE used in computer programming specifically for Python. The platform developed by JetBrains is mainly used in code analysis, graphical debugger etc... It supports web development with Django as well as Data Science with Anaconda."
},
{
"code": null,
"e": 920,
"s": 583,
"text": "OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. It was initially built by Intel but later managed by Willow Garag, presently it is managed by Itseez. It is a cross-platform library which available for programming languages apart from python."
},
{
"code": null,
"e": 982,
"s": 920,
"text": "1) Go to the terminal option at the bottom of the IDE window."
},
{
"code": null,
"e": 1114,
"s": 984,
"text": "2) The pip (package manager) can also be used to download and install OpenCV. To install OpenCV, just type the following command:"
},
{
"code": null,
"e": 1122,
"s": 1114,
"text": "Python3"
},
{
"code": "pip install opencv-python",
"e": 1148,
"s": 1122,
"text": null
},
{
"code": null,
"e": 1252,
"s": 1148,
"text": "3) Now simply import OpenCV in your python program in which you want to use image processing functions."
},
{
"code": null,
"e": 1365,
"s": 1252,
"text": "To check if OpenCV is correctly installed, just run the following program in PyCharm to perform a version check:"
},
{
"code": null,
"e": 1373,
"s": 1365,
"text": "Python3"
},
{
"code": "import cv2print(\"GeeksForGeeks\")print(\"Your OpenCV version is: \" + cv2.__version__)",
"e": 1457,
"s": 1373,
"text": null
},
{
"code": null,
"e": 1502,
"s": 1457,
"text": "GeeksForGeeks\nYour OpenCV version is: 4.4.0\n"
},
{
"code": null,
"e": 1516,
"s": 1502,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 1523,
"s": 1516,
"text": "Python"
}
]
|
Maximum sum subarray removing at most one element | 06 Jul, 2022
Given an array, we need to find maximum sum subarray, removing one element is also allowed to get the maximum sum.
Examples :
Input : arr[] = {1, 2, 3, -4, 5}
Output : 11
Explanation : We can get maximum sum subarray by
removing -4.
Input : arr[] = [-2, -3, 4, -1, -2, 1, 5, -3]
Output : 9
Explanation : We can get maximum sum subarray by
removing -2 as, [4, -1, 1, 5] summing 9, which is
the maximum achievable sum.
If element removal condition is not applied, we can solve this problem using Kadane’s algorithm but here one element can be removed also for increasing maximum sum. This condition can be handled using two arrays, forward and backward array, these arrays store the current maximum subarray sum from starting to ith index, and from ith index to ending respectively.
In below code, two loops are written, first one stores maximum current sum in forward direction in fw[] and other loop stores the same in backward direction in bw[]. Getting current maximum and updation is same as Kadane’s algorithm.
Now when both arrays are created, we can use them for one element removal conditions as follows, at each index i, maximum subarray sum after ignoring i’th element will be fw[i-1] + bw[i+1] so we loop for all possible i values and we choose maximum among them.
Total time complexity and space complexity of solution is O(N)
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to get maximum sum subarray removing// at-most one element#include <bits/stdc++.h>using namespace std; // Method returns maximum sum of all subarray where// removing one element is also allowedint maxSumSubarrayRemovingOneEle(int arr[], int n){ // Maximum sum subarrays in forward and backward // directions int fw[n], bw[n]; // Initialize current max and max so far. int cur_max = arr[0], max_so_far = arr[0]; // calculating maximum sum subarrays in forward // direction fw[0] = arr[0]; for (int i = 1; i < n; i++) { cur_max = max(arr[i], cur_max + arr[i]); max_so_far = max(max_so_far, cur_max); // storing current maximum till ith, in // forward array fw[i] = cur_max; } // calculating maximum sum subarrays in backward // direction cur_max = max_so_far = bw[n-1] = arr[n-1]; for (int i = n-2; i >= 0; i--) { cur_max = max(arr[i], cur_max + arr[i]); max_so_far = max(max_so_far, cur_max); // storing current maximum from ith, in // backward array bw[i] = cur_max; } /* Initializing final ans by max_so_far so that, case when no element is removed to get max sum subarray is also handled */ int fans = max_so_far; // choosing maximum ignoring ith element for (int i = 1; i < n - 1; i++) fans = max(fans,max(0, fw[i - 1]) +max(0, bw[i + 1])); // In this condition we are checking when removing the ith element // so checking the max(0,left)+max(0,right), because maybe // left<0 || right<0 so it wont contribute to the answer if(fans==0){ // if no positive element in array so return max_element return *max_element(arr,arr+n); } return fans; } // Driver code to test above methodsint main(){ int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(arr) / sizeof(arr[0]); cout << maxSumSubarrayRemovingOneEle(arr, n); return 0;}
// Java program to get maximum sum subarray// removing at-most one elementclass GFG { // Method returns maximum sum of all subarray where // removing one element is also allowed static int maxSumSubarrayRemovingOneEle(int arr[], int n) { // Maximum sum subarrays in forward and // backward directions int fw[] = new int[n]; int bw[] = new int[n]; // Initialize current max and max so far. int cur_max = arr[0], max_so_far = arr[0]; // calculating maximum sum subarrays in forward // direction fw[0] = arr[0]; for (int i = 1; i < n; i++) { cur_max = Math.max(arr[i], cur_max + arr[i]); max_so_far = Math.max(max_so_far, cur_max); // storing current maximum till ith, in // forward array fw[i] = cur_max; } // calculating maximum sum subarrays in backward // direction cur_max = max_so_far = bw[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) { cur_max = Math.max(arr[i], cur_max + arr[i]); max_so_far = Math.max(max_so_far, cur_max); // storing current maximum from ith, in // backward array bw[i] = cur_max; } /* Initializing final ans by max_so_far so that, case when no element is removed to get max sum subarray is also handled */ int fans = max_so_far; // choosing maximum ignoring ith element for (int i = 1; i < n - 1; i++) fans = Math.max(fans, fw[i - 1] + bw[i + 1]); return fans; } // Driver code public static void main(String arg[]) { int arr[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n = arr.length; System.out.print(maxSumSubarrayRemovingOneEle( arr, n)); }} // This code is contributed by Anant Agarwal.
# Python program to get maximum sum subarray removing# at-most one element # Method returns maximum sum of all subarray where# removing one element is also alloweddef maxSumSubarrayRemovingOneEle(arr, n): # Maximum sum subarrays in forward and backward # directions fw = [0 for k in range(n)] bw = [0 for k in range(n)] # Initialize current max and max so far. cur_max, max_so_far = arr[0], arr[0] fw[0] = cur_max # calculating maximum sum subarrays in forward # direction for i in range(1,n): cur_max = max(arr[i], cur_max + arr[i]) max_so_far = max(max_so_far, cur_max) # storing current maximum till ith, in # forward array fw[i] = cur_max # calculating maximum sum subarrays in backward # direction cur_max = max_so_far = bw[n-1] = arr[n-1] i = n-2 while i >= 0: cur_max = max(arr[i], cur_max + arr[i]) max_so_far = max(max_so_far, cur_max) # storing current maximum from ith, in # backward array bw[i] = cur_max i -= 1 # Initializing final ans by max_so_far so that, # case when no element is removed to get max sum # subarray is also handled fans = max_so_far # choosing maximum ignoring ith element for i in range(1,n-1): fans = max(fans, fw[i - 1] + bw[i + 1]) return fans # Driver code to test above methodsarr = [-2, -3, 4, -1, -2, 1, 5, -3]n = len(arr)print (maxSumSubarrayRemovingOneEle(arr, n)) # Contributed by: Afzal_Saan
// C# program to get maximum sum subarray// removing at-most one elementusing System;class GFG { // Method returns maximum sum of all subarray where // removing one element is also allowed static int maxSumSubarrayRemovingOneEle(int []arr, int n) { // Maximum sum subarrays in forward and // backward directions int []fw = new int[n]; int []bw = new int[n]; // Initialize current max and max so far. int cur_max = arr[0], max_so_far = arr[0]; // calculating maximum sum subarrays in forward // direction fw[0] = arr[0]; for (int i = 1; i < n; i++) { cur_max = Math.Max(arr[i], cur_max + arr[i]); max_so_far = Math.Max(max_so_far, cur_max); // storing current maximum till ith, in // forward array fw[i] = cur_max; } // calculating maximum sum subarrays in backward // direction cur_max = max_so_far = bw[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) { cur_max = Math.Max(arr[i], cur_max + arr[i]); max_so_far = Math.Max(max_so_far, cur_max); // storing current maximum from ith, in // backward array bw[i] = cur_max; } /* Initializing final ans by max_so_far so that, case when no element is removed to get max sum subarray is also handled */ int fans = max_so_far; // choosing maximum ignoring ith element for (int i = 1; i < n - 1; i++) fans = Math.Max(fans, fw[i - 1] + bw[i + 1]); return fans; } // Driver code public static void Main() { int []arr = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n = arr.Length; Console.WriteLine(maxSumSubarrayRemovingOneEle( arr, n)); }} // This code is contributed by anuj_67.
<?php// PHP program to get maximum// sum subarray removing// at-most one element // Method returns maximum sum// of all subarray where removing// one element is also allowedfunction maxSumSubarrayRemovingOneEle( $arr, $n){ // Maximum sum subarrays in // forward and backward directions $fw = array(); $bw = array(); // Initialize current // max and max so far. $cur_max = $arr[0]; $max_so_far = $arr[0]; // calculating maximum sum // subarrays in forward direction $fw[0] = $arr[0]; for ($i = 1; $i < $n; $i++) { $cur_max = max($arr[$i], $cur_max + $arr[$i]); $max_so_far = max($max_so_far, $cur_max); // storing current maximum till // ith, in forward array $fw[$i] = $cur_max; } // calculating maximum sum // subarrays in backward direction $cur_max = $max_so_far = $bw[$n - 1] = $arr[$n - 1]; for ( $i = $n - 2; $i >= 0; $i--) { $cur_max = max($arr[$i], $cur_max + $arr[$i]); $max_so_far = max($max_so_far, $cur_max); // storing current maximum from // ith, in backward array $bw[$i] = $cur_max; } /* Initializing final ans by max_so_far so that, case when no element is removed to get max sum subarray is also handled */ $fans = $max_so_far; // choosing maximum // ignoring ith element for ($i = 1; $i < $n - 1; $i++) $fans = max($fans, $fw[$i - 1] + $bw[$i + 1]); return $fans;} // Driver Code$arr = array(-2, -3, 4, -1, -2, 1, 5, -3);$n = count($arr);echo maxSumSubarrayRemovingOneEle($arr, $n); // This code is contributed by anuj_67.?>
<script> // JavaScript program to get maximum sum subarray// removing at-most one element // Method returns maximum sum of all subarray where// removing one element is also allowedfunction maxSumSubarrayRemovingOneEle(arr, n){ // Maximum sum subarrays in forward and // backward directions let fw = []; let bw = []; // Initialize current max and max so far. let cur_max = arr[0], max_so_far = arr[0]; // calculating maximum sum subarrays in forward // direction fw[0] = arr[0]; for(let i = 1; i < n; i++) { cur_max = Math.max(arr[i], cur_max + arr[i]); max_so_far = Math.max(max_so_far, cur_max); // Storing current maximum till ith, // in forward array fw[i] = cur_max; } // Calculating maximum sum subarrays // in backward direction cur_max = max_so_far = bw[n - 1] = arr[n - 1]; for(let i = n - 2; i >= 0; i--) { cur_max = Math.max(arr[i], cur_max + arr[i]); max_so_far = Math.max(max_so_far, cur_max); // Storing current maximum from ith, in // backward array bw[i] = cur_max; } /* Initializing final ans by max_so_far so that, case when no element is removed to get max sum subarray is also handled */ let fans = max_so_far; // Choosing maximum ignoring ith element for(let i = 1; i < n - 1; i++) fans = Math.max(fans, fw[i - 1] + bw[i + 1]); return fans;} // Driver Codelet arr = [ -2, -3, 4, -1, -2, 1, 5, -3 ];let n = arr.length; document.write( maxSumSubarrayRemovingOneEle(arr, n)); </script>
Output :
9
Time Complexity : O(n) Auxiliary Space : O(n)
This article is contributed by Vinish Thanai If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
vt_m
rogerhong1996
code_hunt
drunkenstein
amartyaghoshgfg
hardikkoriintern
subarray
subarray-sum
Arrays
Dynamic Programming
Arrays
Dynamic Programming
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
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Find if there is a path between two vertices in an undirected graph
Subset Sum Problem | DP-25 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 167,
"s": 52,
"text": "Given an array, we need to find maximum sum subarray, removing one element is also allowed to get the maximum sum."
},
{
"code": null,
"e": 179,
"s": 167,
"text": "Examples : "
},
{
"code": null,
"e": 474,
"s": 179,
"text": "Input : arr[] = {1, 2, 3, -4, 5}\nOutput : 11\nExplanation : We can get maximum sum subarray by\nremoving -4.\n\nInput : arr[] = [-2, -3, 4, -1, -2, 1, 5, -3]\nOutput : 9\nExplanation : We can get maximum sum subarray by\nremoving -2 as, [4, -1, 1, 5] summing 9, which is \nthe maximum achievable sum."
},
{
"code": null,
"e": 839,
"s": 474,
"text": "If element removal condition is not applied, we can solve this problem using Kadane’s algorithm but here one element can be removed also for increasing maximum sum. This condition can be handled using two arrays, forward and backward array, these arrays store the current maximum subarray sum from starting to ith index, and from ith index to ending respectively. "
},
{
"code": null,
"e": 1074,
"s": 839,
"text": "In below code, two loops are written, first one stores maximum current sum in forward direction in fw[] and other loop stores the same in backward direction in bw[]. Getting current maximum and updation is same as Kadane’s algorithm. "
},
{
"code": null,
"e": 1335,
"s": 1074,
"text": "Now when both arrays are created, we can use them for one element removal conditions as follows, at each index i, maximum subarray sum after ignoring i’th element will be fw[i-1] + bw[i+1] so we loop for all possible i values and we choose maximum among them. "
},
{
"code": null,
"e": 1399,
"s": 1335,
"text": "Total time complexity and space complexity of solution is O(N) "
},
{
"code": null,
"e": 1415,
"s": 1399,
"text": "Implementation:"
},
{
"code": null,
"e": 1419,
"s": 1415,
"text": "C++"
},
{
"code": null,
"e": 1424,
"s": 1419,
"text": "Java"
},
{
"code": null,
"e": 1432,
"s": 1424,
"text": "Python3"
},
{
"code": null,
"e": 1435,
"s": 1432,
"text": "C#"
},
{
"code": null,
"e": 1439,
"s": 1435,
"text": "PHP"
},
{
"code": null,
"e": 1450,
"s": 1439,
"text": "Javascript"
},
{
"code": "// C++ program to get maximum sum subarray removing// at-most one element#include <bits/stdc++.h>using namespace std; // Method returns maximum sum of all subarray where// removing one element is also allowedint maxSumSubarrayRemovingOneEle(int arr[], int n){ // Maximum sum subarrays in forward and backward // directions int fw[n], bw[n]; // Initialize current max and max so far. int cur_max = arr[0], max_so_far = arr[0]; // calculating maximum sum subarrays in forward // direction fw[0] = arr[0]; for (int i = 1; i < n; i++) { cur_max = max(arr[i], cur_max + arr[i]); max_so_far = max(max_so_far, cur_max); // storing current maximum till ith, in // forward array fw[i] = cur_max; } // calculating maximum sum subarrays in backward // direction cur_max = max_so_far = bw[n-1] = arr[n-1]; for (int i = n-2; i >= 0; i--) { cur_max = max(arr[i], cur_max + arr[i]); max_so_far = max(max_so_far, cur_max); // storing current maximum from ith, in // backward array bw[i] = cur_max; } /* Initializing final ans by max_so_far so that, case when no element is removed to get max sum subarray is also handled */ int fans = max_so_far; // choosing maximum ignoring ith element for (int i = 1; i < n - 1; i++) fans = max(fans,max(0, fw[i - 1]) +max(0, bw[i + 1])); // In this condition we are checking when removing the ith element // so checking the max(0,left)+max(0,right), because maybe // left<0 || right<0 so it wont contribute to the answer if(fans==0){ // if no positive element in array so return max_element return *max_element(arr,arr+n); } return fans; } // Driver code to test above methodsint main(){ int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(arr) / sizeof(arr[0]); cout << maxSumSubarrayRemovingOneEle(arr, n); return 0;}",
"e": 3410,
"s": 1450,
"text": null
},
{
"code": "// Java program to get maximum sum subarray// removing at-most one elementclass GFG { // Method returns maximum sum of all subarray where // removing one element is also allowed static int maxSumSubarrayRemovingOneEle(int arr[], int n) { // Maximum sum subarrays in forward and // backward directions int fw[] = new int[n]; int bw[] = new int[n]; // Initialize current max and max so far. int cur_max = arr[0], max_so_far = arr[0]; // calculating maximum sum subarrays in forward // direction fw[0] = arr[0]; for (int i = 1; i < n; i++) { cur_max = Math.max(arr[i], cur_max + arr[i]); max_so_far = Math.max(max_so_far, cur_max); // storing current maximum till ith, in // forward array fw[i] = cur_max; } // calculating maximum sum subarrays in backward // direction cur_max = max_so_far = bw[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) { cur_max = Math.max(arr[i], cur_max + arr[i]); max_so_far = Math.max(max_so_far, cur_max); // storing current maximum from ith, in // backward array bw[i] = cur_max; } /* Initializing final ans by max_so_far so that, case when no element is removed to get max sum subarray is also handled */ int fans = max_so_far; // choosing maximum ignoring ith element for (int i = 1; i < n - 1; i++) fans = Math.max(fans, fw[i - 1] + bw[i + 1]); return fans; } // Driver code public static void main(String arg[]) { int arr[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n = arr.length; System.out.print(maxSumSubarrayRemovingOneEle( arr, n)); }} // This code is contributed by Anant Agarwal.",
"e": 5403,
"s": 3410,
"text": null
},
{
"code": "# Python program to get maximum sum subarray removing# at-most one element # Method returns maximum sum of all subarray where# removing one element is also alloweddef maxSumSubarrayRemovingOneEle(arr, n): # Maximum sum subarrays in forward and backward # directions fw = [0 for k in range(n)] bw = [0 for k in range(n)] # Initialize current max and max so far. cur_max, max_so_far = arr[0], arr[0] fw[0] = cur_max # calculating maximum sum subarrays in forward # direction for i in range(1,n): cur_max = max(arr[i], cur_max + arr[i]) max_so_far = max(max_so_far, cur_max) # storing current maximum till ith, in # forward array fw[i] = cur_max # calculating maximum sum subarrays in backward # direction cur_max = max_so_far = bw[n-1] = arr[n-1] i = n-2 while i >= 0: cur_max = max(arr[i], cur_max + arr[i]) max_so_far = max(max_so_far, cur_max) # storing current maximum from ith, in # backward array bw[i] = cur_max i -= 1 # Initializing final ans by max_so_far so that, # case when no element is removed to get max sum # subarray is also handled fans = max_so_far # choosing maximum ignoring ith element for i in range(1,n-1): fans = max(fans, fw[i - 1] + bw[i + 1]) return fans # Driver code to test above methodsarr = [-2, -3, 4, -1, -2, 1, 5, -3]n = len(arr)print (maxSumSubarrayRemovingOneEle(arr, n)) # Contributed by: Afzal_Saan",
"e": 6912,
"s": 5403,
"text": null
},
{
"code": "// C# program to get maximum sum subarray// removing at-most one elementusing System;class GFG { // Method returns maximum sum of all subarray where // removing one element is also allowed static int maxSumSubarrayRemovingOneEle(int []arr, int n) { // Maximum sum subarrays in forward and // backward directions int []fw = new int[n]; int []bw = new int[n]; // Initialize current max and max so far. int cur_max = arr[0], max_so_far = arr[0]; // calculating maximum sum subarrays in forward // direction fw[0] = arr[0]; for (int i = 1; i < n; i++) { cur_max = Math.Max(arr[i], cur_max + arr[i]); max_so_far = Math.Max(max_so_far, cur_max); // storing current maximum till ith, in // forward array fw[i] = cur_max; } // calculating maximum sum subarrays in backward // direction cur_max = max_so_far = bw[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) { cur_max = Math.Max(arr[i], cur_max + arr[i]); max_so_far = Math.Max(max_so_far, cur_max); // storing current maximum from ith, in // backward array bw[i] = cur_max; } /* Initializing final ans by max_so_far so that, case when no element is removed to get max sum subarray is also handled */ int fans = max_so_far; // choosing maximum ignoring ith element for (int i = 1; i < n - 1; i++) fans = Math.Max(fans, fw[i - 1] + bw[i + 1]); return fans; } // Driver code public static void Main() { int []arr = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n = arr.Length; Console.WriteLine(maxSumSubarrayRemovingOneEle( arr, n)); }} // This code is contributed by anuj_67.",
"e": 8897,
"s": 6912,
"text": null
},
{
"code": "<?php// PHP program to get maximum// sum subarray removing// at-most one element // Method returns maximum sum// of all subarray where removing// one element is also allowedfunction maxSumSubarrayRemovingOneEle( $arr, $n){ // Maximum sum subarrays in // forward and backward directions $fw = array(); $bw = array(); // Initialize current // max and max so far. $cur_max = $arr[0]; $max_so_far = $arr[0]; // calculating maximum sum // subarrays in forward direction $fw[0] = $arr[0]; for ($i = 1; $i < $n; $i++) { $cur_max = max($arr[$i], $cur_max + $arr[$i]); $max_so_far = max($max_so_far, $cur_max); // storing current maximum till // ith, in forward array $fw[$i] = $cur_max; } // calculating maximum sum // subarrays in backward direction $cur_max = $max_so_far = $bw[$n - 1] = $arr[$n - 1]; for ( $i = $n - 2; $i >= 0; $i--) { $cur_max = max($arr[$i], $cur_max + $arr[$i]); $max_so_far = max($max_so_far, $cur_max); // storing current maximum from // ith, in backward array $bw[$i] = $cur_max; } /* Initializing final ans by max_so_far so that, case when no element is removed to get max sum subarray is also handled */ $fans = $max_so_far; // choosing maximum // ignoring ith element for ($i = 1; $i < $n - 1; $i++) $fans = max($fans, $fw[$i - 1] + $bw[$i + 1]); return $fans;} // Driver Code$arr = array(-2, -3, 4, -1, -2, 1, 5, -3);$n = count($arr);echo maxSumSubarrayRemovingOneEle($arr, $n); // This code is contributed by anuj_67.?>",
"e": 10664,
"s": 8897,
"text": null
},
{
"code": "<script> // JavaScript program to get maximum sum subarray// removing at-most one element // Method returns maximum sum of all subarray where// removing one element is also allowedfunction maxSumSubarrayRemovingOneEle(arr, n){ // Maximum sum subarrays in forward and // backward directions let fw = []; let bw = []; // Initialize current max and max so far. let cur_max = arr[0], max_so_far = arr[0]; // calculating maximum sum subarrays in forward // direction fw[0] = arr[0]; for(let i = 1; i < n; i++) { cur_max = Math.max(arr[i], cur_max + arr[i]); max_so_far = Math.max(max_so_far, cur_max); // Storing current maximum till ith, // in forward array fw[i] = cur_max; } // Calculating maximum sum subarrays // in backward direction cur_max = max_so_far = bw[n - 1] = arr[n - 1]; for(let i = n - 2; i >= 0; i--) { cur_max = Math.max(arr[i], cur_max + arr[i]); max_so_far = Math.max(max_so_far, cur_max); // Storing current maximum from ith, in // backward array bw[i] = cur_max; } /* Initializing final ans by max_so_far so that, case when no element is removed to get max sum subarray is also handled */ let fans = max_so_far; // Choosing maximum ignoring ith element for(let i = 1; i < n - 1; i++) fans = Math.max(fans, fw[i - 1] + bw[i + 1]); return fans;} // Driver Codelet arr = [ -2, -3, 4, -1, -2, 1, 5, -3 ];let n = arr.length; document.write( maxSumSubarrayRemovingOneEle(arr, n)); </script>",
"e": 12281,
"s": 10664,
"text": null
},
{
"code": null,
"e": 12291,
"s": 12281,
"text": "Output : "
},
{
"code": null,
"e": 12293,
"s": 12291,
"text": "9"
},
{
"code": null,
"e": 12339,
"s": 12293,
"text": "Time Complexity : O(n) Auxiliary Space : O(n)"
},
{
"code": null,
"e": 12636,
"s": 12339,
"text": "This article is contributed by Vinish Thanai If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 12641,
"s": 12636,
"text": "vt_m"
},
{
"code": null,
"e": 12655,
"s": 12641,
"text": "rogerhong1996"
},
{
"code": null,
"e": 12665,
"s": 12655,
"text": "code_hunt"
},
{
"code": null,
"e": 12678,
"s": 12665,
"text": "drunkenstein"
},
{
"code": null,
"e": 12694,
"s": 12678,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 12711,
"s": 12694,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 12720,
"s": 12711,
"text": "subarray"
},
{
"code": null,
"e": 12733,
"s": 12720,
"text": "subarray-sum"
},
{
"code": null,
"e": 12740,
"s": 12733,
"text": "Arrays"
},
{
"code": null,
"e": 12760,
"s": 12740,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 12767,
"s": 12760,
"text": "Arrays"
},
{
"code": null,
"e": 12787,
"s": 12767,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 12885,
"s": 12787,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12953,
"s": 12885,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 12997,
"s": 12953,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 13029,
"s": 12997,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 13077,
"s": 13029,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 13091,
"s": 13077,
"text": "Linear Search"
},
{
"code": null,
"e": 13121,
"s": 13091,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 13150,
"s": 13121,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 13184,
"s": 13150,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 13252,
"s": 13184,
"text": "Find if there is a path between two vertices in an undirected graph"
}
]
|
Zoho Interview | Set 3 (Off-Campus) | 22 Jul, 2019
Hi!! I recently attended ZOHO off-campus drive.
ROUND 1: WRITTENAPTITUDE(1 hr and 20 minutes-20 questions): Problems on average, probability, time & distance, alligation&mixture,ratio, HCF & LCM and few a puzzles.
TECHNICAL(45 minutes-10 questions): Output for C questions. Practice questions in geekquiz.com and C output questions in geeksforgeeks.org. Questions in pointers, strings, matrix etc.
Nearly 60 students were selected out of 600 candidates. They didn’t select the top 60. They had a cutoff and those who cleared the cutoff were called for the next round
ROUND 2: SIMPLE CODING(3 hours)
1. Write a program to give the following output for the given input
Eg 1: Input: a1b10
Output: abbbbbbbbbb
Eg: 2: Input: b3c6d15
Output: bbbccccccddddddddddddddd
The number varies from 1 to 99.
2. Write a program to sort the elements in odd positions in descending order and elements in ascending order
Eg 1: Input: 13,2 4,15,12,10,5
Output: 13,2,12,10,5,15,4
Eg 2: Input: 1,2,3,4,5,6,7,8,9
Output: 9,2,7,4,5,6,3,8,1
3. Write a program to print the following output for the given input. You can assume the string is of odd length
Eg 1: Input: 12345
Output:
1 5
2 4
3
2 4
1 5
Eg 2: Input: geeksforgeeks
Output:
g s
e k
e e
k e
s g
f r
o
f r
s g
k e
e e
e k
g s
4. Find if a String2 is substring of String1. If it is, return the index of the first occurrence. else return -1.
Eg 1:Input:
String 1: test123string
String 2: 123
Output: 4
Eg 2: Input:
String 1: testing12
String 2: 1234
Output: -1
5. Given two sorted arrays, merge them such that the elements are not repeated
Eg 1: Input:
Array 1: 2,4,5,6,7,9,10,13
Array 2: 2,3,4,5,6,7,8,9,11,15
Output:
Merged array: 2,3,4,5,6,7,8,9,10,11,13,15
6. Using Recursion reverse the string such as
Eg 1: Input: one two three
Output: three two one
Eg 2: Input: I love india
Output: india love I
19 cleared this round and they were called for the next round. The next round took place on the next day
ROUND 3: COMPLEX CODING(3 hours)
1) Design a Call taxi booking application-There are n number of taxi’s. For simplicity, assume 4. But it should work for any number of taxi’s.-The are 6 points(A,B,C,D,E,F)-All the points are in a straight line, and each point is 15kms away from the adjacent points.-It takes 60 mins to travel from one point to another-Each taxi charges Rs.100 minimum for the first 5 kilometers and Rs.10 for the subsequent kilometers.-For simplicity, time can be entered as absolute time. Eg: 9hrs, 15hrs etc.-All taxi’s are initially stationed at A.-When a customer books a Taxi, a free taxi at that point is allocated-If no free taxi is available at that point, a free taxi at the nearest point is allocated.-If two taxi’s are free at the same point, one with lower earning is allocated-Note that the taxi only charges the customer from the pickup point to the drop point. Not the distance it travels from an adjacent point to pickup the customer.-If no taxi is free at that time, booking is rejected
Design modules for
1) Call taxi booking
Input 1:
Customer ID: 1
Pickup Point: A
Drop Point: B
Pickup Time: 9
Output 1:
Taxi can be allotted.
Taxi-1 is allotted
Input 2:
Customer ID: 2
Pickup Point: B
Drop Point: D
Pickup Time: 9
Output 1:
Taxi can be allotted.
Taxi-2 is allotted
(Note: Since Taxi-1 would have completed its journey when second booking is done, so Taxi-2 from nearest point A which is free is allocated)
Input 3:
Customer ID: 3
Pickup Point: B
Drop Point: C
Pickup Time: 12
Output 1:
Taxi can be allotted.
Taxi-1 is allotted
2) Display the Taxi details
Taxi No: Total Earnings:
BookingID CustomerID From To PickupTime DropTime Amount
Output:
Taxi-1 Total Earnings: Rs. 400
1 1 A B 9 10 200
3 3 B C 12 13 200
Taxi-2 Total Earnings: Rs. 350
2 2 B D 9 11 350
These were just sample inputs. It should work for any input that they give.Those who finished both the modules within 3 hours and if it worked for all the inputs they give, those candidates were given extra modules to work with.
Only 9 candidates made it to the next round
ROUND 4 : FIRST FACE-TO-FACE(TECHNICAL)Questions were on project, c, oops concepts, DBMS and a few puzzles. They might ask you more on new scenarios relating to your project.
ROUND 5: SECOND FACE-TO-FACE(TECHNICAL)Question were on c, c++, java(like threads, synchronization etc.), Discussion about questions from first, second and third round. He even asked me to solve a few questions from the first round. He gave me a few puzzles to solve
ROUND 6: FIRST GENERAL HRGeneral questions about my pros and cons and discussion on my resume(be thorough with your resume). She finally asked me if I had any queries.
ROUND 7: SECOND GENERAL HRShe asked me some family details and gave some scenarios and asked me to what I will do in such situations(like if I am given the power to change 3 things in india, what all will I change) and a few general questions.
I didn’t get direct placement in ZOHO but I got an internship offer. If I perform well in my internship, I will get an offer. Round 3 was the toughest and if you perform exceptionally well and as they expect in that round, you will definitely make it through. Many thanks to geeksforgeeks.org for helping me out in my preparation.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Zoho
Interview Experiences
Zoho
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jul, 2019"
},
{
"code": null,
"e": 102,
"s": 54,
"text": "Hi!! I recently attended ZOHO off-campus drive."
},
{
"code": null,
"e": 268,
"s": 102,
"text": "ROUND 1: WRITTENAPTITUDE(1 hr and 20 minutes-20 questions): Problems on average, probability, time & distance, alligation&mixture,ratio, HCF & LCM and few a puzzles."
},
{
"code": null,
"e": 452,
"s": 268,
"text": "TECHNICAL(45 minutes-10 questions): Output for C questions. Practice questions in geekquiz.com and C output questions in geeksforgeeks.org. Questions in pointers, strings, matrix etc."
},
{
"code": null,
"e": 621,
"s": 452,
"text": "Nearly 60 students were selected out of 600 candidates. They didn’t select the top 60. They had a cutoff and those who cleared the cutoff were called for the next round"
},
{
"code": null,
"e": 653,
"s": 621,
"text": "ROUND 2: SIMPLE CODING(3 hours)"
},
{
"code": null,
"e": 721,
"s": 653,
"text": "1. Write a program to give the following output for the given input"
},
{
"code": null,
"e": 864,
"s": 721,
"text": "Eg 1: Input: a1b10\n Output: abbbbbbbbbb\nEg: 2: Input: b3c6d15\n Output: bbbccccccddddddddddddddd\nThe number varies from 1 to 99."
},
{
"code": null,
"e": 973,
"s": 864,
"text": "2. Write a program to sort the elements in odd positions in descending order and elements in ascending order"
},
{
"code": null,
"e": 1104,
"s": 973,
"text": "Eg 1: Input: 13,2 4,15,12,10,5\n Output: 13,2,12,10,5,15,4\nEg 2: Input: 1,2,3,4,5,6,7,8,9\n Output: 9,2,7,4,5,6,3,8,1 "
},
{
"code": null,
"e": 1217,
"s": 1104,
"text": "3. Write a program to print the following output for the given input. You can assume the string is of odd length"
},
{
"code": null,
"e": 1630,
"s": 1217,
"text": "Eg 1: Input: 12345\n Output:\n1 5\n 2 4\n 3\n 2 4\n1 5\nEg 2: Input: geeksforgeeks\n Output:\ng s\n e k\n e e\n k e\n s g\n f r\n o\n f r\n s g\n k e\n e e\n e k\ng s "
},
{
"code": null,
"e": 1744,
"s": 1630,
"text": "4. Find if a String2 is substring of String1. If it is, return the index of the first occurrence. else return -1."
},
{
"code": null,
"e": 1913,
"s": 1744,
"text": "Eg 1:Input:\n String 1: test123string\n String 2: 123\n Output: 4\nEg 2: Input:\n String 1: testing12\n String 2: 1234 \n Output: -1"
},
{
"code": null,
"e": 1992,
"s": 1913,
"text": "5. Given two sorted arrays, merge them such that the elements are not repeated"
},
{
"code": null,
"e": 2144,
"s": 1992,
"text": "Eg 1: Input:\n Array 1: 2,4,5,6,7,9,10,13\n Array 2: 2,3,4,5,6,7,8,9,11,15\n Output:\n Merged array: 2,3,4,5,6,7,8,9,10,11,13,15 "
},
{
"code": null,
"e": 2190,
"s": 2144,
"text": "6. Using Recursion reverse the string such as"
},
{
"code": null,
"e": 2299,
"s": 2190,
"text": "Eg 1: Input: one two three\n Output: three two one\nEg 2: Input: I love india\n Output: india love I "
},
{
"code": null,
"e": 2404,
"s": 2299,
"text": "19 cleared this round and they were called for the next round. The next round took place on the next day"
},
{
"code": null,
"e": 2437,
"s": 2404,
"text": "ROUND 3: COMPLEX CODING(3 hours)"
},
{
"code": null,
"e": 3426,
"s": 2437,
"text": "1) Design a Call taxi booking application-There are n number of taxi’s. For simplicity, assume 4. But it should work for any number of taxi’s.-The are 6 points(A,B,C,D,E,F)-All the points are in a straight line, and each point is 15kms away from the adjacent points.-It takes 60 mins to travel from one point to another-Each taxi charges Rs.100 minimum for the first 5 kilometers and Rs.10 for the subsequent kilometers.-For simplicity, time can be entered as absolute time. Eg: 9hrs, 15hrs etc.-All taxi’s are initially stationed at A.-When a customer books a Taxi, a free taxi at that point is allocated-If no free taxi is available at that point, a free taxi at the nearest point is allocated.-If two taxi’s are free at the same point, one with lower earning is allocated-Note that the taxi only charges the customer from the pickup point to the drop point. Not the distance it travels from an adjacent point to pickup the customer.-If no taxi is free at that time, booking is rejected"
},
{
"code": null,
"e": 3445,
"s": 3426,
"text": "Design modules for"
},
{
"code": null,
"e": 3714,
"s": 3445,
"text": "1) Call taxi booking \nInput 1:\nCustomer ID: 1\nPickup Point: A\nDrop Point: B\nPickup Time: 9\n\nOutput 1:\nTaxi can be allotted.\nTaxi-1 is allotted\n\nInput 2:\nCustomer ID: 2\nPickup Point: B\nDrop Point: D\nPickup Time: 9\n\nOutput 1:\nTaxi can be allotted.\nTaxi-2 is allotted "
},
{
"code": null,
"e": 3855,
"s": 3714,
"text": "(Note: Since Taxi-1 would have completed its journey when second booking is done, so Taxi-2 from nearest point A which is free is allocated)"
},
{
"code": null,
"e": 3979,
"s": 3855,
"text": "\nInput 3:\nCustomer ID: 3\nPickup Point: B\nDrop Point: C\nPickup Time: 12\n\nOutput 1:\nTaxi can be allotted.\nTaxi-1 is allotted "
},
{
"code": null,
"e": 4007,
"s": 3979,
"text": "2) Display the Taxi details"
},
{
"code": null,
"e": 4298,
"s": 4007,
"text": "\nTaxi No: Total Earnings:\nBookingID CustomerID From To PickupTime DropTime Amount\n \nOutput:\nTaxi-1 Total Earnings: Rs. 400\n\n1 1 A B 9 10 200\n3 3 B C 12 13 200\n\nTaxi-2 Total Earnings: Rs. 350\n2 2 B D 9 11 350 "
},
{
"code": null,
"e": 4527,
"s": 4298,
"text": "These were just sample inputs. It should work for any input that they give.Those who finished both the modules within 3 hours and if it worked for all the inputs they give, those candidates were given extra modules to work with."
},
{
"code": null,
"e": 4571,
"s": 4527,
"text": "Only 9 candidates made it to the next round"
},
{
"code": null,
"e": 4746,
"s": 4571,
"text": "ROUND 4 : FIRST FACE-TO-FACE(TECHNICAL)Questions were on project, c, oops concepts, DBMS and a few puzzles. They might ask you more on new scenarios relating to your project."
},
{
"code": null,
"e": 5013,
"s": 4746,
"text": "ROUND 5: SECOND FACE-TO-FACE(TECHNICAL)Question were on c, c++, java(like threads, synchronization etc.), Discussion about questions from first, second and third round. He even asked me to solve a few questions from the first round. He gave me a few puzzles to solve"
},
{
"code": null,
"e": 5181,
"s": 5013,
"text": "ROUND 6: FIRST GENERAL HRGeneral questions about my pros and cons and discussion on my resume(be thorough with your resume). She finally asked me if I had any queries."
},
{
"code": null,
"e": 5425,
"s": 5181,
"text": "ROUND 7: SECOND GENERAL HRShe asked me some family details and gave some scenarios and asked me to what I will do in such situations(like if I am given the power to change 3 things in india, what all will I change) and a few general questions."
},
{
"code": null,
"e": 5756,
"s": 5425,
"text": "I didn’t get direct placement in ZOHO but I got an internship offer. If I perform well in my internship, I will get an offer. Round 3 was the toughest and if you perform exceptionally well and as they expect in that round, you will definitely make it through. Many thanks to geeksforgeeks.org for helping me out in my preparation."
},
{
"code": null,
"e": 5977,
"s": 5756,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 5982,
"s": 5977,
"text": "Zoho"
},
{
"code": null,
"e": 6004,
"s": 5982,
"text": "Interview Experiences"
},
{
"code": null,
"e": 6009,
"s": 6004,
"text": "Zoho"
}
]
|
C# | Type.GetProperties() Method | 10 Dec, 2019
Type.GetProperties() Method is used to get the properties of the current Type. There are 2 methods in the overload list of this method as follows:
GetProperties() Method
GetProperties(BindingFlags) Method
This method is used to return all the public properties of the current Type.
Syntax: public System.Reflection.PropertyInfo[] GetProperties ();
Return Value: This method returns an array of PropertyInfo objects representing all public properties of the current Type or an empty array of type PropertyInfo if the current Type does not have public properties.
Below programs illustrate the use of Type.GetProperties() Method:
Example 1:
// C# program to demonstrate the// Type.GetProperties() Methodusing System;using System.Globalization;using System.Reflection; // Defining class Emptypublic class Empty { } class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(string); // try-catch block for handling Exception try { // using GetProperties() Method PropertyInfo[] type = objType.GetProperties(); // Display the Result Console.WriteLine("Properties of current type is: "); for (int i = 0; i < type.Length; i++) Console.WriteLine(" {0}", type[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Properties of current type is:
Int32 Length
Char Chars [Int32]
Example 2:
// C# program to demonstrate the// Type.GetProperties() Methodusing System;using System.Globalization;using System.Reflection; // Defining class Emptypublic class Empty {} class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(System.Type); // try-catch block for handling Exception try { // using GetProperties() Method PropertyInfo[] type = objType.GetProperties(); // Display the Result Console.WriteLine("Properties of current type is: "); for (int i = 0; i < 10; i++) Console.WriteLine(" {0}", type[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Properties of current type is:
System.Reflection.MemberTypes MemberType
System.Type DeclaringType
System.Reflection.MethodBase DeclaringMethod
System.Type ReflectedType
System.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute
System.Guid GUID
System.Reflection.Binder DefaultBinder
System.Reflection.Module Module
System.Reflection.Assembly Assembly
System.RuntimeTypeHandle TypeHandle
This method is used to search for the properties of the current Type, using the specified binding constraints when overridden in a derived class.
Syntax: public abstract System.Reflection.PropertyInfo[] GetProperties (System.Reflection.BindingFlags bindingAttr);Here, it takes a bitmask comprised of one or more BindingFlags that specify how the search is conducted or Zero, to return null.
Return Value: This method returns an array of PropertyInfo objects representing all properties of the current Type that match the specified binding constraints or an empty array of type PropertyInfo, if the current Type does not have properties, or if none of the properties match the binding constraints.
Example 1:
// C# program to demonstrate the// Type.GetProperties(BindingFlags)// Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Dog); // using GetProperties() Method PropertyInfo[] type = objType.GetProperties(BindingFlags.Instance | BindingFlags.Public); // Display the Result Console.WriteLine("Properties of current type is: "); for (int i = 0; i < type.Length; i++) Console.WriteLine(" {0}", type[i]); }} // Defining class Dogpublic class Dog { private string color, breed, type; // Constructor public Dog(string color, string breed, string type) { this.color = color; this.breed = breed; this.type = type; } // Color Property public String Color { get { return color; } } // Breed Property public String Breed { get { return breed; } } // Type Property public String Type { get { return type; } } // BloodGroup Property private String BloodGroup { get { return "AB+"; } }}
Properties of current type is:
System.String Color
System.String Breed
System.String Type
Example 2:
// C# program to demonstrate the// Type.GetProperties(BindingFlags)// Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Dog); // using GetProperties() Method PropertyInfo[] type = objType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic); // Display the Result Console.WriteLine("Properties of current type is: "); for (int i = 0; i < type.Length; i++) Console.WriteLine(" {0}", type[i]); }} // Defining class Dogpublic class Dog { private string color, breed, type, bp; // Constructor public Dog(string color, string breed, string type, string bp) { this.color = color; this.breed = breed; this.type = type; this.bp = bp; } // Color Property public String Color { get { return color; } } // Breed Property public String Breed { get { return breed; } } // Type Property public String Type { get { return type; } } // BloodGroup Property protected String BloodGroup { get { return "AB+"; } } // BloodPressure Property protected String BloodPressure { get { return bp; } }}
Properties of current type is:
System.String BloodGroup
System.String BloodPressure
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.type.getproperties?view=netframework-4.8
shubham_singh
CSharp-method
CSharp-Type-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Dec, 2019"
},
{
"code": null,
"e": 175,
"s": 28,
"text": "Type.GetProperties() Method is used to get the properties of the current Type. There are 2 methods in the overload list of this method as follows:"
},
{
"code": null,
"e": 198,
"s": 175,
"text": "GetProperties() Method"
},
{
"code": null,
"e": 233,
"s": 198,
"text": "GetProperties(BindingFlags) Method"
},
{
"code": null,
"e": 310,
"s": 233,
"text": "This method is used to return all the public properties of the current Type."
},
{
"code": null,
"e": 376,
"s": 310,
"text": "Syntax: public System.Reflection.PropertyInfo[] GetProperties ();"
},
{
"code": null,
"e": 590,
"s": 376,
"text": "Return Value: This method returns an array of PropertyInfo objects representing all public properties of the current Type or an empty array of type PropertyInfo if the current Type does not have public properties."
},
{
"code": null,
"e": 656,
"s": 590,
"text": "Below programs illustrate the use of Type.GetProperties() Method:"
},
{
"code": null,
"e": 667,
"s": 656,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Type.GetProperties() Methodusing System;using System.Globalization;using System.Reflection; // Defining class Emptypublic class Empty { } class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(string); // try-catch block for handling Exception try { // using GetProperties() Method PropertyInfo[] type = objType.GetProperties(); // Display the Result Console.WriteLine(\"Properties of current type is: \"); for (int i = 0; i < type.Length; i++) Console.WriteLine(\" {0}\", type[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 1630,
"s": 667,
"text": null
},
{
"code": null,
"e": 1697,
"s": 1630,
"text": "Properties of current type is: \n Int32 Length\n Char Chars [Int32]\n"
},
{
"code": null,
"e": 1708,
"s": 1697,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the// Type.GetProperties() Methodusing System;using System.Globalization;using System.Reflection; // Defining class Emptypublic class Empty {} class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(System.Type); // try-catch block for handling Exception try { // using GetProperties() Method PropertyInfo[] type = objType.GetProperties(); // Display the Result Console.WriteLine(\"Properties of current type is: \"); for (int i = 0; i < 10; i++) Console.WriteLine(\" {0}\", type[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 2667,
"s": 1708,
"text": null
},
{
"code": null,
"e": 3083,
"s": 2667,
"text": "Properties of current type is: \n System.Reflection.MemberTypes MemberType\n System.Type DeclaringType\n System.Reflection.MethodBase DeclaringMethod\n System.Type ReflectedType\n System.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute\n System.Guid GUID\n System.Reflection.Binder DefaultBinder\n System.Reflection.Module Module\n System.Reflection.Assembly Assembly\n System.RuntimeTypeHandle TypeHandle\n"
},
{
"code": null,
"e": 3229,
"s": 3083,
"text": "This method is used to search for the properties of the current Type, using the specified binding constraints when overridden in a derived class."
},
{
"code": null,
"e": 3474,
"s": 3229,
"text": "Syntax: public abstract System.Reflection.PropertyInfo[] GetProperties (System.Reflection.BindingFlags bindingAttr);Here, it takes a bitmask comprised of one or more BindingFlags that specify how the search is conducted or Zero, to return null."
},
{
"code": null,
"e": 3780,
"s": 3474,
"text": "Return Value: This method returns an array of PropertyInfo objects representing all properties of the current Type that match the specified binding constraints or an empty array of type PropertyInfo, if the current Type does not have properties, or if none of the properties match the binding constraints."
},
{
"code": null,
"e": 3791,
"s": 3780,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Type.GetProperties(BindingFlags)// Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Dog); // using GetProperties() Method PropertyInfo[] type = objType.GetProperties(BindingFlags.Instance | BindingFlags.Public); // Display the Result Console.WriteLine(\"Properties of current type is: \"); for (int i = 0; i < type.Length; i++) Console.WriteLine(\" {0}\", type[i]); }} // Defining class Dogpublic class Dog { private string color, breed, type; // Constructor public Dog(string color, string breed, string type) { this.color = color; this.breed = breed; this.type = type; } // Color Property public String Color { get { return color; } } // Breed Property public String Breed { get { return breed; } } // Type Property public String Type { get { return type; } } // BloodGroup Property private String BloodGroup { get { return \"AB+\"; } }}",
"e": 5008,
"s": 3791,
"text": null
},
{
"code": null,
"e": 5103,
"s": 5008,
"text": "Properties of current type is: \n System.String Color\n System.String Breed\n System.String Type\n"
},
{
"code": null,
"e": 5114,
"s": 5103,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the// Type.GetProperties(BindingFlags)// Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Dog); // using GetProperties() Method PropertyInfo[] type = objType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic); // Display the Result Console.WriteLine(\"Properties of current type is: \"); for (int i = 0; i < type.Length; i++) Console.WriteLine(\" {0}\", type[i]); }} // Defining class Dogpublic class Dog { private string color, breed, type, bp; // Constructor public Dog(string color, string breed, string type, string bp) { this.color = color; this.breed = breed; this.type = type; this.bp = bp; } // Color Property public String Color { get { return color; } } // Breed Property public String Breed { get { return breed; } } // Type Property public String Type { get { return type; } } // BloodGroup Property protected String BloodGroup { get { return \"AB+\"; } } // BloodPressure Property protected String BloodPressure { get { return bp; } }}",
"e": 6491,
"s": 5114,
"text": null
},
{
"code": null,
"e": 6579,
"s": 6491,
"text": "Properties of current type is: \n System.String BloodGroup\n System.String BloodPressure\n"
},
{
"code": null,
"e": 6590,
"s": 6579,
"text": "Reference:"
},
{
"code": null,
"e": 6682,
"s": 6590,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.type.getproperties?view=netframework-4.8"
},
{
"code": null,
"e": 6696,
"s": 6682,
"text": "shubham_singh"
},
{
"code": null,
"e": 6710,
"s": 6696,
"text": "CSharp-method"
},
{
"code": null,
"e": 6728,
"s": 6710,
"text": "CSharp-Type-Class"
},
{
"code": null,
"e": 6731,
"s": 6728,
"text": "C#"
}
]
|
Setting python3 as Default in Linux | 23 Jul, 2020
Python 2 support ended on 1-January-2020, and many major projects already signed the Python 3 Statement that declares that they will remove Python 2 support. However many of us prefer to code on python interpreter for tiny code snippets, instead of making .py files. And when we fire command ‘python’ on the terminal, interpreter of python2 gets launched by default.
Which leaves us with no choice other than, explicitly typing python3. However, we can set python3 as default by firing two commands on terminal
echo "alias python='python3'" >> .bashrc
source .bashrc
Now if we check in the terminal by just running the “python” command it would result in the following:
The interpreter of python 3 was launched, rather than an interpreter of python2. We basically wrote a permanent alias in .bashrc, which replaces command python as python3 and we reloaded the .bashrc file.
Linux-Unix
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jul, 2020"
},
{
"code": null,
"e": 397,
"s": 28,
"text": "Python 2 support ended on 1-January-2020, and many major projects already signed the Python 3 Statement that declares that they will remove Python 2 support. However many of us prefer to code on python interpreter for tiny code snippets, instead of making .py files. And when we fire command ‘python’ on the terminal, interpreter of python2 gets launched by default. "
},
{
"code": null,
"e": 541,
"s": 397,
"text": "Which leaves us with no choice other than, explicitly typing python3. However, we can set python3 as default by firing two commands on terminal"
},
{
"code": null,
"e": 598,
"s": 541,
"text": "echo \"alias python='python3'\" >> .bashrc\nsource .bashrc\n"
},
{
"code": null,
"e": 701,
"s": 598,
"text": "Now if we check in the terminal by just running the “python” command it would result in the following:"
},
{
"code": null,
"e": 906,
"s": 701,
"text": "The interpreter of python 3 was launched, rather than an interpreter of python2. We basically wrote a permanent alias in .bashrc, which replaces command python as python3 and we reloaded the .bashrc file."
},
{
"code": null,
"e": 917,
"s": 906,
"text": "Linux-Unix"
},
{
"code": null,
"e": 924,
"s": 917,
"text": "Python"
}
]
|
Mathematics | Predicates and Quantifiers | Set 1 | 03 Jul, 2021
Prerequisite : Introduction to Propositional Logic
IntroductionConsider the following example. We need to convert the following sentence into a mathematical statement using propositional logic only.
"Every person who is 18 years or older, is eligible to vote."
The above statement cannot be adequately expressed using only propositional logic. The problem in trying to do so is that propositional logic is not expressive enough to deal with quantified variables. It would have been easier if the statement were referring to a specific person. But since it is not the case and the statement applies to all people who are 18 years or older, we are stuck.Therefore we need a more powerful type of logic.
Predicate LogicPredicate logic is an extension of Propositional logic. It adds the concept of predicates and quantifiers to better capture the meaning of statements that cannot be adequately expressed by propositional logic.
What is a predicate?
Consider the statement, “ is greater than 3′′. It has two parts. The first part, the variable , is the subject of the statement. The second part, “is greater than 3”, is the predicate. It refers to a property that the subject of the statement can have.The statement “ is greater than 3′′ can be denoted by where denotes the predicate “is greater than 3” and is the variable.The predicate can be considered as a function. It tells the truth value of the statement at . Once a value has been assigned to the variable , the statement becomes a proposition and has a truth or false(tf) value.In general, a statement involving n variables can be denoted by . Here is also referred to as n-place predicate or a n-ary predicate.
Example 1: Let denote the statement “ > 10′′. What are the truth values of and ?Solution: is equivalent to the statement 11 > 10, which is True. is equivalent to the statement 5 > 10, which is False.
Solution: is equivalent to the statement 11 > 10, which is True. is equivalent to the statement 5 > 10, which is False.
Example 2: Let denote the statement ““. What is the truth value of the propositions and ?Solution: is the statement 1 = 3 + 1, which is False. is the statement 2 = 1 + 1, which is True.
What are quantifiers?
In predicate logic, predicates are used alongside quantifiers to express the extent to which a predicate is true over a range of elements. Using quantifiers to create such propositions is called quantification.
There are two types of quantification-
1. Universal Quantification- Mathematical statements sometimes assert that a property is true for all the values of a variable in a particular domain, called the domain of discourse. Such a statement is expressed using universal quantification.The universal quantification of for a particular domain is the proposition that asserts that is true for all values of in this domain. The domain is very important here since it decides the possible values of . The meaning of the universal quantification of changes when the domain is changed. The domain must be specified when a universal quantification is used, as without it, it has no meaning.
Formally,
The universal quantification of is the statement
" for all values of in the domain"
The notation denotes the universal quantification of .
Here is called the universal quantifier.
is read as "for all ".
Example 1: Let be the statement “ > “. What is the truth value of the statement ?Solution: As is greater than for any real number, so for all or .
2. Existential Quantification- Some mathematical statements assert that there is an element with a certain property. Such statements are expressed by existential quantification. Existential quantification can be used to form a proposition that is true if and only if is true for at least one value of in the domain.
Formally,
The existential quantification of is the statement
"There exists an element in the domain such that "
The notation denotes the existential quantification of .
Here is called the existential quantifier.
is read as "There is atleast one such such that ".
Example : Let be the statement “ > 5′′. What is the truth value of the statement ?Solution: is true for all real numbers greater than 5 and false for all real numbers less than 5. So .
To summarise,
Now if we try to convert the statement, given in the beginning of this article, into a mathematical statement using predicate logic, we would get something like-
Here, P(x) is the statement "x is 18 years or older and,
Q(x) is the statement "x is eligible to vote".
Notice that the given statement is not mentioned as a biconditional and yet we used one. This is because Natural language is ambiguous sometimes, and we made an assumption. This assumption was made since it is true that a person can vote if and only if he/she is 18 years or older. Refer Introduction to Propositional Logic for more explanation.
Other Quantifiers –Although the universal and existential quantifiers are the most important in Mathematics and Computer Science, they are not the only ones. In Fact, there is no limitation on the number of different quantifiers that can be defined, such as “exactly two”, “there are no more than three”, “there are at least 10”, and so on.Of all the other possible quantifiers, the one that is seen most often is the uniqueness quantifier, denoted by .
The notation states "There exists a unique such that is true".
Quantifiers with restricted domainsAs we know that quantifiers are meaningless if the variables they bind do not have a domain. The following abbreviated notation is used to restrict the domain of the variables- > 0, > 0.The above statement restricts the domain of , and is a shorthand for writing another proposition, that says , in the statement.If we try to rewrite this statement using an implication, we would get- > >Similarly, a statement using Existential quantifier can be restated using conjunction between the domain restricting proposition and the actual predicate.
Restriction of universal quantification is the same as the universal quantification of a conditional statement.Restriction of an existential quantification is the same as the existential quantification of conjunction.
Restriction of universal quantification is the same as the universal quantification of a conditional statement.
Restriction of an existential quantification is the same as the existential quantification of conjunction.
Definitions to Note:
1. Binding variables- A variable whose occurrence is bound by a quantifier is calleda bound variable. Variables not bound by any quantifiers are called free variables.2. Scope- The part of the logical expression to which a quantifier is applied is calledthe scope of the quantifier.
This topic has been covered in two parts. The second part of this topic is explained in another article – Predicates and Quantifiers – Set 2
References-First Order Logic – WikipediaQuantifiers – WikipediaDiscrete Mathematics and its Applications, by Kenneth H Rosen
This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
howdyganesh
VaibhavRai3
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jul, 2021"
},
{
"code": null,
"e": 103,
"s": 52,
"text": "Prerequisite : Introduction to Propositional Logic"
},
{
"code": null,
"e": 251,
"s": 103,
"text": "IntroductionConsider the following example. We need to convert the following sentence into a mathematical statement using propositional logic only."
},
{
"code": null,
"e": 314,
"s": 251,
"text": "\"Every person who is 18 years or older, is eligible to vote.\"\n"
},
{
"code": null,
"e": 754,
"s": 314,
"text": "The above statement cannot be adequately expressed using only propositional logic. The problem in trying to do so is that propositional logic is not expressive enough to deal with quantified variables. It would have been easier if the statement were referring to a specific person. But since it is not the case and the statement applies to all people who are 18 years or older, we are stuck.Therefore we need a more powerful type of logic."
},
{
"code": null,
"e": 979,
"s": 754,
"text": "Predicate LogicPredicate logic is an extension of Propositional logic. It adds the concept of predicates and quantifiers to better capture the meaning of statements that cannot be adequately expressed by propositional logic."
},
{
"code": null,
"e": 1000,
"s": 979,
"text": "What is a predicate?"
},
{
"code": null,
"e": 1730,
"s": 1000,
"text": "Consider the statement, “ is greater than 3′′. It has two parts. The first part, the variable , is the subject of the statement. The second part, “is greater than 3”, is the predicate. It refers to a property that the subject of the statement can have.The statement “ is greater than 3′′ can be denoted by where denotes the predicate “is greater than 3” and is the variable.The predicate can be considered as a function. It tells the truth value of the statement at . Once a value has been assigned to the variable , the statement becomes a proposition and has a truth or false(tf) value.In general, a statement involving n variables can be denoted by . Here is also referred to as n-place predicate or a n-ary predicate."
},
{
"code": null,
"e": 1933,
"s": 1730,
"text": "Example 1: Let denote the statement “ > 10′′. What are the truth values of and ?Solution: is equivalent to the statement 11 > 10, which is True. is equivalent to the statement 5 > 10, which is False."
},
{
"code": null,
"e": 2054,
"s": 1933,
"text": "Solution: is equivalent to the statement 11 > 10, which is True. is equivalent to the statement 5 > 10, which is False."
},
{
"code": null,
"e": 2244,
"s": 2054,
"text": "Example 2: Let denote the statement ““. What is the truth value of the propositions and ?Solution: is the statement 1 = 3 + 1, which is False. is the statement 2 = 1 + 1, which is True."
},
{
"code": null,
"e": 2266,
"s": 2244,
"text": "What are quantifiers?"
},
{
"code": null,
"e": 2477,
"s": 2266,
"text": "In predicate logic, predicates are used alongside quantifiers to express the extent to which a predicate is true over a range of elements. Using quantifiers to create such propositions is called quantification."
},
{
"code": null,
"e": 2516,
"s": 2477,
"text": "There are two types of quantification-"
},
{
"code": null,
"e": 3162,
"s": 2516,
"text": "1. Universal Quantification- Mathematical statements sometimes assert that a property is true for all the values of a variable in a particular domain, called the domain of discourse. Such a statement is expressed using universal quantification.The universal quantification of for a particular domain is the proposition that asserts that is true for all values of in this domain. The domain is very important here since it decides the possible values of . The meaning of the universal quantification of changes when the domain is changed. The domain must be specified when a universal quantification is used, as without it, it has no meaning."
},
{
"code": null,
"e": 3384,
"s": 3162,
"text": "Formally,\nThe universal quantification of is the statement\n\" for all values of in the domain\"\n\nThe notation denotes the universal quantification of .\nHere is called the universal quantifier.\n is read as \"for all \". \n"
},
{
"code": null,
"e": 3536,
"s": 3384,
"text": "Example 1: Let be the statement “ > “. What is the truth value of the statement ?Solution: As is greater than for any real number, so for all or ."
},
{
"code": null,
"e": 3854,
"s": 3536,
"text": "2. Existential Quantification- Some mathematical statements assert that there is an element with a certain property. Such statements are expressed by existential quantification. Existential quantification can be used to form a proposition that is true if and only if is true for at least one value of in the domain."
},
{
"code": null,
"e": 4127,
"s": 3854,
"text": "Formally,\nThe existential quantification of is the statement\n\"There exists an element in the domain such that \"\n\nThe notation denotes the existential quantification of .\nHere is called the existential quantifier. \n is read as \"There is atleast one such such that \". \n"
},
{
"code": null,
"e": 4316,
"s": 4127,
"text": "Example : Let be the statement “ > 5′′. What is the truth value of the statement ?Solution: is true for all real numbers greater than 5 and false for all real numbers less than 5. So ."
},
{
"code": null,
"e": 4330,
"s": 4316,
"text": "To summarise,"
},
{
"code": null,
"e": 4494,
"s": 4332,
"text": "Now if we try to convert the statement, given in the beginning of this article, into a mathematical statement using predicate logic, we would get something like-"
},
{
"code": null,
"e": 4601,
"s": 4494,
"text": "\nHere, P(x) is the statement \"x is 18 years or older and,\nQ(x) is the statement \"x is eligible to vote\".\n\n"
},
{
"code": null,
"e": 4947,
"s": 4601,
"text": "Notice that the given statement is not mentioned as a biconditional and yet we used one. This is because Natural language is ambiguous sometimes, and we made an assumption. This assumption was made since it is true that a person can vote if and only if he/she is 18 years or older. Refer Introduction to Propositional Logic for more explanation."
},
{
"code": null,
"e": 5401,
"s": 4947,
"text": "Other Quantifiers –Although the universal and existential quantifiers are the most important in Mathematics and Computer Science, they are not the only ones. In Fact, there is no limitation on the number of different quantifiers that can be defined, such as “exactly two”, “there are no more than three”, “there are at least 10”, and so on.Of all the other possible quantifiers, the one that is seen most often is the uniqueness quantifier, denoted by ."
},
{
"code": null,
"e": 5468,
"s": 5401,
"text": "The notation states \"There exists a unique such that is true\".\n"
},
{
"code": null,
"e": 6048,
"s": 5468,
"text": "Quantifiers with restricted domainsAs we know that quantifiers are meaningless if the variables they bind do not have a domain. The following abbreviated notation is used to restrict the domain of the variables- > 0, > 0.The above statement restricts the domain of , and is a shorthand for writing another proposition, that says , in the statement.If we try to rewrite this statement using an implication, we would get- > >Similarly, a statement using Existential quantifier can be restated using conjunction between the domain restricting proposition and the actual predicate."
},
{
"code": null,
"e": 6266,
"s": 6048,
"text": "Restriction of universal quantification is the same as the universal quantification of a conditional statement.Restriction of an existential quantification is the same as the existential quantification of conjunction."
},
{
"code": null,
"e": 6378,
"s": 6266,
"text": "Restriction of universal quantification is the same as the universal quantification of a conditional statement."
},
{
"code": null,
"e": 6485,
"s": 6378,
"text": "Restriction of an existential quantification is the same as the existential quantification of conjunction."
},
{
"code": null,
"e": 6506,
"s": 6485,
"text": "Definitions to Note:"
},
{
"code": null,
"e": 6789,
"s": 6506,
"text": "1. Binding variables- A variable whose occurrence is bound by a quantifier is calleda bound variable. Variables not bound by any quantifiers are called free variables.2. Scope- The part of the logical expression to which a quantifier is applied is calledthe scope of the quantifier."
},
{
"code": null,
"e": 6930,
"s": 6789,
"text": "This topic has been covered in two parts. The second part of this topic is explained in another article – Predicates and Quantifiers – Set 2"
},
{
"code": null,
"e": 7055,
"s": 6930,
"text": "References-First Order Logic – WikipediaQuantifiers – WikipediaDiscrete Mathematics and its Applications, by Kenneth H Rosen"
},
{
"code": null,
"e": 7353,
"s": 7055,
"text": "This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 7478,
"s": 7353,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 7490,
"s": 7478,
"text": "howdyganesh"
},
{
"code": null,
"e": 7502,
"s": 7490,
"text": "VaibhavRai3"
},
{
"code": null,
"e": 7526,
"s": 7502,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 7534,
"s": 7526,
"text": "GATE CS"
}
]
|
Check if two Integer are anagrams of each other | 18 May, 2022
Given two integers A and B, the task is to check whether the given numbers are anagrams of each other or not. Just like strings, a number is said to be an anagram of some other number if it can be made equal to the other number by just shuffling the digits in it.Examples:
Input: A = 204, B = 240 Output: Yes
Input: A = 23, B = 959 Output: No
Approach: Create two arrays freqA[] and freqB[] where freqA[i] and freqB[i] will store the frequency of digit i in a and b respectively. Now traverse the frequency arrays and for any digit i if freqA[i] != freqB[i] then the numbers are not anagrams of each other else they are.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; const int TEN = 10; // Function to update the frequency array// such that freq[i] stores the// frequency of digit i in nvoid updateFreq(int n, int freq[]){ // While there are digits // left to process while (n) { int digit = n % TEN; // Update the frequency of // the current digit freq[digit]++; // Remove the last digit n /= TEN; }} // Function that returns true if a and b// are anagarams of each otherbool areAnagrams(int a, int b){ // To store the frequencies of // the digits in a and b int freqA[TEN] = { 0 }; int freqB[TEN] = { 0 }; // Update the frequency of // the digits in a updateFreq(a, freqA); // Update the frequency of // the digits in b updateFreq(b, freqB); // Match the frequencies of // the common digits for (int i = 0; i < TEN; i++) { // If frequency differs for any digit // then the numbers are not // anagrams of each other if (freqA[i] != freqB[i]) return false; } return true;} // Driver codeint main(){ int a = 240, b = 204; if (areAnagrams(a, b)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation of the approachclass GFG{ static final int TEN = 10; // Function to update the frequency array // such that freq[i] stores the // frequency of digit i in n static void updateFreq(int n, int [] freq) { // While there are digits // left to process while (n > 0) { int digit = n % TEN; // Update the frequency of // the current digit freq[digit]++; // Remove the last digit n /= TEN; } } // Function that returns true if a and b // are anagarams of each other static boolean areAnagrams(int a, int b) { // To store the frequencies of // the digits in a and b int [] freqA = new int[TEN]; int [] freqB = new int[TEN]; // Update the frequency of // the digits in a updateFreq(a, freqA); // Update the frequency of // the digits in b updateFreq(b, freqB); // Match the frequencies of // the common digits for (int i = 0; i < TEN; i++) { // If frequency differs for any digit // then the numbers are not // anagrams of each other if (freqA[i] != freqB[i]) return false; } return true; } // Driver code public static void main (String[] args) { int a = 204, b = 240; if (areAnagrams(a, b)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by ihirtik
# Python3 implementation of the approachTEN = 10 # Function to update the frequency array# such that freq[i] stores the# frequency of digit i in ndef updateFreq(n, freq) : # While there are digits # left to process while (n) : digit = n % TEN # Update the frequency of # the current digit freq[digit] += 1 # Remove the last digit n //= TEN # Function that returns true if a and b# are anagarams of each otherdef areAnagrams(a, b): # To store the frequencies of # the digits in a and b freqA = [ 0 ] * TEN freqB = [ 0 ] * TEN # Update the frequency of # the digits in a updateFreq(a, freqA) # Update the frequency of # the digits in b updateFreq(b, freqB) # Match the frequencies of # the common digits for i in range(TEN): # If frequency differs for any digit # then the numbers are not # anagrams of each other if (freqA[i] != freqB[i]): return False return True # Driver codea = 240b = 204 if (areAnagrams(a, b)): print("Yes")else: print("No") # This code is contributed by# divyamohan123
// C# implementation of the approachusing System; class GFG{ static int TEN = 10; // Function to update the frequency array // such that freq[i] stores the // frequency of digit i in n static void updateFreq(int n, int [] freq) { // While there are digits // left to process while (n > 0) { int digit = n % TEN; // Update the frequency of // the current digit freq[digit]++; // Remove the last digit n /= TEN; } } // Function that returns true if a and b // are anagarams of each other static bool areAnagrams(int a, int b) { // To store the frequencies of // the digits in a and b int [] freqA = new int[TEN]; int [] freqB = new int[TEN];; // Update the frequency of // the digits in a updateFreq(a, freqA); // Update the frequency of // the digits in b updateFreq(b, freqB); // Match the frequencies of // the common digits for (int i = 0; i < TEN; i++) { // If frequency differs for any digit // then the numbers are not // anagrams of each other if (freqA[i] != freqB[i]) return false; } return true; } // Driver code public static void Main () { int a = 204, b = 240; if (areAnagrams(a, b)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by ihirtik
<script>// Javascript implementation of the approach const TEN = 10; // Function to update the frequency array// such that freq[i] stores the// frequency of digit i in nfunction updateFreq(n, freq){ // While there are digits // left to process while (n) { let digit = n % TEN; // Update the frequency of // the current digit freq[digit]++; // Remove the last digit n = parseInt(n / TEN); }} // Function that returns true if a and b// are anagarams of each otherfunction areAnagrams(a, b){ // To store the frequencies of // the digits in a and b let freqA = new Array(TEN).fill(0); let freqB = new Array(TEN).fill(0); // Update the frequency of // the digits in a updateFreq(a, freqA); // Update the frequency of // the digits in b updateFreq(b, freqB); // Match the frequencies of // the common digits for (let i = 0; i < TEN; i++) { // If frequency differs for any digit // then the numbers are not // anagrams of each other if (freqA[i] != freqB[i]) return false; } return true;} // Driver code let a = 240, b = 204; if (areAnagrams(a, b)) document.write("Yes"); else document.write("Yes"); </script>
Yes
Convert two integers to string.
Sort the strings and check if they are equal.
Print Yes if they are equal.
Else no.
Below is the implementation:
C++
Python3
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if a and b// are anagarams of each otherbool areAnagrams(int a, int b){ // Converting numbers to strings string c = to_string(a); string d = to_string(b); // Checking if the sorting values // of two strings are equal sort(c.begin(), c.end()); sort(d.begin(), d.end()); if (c == d) return true; else return false;} // Driver codeint main(){ int a = 240; int b = 204; if (areAnagrams(a, b)) cout << "Yes"; else cout << "No";} // This code is contributed by ukasp.
# Python3 implementation of the approach# Function that returns true if a and b# are anagarams of each otherdef areAnagrams(a, b): # Converting numbers to strings a = str(a) b = str(b) # Checking if the sorting values # of two strings are equal if(sorted(a) == sorted(b)): return True else: return False # Driver codea = 240b = 204 if (areAnagrams(a, b)): print("Yes")else: print("No") # This code is contributed by vikkycirus
<script> // JavaScript implementation of the approach// Function that returns true if a and b// are anagarams of each otherfunction areAnagrams(a, b){ // Converting numbers to strings a = a.toString().split("").sort().join("") b = b.toString().split("").sort().join("") // Checking if the sorting values // of two strings are equal if(a == b){ return true } else return false} // Driver codelet a = 240let b = 204 if (areAnagrams(a, b)) document.write("Yes")else document.write("No") // This code is contributed by shinjanpatra </script>
Output:
Yes
ihritik
divyamohan123
vikkycirus
subham348
ukasp
shinjanpatra
number-digits
Hash
Mathematical
Hash
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Longest Consecutive Subsequence
Counting frequencies of array elements
Sort string of characters
Hashing | Set 2 (Separate Chaining)
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": 28,
"s": 0,
"text": "\n18 May, 2022"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "Given two integers A and B, the task is to check whether the given numbers are anagrams of each other or not. Just like strings, a number is said to be an anagram of some other number if it can be made equal to the other number by just shuffling the digits in it.Examples: "
},
{
"code": null,
"e": 338,
"s": 302,
"text": "Input: A = 204, B = 240 Output: Yes"
},
{
"code": null,
"e": 373,
"s": 338,
"text": "Input: A = 23, B = 959 Output: No "
},
{
"code": null,
"e": 701,
"s": 373,
"text": "Approach: Create two arrays freqA[] and freqB[] where freqA[i] and freqB[i] will store the frequency of digit i in a and b respectively. Now traverse the frequency arrays and for any digit i if freqA[i] != freqB[i] then the numbers are not anagrams of each other else they are.Below is the implementation of the above approach:"
},
{
"code": null,
"e": 705,
"s": 701,
"text": "C++"
},
{
"code": null,
"e": 710,
"s": 705,
"text": "Java"
},
{
"code": null,
"e": 718,
"s": 710,
"text": "Python3"
},
{
"code": null,
"e": 721,
"s": 718,
"text": "C#"
},
{
"code": null,
"e": 732,
"s": 721,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int TEN = 10; // Function to update the frequency array// such that freq[i] stores the// frequency of digit i in nvoid updateFreq(int n, int freq[]){ // While there are digits // left to process while (n) { int digit = n % TEN; // Update the frequency of // the current digit freq[digit]++; // Remove the last digit n /= TEN; }} // Function that returns true if a and b// are anagarams of each otherbool areAnagrams(int a, int b){ // To store the frequencies of // the digits in a and b int freqA[TEN] = { 0 }; int freqB[TEN] = { 0 }; // Update the frequency of // the digits in a updateFreq(a, freqA); // Update the frequency of // the digits in b updateFreq(b, freqB); // Match the frequencies of // the common digits for (int i = 0; i < TEN; i++) { // If frequency differs for any digit // then the numbers are not // anagrams of each other if (freqA[i] != freqB[i]) return false; } return true;} // Driver codeint main(){ int a = 240, b = 204; if (areAnagrams(a, b)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 2011,
"s": 732,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ static final int TEN = 10; // Function to update the frequency array // such that freq[i] stores the // frequency of digit i in n static void updateFreq(int n, int [] freq) { // While there are digits // left to process while (n > 0) { int digit = n % TEN; // Update the frequency of // the current digit freq[digit]++; // Remove the last digit n /= TEN; } } // Function that returns true if a and b // are anagarams of each other static boolean areAnagrams(int a, int b) { // To store the frequencies of // the digits in a and b int [] freqA = new int[TEN]; int [] freqB = new int[TEN]; // Update the frequency of // the digits in a updateFreq(a, freqA); // Update the frequency of // the digits in b updateFreq(b, freqB); // Match the frequencies of // the common digits for (int i = 0; i < TEN; i++) { // If frequency differs for any digit // then the numbers are not // anagrams of each other if (freqA[i] != freqB[i]) return false; } return true; } // Driver code public static void main (String[] args) { int a = 204, b = 240; if (areAnagrams(a, b)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by ihirtik ",
"e": 3647,
"s": 2011,
"text": null
},
{
"code": "# Python3 implementation of the approachTEN = 10 # Function to update the frequency array# such that freq[i] stores the# frequency of digit i in ndef updateFreq(n, freq) : # While there are digits # left to process while (n) : digit = n % TEN # Update the frequency of # the current digit freq[digit] += 1 # Remove the last digit n //= TEN # Function that returns true if a and b# are anagarams of each otherdef areAnagrams(a, b): # To store the frequencies of # the digits in a and b freqA = [ 0 ] * TEN freqB = [ 0 ] * TEN # Update the frequency of # the digits in a updateFreq(a, freqA) # Update the frequency of # the digits in b updateFreq(b, freqB) # Match the frequencies of # the common digits for i in range(TEN): # If frequency differs for any digit # then the numbers are not # anagrams of each other if (freqA[i] != freqB[i]): return False return True # Driver codea = 240b = 204 if (areAnagrams(a, b)): print(\"Yes\")else: print(\"No\") # This code is contributed by# divyamohan123",
"e": 4797,
"s": 3647,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int TEN = 10; // Function to update the frequency array // such that freq[i] stores the // frequency of digit i in n static void updateFreq(int n, int [] freq) { // While there are digits // left to process while (n > 0) { int digit = n % TEN; // Update the frequency of // the current digit freq[digit]++; // Remove the last digit n /= TEN; } } // Function that returns true if a and b // are anagarams of each other static bool areAnagrams(int a, int b) { // To store the frequencies of // the digits in a and b int [] freqA = new int[TEN]; int [] freqB = new int[TEN];; // Update the frequency of // the digits in a updateFreq(a, freqA); // Update the frequency of // the digits in b updateFreq(b, freqB); // Match the frequencies of // the common digits for (int i = 0; i < TEN; i++) { // If frequency differs for any digit // then the numbers are not // anagrams of each other if (freqA[i] != freqB[i]) return false; } return true; } // Driver code public static void Main () { int a = 204, b = 240; if (areAnagrams(a, b)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by ihirtik",
"e": 6414,
"s": 4797,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach const TEN = 10; // Function to update the frequency array// such that freq[i] stores the// frequency of digit i in nfunction updateFreq(n, freq){ // While there are digits // left to process while (n) { let digit = n % TEN; // Update the frequency of // the current digit freq[digit]++; // Remove the last digit n = parseInt(n / TEN); }} // Function that returns true if a and b// are anagarams of each otherfunction areAnagrams(a, b){ // To store the frequencies of // the digits in a and b let freqA = new Array(TEN).fill(0); let freqB = new Array(TEN).fill(0); // Update the frequency of // the digits in a updateFreq(a, freqA); // Update the frequency of // the digits in b updateFreq(b, freqB); // Match the frequencies of // the common digits for (let i = 0; i < TEN; i++) { // If frequency differs for any digit // then the numbers are not // anagrams of each other if (freqA[i] != freqB[i]) return false; } return true;} // Driver code let a = 240, b = 204; if (areAnagrams(a, b)) document.write(\"Yes\"); else document.write(\"Yes\"); </script>",
"e": 7688,
"s": 6414,
"text": null
},
{
"code": null,
"e": 7692,
"s": 7688,
"text": "Yes"
},
{
"code": null,
"e": 7726,
"s": 7694,
"text": "Convert two integers to string."
},
{
"code": null,
"e": 7772,
"s": 7726,
"text": "Sort the strings and check if they are equal."
},
{
"code": null,
"e": 7801,
"s": 7772,
"text": "Print Yes if they are equal."
},
{
"code": null,
"e": 7810,
"s": 7801,
"text": "Else no."
},
{
"code": null,
"e": 7839,
"s": 7810,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 7843,
"s": 7839,
"text": "C++"
},
{
"code": null,
"e": 7851,
"s": 7843,
"text": "Python3"
},
{
"code": null,
"e": 7862,
"s": 7851,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if a and b// are anagarams of each otherbool areAnagrams(int a, int b){ // Converting numbers to strings string c = to_string(a); string d = to_string(b); // Checking if the sorting values // of two strings are equal sort(c.begin(), c.end()); sort(d.begin(), d.end()); if (c == d) return true; else return false;} // Driver codeint main(){ int a = 240; int b = 204; if (areAnagrams(a, b)) cout << \"Yes\"; else cout << \"No\";} // This code is contributed by ukasp.",
"e": 8508,
"s": 7862,
"text": null
},
{
"code": "# Python3 implementation of the approach# Function that returns true if a and b# are anagarams of each otherdef areAnagrams(a, b): # Converting numbers to strings a = str(a) b = str(b) # Checking if the sorting values # of two strings are equal if(sorted(a) == sorted(b)): return True else: return False # Driver codea = 240b = 204 if (areAnagrams(a, b)): print(\"Yes\")else: print(\"No\") # This code is contributed by vikkycirus",
"e": 8985,
"s": 8508,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach// Function that returns true if a and b// are anagarams of each otherfunction areAnagrams(a, b){ // Converting numbers to strings a = a.toString().split(\"\").sort().join(\"\") b = b.toString().split(\"\").sort().join(\"\") // Checking if the sorting values // of two strings are equal if(a == b){ return true } else return false} // Driver codelet a = 240let b = 204 if (areAnagrams(a, b)) document.write(\"Yes\")else document.write(\"No\") // This code is contributed by shinjanpatra </script>",
"e": 9574,
"s": 8985,
"text": null
},
{
"code": null,
"e": 9582,
"s": 9574,
"text": "Output:"
},
{
"code": null,
"e": 9586,
"s": 9582,
"text": "Yes"
},
{
"code": null,
"e": 9594,
"s": 9586,
"text": "ihritik"
},
{
"code": null,
"e": 9608,
"s": 9594,
"text": "divyamohan123"
},
{
"code": null,
"e": 9619,
"s": 9608,
"text": "vikkycirus"
},
{
"code": null,
"e": 9629,
"s": 9619,
"text": "subham348"
},
{
"code": null,
"e": 9635,
"s": 9629,
"text": "ukasp"
},
{
"code": null,
"e": 9648,
"s": 9635,
"text": "shinjanpatra"
},
{
"code": null,
"e": 9662,
"s": 9648,
"text": "number-digits"
},
{
"code": null,
"e": 9667,
"s": 9662,
"text": "Hash"
},
{
"code": null,
"e": 9680,
"s": 9667,
"text": "Mathematical"
},
{
"code": null,
"e": 9685,
"s": 9680,
"text": "Hash"
},
{
"code": null,
"e": 9698,
"s": 9685,
"text": "Mathematical"
},
{
"code": null,
"e": 9796,
"s": 9698,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9834,
"s": 9796,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 9866,
"s": 9834,
"text": "Longest Consecutive Subsequence"
},
{
"code": null,
"e": 9905,
"s": 9866,
"text": "Counting frequencies of array elements"
},
{
"code": null,
"e": 9931,
"s": 9905,
"text": "Sort string of characters"
},
{
"code": null,
"e": 9967,
"s": 9931,
"text": "Hashing | Set 2 (Separate Chaining)"
},
{
"code": null,
"e": 9997,
"s": 9967,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 10040,
"s": 9997,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 10100,
"s": 10040,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10115,
"s": 10100,
"text": "C++ Data Types"
}
]
|
Validation of Equation Given as String | 01 Feb, 2019
Given a string in the form of an equation i.e A + B + C – D = E where A, B, C, D and E are integers and -, + and = are operators. The task is to print Valid if the equation is valid else print Invalid.Note: String only comprises of the characters from the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, +, -, =}.
Examples:
Input: str = “1+1+1+1=7”Output: Invalid
Input: str = “12+13-14+1=12”Output: Valid
Approach:
Traverse the string and store all the operands in an array operands[] and all the operators in an array operators[].
Now perform the arithmetic operation stored in operators[0] on operands[0] and operands[1] and store it in ans.
Then perform the seconds arithmetic operation i.e. operators[1] on ans and operators[2] and so on.
Finally, compare the ans calculated with the last operand i.e. operands[4]. If they’re equal then print Valid else print Invalid.
Below is the implementation of the above approach:
C++
Python3
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if the equation is validbool isValid(string str){ int k = 0; string operands[5] = ""; char operators[4]; long ans = 0, ans1 = 0, ans2 = 0; for (int i = 0; i < str.length(); i++) { // If it is an integer then add it to another string array if (str[i] != '+' && str[i] != '=' && str[i] != '-') operands[k] += str[i]; else { operators[k] = str[i]; // Evaluation of 1st operator if (k == 1) { if (operators[k - 1] == '+') ans += stol(operands[k - 1]) + stol(operands[k]); if (operators[k - 1] == '-') ans += stol(operands[k - 1]) - stol(operands[k]); } // Evaluation of 2nd operator if (k == 2) { if (operators[k - 1] == '+') ans1 += ans + stol(operands[k]); if (operators[k - 1] == '-') ans1 -= ans - stol(operands[k]); } // Evaluation of 3rd operator if (k == 3) { if (operators[k - 1] == '+') ans2 += ans1 + stol(operands[k]); if (operators[k - 1] == '-') ans2 -= ans1 - stol(operands[k]); } k++; } } // If the LHS result is equal to the RHS if (ans2 == stol(operands[4])) return true; else return false;} // Driver codeint main(){ string str = "2+5+3+1=11"; if (isValid(str)) cout << "Valid"; else cout << "Invalid"; return 0;}
# Python3 implementation of the approach # Function that returns true if # the equation is valid def isValid(string) : k = 0; operands = [""] * 5 ; operators = [""] * 4 ; ans = 0 ; ans1 = 0; ans2 = 0; for i in range(len(string)) : # If it is an integer then add # it to another string array if (string[i] != '+' and string[i] != '=' and string[i] != '-') : operands[k] += string[i]; else : operators[k] = string[i]; # Evaluation of 1st operator if (k == 1) : if (operators[k - 1] == '+') : ans += int(operands[k - 1]) + int(operands[k]); if (operators[k - 1] == '-') : ans += int(operands[k - 1]) - int(operands[k]); # Evaluation of 2nd operator if (k == 2) : if (operators[k - 1] == '+') : ans1 += ans + int(operands[k]); if (operators[k - 1] == '-') : ans1 -= ans - int(operands[k]); # Evaluation of 3rd operator if (k == 3) : if (operators[k - 1] == '+') : ans2 += ans1 + int(operands[k]); if (operators[k - 1] == '-') : ans2 -= ans1 - int(operands[k]); k += 1 # If the LHS result is equal to the RHS if (ans2 == int(operands[4])) : return True; else : return False; # Driver code if __name__ == "__main__" : string = "2 + 5 + 3 + 1 = 11"; if (isValid(string)) : print("Valid"); else : print("Invalid"); # This code is contributed by Ryuga
Valid
ankthon
C++ Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 329,
"s": 28,
"text": "Given a string in the form of an equation i.e A + B + C – D = E where A, B, C, D and E are integers and -, + and = are operators. The task is to print Valid if the equation is valid else print Invalid.Note: String only comprises of the characters from the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, +, -, =}."
},
{
"code": null,
"e": 339,
"s": 329,
"text": "Examples:"
},
{
"code": null,
"e": 379,
"s": 339,
"text": "Input: str = “1+1+1+1=7”Output: Invalid"
},
{
"code": null,
"e": 421,
"s": 379,
"text": "Input: str = “12+13-14+1=12”Output: Valid"
},
{
"code": null,
"e": 431,
"s": 421,
"text": "Approach:"
},
{
"code": null,
"e": 548,
"s": 431,
"text": "Traverse the string and store all the operands in an array operands[] and all the operators in an array operators[]."
},
{
"code": null,
"e": 660,
"s": 548,
"text": "Now perform the arithmetic operation stored in operators[0] on operands[0] and operands[1] and store it in ans."
},
{
"code": null,
"e": 759,
"s": 660,
"text": "Then perform the seconds arithmetic operation i.e. operators[1] on ans and operators[2] and so on."
},
{
"code": null,
"e": 889,
"s": 759,
"text": "Finally, compare the ans calculated with the last operand i.e. operands[4]. If they’re equal then print Valid else print Invalid."
},
{
"code": null,
"e": 940,
"s": 889,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 944,
"s": 940,
"text": "C++"
},
{
"code": null,
"e": 952,
"s": 944,
"text": "Python3"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if the equation is validbool isValid(string str){ int k = 0; string operands[5] = \"\"; char operators[4]; long ans = 0, ans1 = 0, ans2 = 0; for (int i = 0; i < str.length(); i++) { // If it is an integer then add it to another string array if (str[i] != '+' && str[i] != '=' && str[i] != '-') operands[k] += str[i]; else { operators[k] = str[i]; // Evaluation of 1st operator if (k == 1) { if (operators[k - 1] == '+') ans += stol(operands[k - 1]) + stol(operands[k]); if (operators[k - 1] == '-') ans += stol(operands[k - 1]) - stol(operands[k]); } // Evaluation of 2nd operator if (k == 2) { if (operators[k - 1] == '+') ans1 += ans + stol(operands[k]); if (operators[k - 1] == '-') ans1 -= ans - stol(operands[k]); } // Evaluation of 3rd operator if (k == 3) { if (operators[k - 1] == '+') ans2 += ans1 + stol(operands[k]); if (operators[k - 1] == '-') ans2 -= ans1 - stol(operands[k]); } k++; } } // If the LHS result is equal to the RHS if (ans2 == stol(operands[4])) return true; else return false;} // Driver codeint main(){ string str = \"2+5+3+1=11\"; if (isValid(str)) cout << \"Valid\"; else cout << \"Invalid\"; return 0;}",
"e": 2643,
"s": 952,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function that returns true if # the equation is valid def isValid(string) : k = 0; operands = [\"\"] * 5 ; operators = [\"\"] * 4 ; ans = 0 ; ans1 = 0; ans2 = 0; for i in range(len(string)) : # If it is an integer then add # it to another string array if (string[i] != '+' and string[i] != '=' and string[i] != '-') : operands[k] += string[i]; else : operators[k] = string[i]; # Evaluation of 1st operator if (k == 1) : if (operators[k - 1] == '+') : ans += int(operands[k - 1]) + int(operands[k]); if (operators[k - 1] == '-') : ans += int(operands[k - 1]) - int(operands[k]); # Evaluation of 2nd operator if (k == 2) : if (operators[k - 1] == '+') : ans1 += ans + int(operands[k]); if (operators[k - 1] == '-') : ans1 -= ans - int(operands[k]); # Evaluation of 3rd operator if (k == 3) : if (operators[k - 1] == '+') : ans2 += ans1 + int(operands[k]); if (operators[k - 1] == '-') : ans2 -= ans1 - int(operands[k]); k += 1 # If the LHS result is equal to the RHS if (ans2 == int(operands[4])) : return True; else : return False; # Driver code if __name__ == \"__main__\" : string = \"2 + 5 + 3 + 1 = 11\"; if (isValid(string)) : print(\"Valid\"); else : print(\"Invalid\"); # This code is contributed by Ryuga",
"e": 4387,
"s": 2643,
"text": null
},
{
"code": null,
"e": 4394,
"s": 4387,
"text": "Valid\n"
},
{
"code": null,
"e": 4402,
"s": 4394,
"text": "ankthon"
},
{
"code": null,
"e": 4415,
"s": 4402,
"text": "C++ Programs"
},
{
"code": null,
"e": 4423,
"s": 4415,
"text": "Strings"
},
{
"code": null,
"e": 4431,
"s": 4423,
"text": "Strings"
}
]
|
How to scroll automatically to a particular element using JQuery? | 03 Aug, 2021
The task is to scroll to a particular element automatically. Below are the approaches:
Approach 1:
Get the height of the element by .position().top property.
Use .scrollTop() method to set the vertical position of the scrollbar equal to the calculated height of the particular element.
Example 1: This example uses the approach discussed above.
<!DOCTYPE HTML><html> <head> <title> How to scroll automatically to a particular element. </title> <style> #GFG_DOWN { margin-top: 370px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style="text-align:center;"> <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> <p id="GFG_DOWN" style="color:green; font-size: 30px; font-weight: bold;"> This is element. </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to scroll to the particular element."; function gfg_Run() { $(window).scrollTop($('#GFG_DOWN').position().top); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Get the height of the element by .offset().top property.
Use .animate() method to animate to the element.
Example 2: This example uses the approach discussed above.
<!DOCTYPE HTML><html> <head> <title> How to scroll automatically to a particular element. </title> <style> #GFG_DOWN { margin-top: 400px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style="text-align:center;"> <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> <p id="GFG_DOWN" style="color:green; font-size: 30px; font-weight: bold;"> This is element. </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to scroll to the particular element."; function gfg_Run() { $('html, body').animate({ scrollTop: $("#GFG_DOWN").offset().top }, 500); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Misc
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery | children() with Examples
How to get the value in an input text box using jQuery ?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | change() with Examples
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": "\n03 Aug, 2021"
},
{
"code": null,
"e": 115,
"s": 28,
"text": "The task is to scroll to a particular element automatically. Below are the approaches:"
},
{
"code": null,
"e": 127,
"s": 115,
"text": "Approach 1:"
},
{
"code": null,
"e": 186,
"s": 127,
"text": "Get the height of the element by .position().top property."
},
{
"code": null,
"e": 314,
"s": 186,
"text": "Use .scrollTop() method to set the vertical position of the scrollbar equal to the calculated height of the particular element."
},
{
"code": null,
"e": 373,
"s": 314,
"text": "Example 1: This example uses the approach discussed above."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to scroll automatically to a particular element. </title> <style> #GFG_DOWN { margin-top: 370px; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <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> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 30px; font-weight: bold;\"> This is element. </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to scroll to the particular element.\"; function gfg_Run() { $(window).scrollTop($('#GFG_DOWN').position().top); } </script></body> </html>",
"e": 1413,
"s": 373,
"text": null
},
{
"code": null,
"e": 1421,
"s": 1413,
"text": "Output:"
},
{
"code": null,
"e": 1452,
"s": 1421,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 1482,
"s": 1452,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 1494,
"s": 1482,
"text": "Approach 2:"
},
{
"code": null,
"e": 1551,
"s": 1494,
"text": "Get the height of the element by .offset().top property."
},
{
"code": null,
"e": 1600,
"s": 1551,
"text": "Use .animate() method to animate to the element."
},
{
"code": null,
"e": 1659,
"s": 1600,
"text": "Example 2: This example uses the approach discussed above."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to scroll automatically to a particular element. </title> <style> #GFG_DOWN { margin-top: 400px; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <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> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 30px; font-weight: bold;\"> This is element. </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to scroll to the particular element.\"; function gfg_Run() { $('html, body').animate({ scrollTop: $(\"#GFG_DOWN\").offset().top }, 500); } </script></body> </html>",
"e": 2735,
"s": 1659,
"text": null
},
{
"code": null,
"e": 2743,
"s": 2735,
"text": "Output:"
},
{
"code": null,
"e": 2774,
"s": 2743,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 2804,
"s": 2774,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 3072,
"s": 2804,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 3084,
"s": 3072,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 3091,
"s": 3084,
"text": "JQuery"
},
{
"code": null,
"e": 3108,
"s": 3091,
"text": "Web Technologies"
},
{
"code": null,
"e": 3135,
"s": 3108,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3233,
"s": 3135,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3267,
"s": 3233,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 3324,
"s": 3267,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 3397,
"s": 3324,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 3420,
"s": 3397,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 3452,
"s": 3420,
"text": "jQuery | change() with Examples"
},
{
"code": null,
"e": 3485,
"s": 3452,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3547,
"s": 3485,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3608,
"s": 3547,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3658,
"s": 3608,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Find Weakly Connected Components in a Directed Graph | 28 Oct, 2021
Weakly Connected Graph:
A directed graph ‘G = (V, E)’ is weakly connected if the underlying undirected graph Ĝ is connected.
The underlying undirected graph is the graph Ĝ = (V, Ê) where Ê represents the set of undirected edges that is obtained by removing the arrowheads from the directed edges and making them bidirectional in G.
Example:
The directed graph G above is weakly connected since its underlying undirected graph Ĝ is connected.
Weakly Connected Component:
Given a directed graph, a weakly connected component (WCC) is a subgraph of the original graph where all vertices are connected to each other by some path, ignoring the direction of edges.
Example:
In the above directed graph, there are two weakly connected components:
[0, 1, 2, 3]
[4, 5]
Algorithm to find Weakly Connected Component:
It uses the algorithm to find connected components of an undirected graph.
Construct the underlying undirected graph of the given directed graph.
Find all the connected components of the undirected graph.
The connected components of the undirected graph will be the weakly connected components of the directed graph.
Implementation:
Below is the code of Weakly Connected Component which takes a directed graph DG as input and returns all the weakly connected components WCC of the input graph.
Java
// Java Code for the above algorithmimport java.util.ArrayList; class Graph { int vertices; ArrayList<ArrayList<Integer> > adjacencyList; public Graph(int vertices) { this.vertices = vertices; adjacencyList = new ArrayList<>(vertices); for (int i = 0; i < this.vertices; i++) adjacencyList.add(new ArrayList<>()); } public void addEdge(int u, int v) { // Use of noEdge(int, int) // prevents duplication of edges if (noEdge(u, v)) adjacencyList.get(u).add(v); } // Returns true if there does NOT exist // any edge from u to v boolean noEdge(int u, int v) { for (int destination : adjacencyList.get(u)) if (destination == v) return false; return true; }} class WCC { private final Graph directedGraph; public WCC(Graph directedGraph) { this.directedGraph = directedGraph; } // Finds all the connected components // of the given undirected graph private ArrayList<ArrayList<Integer> > connectedComponents(Graph undirectedGraph) { ArrayList<ArrayList<Integer> > connectedComponents = new ArrayList<>(); boolean[] isVisited = new boolean[undirectedGraph.vertices]; for (int i = 0; i < undirectedGraph.vertices; i++) { if (!isVisited[i]) { ArrayList<Integer> component = new ArrayList<>(); findConnectedComponent(i, isVisited, component, undirectedGraph); connectedComponents.add(component); } } return connectedComponents; } // Finds a connected component // starting from source using DFS private void findConnectedComponent(int src, boolean[] isVisited, ArrayList<Integer> component, Graph undirectedGraph) { isVisited[src] = true; component.add(src); for (int v : undirectedGraph.adjacencyList.get(src)) if (!isVisited[v]) findConnectedComponent(v, isVisited, component, undirectedGraph); } public ArrayList<ArrayList<Integer> > weaklyConnectedComponents() { // Step 1: Construct the // underlying undirected graph Graph undirectedGraph = new Graph(directedGraph.vertices); for (int u = 0; u < directedGraph.vertices; u++) { for (int v : directedGraph.adjacencyList.get(u)) { undirectedGraph.addEdge(u, v); undirectedGraph.addEdge(v, u); } } // Step 2: Find the connected components // of the undirected graph return connectedComponents(undirectedGraph); }} public class WCCDemo { // Driver Code public static void main(String[] args) { Graph directedGraph = new Graph(6); directedGraph.addEdge(0, 1); directedGraph.addEdge(0, 2); directedGraph.addEdge(3, 1); directedGraph.addEdge(3, 2); directedGraph.addEdge(4, 5); ArrayList<ArrayList<Integer> > weaklyConnectedComponents = new WCC(directedGraph) .weaklyConnectedComponents(); int index = 1; for (ArrayList<Integer> component : weaklyConnectedComponents) { System.out.print("Component " + index++ + ": "); for (Integer i : component) System.out.print(i + " "); System.out.println(); } }}
Component 1: 0 1 3 2
Component 2: 4 5
Time complexity: O(V+E)
TrueGeek-2021
Algorithms
Data Structures
Graph
TrueGeek
Data Structures
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Oct, 2021"
},
{
"code": null,
"e": 52,
"s": 28,
"text": "Weakly Connected Graph:"
},
{
"code": null,
"e": 155,
"s": 52,
"text": "A directed graph ‘G = (V, E)’ is weakly connected if the underlying undirected graph Ĝ is connected. "
},
{
"code": null,
"e": 365,
"s": 155,
"text": "The underlying undirected graph is the graph Ĝ = (V, Ê) where Ê represents the set of undirected edges that is obtained by removing the arrowheads from the directed edges and making them bidirectional in G."
},
{
"code": null,
"e": 374,
"s": 365,
"text": "Example:"
},
{
"code": null,
"e": 476,
"s": 374,
"text": "The directed graph G above is weakly connected since its underlying undirected graph Ĝ is connected."
},
{
"code": null,
"e": 504,
"s": 476,
"text": "Weakly Connected Component:"
},
{
"code": null,
"e": 693,
"s": 504,
"text": "Given a directed graph, a weakly connected component (WCC) is a subgraph of the original graph where all vertices are connected to each other by some path, ignoring the direction of edges."
},
{
"code": null,
"e": 702,
"s": 693,
"text": "Example:"
},
{
"code": null,
"e": 774,
"s": 702,
"text": "In the above directed graph, there are two weakly connected components:"
},
{
"code": null,
"e": 787,
"s": 774,
"text": "[0, 1, 2, 3]"
},
{
"code": null,
"e": 794,
"s": 787,
"text": "[4, 5]"
},
{
"code": null,
"e": 840,
"s": 794,
"text": "Algorithm to find Weakly Connected Component:"
},
{
"code": null,
"e": 916,
"s": 840,
"text": " It uses the algorithm to find connected components of an undirected graph."
},
{
"code": null,
"e": 988,
"s": 916,
"text": "Construct the underlying undirected graph of the given directed graph. "
},
{
"code": null,
"e": 1048,
"s": 988,
"text": "Find all the connected components of the undirected graph. "
},
{
"code": null,
"e": 1160,
"s": 1048,
"text": "The connected components of the undirected graph will be the weakly connected components of the directed graph."
},
{
"code": null,
"e": 1177,
"s": 1160,
"text": "Implementation: "
},
{
"code": null,
"e": 1338,
"s": 1177,
"text": "Below is the code of Weakly Connected Component which takes a directed graph DG as input and returns all the weakly connected components WCC of the input graph."
},
{
"code": null,
"e": 1343,
"s": 1338,
"text": "Java"
},
{
"code": "// Java Code for the above algorithmimport java.util.ArrayList; class Graph { int vertices; ArrayList<ArrayList<Integer> > adjacencyList; public Graph(int vertices) { this.vertices = vertices; adjacencyList = new ArrayList<>(vertices); for (int i = 0; i < this.vertices; i++) adjacencyList.add(new ArrayList<>()); } public void addEdge(int u, int v) { // Use of noEdge(int, int) // prevents duplication of edges if (noEdge(u, v)) adjacencyList.get(u).add(v); } // Returns true if there does NOT exist // any edge from u to v boolean noEdge(int u, int v) { for (int destination : adjacencyList.get(u)) if (destination == v) return false; return true; }} class WCC { private final Graph directedGraph; public WCC(Graph directedGraph) { this.directedGraph = directedGraph; } // Finds all the connected components // of the given undirected graph private ArrayList<ArrayList<Integer> > connectedComponents(Graph undirectedGraph) { ArrayList<ArrayList<Integer> > connectedComponents = new ArrayList<>(); boolean[] isVisited = new boolean[undirectedGraph.vertices]; for (int i = 0; i < undirectedGraph.vertices; i++) { if (!isVisited[i]) { ArrayList<Integer> component = new ArrayList<>(); findConnectedComponent(i, isVisited, component, undirectedGraph); connectedComponents.add(component); } } return connectedComponents; } // Finds a connected component // starting from source using DFS private void findConnectedComponent(int src, boolean[] isVisited, ArrayList<Integer> component, Graph undirectedGraph) { isVisited[src] = true; component.add(src); for (int v : undirectedGraph.adjacencyList.get(src)) if (!isVisited[v]) findConnectedComponent(v, isVisited, component, undirectedGraph); } public ArrayList<ArrayList<Integer> > weaklyConnectedComponents() { // Step 1: Construct the // underlying undirected graph Graph undirectedGraph = new Graph(directedGraph.vertices); for (int u = 0; u < directedGraph.vertices; u++) { for (int v : directedGraph.adjacencyList.get(u)) { undirectedGraph.addEdge(u, v); undirectedGraph.addEdge(v, u); } } // Step 2: Find the connected components // of the undirected graph return connectedComponents(undirectedGraph); }} public class WCCDemo { // Driver Code public static void main(String[] args) { Graph directedGraph = new Graph(6); directedGraph.addEdge(0, 1); directedGraph.addEdge(0, 2); directedGraph.addEdge(3, 1); directedGraph.addEdge(3, 2); directedGraph.addEdge(4, 5); ArrayList<ArrayList<Integer> > weaklyConnectedComponents = new WCC(directedGraph) .weaklyConnectedComponents(); int index = 1; for (ArrayList<Integer> component : weaklyConnectedComponents) { System.out.print(\"Component \" + index++ + \": \"); for (Integer i : component) System.out.print(i + \" \"); System.out.println(); } }}",
"e": 5076,
"s": 1343,
"text": null
},
{
"code": null,
"e": 5116,
"s": 5076,
"text": "Component 1: 0 1 3 2 \nComponent 2: 4 5 "
},
{
"code": null,
"e": 5140,
"s": 5116,
"text": "Time complexity: O(V+E)"
},
{
"code": null,
"e": 5154,
"s": 5140,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 5165,
"s": 5154,
"text": "Algorithms"
},
{
"code": null,
"e": 5181,
"s": 5165,
"text": "Data Structures"
},
{
"code": null,
"e": 5187,
"s": 5181,
"text": "Graph"
},
{
"code": null,
"e": 5196,
"s": 5187,
"text": "TrueGeek"
},
{
"code": null,
"e": 5212,
"s": 5196,
"text": "Data Structures"
},
{
"code": null,
"e": 5218,
"s": 5212,
"text": "Graph"
},
{
"code": null,
"e": 5229,
"s": 5218,
"text": "Algorithms"
}
]
|
Longest K unique characters substring | Practice | GeeksforGeeks | Given a string you need to print the size of the longest possible substring that has exactly K unique characters. If there is no possible substring then print -1.
Example 1:
Input:
S = "aabacbebebe", K = 3
Output: 7
Explanation: "cbebebe" is the longest
substring with K distinct characters.
Example 2:
Input:
S = "aaaa", K = 2
Output: -1
Explanation: There's no substring with K
distinct characters.
Your Task:
You don't need to read input or print anything. Your task is to complete the function longestKSubstr() which takes the string S and an integer K as input and returns the length of the longest substring with exactly K distinct characters. If there is no substring with exactly K distinct characters then return -1.
Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ |S| ≤ 105
1 ≤ K ≤ 105
0
kushwahdeepu505526 minutes ago
geeks help geeks ...
time 0.05s and space O(1);
cpp easy to understand solutions
vector<int>v(26,0);
int count=0;
int i=0,j=0;
int maxe=-1;
while(i<s.size())
{
v[s[i]-'a']++;
if(v[s[i]-'a']==1)
count++;
if(count==k)
{
maxe=max(maxe,i-j+1);
}
if(count>k)
{
while(count>k)
{
v[s[j]-'a']--;
if(v[s[j]-'a']==0)
{
count--;
}
j++;
}
}
i++;
}
return maxe;
0
19ucs0932 days ago
@admin Please update the expected auxiliary space to O(N) as I think there is no solution for this question that can be done with constant space
+2
shahabuddinbravo402 days ago
class Solution{ public: int longestKSubstr(string s, int k) { int i=0,j=0,mx=-1; unordered_map<char,int>m; for(j=0;j<s.size();j++){ m[s[j]]++; if(m.size()==k){ mx=max((j-i+1),mx); } if(m.size()>k){ while(m.size()>k){ m[s[i]]--; if(m[s[i]]==0){ m.erase(s[i]); } i++; } } } return mx; }};
0
dibyenducse214 days ago
int longestKSubstr(string s, int k) { int len; int maxs=-1; int slen=s.size(); int i=0, j=0; unordered_map<int, int>mp;
for(j=0; j<slen; j++) { mp[s[j]-'a']++; if(mp.size()==k) { len=j-i+1; maxs=max(len, maxs); } while(mp.size()>k) { mp[s[i]-'a']--; if(mp[s[i]-'a']==0) mp.erase(s[i]-'a'); i++; } } return maxs; }
+2
saurabhjejurkar191 week ago
Java Solution by Legend Aditya Verma|| O(N) TC || O(N) SC
class Solution {
public int longestkSubstr(String s, int k) {
// code here
HashMap<Character,Integer> hm=new HashMap<>();
int i=0;
int j=0;
int n=s.length();
int max=0;
while(j<n){
char ch=s.charAt(j);
hm.put(ch,hm.getOrDefault(ch,0)+1);
if(hm.size()<k){
j++;
}else if(hm.size()==k){
max=Math.max(j-i+1,max);
j++;
}else if(hm.size()>k){
while(hm.size()>k){
hm.put(s.charAt(i),hm.get(s.charAt(i))-1);
if(hm.get(s.charAt(i))==0){
hm.remove(s.charAt(i));
}
i++;
if(hm.size()==k){
max=Math.max(j-i+1,max);}
}
j++;
}
}
if(max==0) return -1;
return max;
}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints. | [
{
"code": null,
"e": 401,
"s": 238,
"text": "Given a string you need to print the size of the longest possible substring that has exactly K unique characters. If there is no possible substring then print -1."
},
{
"code": null,
"e": 413,
"s": 401,
"text": "\nExample 1:"
},
{
"code": null,
"e": 533,
"s": 413,
"text": "Input:\nS = \"aabacbebebe\", K = 3\nOutput: 7\nExplanation: \"cbebebe\" is the longest \nsubstring with K distinct characters.\n"
},
{
"code": null,
"e": 544,
"s": 533,
"text": "Example 2:"
},
{
"code": null,
"e": 644,
"s": 544,
"text": "Input: \nS = \"aaaa\", K = 2\nOutput: -1\nExplanation: There's no substring with K\ndistinct characters.\n"
},
{
"code": null,
"e": 970,
"s": 644,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function longestKSubstr() which takes the string S and an integer K as input and returns the length of the longest substring with exactly K distinct characters. If there is no substring with exactly K distinct characters then return -1."
},
{
"code": null,
"e": 1037,
"s": 970,
"text": "\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1077,
"s": 1037,
"text": "\nConstraints:\n1 ≤ |S| ≤ 105\n1 ≤ K ≤ 105"
},
{
"code": null,
"e": 1079,
"s": 1077,
"text": "0"
},
{
"code": null,
"e": 1110,
"s": 1079,
"text": "kushwahdeepu505526 minutes ago"
},
{
"code": null,
"e": 1131,
"s": 1110,
"text": "geeks help geeks ..."
},
{
"code": null,
"e": 1158,
"s": 1131,
"text": "time 0.05s and space O(1);"
},
{
"code": null,
"e": 1191,
"s": 1158,
"text": "cpp easy to understand solutions"
},
{
"code": null,
"e": 1497,
"s": 1191,
"text": "vector<int>v(26,0);\nint count=0;\nint i=0,j=0;\nint maxe=-1;\nwhile(i<s.size())\n{\n\n v[s[i]-'a']++;\n if(v[s[i]-'a']==1)\n count++;\n if(count==k)\n {\n maxe=max(maxe,i-j+1);\n }\n if(count>k)\n {\n while(count>k)\n {\n v[s[j]-'a']--;\n if(v[s[j]-'a']==0)\n {\n count--;\n }\n j++;\n }\n }\n i++;\n}\nreturn maxe;"
},
{
"code": null,
"e": 1503,
"s": 1501,
"text": "0"
},
{
"code": null,
"e": 1522,
"s": 1503,
"text": "19ucs0932 days ago"
},
{
"code": null,
"e": 1668,
"s": 1522,
"text": "@admin Please update the expected auxiliary space to O(N) as I think there is no solution for this question that can be done with constant space "
},
{
"code": null,
"e": 1671,
"s": 1668,
"text": "+2"
},
{
"code": null,
"e": 1700,
"s": 1671,
"text": "shahabuddinbravo402 days ago"
},
{
"code": null,
"e": 2192,
"s": 1700,
"text": "class Solution{ public: int longestKSubstr(string s, int k) { int i=0,j=0,mx=-1; unordered_map<char,int>m; for(j=0;j<s.size();j++){ m[s[j]]++; if(m.size()==k){ mx=max((j-i+1),mx); } if(m.size()>k){ while(m.size()>k){ m[s[i]]--; if(m[s[i]]==0){ m.erase(s[i]); } i++; } } } return mx; }};"
},
{
"code": null,
"e": 2194,
"s": 2192,
"text": "0"
},
{
"code": null,
"e": 2218,
"s": 2194,
"text": "dibyenducse214 days ago"
},
{
"code": null,
"e": 2353,
"s": 2218,
"text": "int longestKSubstr(string s, int k) { int len; int maxs=-1; int slen=s.size(); int i=0, j=0; unordered_map<int, int>mp;"
},
{
"code": null,
"e": 2675,
"s": 2353,
"text": " for(j=0; j<slen; j++) { mp[s[j]-'a']++; if(mp.size()==k) { len=j-i+1; maxs=max(len, maxs); } while(mp.size()>k) { mp[s[i]-'a']--; if(mp[s[i]-'a']==0) mp.erase(s[i]-'a'); i++; } } return maxs; }"
},
{
"code": null,
"e": 2678,
"s": 2675,
"text": "+2"
},
{
"code": null,
"e": 2706,
"s": 2678,
"text": "saurabhjejurkar191 week ago"
},
{
"code": null,
"e": 2764,
"s": 2706,
"text": "Java Solution by Legend Aditya Verma|| O(N) TC || O(N) SC"
},
{
"code": null,
"e": 3752,
"s": 2764,
"text": "class Solution {\n public int longestkSubstr(String s, int k) {\n // code here\n HashMap<Character,Integer> hm=new HashMap<>();\n \n int i=0;\n int j=0;\n int n=s.length();\n \n int max=0;\n \n while(j<n){\n char ch=s.charAt(j);\n hm.put(ch,hm.getOrDefault(ch,0)+1);\n \n if(hm.size()<k){\n j++;\n }else if(hm.size()==k){\n max=Math.max(j-i+1,max);\n j++;\n }else if(hm.size()>k){\n while(hm.size()>k){\n hm.put(s.charAt(i),hm.get(s.charAt(i))-1);\n if(hm.get(s.charAt(i))==0){\n hm.remove(s.charAt(i));\n }\n i++;\n if(hm.size()==k){\n max=Math.max(j-i+1,max);}\n }\n j++;\n }\n }\n if(max==0) return -1;\n return max;\n }\n}"
},
{
"code": null,
"e": 3898,
"s": 3752,
"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": 3934,
"s": 3898,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3944,
"s": 3934,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3954,
"s": 3944,
"text": "\nContest\n"
},
{
"code": null,
"e": 4017,
"s": 3954,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4202,
"s": 4017,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 4486,
"s": 4202,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 4632,
"s": 4486,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 4709,
"s": 4632,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 4750,
"s": 4709,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 4778,
"s": 4750,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 4849,
"s": 4778,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 5036,
"s": 4849,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
]
|
Java Program to Toss a Coin | Let’s say we have a coin and 10 chances. Here, we will first initialize the values for head, tail and chances −
int heads = 0;
int tails = 0;
int chances = 10;
Now, we will get the head and tail values using the Random object −
for (int i = 1; i<= chances; i++) {
if (t.chanceFunc().equals("tails")) {
tails++;
} else {
heads++;
}
}
Above, the function chanceFunc() is having Random class with the nextInt() method to get the next random value. The condition is checked and the heads and tails values are returned −
public String chanceFunc() {
Random r = new Random();
int chance = r.nextInt(2);
if (chance == 1) {
return"tails";
} else {
return"heads";
}
}
Live Demo
import java.util.Random;
class Toss {
public String chanceFunc() {
Random r = new Random();
int chance = r.nextInt(2);
if (chance == 1) {
return"tails";
} else {
return"heads";
}
}
}
public class Demo {
public static void main(String[] args) {
Toss t = new Toss();
int heads = 0;
int tails = 0;
int chances = 10;
for (int i = 1; i<= chances; i++) {
if (t.chanceFunc().equals("tails")) {
tails++;
} else {
heads++;
}
}
System.out.println("Chances = " + chances);
System.out.println("Heads: " + heads);
System.out.println("Tails: " + tails);
}
}
Chances = 10
Heads: 3
Tails: 7
Let us run the program again −
Chances = 10
Heads: 4
Tails: 6 | [
{
"code": null,
"e": 1174,
"s": 1062,
"text": "Let’s say we have a coin and 10 chances. Here, we will first initialize the values for head, tail and chances −"
},
{
"code": null,
"e": 1222,
"s": 1174,
"text": "int heads = 0;\nint tails = 0;\nint chances = 10;"
},
{
"code": null,
"e": 1290,
"s": 1222,
"text": "Now, we will get the head and tail values using the Random object −"
},
{
"code": null,
"e": 1416,
"s": 1290,
"text": "for (int i = 1; i<= chances; i++) {\n if (t.chanceFunc().equals(\"tails\")) {\n tails++;\n } else {\n heads++;\n }\n}"
},
{
"code": null,
"e": 1599,
"s": 1416,
"text": "Above, the function chanceFunc() is having Random class with the nextInt() method to get the next random value. The condition is checked and the heads and tails values are returned −"
},
{
"code": null,
"e": 1769,
"s": 1599,
"text": "public String chanceFunc() {\n Random r = new Random();\n int chance = r.nextInt(2);\n if (chance == 1) {\n return\"tails\";\n } else {\n return\"heads\";\n }\n}"
},
{
"code": null,
"e": 1780,
"s": 1769,
"text": " Live Demo"
},
{
"code": null,
"e": 2489,
"s": 1780,
"text": "import java.util.Random;\nclass Toss {\n public String chanceFunc() {\n Random r = new Random();\n int chance = r.nextInt(2);\n if (chance == 1) {\n return\"tails\";\n } else {\n return\"heads\";\n }\n }\n}\npublic class Demo {\n public static void main(String[] args) {\n Toss t = new Toss();\n int heads = 0;\n int tails = 0;\n int chances = 10;\n for (int i = 1; i<= chances; i++) {\n if (t.chanceFunc().equals(\"tails\")) {\n tails++;\n } else {\n heads++;\n }\n }\n System.out.println(\"Chances = \" + chances);\n System.out.println(\"Heads: \" + heads);\n System.out.println(\"Tails: \" + tails);\n }\n}"
},
{
"code": null,
"e": 2520,
"s": 2489,
"text": "Chances = 10\nHeads: 3\nTails: 7"
},
{
"code": null,
"e": 2551,
"s": 2520,
"text": "Let us run the program again −"
},
{
"code": null,
"e": 2582,
"s": 2551,
"text": "Chances = 10\nHeads: 4\nTails: 6"
}
]
|
Lower case to upper case | Practice | GeeksforGeeks | Given a string str containing only lowercase letters, generate a string with the same letters, but in uppercase.
Example 1:
Input:
str = "geeks"
Output: GEEKS
Example 2:
Input:
str = "geeksforgeeks"
Output: GEEKSFORGEEKS
Your Task:
You don't need to read input or print anything. Your task is to complete the function to_upper() which takes the string str as an argument and returns the resultant string.
Expected Time Complexity: O(length of the string).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ length of the string ≤ 50
0
visionsameer394 days ago
IN PYTHON
class Solution: def to_upper(self, str): return str.upper()
+1
mayank180919991 week ago
string to_upper(string str){
//code
for(int i=0;i<str.length();i++){
if(islower(str[i])){
str[i]=str[i]-32;
}
}
return str;
}
0
avicode4243 weeks ago
class Solution { String to_upper(String str) { // code here String str1 = str.toUpperCase(); return str1; }}
0
priyaranjandash1 month ago
class Solution { String to_upper(String str) { return str.toUpperCase(); }}
0
shivanshixa312 months ago
string to_upper(string str){
//code
for(int i=0;i<str.length();i++){
str[i] -= 32;
}
return str;
}
0
vikkrammor2 months ago
String to_upper(String str) { return str.toUpperCase(); }
0
jaatgfg112 months ago
string to_upper(string str){ int n=str.length(); for(int i=0;i<n;i++){ str[i]=str[i]-32; } return str; }
0
abythankachan3143 months ago
Python code
Time taken : 0.0
def to_upper(self,str):
return str.upper()
0
mris127893 months ago
IN C++ LANGUAGE :
for(int i=0;str[i]!='\0';i++) str[i]-=32; return str;
0
shaktig1011013 months ago
package string;public class Greek {String to_Upper(String str){String st=str; System.out.println(st.toUpperCase());return st;}public static void main(String[] args) {Greek obj=new Greek();obj.to_Upper("geeks");obj.to_Upper("geeksforgeeks");}}
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": 351,
"s": 238,
"text": "Given a string str containing only lowercase letters, generate a string with the same letters, but in uppercase."
},
{
"code": null,
"e": 362,
"s": 351,
"text": "Example 1:"
},
{
"code": null,
"e": 397,
"s": 362,
"text": "Input:\nstr = \"geeks\"\nOutput: GEEKS"
},
{
"code": null,
"e": 408,
"s": 397,
"text": "Example 2:"
},
{
"code": null,
"e": 459,
"s": 408,
"text": "Input:\nstr = \"geeksforgeeks\"\nOutput: GEEKSFORGEEKS"
},
{
"code": null,
"e": 643,
"s": 459,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function to_upper() which takes the string str as an argument and returns the resultant string."
},
{
"code": null,
"e": 726,
"s": 643,
"text": "Expected Time Complexity: O(length of the string).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 769,
"s": 726,
"text": "Constraints:\n1 ≤ length of the string ≤ 50"
},
{
"code": null,
"e": 771,
"s": 769,
"text": "0"
},
{
"code": null,
"e": 796,
"s": 771,
"text": "visionsameer394 days ago"
},
{
"code": null,
"e": 806,
"s": 796,
"text": "IN PYTHON"
},
{
"code": null,
"e": 874,
"s": 806,
"text": "class Solution: def to_upper(self, str): return str.upper()"
},
{
"code": null,
"e": 877,
"s": 874,
"text": "+1"
},
{
"code": null,
"e": 902,
"s": 877,
"text": "mayank180919991 week ago"
},
{
"code": null,
"e": 1069,
"s": 902,
"text": "string to_upper(string str){\n //code\n for(int i=0;i<str.length();i++){\n if(islower(str[i])){\n str[i]=str[i]-32;\n }\n }\n return str;\n}"
},
{
"code": null,
"e": 1071,
"s": 1069,
"text": "0"
},
{
"code": null,
"e": 1093,
"s": 1071,
"text": "avicode4243 weeks ago"
},
{
"code": null,
"e": 1229,
"s": 1093,
"text": "class Solution { String to_upper(String str) { // code here String str1 = str.toUpperCase(); return str1; }}"
},
{
"code": null,
"e": 1231,
"s": 1229,
"text": "0"
},
{
"code": null,
"e": 1258,
"s": 1231,
"text": "priyaranjandash1 month ago"
},
{
"code": null,
"e": 1350,
"s": 1258,
"text": "class Solution { String to_upper(String str) { return str.toUpperCase(); }} "
},
{
"code": null,
"e": 1352,
"s": 1350,
"text": "0"
},
{
"code": null,
"e": 1378,
"s": 1352,
"text": "shivanshixa312 months ago"
},
{
"code": null,
"e": 1501,
"s": 1378,
"text": "string to_upper(string str){\n //code\n for(int i=0;i<str.length();i++){\n str[i] -= 32;\n }\n return str;\n}"
},
{
"code": null,
"e": 1503,
"s": 1501,
"text": "0"
},
{
"code": null,
"e": 1526,
"s": 1503,
"text": "vikkrammor2 months ago"
},
{
"code": null,
"e": 1596,
"s": 1526,
"text": "String to_upper(String str) { return str.toUpperCase(); }"
},
{
"code": null,
"e": 1598,
"s": 1596,
"text": "0"
},
{
"code": null,
"e": 1620,
"s": 1598,
"text": "jaatgfg112 months ago"
},
{
"code": null,
"e": 1741,
"s": 1620,
"text": "string to_upper(string str){ int n=str.length(); for(int i=0;i<n;i++){ str[i]=str[i]-32; } return str; }"
},
{
"code": null,
"e": 1747,
"s": 1745,
"text": "0"
},
{
"code": null,
"e": 1776,
"s": 1747,
"text": "abythankachan3143 months ago"
},
{
"code": null,
"e": 1788,
"s": 1776,
"text": "Python code"
},
{
"code": null,
"e": 1805,
"s": 1788,
"text": "Time taken : 0.0"
},
{
"code": null,
"e": 1829,
"s": 1805,
"text": "def to_upper(self,str):"
},
{
"code": null,
"e": 1853,
"s": 1829,
"text": " return str.upper()"
},
{
"code": null,
"e": 1855,
"s": 1853,
"text": "0"
},
{
"code": null,
"e": 1877,
"s": 1855,
"text": "mris127893 months ago"
},
{
"code": null,
"e": 1895,
"s": 1877,
"text": "IN C++ LANGUAGE :"
},
{
"code": null,
"e": 1961,
"s": 1895,
"text": "for(int i=0;str[i]!='\\0';i++) str[i]-=32; return str;"
},
{
"code": null,
"e": 1963,
"s": 1961,
"text": "0"
},
{
"code": null,
"e": 1989,
"s": 1963,
"text": "shaktig1011013 months ago"
},
{
"code": null,
"e": 2241,
"s": 1989,
"text": "package string;public class Greek {String to_Upper(String str){String st=str; System.out.println(st.toUpperCase());return st;}public static void main(String[] args) {Greek obj=new Greek();obj.to_Upper(\"geeks\");obj.to_Upper(\"geeksforgeeks\");}} "
},
{
"code": null,
"e": 2391,
"s": 2245,
"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": 2427,
"s": 2391,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2437,
"s": 2427,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2447,
"s": 2437,
"text": "\nContest\n"
},
{
"code": null,
"e": 2510,
"s": 2447,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2658,
"s": 2510,
"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": 2866,
"s": 2658,
"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": 2972,
"s": 2866,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Plotting grids across the subplots in Python Matplotlib | To plot grids across the subplots in Python Matplotlib, we can create multiple subplots and set the spine visibility false out of multiple axes.
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots using subplots() method.
Add a subplot to the current figure and set its spine visibility as false.
Turn off the a☓3 labels.
Share the X-axis accordingly.
Configure the grid lines for a☓1, a☓2 and a☓3.
To display the figure, use show() method.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, (ax1, ax2) = plt.subplots(nrows=2)
ax3 = fig.add_subplot(111, zorder=-1)
for _, spine in ax3.spines.items():
spine.set_visible(False)
ax3.tick_params(labelleft=False, labelbottom=False, left=False, right=False)
ax3.get_shared_x_axes().join(ax3, ax1)
ax3.grid(axis="x")
ax1.grid()
ax2.grid()
plt.show() | [
{
"code": null,
"e": 1207,
"s": 1062,
"text": "To plot grids across the subplots in Python Matplotlib, we can create multiple subplots and set the spine visibility false out of multiple axes."
},
{
"code": null,
"e": 1283,
"s": 1207,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1346,
"s": 1283,
"text": "Create a figure and a set of subplots using subplots() method."
},
{
"code": null,
"e": 1421,
"s": 1346,
"text": "Add a subplot to the current figure and set its spine visibility as false."
},
{
"code": null,
"e": 1446,
"s": 1421,
"text": "Turn off the a☓3 labels."
},
{
"code": null,
"e": 1476,
"s": 1446,
"text": "Share the X-axis accordingly."
},
{
"code": null,
"e": 1523,
"s": 1476,
"text": "Configure the grid lines for a☓1, a☓2 and a☓3."
},
{
"code": null,
"e": 1565,
"s": 1523,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1999,
"s": 1565,
"text": "import matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig, (ax1, ax2) = plt.subplots(nrows=2)\nax3 = fig.add_subplot(111, zorder=-1)\n\nfor _, spine in ax3.spines.items():\n spine.set_visible(False)\n\nax3.tick_params(labelleft=False, labelbottom=False, left=False, right=False)\nax3.get_shared_x_axes().join(ax3, ax1)\nax3.grid(axis=\"x\")\n\nax1.grid()\nax2.grid()\n\nplt.show()"
}
]
|
How to Fix: TypeError: cannot perform reduce with flexible type - GeeksforGeeks | 28 Nov, 2021
In this article we will discuss TypeError: cannot perform reduce with flexible type and how can we fix it. This error may occur when we find the mean for a two-dimensional NumPy array which consists of data of multiple types.
Dataset in use:
Student ID
Student Name
Branch
Marks
101
Harry
CSE
87
102
Ron
ECE
88
103
Alexa
CSE
72
When we create this table using NumPy then this 2D Array consists of data with multiple types. In this, we had String and Integer datatypes. To find the mean value for any of the numeric columns like Marks, it throws TypeError, because it doesn’t know how to take mean when not all the values are numbers (i.e. Student Name, Branch consists data of type string).
Example: Error producing code
Python3
# import necessary packagesimport numpy as np # create a 2D Arraystudents = np.array([['Student ID', 'Student Name', 'Branch', 'Marks'], [101, 'Hary', 'CSE', 87], [102, 'Ron', 'ECE', 88], [103, 'Alexa', 'CSE', 72]]) # mean of marks(3rd column)print(students[:, 3].mean())
Output:
To overcome this problem create a 2D array using Pandas DataFrame instead of NumPy. Since DataFrame has an index value for each row and name for each column, it helps the interpreter to distinguish between columns of different types.
This single alternative fixes the issue efficiently.
Example: Fixed code
Python3
# import necessary packagesimport pandas as pd # create dataframestudents = pd.DataFrame({'student_ID': [101, 102, 103], 'student_Name': ['Hary', 'Ron', 'Alexa'], 'Branch': ['CSE', 'ECE', 'CSE'], 'Marks': [87, 88, 72]})# Tableprint(students) # mean values for all numeric columnsprint(students.mean())
Output:
Students Table and Mean Values Results
In the above example, dataframe mean value is generated for all columns with numeric type if the column name is not specified- student_ID and Marks columns are of type float. So it calculates the mean for those 2 columns and the rest of the columns are of type string. So it won’t calculate the mean value.
Picked
Python How-to-fix
Python-numpy
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()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 24127,
"s": 23901,
"text": "In this article we will discuss TypeError: cannot perform reduce with flexible type and how can we fix it. This error may occur when we find the mean for a two-dimensional NumPy array which consists of data of multiple types."
},
{
"code": null,
"e": 24143,
"s": 24127,
"text": "Dataset in use:"
},
{
"code": null,
"e": 24154,
"s": 24143,
"text": "Student ID"
},
{
"code": null,
"e": 24167,
"s": 24154,
"text": "Student Name"
},
{
"code": null,
"e": 24174,
"s": 24167,
"text": "Branch"
},
{
"code": null,
"e": 24180,
"s": 24174,
"text": "Marks"
},
{
"code": null,
"e": 24184,
"s": 24180,
"text": "101"
},
{
"code": null,
"e": 24190,
"s": 24184,
"text": "Harry"
},
{
"code": null,
"e": 24194,
"s": 24190,
"text": "CSE"
},
{
"code": null,
"e": 24197,
"s": 24194,
"text": "87"
},
{
"code": null,
"e": 24201,
"s": 24197,
"text": "102"
},
{
"code": null,
"e": 24205,
"s": 24201,
"text": "Ron"
},
{
"code": null,
"e": 24209,
"s": 24205,
"text": "ECE"
},
{
"code": null,
"e": 24212,
"s": 24209,
"text": "88"
},
{
"code": null,
"e": 24216,
"s": 24212,
"text": "103"
},
{
"code": null,
"e": 24222,
"s": 24216,
"text": "Alexa"
},
{
"code": null,
"e": 24226,
"s": 24222,
"text": "CSE"
},
{
"code": null,
"e": 24229,
"s": 24226,
"text": "72"
},
{
"code": null,
"e": 24592,
"s": 24229,
"text": "When we create this table using NumPy then this 2D Array consists of data with multiple types. In this, we had String and Integer datatypes. To find the mean value for any of the numeric columns like Marks, it throws TypeError, because it doesn’t know how to take mean when not all the values are numbers (i.e. Student Name, Branch consists data of type string)."
},
{
"code": null,
"e": 24622,
"s": 24592,
"text": "Example: Error producing code"
},
{
"code": null,
"e": 24630,
"s": 24622,
"text": "Python3"
},
{
"code": "# import necessary packagesimport numpy as np # create a 2D Arraystudents = np.array([['Student ID', 'Student Name', 'Branch', 'Marks'], [101, 'Hary', 'CSE', 87], [102, 'Ron', 'ECE', 88], [103, 'Alexa', 'CSE', 72]]) # mean of marks(3rd column)print(students[:, 3].mean())",
"e": 24964,
"s": 24630,
"text": null
},
{
"code": null,
"e": 24972,
"s": 24964,
"text": "Output:"
},
{
"code": null,
"e": 25206,
"s": 24972,
"text": "To overcome this problem create a 2D array using Pandas DataFrame instead of NumPy. Since DataFrame has an index value for each row and name for each column, it helps the interpreter to distinguish between columns of different types."
},
{
"code": null,
"e": 25259,
"s": 25206,
"text": "This single alternative fixes the issue efficiently."
},
{
"code": null,
"e": 25279,
"s": 25259,
"text": "Example: Fixed code"
},
{
"code": null,
"e": 25287,
"s": 25279,
"text": "Python3"
},
{
"code": "# import necessary packagesimport pandas as pd # create dataframestudents = pd.DataFrame({'student_ID': [101, 102, 103], 'student_Name': ['Hary', 'Ron', 'Alexa'], 'Branch': ['CSE', 'ECE', 'CSE'], 'Marks': [87, 88, 72]})# Tableprint(students) # mean values for all numeric columnsprint(students.mean())",
"e": 25663,
"s": 25287,
"text": null
},
{
"code": null,
"e": 25671,
"s": 25663,
"text": "Output:"
},
{
"code": null,
"e": 25710,
"s": 25671,
"text": "Students Table and Mean Values Results"
},
{
"code": null,
"e": 26017,
"s": 25710,
"text": "In the above example, dataframe mean value is generated for all columns with numeric type if the column name is not specified- student_ID and Marks columns are of type float. So it calculates the mean for those 2 columns and the rest of the columns are of type string. So it won’t calculate the mean value."
},
{
"code": null,
"e": 26024,
"s": 26017,
"text": "Picked"
},
{
"code": null,
"e": 26042,
"s": 26024,
"text": "Python How-to-fix"
},
{
"code": null,
"e": 26055,
"s": 26042,
"text": "Python-numpy"
},
{
"code": null,
"e": 26062,
"s": 26055,
"text": "Python"
},
{
"code": null,
"e": 26160,
"s": 26062,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26169,
"s": 26160,
"text": "Comments"
},
{
"code": null,
"e": 26182,
"s": 26169,
"text": "Old Comments"
},
{
"code": null,
"e": 26214,
"s": 26182,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26270,
"s": 26214,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26312,
"s": 26270,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26354,
"s": 26312,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26390,
"s": 26354,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26412,
"s": 26390,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26451,
"s": 26412,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26478,
"s": 26451,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26509,
"s": 26478,
"text": "Python | os.path.join() method"
}
]
|
What are relative locators in Selenium 4.0? | The relative or friendly locators in Selenium 4.0 are available with the tagname attribute of the element.
above() - Webelement located above with respect to the specified element.Syntax −driver.findElement(withTagName(“<<tagnamevalue>>”).above(element));
above() - Webelement located above with respect to the specified element.
Syntax −
driver.findElement(withTagName(“<<tagnamevalue>>”).above(element));
below() - Webelement located below with respect to the specified element.Syntax −driver.findElement(withTagName(“<<tagnamevalue>>”).below(element));
below() - Webelement located below with respect to the specified element.
Syntax −
driver.findElement(withTagName(“<<tagnamevalue>>”).below(element));
toLeftof() - Webelement located to the left of the specified element.Syntax −driver.findElement(withTagName(“<<tagnamevalue>>”).toLeftOf(element));
toLeftof() - Webelement located to the left of the specified element.
Syntax −
driver.findElement(withTagName(“<<tagnamevalue>>”).toLeftOf(element));
toRightOf() - Webelement located to the right of the specified element.Syntax −driver.findElement(withTagName(“<<tagnamevalue>>”).toRightOf(element));
toRightOf() - Webelement located to the right of the specified element.
Syntax −
driver.findElement(withTagName(“<<tagnamevalue>>”).toRightOf(element));
Code Implementation with relative Locators.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import static org.openqa.selenium.support.locators.RelativeLocator
.withTagName;
public class RelLocator {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/about/about_careers.htm";
driver.get(url);
// maximizing browser with maximize()
river.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement head_label = driver.findElement(By.cssSelector("li[class='heading']"));
// getting the link text just below head_label web element
String txt = driver.findElement(withTagName("a").below(head_label))
.getText();
System.out.println("The text below heading is " + txt);
WebElement write =
driver.findElement(By.xpath("//a[text()='Write for us']"));
// getting the heading just above Write for us web link
String txtabove = driver.findElement(withTagName("li").above(write))
.getText();
System.out.println("The text above link is " + txtabove);
WebElement searchinp =
driver.findElement(By.xpath("//input[@name='search']"));
// getting the search button to the right of edit box searchinp.
driver.findElement(withTagName("button").toRightOf(searchinp))
.click();
WebElement prntlnk =
driver.findElement(By.xpath("//a[@class=' hide-on-mobile']"));
// getting the previous page link to the left of prntlnk.
String prevlink =
driver.findElement(withTagName("a").toLeftOf(prntlnk))
.getText();
System.out.println("The text left of link is " + prevlink);
driver.close();
}
} | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "The relative or friendly locators in Selenium 4.0 are available with the tagname attribute of the element."
},
{
"code": null,
"e": 1318,
"s": 1169,
"text": "above() - Webelement located above with respect to the specified element.Syntax −driver.findElement(withTagName(“<<tagnamevalue>>”).above(element));"
},
{
"code": null,
"e": 1392,
"s": 1318,
"text": "above() - Webelement located above with respect to the specified element."
},
{
"code": null,
"e": 1401,
"s": 1392,
"text": "Syntax −"
},
{
"code": null,
"e": 1469,
"s": 1401,
"text": "driver.findElement(withTagName(“<<tagnamevalue>>”).above(element));"
},
{
"code": null,
"e": 1618,
"s": 1469,
"text": "below() - Webelement located below with respect to the specified element.Syntax −driver.findElement(withTagName(“<<tagnamevalue>>”).below(element));"
},
{
"code": null,
"e": 1692,
"s": 1618,
"text": "below() - Webelement located below with respect to the specified element."
},
{
"code": null,
"e": 1701,
"s": 1692,
"text": "Syntax −"
},
{
"code": null,
"e": 1769,
"s": 1701,
"text": "driver.findElement(withTagName(“<<tagnamevalue>>”).below(element));"
},
{
"code": null,
"e": 1917,
"s": 1769,
"text": "toLeftof() - Webelement located to the left of the specified element.Syntax −driver.findElement(withTagName(“<<tagnamevalue>>”).toLeftOf(element));"
},
{
"code": null,
"e": 1987,
"s": 1917,
"text": "toLeftof() - Webelement located to the left of the specified element."
},
{
"code": null,
"e": 1996,
"s": 1987,
"text": "Syntax −"
},
{
"code": null,
"e": 2067,
"s": 1996,
"text": "driver.findElement(withTagName(“<<tagnamevalue>>”).toLeftOf(element));"
},
{
"code": null,
"e": 2218,
"s": 2067,
"text": "toRightOf() - Webelement located to the right of the specified element.Syntax −driver.findElement(withTagName(“<<tagnamevalue>>”).toRightOf(element));"
},
{
"code": null,
"e": 2290,
"s": 2218,
"text": "toRightOf() - Webelement located to the right of the specified element."
},
{
"code": null,
"e": 2299,
"s": 2290,
"text": "Syntax −"
},
{
"code": null,
"e": 2371,
"s": 2299,
"text": "driver.findElement(withTagName(“<<tagnamevalue>>”).toRightOf(element));"
},
{
"code": null,
"e": 2415,
"s": 2371,
"text": "Code Implementation with relative Locators."
},
{
"code": null,
"e": 4427,
"s": 2415,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport static org.openqa.selenium.support.locators.RelativeLocator\n.withTagName;\npublic class RelLocator {\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/about/about_careers.htm\";\n driver.get(url);\n // maximizing browser with maximize()\n river.manage().window().maximize();\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n WebElement head_label = driver.findElement(By.cssSelector(\"li[class='heading']\"));\n // getting the link text just below head_label web element\n String txt = driver.findElement(withTagName(\"a\").below(head_label))\n .getText();\n System.out.println(\"The text below heading is \" + txt);\n WebElement write =\n driver.findElement(By.xpath(\"//a[text()='Write for us']\"));\n // getting the heading just above Write for us web link\n String txtabove = driver.findElement(withTagName(\"li\").above(write))\n .getText();\n System.out.println(\"The text above link is \" + txtabove);\n WebElement searchinp =\n driver.findElement(By.xpath(\"//input[@name='search']\"));\n // getting the search button to the right of edit box searchinp.\n driver.findElement(withTagName(\"button\").toRightOf(searchinp))\n .click();\n WebElement prntlnk =\n driver.findElement(By.xpath(\"//a[@class=' hide-on-mobile']\"));\n // getting the previous page link to the left of prntlnk.\n String prevlink =\n driver.findElement(withTagName(\"a\").toLeftOf(prntlnk))\n .getText();\n System.out.println(\"The text left of link is \" + prevlink);\n driver.close();\n }\n}"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.